Codebase list cyrus-imapd / lintian-fixes/main imap / mbdump.c
lintian-fixes/main

Tree @lintian-fixes/main (Download .tar.gz)

mbdump.c @lintian-fixes/mainraw · history · blame

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
/* mbdump.c -- Mailbox dump routines
 *
 * Copyright (c) 1994-2008 Carnegie Mellon University.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The name "Carnegie Mellon University" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For permission or any legal
 *    details, please contact
 *      Carnegie Mellon University
 *      Center for Technology Transfer and Enterprise Creation
 *      4615 Forbes Avenue
 *      Suite 302
 *      Pittsburgh, PA  15213
 *      (412) 268-7393, fax: (412) 268-7395
 *      innovation@andrew.cmu.edu
 *
 * 4. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by Computing Services
 *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
 *
 * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
 * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <config.h>

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sysexits.h>
#include <syslog.h>
#include <sys/types.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <ctype.h>
#include <dirent.h>
#include <utime.h>

#include "annotate.h"
#ifdef WITH_DAV
#include "dav_db.h"
#endif
#include "global.h"
#include "map.h"
#include "mappedfile.h"
#include "mbdump.h"
#include "mboxkey.h"
#include "mboxlist.h"
#include "quota.h"
#include "retry.h"
#include "seen.h"
#include "seqset.h"
#include "xmalloc.h"
#include "xstrlcpy.h"
#include "user.h"
#include "util.h"
#include "index.h"

/* generated headers are not necessarily in current directory */
#include "imap/imap_err.h"

static int dump_file(int first, int sync,
                     struct protstream *pin, struct protstream *pout,
                     const char *filename, const char *ftag,
                     const char *fbase, unsigned long flen);

static void downgrade_header(struct index_header *i, char *buf, int version,
                             int header_size, int record_size)
                             __attribute__((noinline));
static void header_set_num_records(char *buf, unsigned int nrecords)
                             __attribute__((noinline));

/* support for downgrading index files on copying back to an
 * earlier version of Cyrus */
static void downgrade_header(struct index_header *i, char *buf, int version,
                             int header_size, int record_size)
{
    unsigned UP_version = version;
    unsigned UP_validopts = 15;
    unsigned UP_num_records = i->exists;

    memset(buf, 0, INDEX_HEADER_SIZE);

    if (version < 10)
        UP_validopts = 3;
    /* was just called POP3_NEW_UIDL back then, single value */
    if (version < 8)
        UP_validopts = 1;

    /* has to match cyrus.cache still */
    *((bit32 *)(buf+OFFSET_GENERATION_NO)) = htonl(i->generation_no);
    *((bit32 *)(buf+OFFSET_FORMAT)) = htonl(i->format);
    /* version is changed of course */
    *((bit32 *)(buf+OFFSET_MINOR_VERSION)) = htonl(UP_version);
    *((bit32 *)(buf+OFFSET_START_OFFSET)) = htonl(header_size);
    *((bit32 *)(buf+OFFSET_RECORD_SIZE)) = htonl(record_size);
    /* NUM_RECORDS replaces "exists" in the older headers */
    *((bit32 *)(buf+OFFSET_NUM_RECORDS)) = htonl(UP_num_records);
    *((bit32 *)(buf+OFFSET_LAST_APPENDDATE)) = htonl(i->last_appenddate);
    *((bit32 *)(buf+OFFSET_LAST_UID)) = htonl(i->last_uid);

    /* quotas may be 64bit now */
    *((bit64 *)(buf+OFFSET_QUOTA_MAILBOX_USED)) = htonll(i->quota_mailbox_used);

    *((bit32 *)(buf+OFFSET_POP3_LAST_LOGIN)) = htonl(i->pop3_last_login);
    *((bit32 *)(buf+OFFSET_UIDVALIDITY)) = htonl(i->uidvalidity);
    *((bit32 *)(buf+OFFSET_DELETED)) = htonl(i->deleted);
    *((bit32 *)(buf+OFFSET_ANSWERED)) = htonl(i->answered);
    *((bit32 *)(buf+OFFSET_FLAGGED)) = htonl(i->flagged);
    *((bit32 *)(buf+OFFSET_MAILBOX_OPTIONS)) = htonl(i->options & UP_validopts);
    *((bit32 *)(buf+OFFSET_LEAKED_CACHE)) = htonl(i->leaked_cache_records);
    /* don't put values in the "SPARE" spots */
    if (version < 8) return;
    align_htonll(buf+OFFSET_HIGHESTMODSEQ, i->highestmodseq);
}

static void downgrade_record(const struct index_record *record, char *buf,
                             int version)
{
    int n;
    unsigned UP_content_offset = record->header_size;
    unsigned UP_validflags = 15;
    unsigned UP_modseqbase = OFFSET_MODSEQ;

    /* GUID was UUID and only 12 bytes long in versions 8 and 9.
     * it doesn't hurt to write it to the buffer in older versions,
     * because it won't be written out to file anyway due to the
     * record_size value. */
    if (version < 10)
        UP_modseqbase = OFFSET_MESSAGE_GUID+12;

    *((bit32 *)(buf+OFFSET_UID)) = htonl(record->uid);
    *((bit32 *)(buf+OFFSET_INTERNALDATE)) = htonl(record->internaldate);
    *((bit32 *)(buf+OFFSET_SENTDATE)) = htonl(record->sentdate);
    *((bit32 *)(buf+OFFSET_SIZE)) = htonl(record->size);
    *((bit32 *)(buf+OFFSET_HEADER_SIZE)) = htonl(record->header_size);
    /* content_offset in previous versions, identical to header_size */
    *((bit32 *)(buf+OFFSET_GMTIME)) = htonl(UP_content_offset);
    *((bit32 *)(buf+OFFSET_CACHE_OFFSET)) = htonl(record->cache_offset);
    *((bit32 *)(buf+OFFSET_LAST_UPDATED)) = htonl(record->last_updated);
    *((bit32 *)(buf+OFFSET_SYSTEM_FLAGS))
        = htonl(record->system_flags & UP_validflags);
    for (n = 0; n < MAX_USER_FLAGS/32; n++) {
        *((bit32 *)(buf+OFFSET_USER_FLAGS+4*n)) = htonl(record->user_flags[n]);
    }
    *((bit32 *)(buf+OFFSET_SAVEDATE)) = 0;
    *((bit32 *)(buf+OFFSET_CACHE_VERSION)) = htonl(record->cache_version);
    message_guid_export(&record->guid, buf+OFFSET_MESSAGE_GUID);
    *((bit64 *)(buf+UP_modseqbase)) = htonll(record->modseq);
}

static void header_set_num_records(char *buf, unsigned int nrecords)
{
    *((bit32 *)(buf+OFFSET_NUM_RECORDS)) = htonl(nrecords);
}

/* create a downgraded index file in cyrus.index.  We don't copy back
 * expunged messages, sorry */
static int dump_index(struct mailbox *mailbox, int oldversion,
                      seqset_t *expunged_seq, int first, int sync,
                      struct protstream *pin, struct protstream *pout)
{
    char oldname[MAX_MAILBOX_PATH];
    const char *fname;
    int oldindex_fd = -1;
    indexbuffer_t headerbuf;
    indexbuffer_t recordbuf;
    char *hbuf = (char *)headerbuf.buf;
    char *rbuf = (char *)recordbuf.buf;
    int header_size;
    int record_size;
    int n, r;

    if (oldversion == 6) {
        header_size = 76;
        record_size = 60;
    }
    else if (oldversion == 7) {
        header_size = 76;
        record_size = 72;
    }
    else if (oldversion == 8) {
        header_size = 92;
        record_size = 80;
    }
    else if (oldversion == 9) {
        header_size = 96;
        record_size = 80;
    }
    else if (oldversion == 10) {
        header_size = 96;
        record_size = 88;
    }
    else {
        return IMAP_MAILBOX_BADFORMAT;
    }

    fname = mailbox_meta_fname(mailbox, META_INDEX);
    snprintf(oldname, MAX_MAILBOX_PATH, "%s.OLD", fname);

    oldindex_fd = open(oldname, O_RDWR|O_TRUNC|O_CREAT, 0666);
    if (oldindex_fd == -1) goto fail;

    downgrade_header(&mailbox->i, hbuf, oldversion,
                     header_size, record_size);

    /* Write header - everything we'll say */
    n = retry_write(oldindex_fd, hbuf, header_size);
    if (n == -1) goto fail;

    struct mailbox_iter *iter = mailbox_iter_init(mailbox, 0, ITER_SKIP_UNLINKED);
    const message_t *msg;
    while ((msg = mailbox_iter_step(iter))) {
        const struct index_record *record = msg_record(msg);
        /* we have to make sure expunged records don't get the
         * file copied, or a reconstruct could bring them back
         * to life!  It we're not creating an expunged file... */
        if (record->internal_flags & FLAG_INTERNAL_EXPUNGED) {
            if (oldversion < 9) seqset_add(expunged_seq, record->uid, 1);
            continue;
        }
        /* not making sure exists matches, we do trust a bit */
        downgrade_record(record, rbuf, oldversion);
        n = retry_write(oldindex_fd, rbuf, record_size);
        if (n == -1) break;
    }
    mailbox_iter_done(&iter);
    if (n == -1) goto fail;

    close(oldindex_fd);
    r = dump_file(first, sync, pin, pout, oldname, "cyrus.index", NULL, 0);
    unlink(oldname);
    if (r) return r;

    /* create cyrus.expunge */
    if (oldversion > 8 && mailbox->i.num_records > mailbox->i.exists) {
        int nexpunge = mailbox->i.num_records - mailbox->i.exists;
        fname = mailbox_meta_fname(mailbox, META_EXPUNGE);
        snprintf(oldname, MAX_MAILBOX_PATH, "%s.OLD", fname);

        oldindex_fd = open(oldname, O_RDWR|O_TRUNC|O_CREAT, 0666);
        if (oldindex_fd == -1) goto fail;

        header_set_num_records(hbuf, nexpunge);

        /* Write header - everything we'll say */
        n = retry_write(oldindex_fd, hbuf, header_size);
        if (n == -1) goto fail;

        iter = mailbox_iter_init(mailbox, 0, ITER_SKIP_UNLINKED);
        while ((msg = mailbox_iter_step(iter))) {
            const struct index_record *record = msg_record(msg);
            /* ignore non-expunged records */
            if (!(record->internal_flags & FLAG_INTERNAL_EXPUNGED))
                continue;
            downgrade_record(record, rbuf, oldversion);
            n = retry_write(oldindex_fd, rbuf, record_size);
            if (n == -1) {
                mailbox_iter_done(&iter);
                goto fail;
	    }
        }
        mailbox_iter_done(&iter);

        close(oldindex_fd);
        r = dump_file(first, sync, pin, pout, oldname, "cyrus.expunge", NULL, 0);
        unlink(oldname);
        if (r) return r;
    }

    return 0;

fail:
    if (oldindex_fd != -1)
        close(oldindex_fd);
    unlink(oldname);

    return IMAP_IOERROR;
}

/* is this the active script? */
static int sieve_isactive(const char *sievepath, const char *name)
{
    char filename[1024];
    char linkname[1024];
    char activelink[1024];
    char *file, *link;
    int len;

    snprintf(filename, sizeof(filename), "%s/%s", sievepath, name);
    snprintf(linkname, sizeof(linkname), "%s/defaultbc", sievepath);

    len = readlink(linkname, activelink, sizeof(activelink)-1);
    if(len < 0) {
        if(errno != ENOENT) syslog(LOG_ERR, "readlink(defaultbc): %m");
        return 0;
    }

    activelink[len] = '\0';

    /* Only compare the part of the file after the last /,
     * since that is what timsieved does */
    file = strrchr(filename, '/');
    link = strrchr(activelink, '/');
    if(!file) file = filename;
    else file++;
    if(!link) link = activelink;
    else link++;

    if (!strcmp(file, link)) {
        return 1;
    } else {
        return 0;
    }
}

struct dump_annotation_rock
{
    struct protstream *pout;
    const char *tag;
};

static int dump_annotations(const char *mailbox __attribute__((unused)),
                            uint32_t uid  __attribute__((unused)),
                            const char *entry,
                            const char *userid,
                            const struct buf *value,
                            const struct annotate_metadata *mdata __attribute__((unused)),
                            void *rock)
{
    struct dump_annotation_rock *ctx = (struct dump_annotation_rock *)rock;

    /* "A-" userid entry */
    /* entry is delimited by its leading / */
    char *ename;
    static const char contenttype[] = "text/plain"; /* fake */

    /* Transfer all attributes for this annotation, don't transfer size
     * separately since that can be implicitly determined */

    prot_putc(' ', ctx->pout);
    ename = strconcat("A-", userid, entry, (char *)NULL);
    prot_printliteral(ctx->pout, ename, strlen(ename));
    free(ename);

    prot_printf(ctx->pout, " (%ld ", 0L);  /* was modifiedsince */
    prot_printliteral(ctx->pout, value->s, value->len);
    prot_putc(' ', ctx->pout);
    prot_printliteral(ctx->pout, contenttype, strlen(contenttype));
    prot_putc(')', ctx->pout);

    return 0;
}

static int dump_file(int first, int sync,
                     struct protstream *pin, struct protstream *pout,
                     const char *filename, const char *ftag,
                     const char *fbase, unsigned long flen)
{
    int filefd;
    const char *base;
    size_t len;
    struct stat sbuf;
    int c;

    /* map file */
    syslog(LOG_DEBUG, "wanting to dump %s", filename);
    if (fbase) {
        /* already mapped */
        base = fbase;

        /* we need to check real file size since actual mmap size may be larger */
        if (stat(filename, &sbuf) == -1) {
            syslog(LOG_ERR, "IOERROR: stat on %s: %m", filename);
            fatal("can't stat message file", EX_OSFILE);
        }
        if ((unsigned long)sbuf.st_size > flen) {
           syslog(LOG_ERR, "IOERROR: size mismatch on %s", filename);
           return IMAP_SYS_ERROR;
        }
        len = sbuf.st_size;
    }
    else {
        filefd = open(filename, O_RDONLY, 0666);
        if (filefd == -1) {
            /* If an optional file doesn't exist, skip it */
            if (errno == ENOENT) return 0;
            syslog(LOG_ERR, "IOERROR: open on %s: %m", filename);
            return IMAP_SYS_ERROR;
        }

        if (fstat(filefd, &sbuf) == -1) {
            syslog(LOG_ERR, "IOERROR: fstat on %s: %m", filename);
            fatal("can't fstat message file", EX_OSFILE);
        }

        base = NULL;
        len = 0;

        map_refresh(filefd, 1, &base, &len, sbuf.st_size, filename, NULL);

        close(filefd);
    }

    /* send: name, size, and contents */
    if (first) {
        prot_printf(pout, " {" SIZE_T_FMT "}\r\n", strlen(ftag));

        if (sync) {
            /* synchronize */
            c = prot_getc(pin);
            eatline(pin, c); /* We eat it no matter what */
            if (c != '+') {
                /* Synchronization Failure, Abort! */
                syslog(LOG_ERR, "Sync Error: expected '+' got '%c'",c);
                return IMAP_SERVER_UNAVAILABLE;
            }
        }

        prot_printf(pout, "%s {%lu%s}\r\n",
                    ftag, (long unsigned)len, (sync ? "+" : ""));
    } else {
        prot_printf(pout, " {" SIZE_T_FMT "%s}\r\n%s {%lu%s}\r\n",
                    strlen(ftag), (sync ? "+" : ""),
                    ftag, (long unsigned)len, (sync ? "+" : ""));
    }
    prot_write(pout, base, len);
    if (!fbase) map_free(&base, &len);

    return 0;
}

struct data_file {
    int metaname;
    char *fname;
};

/* even though 2.4.x doesn't use cyrus.expunge, we need to be aware
 * that it may exist so XFER from any 2.3.x server will work
 */
static struct data_file data_files[] = {
    { META_HEADER,  "cyrus.header"  },
    { META_INDEX,   "cyrus.index"   },
    { META_CACHE,   "cyrus.cache"   },
    { META_EXPUNGE, "cyrus.expunge" },
#ifdef WITH_DAV
    { META_DAV,     "cyrus.dav"     },
#endif
    { 0, NULL }
};

enum { SEEN_DB = 0, SUBS_DB = 1, MBOXKEY_DB = 2, DAV_DB = 3 };
static int NUM_USER_DATA_FILES = 4;

EXPORTED int dump_mailbox(const char *tag, struct mailbox *mailbox, uint32_t uid_start,
                 int oldversion,
                 struct protstream *pin, struct protstream *pout,
                 struct auth_state *auth_state __attribute((unused)))
{
    DIR *mbdir = NULL;
    int r = 0;
    struct dirent *next = NULL;
    char filename[MAX_MAILBOX_PATH + 1024];
    const char *fname;
    int first = 1;
    int i;
    char *userid = NULL;
    struct quota q;
    struct data_file *df;
    seqset_t *expunged_seq = NULL;
    const char *dirpath = mailbox_datapath(mailbox, 0);

    /* XXX - archivepath */

    mbdir = opendir(dirpath);
    if (!mbdir && errno == EACCES) {
        syslog(LOG_ERR,
               "could not dump mailbox %s (permission denied)", mailbox_name(mailbox));
        return IMAP_PERMISSION_DENIED;
    } else if (!mbdir) {
        syslog(LOG_ERR,
               "could not dump mailbox %s (unknown error)", mailbox_name(mailbox));
        return IMAP_SYS_ERROR;
    }

    /* after this point we have to both close the directory and unlock
     * the mailbox */

    if (tag) prot_printf(pout, "%s DUMP ", tag);
    (void)prot_putc('(', pout);

    /* The first member is either a number (if it is a quota root), or NIL
     * (if it isn't) */
    {
        quota_init(&q, mailbox_name(mailbox));
        r = quota_read(&q, NULL, 0);

        if (!r) {
            prot_printf(pout, QUOTA_T_FMT, q.limits[QUOTA_STORAGE]);
        } else {
            prot_printf(pout, "NIL");
            if (r == IMAP_QUOTAROOT_NONEXISTENT) r = 0;
            /* do not send other quota data later */
            quota_free(&q);
        }
    }

    /* Dump cyrus data files */
    for (df = data_files; df->metaname; df++) {
        const char *fbase = NULL;
        unsigned long flen = 0;

        switch (df->metaname) {
        case META_INDEX:
            if (mailbox->index_base) {
                fbase = mailbox->index_base;
                flen = mailbox->index_len;
            }
            break;

        case META_CACHE:
            {
                /* XXX - multi-cache-file support */
                struct mappedfile *cachefile = ptrarray_nth(&mailbox->caches, 0);
                if (cachefile) {
                    fbase = mappedfile_base(cachefile);
                    flen = mappedfile_size(cachefile);
                }
            }
            break;

        default:
            break;
        }

        if (df->metaname == META_INDEX && oldversion < MAILBOX_MINOR_VERSION) {
            expunged_seq = seqset_init(mailbox->i.last_uid, SEQ_SPARSE);
            syslog(LOG_NOTICE, "%s downgrading index to version %d for XFER",
                   mailbox_name(mailbox), oldversion);

            r = dump_index(mailbox, oldversion, expunged_seq,
                           first, !tag, pin, pout);
            if (r) goto done;

        } else {
            fname = mailbox_meta_fname(mailbox, df->metaname);
            r = dump_file(first, !tag, pin, pout, fname, df->fname, fbase, flen);
            if (r) goto done;
        }

        first = 0;
    }

    /* Dump message files */
    while ((next = readdir(mbdir)) != NULL) {
        char *name = next->d_name;  /* Alias */
        char *p = name;
        char *fullpath;
        uint32_t uid;

        /* special case for '.' (well, it gets '..' too) */
        if (name[0] == '.') continue;

        /* skip non-message files */
        while (*p && Uisdigit(*p)) p++;
        if (p[0] != '.' || p[1] != '\0') continue;

        /* ensure (number) is >= our target uid */
        uid = atoi(name);
        if (uid < uid_start) continue;

        /* ensure uid is not in the expunged records that got skipped
         * in a downgraded index file */
        if (seqset_ismember(expunged_seq, uid))
           continue;

        /* construct path/filename */
        fullpath = strconcat(dirpath, "/", name, (char *)NULL);
        r = dump_file(0, !tag, pin, pout, fullpath, name, NULL, 0);
        free(fullpath);

        if (r) goto done;
    }

    closedir(mbdir);
    mbdir = NULL;

    /* Dump annotations */
    {
        struct dump_annotation_rock actx;
        actx.tag = tag;
        actx.pout = pout;
        annotatemore_findall_mailbox(mailbox, 0, "*", /*modseq*/0,
                             dump_annotations, (void *) &actx, /*flags*/0);
    }

    /* Dump user files if this is an inbox */
    if (mboxname_isusermailbox(mailbox_name(mailbox), 1)) {
        userid = mboxname_to_userid(mailbox_name(mailbox));
        int sieve_usehomedir = config_getswitch(IMAPOPT_SIEVEUSEHOMEDIR);
        char *fname = NULL, *ftag = NULL;

        /* Dump seen and subs files */
        for (i = 0; i< NUM_USER_DATA_FILES; i++) {

            /* construct path/filename */
            switch (i) {
            case SEEN_DB:
                fname = seen_getpath(userid);
                ftag = "SEEN";
                break;
            case SUBS_DB:
                fname = user_hash_subs(userid);
                ftag = "SUBS";
                break;
            case MBOXKEY_DB:
                fname = mboxkey_getpath(userid);
                ftag = "MBOXKEY";
                break;
            case DAV_DB: {
#ifdef WITH_DAV
                struct buf dav_file = BUF_INITIALIZER;

                dav_getpath_byuserid(&dav_file, userid);
                fname = (char *) buf_cstring(&dav_file);
                ftag = "DAV";
#else
                continue;
#endif
                break;
            }
            default:
                fatal("unknown user data file", EX_OSFILE);
            }

            r = dump_file(0, !tag, pin, pout, fname, ftag, NULL, 0);
            free(fname);
            if (r) goto done;
        }

        /* Dump sieve files
         *
         * xxx can't use home directories currently
         * (it makes almost no sense in the conext of a murder) */
        if (!sieve_usehomedir) {
            const char *sieve_path = user_sieve_path(userid);
            mbdir = opendir(sieve_path);

            if (!mbdir) {
                if (errno != ENOENT)
                    syslog(LOG_ERR,
                           "could not dump sieve scripts in %s: %m)", sieve_path);
            } else {
                char tag_fname[2048];

                while((next = readdir(mbdir)) != NULL) {
                    int length=strlen(next->d_name);
                    /* 7 == strlen(".script"); 3 == strlen(".bc") */
                    if ((length >= 7 &&
                         !strcmp(next->d_name + (length - 7), ".script")) ||
                        (length >= 3 &&
                         !strcmp(next->d_name + (length - 3), ".bc")))
                    {
                        /* create tagged name */
                        if(sieve_isactive(sieve_path, next->d_name)) {
                            snprintf(tag_fname, sizeof(tag_fname),
                                     "SIEVED-%s", next->d_name);
                        } else {
                            snprintf(tag_fname, sizeof(tag_fname),
                                     "SIEVE-%s", next->d_name);
                        }

                        /* construct path/filename */
                        snprintf(filename, sizeof(filename), "%s/%s",
                                 sieve_path, next->d_name);

                        /* dump file */
                        r = dump_file(0, !tag, pin, pout, filename, tag_fname, NULL, 0);
                        if (r) goto done;
                    }
                }

                closedir(mbdir);
                mbdir = NULL;
            }
        } /* end if !sieve_userhomedir */

    } /* end if user INBOX */

    /* Dump quota data */
    if (q.root) {
        const char *ename = "X-QUOTA";
        int res;

        /* ensure there is data to transmit */
        for (res = 0; res < QUOTA_NUMRESOURCES; res++) {
            /* STORAGE quota was already sent */
            if ((res != QUOTA_STORAGE) && (q.limits[res] >= 0)) {
                break;
            }
        }

        if (res < QUOTA_NUMRESOURCES) {
            int sent = 0;

            prot_putc(' ', pout);
            prot_printliteral(pout, ename, strlen(ename));
            prot_printf(pout, " (");

            for (res = 0; res < QUOTA_NUMRESOURCES; res++) {
                if (q.limits[res] < 0) {
                    continue;
                }
                if (sent++) {
                    prot_putc(' ', pout);
                }
                prot_printliteral(pout, quota_names[res], strlen(quota_names[res]));
                prot_putc(' ', pout);
                prot_printf(pout, QUOTA_T_FMT, q.limits[res]);
            }
            prot_putc(')', pout);
        }
        quota_free(&q);
    }

 done:

    prot_printf(pout,")\r\n");

    prot_flush(pout);

    if (mbdir) closedir(mbdir);
    seqset_free(&expunged_seq);
    free(userid);

    return r;
}

static int cleanup_seen_cb(const mbentry_t *mbentry, void *rock)
{
    struct seen *seendb = (struct seen *)rock;
    int r;
    seqset_t *seq = NULL;
    struct mailbox *mailbox = NULL;
    const message_t *msg;
    struct seendata sd = SEENDATA_INITIALIZER;

    r = mailbox_open_iwl(mbentry->name, &mailbox);
    if (r) goto done;

    /* read in the seen data from the seendb */
    r = seen_read(seendb, mailbox_uniqueid(mailbox), &sd);
    if (r) goto done;

    seq = seqset_parse(sd.seenuids, NULL, sd.lastuid);
    seen_freedata(&sd);

    /* update all the seen records */
    struct mailbox_iter *iter = mailbox_iter_init(mailbox, 0, ITER_SKIP_EXPUNGED);
    while ((msg = mailbox_iter_step(iter))) {
        const struct index_record *record = msg_record(msg);
        if (record->system_flags & FLAG_SEEN)
            continue; /* no need to rewrite */
        if (!seqset_ismember(seq, record->uid))
            continue;
        struct index_record copy = *record;
        copy.system_flags |= FLAG_SEEN;
        r = mailbox_rewrite_index_record(mailbox, &copy);
        if (r) break;
    }
    mailbox_iter_done(&iter);

    /* and the header values */
    mailbox_index_dirty(mailbox);
    if (mailbox->i.recentuid < sd.lastuid)
        mailbox->i.recentuid = sd.lastuid;
    if (mailbox->i.recenttime < sd.lastread)
        mailbox->i.recenttime = sd.lastread;

 done:
    seqset_free(&seq);
    mailbox_close(&mailbox);
    return r;
}

static int cleanup_seen_subfolders(const char *mbname)
{
    char *userid = mboxname_to_userid(mbname);
    struct seen *seendb = NULL;
    char buf[MAX_MAILBOX_NAME];
    int r;

    /* not owned by a user */
    if (!userid) return 0;

    /* no need to do inbox, it will have upgraded OK, just
     * the subfolders */

    snprintf(buf, sizeof(buf), "%s.", mbname);

    r = seen_open(userid, SEEN_SILENT, &seendb);
    if (!r) mboxlist_allmbox(buf, cleanup_seen_cb, seendb, /*flags*/0);
    seen_close(&seendb);

    free(userid);

    return 0;
}

EXPORTED int undump_mailbox(const char *mbname,
                   struct protstream *pin, struct protstream *pout,
                   struct auth_state *auth_state __attribute((unused)))
{
    struct buf file = BUF_INITIALIZER;
    struct buf data = BUF_INITIALIZER;
    int c;
    int r = 0;
    int curfile = -1;
    struct mailbox *mailbox = NULL;
    const char *sieve_path = NULL;
    int sieve_usehomedir = config_getswitch(IMAPOPT_SIEVEUSEHOMEDIR);
    char *userid = NULL;
    int first_annotation = 1;
    char *annotation = NULL;
    struct buf content = BUF_INITIALIZER;
    char *seen_file = NULL;
    char *mboxkey_file = NULL;
    quota_t old_quota_usage[QUOTA_NUMRESOURCES];
    int res;
    quota_t newquotas[QUOTA_NUMRESOURCES];
    quota_t quotalimit = -1;
    annotate_state_t *astate = NULL;

    /* Set a Quota (may be -1 for "unlimited") */
    for (res = 0; res < QUOTA_NUMRESOURCES; res++) {
       newquotas[res] = QUOTA_UNLIMITED;
    }

    if (mboxname_isusermailbox(mbname, 1)) {
        userid = mboxname_to_userid(mbname);
        if(!sieve_usehomedir) {
            sieve_path = user_sieve_path(userid);
        }
    }

    c = getword(pin, &data);

    /* we better be in a list now */
    if (c != '(' || data.s[0]) {
        buf_free(&data);
        free(userid);
        eatline(pin, c);
        return IMAP_PROTOCOL_BAD_PARAMETERS;
    }

    /* We should now have a number or a NIL */
    c = getword(pin, &data);
    if (!strcmp(data.s, "NIL")) {
        /* Remove any existing quotaroot */
        mboxlist_unsetquota(mbname);
    } else if (sscanf(data.s, QUOTA_T_FMT, &quotalimit) == 1) {
        /* quota will actually be applied later */
        newquotas[QUOTA_STORAGE] = quotalimit;
    } else {
        /* Huh? */
        buf_free(&data);
        free(userid);
        eatline(pin, c);
        return IMAP_PROTOCOL_BAD_PARAMETERS;
    }

    if(c != ' ' && c != ')') {
        buf_free(&data);
        free(userid);
        eatline(pin, c);
        return IMAP_PROTOCOL_BAD_PARAMETERS;
    } else if(c == ')') {
        goto done;
    }

    r = mailbox_open_exclusive(mbname, &mailbox);
    if (r == IMAP_MAILBOX_NONEXISTENT) {
        mbentry_t *mbentry = NULL;
        r = mboxlist_lookup(mbname, &mbentry, NULL);
        if (!r) r = mailbox_create(mbname, mbentry->mbtype,
                                   mbentry->partition, mbentry->acl,
                                   mbentry->uniqueid, 0, 0, 0, 0, &mailbox);
        mboxlist_entry_free(&mbentry);
    }
    if(r) goto done;

    /* track quota use */
    mailbox_get_usage(mailbox, old_quota_usage);

    astate = annotate_state_new();

    while(1) {
        char fnamebuf[MAX_MAILBOX_PATH + 1024];
        int isnowait, sawdigit;
        unsigned long size;
        unsigned long cutoff = ULONG_MAX / 10;
        unsigned digit, cutlim = ULONG_MAX % 10;
        annotation = NULL;
        buf_reset(&content);
        seen_file = NULL;
        mboxkey_file = NULL;

        c = getastring(pin, pout, &file);
        if(c != ' ') {
            r = IMAP_PROTOCOL_ERROR;
            goto done;
        }

        if(!strncmp(file.s, "A-", 2)) {
            /* Annotation */
            int i;
            char *tmpuserid;

            /* is this the first annotation? re-read cyrus.header/index */
            if (first_annotation) {
                first_annotation = 0;
                mailbox_close(&mailbox);
                r = mailbox_open_exclusive(mbname, &mailbox);
                if (r) goto done;
                r = annotate_state_set_mailbox(astate, mailbox);
                if (r) goto done;
            }

            for(i=2; file.s[i]; i++) {
                if(file.s[i] == '/') break;
            }
            if(!file.s[i]) {
                r = IMAP_PROTOCOL_ERROR;
                goto done;
            }
            tmpuserid = xmalloc(i-2+1);

            memcpy(tmpuserid, &(file.s[2]), i-2);
            tmpuserid[i-2] = '\0';

            annotation = xstrdup(&(file.s[i]));

            if(prot_getc(pin) != '(') {
                r = IMAP_PROTOCOL_ERROR;
                free(tmpuserid);
                goto done;
            }

            /* Parse the modtime...and ignore it */
            c = getword(pin, &data);
            if (c != ' ')  {
                r = IMAP_PROTOCOL_ERROR;
                free(tmpuserid);
                goto done;
            }

            c = getbastring(pin, pout, &content);
            /* xxx binary */

            if(c != ' ') {
                r = IMAP_PROTOCOL_ERROR;
                free(tmpuserid);
                goto done;
            }

            /* got the contenttype...and ignore it */
            c = getastring(pin, pout, &data);

            if(c != ')') {
                r = IMAP_PROTOCOL_ERROR;
                free(tmpuserid);
                goto done;
            }

            annotate_state_write(astate, annotation, tmpuserid,
                                     &content);

            free(tmpuserid);
            free(annotation);
            annotation = NULL;
            buf_reset(&content);

            c = prot_getc(pin);
            if(c == ')') break; /* that was the last item */
            else if(c != ' ') {
                r = IMAP_PROTOCOL_ERROR;
                goto done;
            }

            continue;
        }
        else if (!strcmp(file.s, "X-QUOTA")) {
            /* Quota */
            if (prot_getc(pin) != '(') {
                r = IMAP_PROTOCOL_ERROR;
                goto done;
            }

            for (;;) {
                /* XXX - limit is actually stored in an int value */
                int32_t limit = 0;

                c = getastring(pin, pout, &content);
                if (c != ' ') {
                    r = IMAP_PROTOCOL_ERROR;
                    goto done;
                }
                /* ignore unknown resources */
                res = quota_name_to_resource(content.s);

                c = getint32(pin, &limit);
                if (res >= 0) {
                    newquotas[res] = limit;
                }

                if (c == ')') break;
                else if (c != ' ') {
                    r = IMAP_PROTOCOL_ERROR;
                    goto done;
                }
            }

            c = prot_getc(pin);
            if (c == ')') break; /* that was the last item */
            else if (c != ' ') {
                r = IMAP_PROTOCOL_ERROR;
                goto done;
            }

            continue;
        }

        /* read size of literal */
        c = prot_getc(pin);
        if (c != '{') {
            r = IMAP_PROTOCOL_ERROR;
            goto done;
        }

        size = isnowait = sawdigit = 0;
        while ((c = prot_getc(pin)) != EOF && isdigit(c)) {
            sawdigit = 1;
            digit = c - '0';
            /* check for overflow */
            if (size > cutoff || (size == cutoff && digit > cutlim)) {
                fatal("literal too big", EX_IOERR);
            }
            size = size*10 + digit;
        }
        if (c == '+') {
            isnowait++;
            c = prot_getc(pin);
        }
        if (c == '}') {
            c = prot_getc(pin);
            if (c == '\r') c = prot_getc(pin);
        }
        if (!sawdigit || c != '\n') {
            r = IMAP_PROTOCOL_ERROR;
            goto done;
        }

        if (!isnowait) {
            /* Tell client to send the message */
            prot_printf(pout, "+ go ahead\r\n");
            prot_flush(pout);
        }

        if (userid && !strcmp(file.s, "SUBS")) {
            /* overwriting this outright is absolutely what we want to do */
            char *s = user_hash_subs(userid);
            strlcpy(fnamebuf, s, sizeof(fnamebuf));
            free(s);
#ifdef WITH_DAV
        } else if (userid && !strcmp(file.s, "DAV")) {
            /* overwriting this outright is absolutely what we want to do */
            struct buf dav_file = BUF_INITIALIZER;
            dav_getpath_byuserid(&dav_file, userid);
            strlcpy(fnamebuf, buf_cstring(&dav_file), sizeof(fnamebuf));
            buf_free(&dav_file);
#endif
        } else if (userid && !strcmp(file.s, "SEEN")) {
            seen_file = seen_getpath(userid);

            snprintf(fnamebuf,sizeof(fnamebuf),"%s.%d",seen_file,getpid());
        } else if (userid && !strcmp(file.s, "MBOXKEY")) {
            mboxkey_file = mboxkey_getpath(userid);

            snprintf(fnamebuf,sizeof(fnamebuf),"%s.%d",mboxkey_file,getpid());
        } else if (userid && !strncmp(file.s, "SIEVE", 5)) {
            int isdefault = !strncmp(file.s, "SIEVED", 6);
            char *realname;
            int ret;

            /* skip prefixes */
            if(isdefault) realname = file.s + 7;
            else realname = file.s + 6;

            if(sieve_usehomedir) {
                /* xxx! */
                syslog(LOG_ERR,
                       "dropping sieve file %s since this host is " \
                       "configured for sieve_usehomedir",
                       realname);
                continue;
            } else {
                if(snprintf(fnamebuf, sizeof(fnamebuf),
                            "%s/%s", sieve_path, realname) == -1) {
                    r = IMAP_PROTOCOL_ERROR;
                    goto done;
                } else if(isdefault) {
                    char linkbuf[2048];

                    snprintf(linkbuf, sizeof(linkbuf), "%s/defaultbc",
                             sieve_path);
                    ret = symlink(realname, linkbuf);
                    if(ret && errno == ENOENT) {
                        if(cyrus_mkdir(linkbuf, 0750) == 0) {
                            ret = symlink(realname, linkbuf);
                        }
                    }
                    if(ret) {
                        syslog(LOG_ERR, "symlink(%s, %s): %m", realname,
                               linkbuf);
                        /* Non-fatal,
                           let's get the file transferred if we can */
                    }

                }
            }
        } else {
            struct data_file *df;
            const char *path = NULL;

            /* see if its one of our datafiles */
            for (df = data_files; df->fname && strcmp(df->fname, file.s); df++);
            if (df->metaname) {
                path = mailbox_meta_fname(mailbox, df->metaname);
            } else {
                uint32_t uid;
                const char *ptr = NULL;
                if (!parseuint32(file.s, &ptr, &uid)) {
                    /* is it really a data file? */
                    if (ptr && ptr[0] == '.' && ptr[1] == '\0')
                        path = mailbox_datapath(mailbox, uid);
                }
            }
            if (!path) {
                r = IMAP_PROTOCOL_ERROR;
                goto done;
            }
            strncpy(fnamebuf, path, MAX_MAILBOX_PATH);
        }

        /* if we haven't opened it, do so */
        curfile = open(fnamebuf, O_WRONLY|O_TRUNC|O_CREAT, 0640);
        if(curfile == -1 && errno == ENOENT) {
            if(cyrus_mkdir(fnamebuf, 0750) == 0) {
                curfile = open(fnamebuf, O_WRONLY|O_TRUNC|O_CREAT, 0640);
            }
        }

        if(curfile == -1) {
            syslog(LOG_ERR, "IOERROR: creating %s: %m", fnamebuf);
            r = IMAP_IOERROR;
            goto done;
        }

        /* write data to file */
        while (size) {
            char buf[4096+1];
            int n = prot_read(pin, buf, size > 4096 ? 4096 : size);
            if (!n) {
                syslog(LOG_ERR,
                       "IOERROR: reading message: unexpected end of file");
                r = IMAP_IOERROR;
                goto done;
            }

            size -= n;

            if (write(curfile, buf, n) != n) {
                syslog(LOG_ERR, "IOERROR: writing %s: %m", fnamebuf);
                r = IMAP_IOERROR;
                goto done;
            }
        }

        close(curfile);

        /* we were operating on the seen state, so merge it and cleanup */
        if (seen_file) {
            struct seen *seendb = NULL;
            r = seen_open(userid, SEEN_CREATE, &seendb);
            if (!r) r = seen_merge(seendb, fnamebuf);
            seen_close(&seendb);

            free(seen_file);
            seen_file = NULL;
            unlink(fnamebuf);

            if (r) goto done;
        }
        /* we were operating on the seen state, so merge it and cleanup */
        else if (mboxkey_file) {
            mboxkey_merge(fnamebuf, mboxkey_file);
            free(mboxkey_file);
            mboxkey_file = NULL;

            unlink(fnamebuf);
        }

        c = prot_getc(pin);
        if (c == ')') break;
        if (c != ' ') {
            r = IMAP_PROTOCOL_ERROR;
            goto done;
        }
    }

    /* patch up seen data for subfolders */
    if (userid) {
        r = cleanup_seen_subfolders(mbname);
        /* XXX - patch up seen data here */
    }

 done:
    /* eat the rest of the line, we have atleast a \r\n coming */
    eatline(pin, c);
    buf_free(&file);
    buf_free(&data);

    if (r)
        annotate_state_abort(&mailbox->annot_state);

    if (curfile >= 0) close(curfile);
    /* we fiddled the files under the hood, so we can't do anything
     * BUT close it */
    mailbox_close(&mailbox);

    /* time to apply quota (mailbox must be unlocked) */
    if (!r) {
        for (res = 0; res < QUOTA_NUMRESOURCES; res++) {
            if (newquotas[res] != QUOTA_UNLIMITED) {
                break;
            }
        }
        if (res < QUOTA_NUMRESOURCES) {
            mboxlist_setquotas(mbname, newquotas, 0, 0);
        }
    }

    /* let's make sure the modification times are right */
    if (!r) {
        struct utimbuf settime;
        const char *fname;

        /* cheeky - we're not actually changing anything real */
        r = mailbox_open_irl(mbname, &mailbox);
        if (r) {
            r = 0; /* no point throwing errors */
            goto done2;
        }

        /* update the quota if necessary */
        if (mailbox_quotaroot(mailbox)) {
            quota_t quota_usage[QUOTA_NUMRESOURCES];
            int res;
            int changed = 0;

            mailbox_get_usage(mailbox, quota_usage);
            for (res = 0; res < QUOTA_NUMRESOURCES; res++) {
                quota_usage[res] -= old_quota_usage[res];
                if (quota_usage[res] != 0) {
                    changed++;
                }
            }

            if (changed) {
                r = quota_update_useds(mailbox_quotaroot(mailbox), quota_usage, NULL, 0);
                if (r) goto done2;
            }
        }

        struct mailbox_iter *iter = mailbox_iter_init(mailbox, 0, ITER_SKIP_UNLINKED);
        const message_t *msg;
        while ((msg = mailbox_iter_step(iter))) {
            const struct index_record *record = msg_record(msg);
            fname = mailbox_record_fname(mailbox, record);
            settime.actime = settime.modtime = record->internaldate;
            if (utime(fname, &settime) == -1) {
                r = IMAP_IOERROR;
                mailbox_iter_done(&iter);
                goto done2;
            }
        }
        mailbox_iter_done(&iter);
    }

 done2:
    /* just in case we failed during the modifications, close again */
    mailbox_close(&mailbox);
    if (!r)
        r = annotate_state_commit(&astate);
    else
        annotate_state_abort(&astate);
    free(annotation);
    buf_free(&content);
    free(seen_file);
    free(mboxkey_file);
    free(userid);

    return r;
}