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

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

sync_server.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
/* sync_server.c -- Cyrus synchronization server
 *
 * 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.
 *
 * Original version written by David Carter <dpc22@cam.ac.uk>
 * Rewritten and integrated into Cyrus by Ken Murchison <ken@oceana.com>
 */

#include <config.h>

#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/param.h>
#include <sysexits.h>
#include <syslog.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <ctype.h>

#include <sasl/sasl.h>
#include <sasl/saslutil.h>

#include "assert.h"
#include "annotate.h"
#include "append.h"
#include "auth.h"
#ifdef WITH_DAV
#include "dav_db.h"
#endif /* WITH_DAV */
#include "dlist.h"
#include "global.h"
#include "hash.h"
#include "imparse.h"
#include "imap_proxy.h"
#include "mailbox.h"
#include "map.h"
#include "mboxlist.h"
#include "partlist.h"
#include "proc.h"
#include "prot.h"
#include "quota.h"
#include "seen.h"
#include "sync_log.h"
#include "telemetry.h"
#include "tls.h"
#include "user.h"
#include "util.h"
#include "version.h"
#include "xmalloc.h"
#include "xstrlcat.h"

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

#include "message_guid.h"
#include "sync_support.h"
/*#include "cdb.h"*/

extern int optind;
extern char *optarg;
extern int opterr;

/* for config.c */
const int config_need_data = CONFIG_NEED_PARTITION_DATA;

static sasl_ssf_t extprops_ssf = 0;

#ifdef HAVE_SSL
static SSL *tls_conn;
#endif /* HAVE_SSL */

static sasl_conn_t *sync_saslconn = NULL; /* the sasl connection context */

static char *sync_userid = 0;
static struct namespace sync_namespace;
static struct namespace *sync_namespacep = &sync_namespace;
static struct auth_state *sync_authstate = 0;
static int sync_userisadmin = 0;
static const char *sync_clienthost = "[local]";
static struct protstream *sync_out = NULL;
static struct protstream *sync_in = NULL;
static int sync_logfd = -1;
static int sync_starttls_done = 0;
static int sync_compress_done = 0;
static int sync_sieve_mailbox_enabled = 0;
static int sync_archive_enabled = 0;

static int opt_force = 0;

/* commands that have specific names */
static void cmdloop(void);
static void cmd_authenticate(char *mech, char *resp);
static void cmd_starttls(void);
static void cmd_restart(struct sync_reserve_list **reserve_listp,
                       int realloc);
static void cmd_compress(char *alg);

/* generic commands - in dlist format */
static void cmd_get(struct dlist *kl);
static void cmd_apply(struct dlist *kl,
                      struct sync_reserve_list *reserve_list);
static void cmd_restore(struct dlist *kin,
                        struct sync_reserve_list *reserve_list);

static void usage(void);
void shut_down(int code) __attribute__ ((noreturn));
void shut_down_via_signal(int code) __attribute__ ((noreturn));

extern int saslserver(sasl_conn_t *conn, const char *mech,
                      const char *init_resp, const char *resp_prefix,
                      const char *continuation, const char *empty_resp,
                      struct protstream *pin, struct protstream *pout,
                      int *sasl_result, char **success_data);

static struct saslprops_t saslprops = SASLPROPS_INITIALIZER;

/* the sasl proxy policy context */
static struct proxy_context sync_proxyctx = {
    0, 1, &sync_authstate, &sync_userisadmin, NULL
};

static struct sasl_callback mysasl_cb[] = {
    { SASL_CB_GETOPT, (mysasl_cb_ft *) &mysasl_config, NULL },
    { SASL_CB_PROXY_POLICY, (mysasl_cb_ft *) &mysasl_proxy_policy, (void*) &sync_proxyctx },
    { SASL_CB_CANON_USER, (mysasl_cb_ft *) &mysasl_canon_user, NULL },
    { SASL_CB_LIST_END, NULL, NULL }
};

static void sync_reset(void)
{
    proc_cleanup();

    if (sync_in) {
        prot_NONBLOCK(sync_in);
        prot_fill(sync_in);

        prot_free(sync_in);
    }

    if (sync_out) {
        prot_flush(sync_out);
        prot_free(sync_out);
    }

    sync_in = sync_out = NULL;

#ifdef HAVE_SSL
    if (tls_conn) {
        tls_reset_servertls(&tls_conn);
        tls_conn = NULL;
    }
#endif

    cyrus_reset_stdio();

    sync_clienthost = "[local]";
    if (sync_logfd != -1) {
        close(sync_logfd);
        sync_logfd = -1;
    }
    if (sync_userid != NULL) {
        free(sync_userid);
        sync_userid = NULL;
    }
    if (sync_authstate) {
        auth_freestate(sync_authstate);
        sync_authstate = NULL;
    }
    if (sync_saslconn) {
        sasl_dispose(&sync_saslconn);
        sync_saslconn = NULL;
    }
    sync_starttls_done = 0;
    sync_compress_done = 0;

    sync_sieve_mailbox_enabled = 0;
    sync_archive_enabled = 0;

    saslprops_reset(&saslprops);
}

/*
 * run once when process is forked;
 * MUST NOT exit directly; must return with non-zero error code
 */
int service_init(int argc __attribute__((unused)),
                 char **argv __attribute__((unused)),
                 char **envp __attribute__((unused)))
{
    int opt, r;

    if (geteuid() == 0) fatal("must run as the Cyrus user", EX_USAGE);
    setproctitle_init(argc, argv, envp);

    /* set signal handlers */
    signals_set_shutdown(&shut_down_via_signal);
    signal(SIGPIPE, SIG_IGN);

    /* load the SASL plugins */
    global_sasl_init(1, 1, mysasl_cb);

    while ((opt = getopt(argc, argv, "p:f")) != EOF) {
        switch(opt) {
        case 'p': /* external protection */
            extprops_ssf = atoi(optarg);
            break;
        case 'f':
            opt_force = 1;
            break;
        default:
            usage();
        }
    }

    /* Set namespace -- force standard (internal) */
    if ((r = mboxname_init_namespace(sync_namespacep, 1)) != 0) {
        fatal(error_message(r), EX_CONFIG);
    }

    mboxevent_setnamespace(sync_namespacep);

    return 0;
}

/*
 * Issue the capability banner
 */
static void dobanner(void)
{
    const char *mechlist;
    int mechcount;

    if (!sync_userid) {
        if (sasl_listmech(sync_saslconn, NULL,
                          "* SASL ", " ", "\r\n",
                          &mechlist, NULL, &mechcount) == SASL_OK
            && mechcount > 0) {
            prot_printf(sync_out, "%s", mechlist);
        }

        if (tls_enabled() && !sync_starttls_done) {
            prot_printf(sync_out, "* STARTTLS\r\n");
        }

#ifdef HAVE_ZLIB
        if (!sync_compress_done && !sync_starttls_done) {
            prot_printf(sync_out, "* COMPRESS DEFLATE\r\n");
        }
#endif

        prot_printf(sync_out, "* SIEVE-MAILBOX\r\n");

        if (config_getswitch(IMAPOPT_ARCHIVE_ENABLED)) {
            prot_printf(sync_out, "* REPLICATION-ARCHIVE\r\n");
        }
    }

    prot_printf(sync_out,
                "* OK %s Cyrus sync server %s\r\n",
                config_servername, CYRUS_VERSION);

    prot_flush(sync_out);
}

/*
 * run for each accepted connection
 */
int service_main(int argc __attribute__((unused)),
                 char **argv __attribute__((unused)),
                 char **envp __attribute__((unused)))
{
    const char *localip, *remoteip;
    sasl_security_properties_t *secprops = NULL;
    int timeout;

    signals_poll();

    sync_in = prot_new(0, 0);
    sync_out = prot_new(1, 1);

    /* Force use of LITERAL+ so we don't need two way communications */
    prot_setisclient(sync_in, 1);
    prot_setisclient(sync_out, 1);

    /* Find out name of client host */
    sync_clienthost = get_clienthost(0, &localip, &remoteip);
    if (!strcmp(sync_clienthost, UNIX_SOCKET)) {
        /* we're not connected to an internet socket! */
        sync_userid = xstrdup(cyrus_user());
        sync_userisadmin = 1;
    }
    else {
        if (localip && remoteip) {
            buf_setcstr(&saslprops.ipremoteport, remoteip);
            buf_setcstr(&saslprops.iplocalport, localip);
        }

        /* other params should be filled in */
        if (sasl_server_new("csync", config_servername, NULL,
                            buf_cstringnull_ifempty(&saslprops.iplocalport),
                            buf_cstringnull_ifempty(&saslprops.ipremoteport),
                            NULL, 0, &sync_saslconn) != SASL_OK)
            fatal("SASL failed initializing: sasl_server_new()",EX_TEMPFAIL);

        /* will always return something valid */
        secprops = mysasl_secprops(SASL_SEC_NOANONYMOUS);
        if (sasl_setprop(sync_saslconn, SASL_SEC_PROPS, secprops) != SASL_OK)
            fatal("Failed to set SASL property", EX_TEMPFAIL);

        if (sasl_setprop(sync_saslconn, SASL_SSF_EXTERNAL, &extprops_ssf) != SASL_OK)
            fatal("Failed to set SASL property", EX_TEMPFAIL);

        tcp_disable_nagle(1); /* XXX magic fd */
    }

    proc_register(config_ident, sync_clienthost, NULL, NULL, NULL);

    /* Set inactivity timer */
    timeout = config_getduration(IMAPOPT_SYNC_TIMEOUT, 's');
    if (timeout < 3) timeout = 3;
    prot_settimeout(sync_in, timeout);

    prot_setflushonread(sync_in, sync_out);

    sync_log_init();
    if (!config_getswitch(IMAPOPT_SYNC_LOG_CHAIN))
        sync_log_suppress();

    dobanner();

    cmdloop();

    /* EXIT executed */

    /* cleanup */
    sync_reset();

    return 0;
}

/* Called by service API to shut down the service */
void service_abort(int error)
{
    shut_down(error);
}

static void usage(void)
{
    prot_printf(sync_out, "* usage: sync_server [-C <alt_config>]\r\n");
    prot_flush(sync_out);
    exit(EX_USAGE);
}

/*
 * Cleanly shut down and exit
 */
void shut_down(int code)
{
    in_shutdown = 1;

    libcyrus_run_delayed();

    proc_cleanup();

    seen_done();

    partlist_local_done();

    if (sync_in) {
        prot_NONBLOCK(sync_in);
        prot_fill(sync_in);
        prot_free(sync_in);
    }

    if (sync_out) {
        prot_flush(sync_out);
        prot_free(sync_out);
    }

#ifdef HAVE_SSL
    tls_shutdown_serverengine();
#endif

    saslprops_free(&saslprops);

    cyrus_done();

    exit(code);
}

void shut_down_via_signal(int code __attribute__((unused)))
{
    if (sync_out) {
        prot_puts(sync_out, "BYE shutting down\r\n");
    }

    shut_down(0);
}

EXPORTED void fatal(const char* s, int code)
{
    static int recurse_code = 0;

    if (recurse_code) {
        /* We were called recursively. Just give up */
        proc_cleanup();
        exit(recurse_code);
    }
    recurse_code = code;
    if (sync_out) {
        prot_printf(sync_out, "* Fatal error: %s\r\n", s);
        prot_flush(sync_out);
    }
    syslog(LOG_ERR, "Fatal error: %s", s);
    shut_down(code);
}

/* Reset the given sasl_conn_t to a sane state */
static int reset_saslconn(sasl_conn_t **conn)
{
    int ret;
    sasl_security_properties_t *secprops = NULL;

    sasl_dispose(conn);
    /* do initialization typical of service_main */
    ret = sasl_server_new("csync", config_servername, NULL,
                          buf_cstringnull_ifempty(&saslprops.iplocalport),
                          buf_cstringnull_ifempty(&saslprops.ipremoteport),
                          NULL, 0, conn);
    if (ret != SASL_OK) return ret;

    secprops = mysasl_secprops(SASL_SEC_NOANONYMOUS);
    ret = sasl_setprop(*conn, SASL_SEC_PROPS, secprops);
    if (ret != SASL_OK) return ret;
    /* end of service_main initialization excepting SSF */

    /* If we have TLS/SSL info, set it */
    if (saslprops.ssf) {
        ret = saslprops_set_tls(&saslprops, *conn);
    } else {
        ret = sasl_setprop(*conn, SASL_SSF_EXTERNAL, &extprops_ssf);
    }

    if (ret != SASL_OK) return ret;
    /* End TLS/SSL Info */

    return SASL_OK;
}

static void cmdloop(void)
{
    struct sync_reserve_list *reserve_list;
    static struct buf cmd;
    static struct buf arg1, arg2;
    int c;
    char *p;
    struct dlist *kl;

    syslog(LOG_DEBUG, "cmdloop(): startup");

    reserve_list = sync_reserve_list_create(SYNC_MESSAGE_LIST_HASH_SIZE);

    for (;;) {
        prot_flush(sync_out);

        libcyrus_run_delayed();

        /* Parse command name */
        if ((c = getword(sync_in, &cmd)) == EOF)
            break;

        if (!cmd.s[0]) {
            prot_printf(sync_out, "BAD Null command\r\n");
            eatline(sync_in, c);
            continue;
        }

        if (Uislower(cmd.s[0]))
            cmd.s[0] = toupper((unsigned char) cmd.s[0]);
        for (p = &cmd.s[1]; *p; p++) {
            if (Uisupper(*p)) *p = tolower((unsigned char) *p);
        }

        /* Must be an admin */
        if (sync_userid && !sync_userisadmin) goto noperm;

        switch (cmd.s[0]) {
        case 'A':
            if (!strcmp(cmd.s, "Authenticate")) {
                int haveinitresp = 0;
                if (c != ' ') goto missingargs;
                c = getword(sync_in, &arg1);
                if (!imparse_isatom(arg1.s)) {
                    prot_printf(sync_out, "BAD Invalid mechanism\r\n");
                    eatline(sync_in, c);
                    continue;
                }
                if (c == ' ') {
                    haveinitresp = 1;
                    c = getword(sync_in, &arg2);
                    if (c == EOF) goto missingargs;
                }
                if (c == '\r') c = prot_getc(sync_in);
                if (c != '\n') goto extraargs;

                if (sync_userid) {
                    prot_printf(sync_out, "BAD Already authenticated\r\n");
                    continue;
                }
                cmd_authenticate(arg1.s, haveinitresp ? arg2.s : NULL);
                continue;
            }
            if (!sync_userid) goto nologin;
            if (!strcmp(cmd.s, "Apply")) {
                kl = sync_parseline(sync_in, sync_archive_enabled);
                if (kl) {
                    cmd_apply(kl, reserve_list);
                    dlist_free(&kl);
                }
                else {
                    xsyslog(LOG_ERR, "IOERROR: received bad command",
                                     "command=<%s>", cmd.s);
                    prot_printf(sync_out, "BAD IMAP_PROTOCOL_ERROR Failed to parse APPLY line\r\n");
                }
                continue;
            }
            break;

        case 'C':
            if (!strcmp(cmd.s, "Compress")) {
                if (c != ' ') goto missingargs;
                c = getword(sync_in, &arg1);
                if (c == '\r') c = prot_getc(sync_in);
                if (c != '\n') goto extraargs;
                cmd_compress(arg1.s);
                continue;
            }
            break;

        case 'G':
            if (!sync_userid) goto nologin;
            if (!strcmp(cmd.s, "Get")) {
                kl = sync_parseline(sync_in, sync_archive_enabled);
                if (kl) {
                    cmd_get(kl);
                    dlist_free(&kl);
                }
                else {
                    xsyslog(LOG_ERR, "IOERROR: received bad command",
                                     "command=<%s>", cmd.s);
                    prot_printf(sync_out, "BAD IMAP_PROTOCOL_ERROR Failed to parse GET line\r\n");
                }
                continue;
            }
            break;

        case 'E':
            if (!strcmp(cmd.s, "Exit")) {
                if (c == '\r') c = prot_getc(sync_in);
                if (c != '\n') goto extraargs;
                prot_printf(sync_out, "OK Finished\r\n");
                prot_flush(sync_out);
                goto exit;
            }
            break;

        case 'N':
            if (!strcmp(cmd.s, "Noop")) {
                if (c == '\r') c = prot_getc(sync_in);
                if (c != '\n') goto extraargs;
                prot_printf(sync_out, "OK Noop completed\r\n");
                continue;
            }
            break;

        case 'R':
            if (!strcmp(cmd.s, "Restart")) {
                if (c == '\r') c = prot_getc(sync_in);
                if (c != '\n') goto extraargs;
                /* just clear the GUID cache */
                cmd_restart(&reserve_list, 1);
                prot_printf(sync_out, "OK Restarting\r\n");
                continue;
            }
            if (!sync_userid) goto nologin;
            if (!strcmp(cmd.s, "Restore")) {
                kl = sync_parseline(sync_in, sync_archive_enabled);
                if (kl) {
                    cmd_restore(kl, reserve_list);
                    dlist_free(&kl);
                }
                else {
                    xsyslog(LOG_ERR, "IOERROR: received bad command",
                                     "command=<%s>", cmd.s);
                    prot_printf(sync_out, "BAD IMAP_PROTOCOL_ERROR Failed to parse RESTORE line\r\n");
                }
                continue;
            }
            break;

        case 'S':
            if (!strcmp(cmd.s, "Starttls") && tls_enabled()) {
                if (c == '\r') c = prot_getc(sync_in);
                if (c != '\n') goto extraargs;

                /* XXX  discard any input pipelined after STARTTLS */
                prot_flush(sync_in);

                /* if we've already done SASL fail */
                if (sync_userid != NULL) {
                    prot_printf(sync_out,
                                "BAD Can't Starttls after authentication\r\n");
                    continue;
                }
                /* check if already did a successful tls */
                if (sync_starttls_done == 1) {
                    prot_printf(sync_out,
                                "BAD Already did a successful Starttls\r\n");
                    continue;
                }
                cmd_starttls();
                continue;
            }
            break;

        }

        xsyslog(LOG_ERR, "IOERROR: received bad command",
                         "command=<%s>", cmd.s);
        prot_printf(sync_out, "BAD IMAP_PROTOCOL_ERROR Unrecognized command\r\n");
        eatline(sync_in, c);
        continue;

    nologin:
        prot_printf(sync_out, "NO Please authenticate first\r\n");
        eatline(sync_in, c);
        continue;

    noperm:
        prot_printf(sync_out, "NO %s\r\n",
                    error_message(IMAP_PERMISSION_DENIED));
        eatline(sync_in, c);
        continue;

    missingargs:
        prot_printf(sync_out, "BAD Missing required argument to %s\r\n", cmd.s);
        eatline(sync_in, c);
        continue;

    extraargs:
        prot_printf(sync_out, "BAD Unexpected extra arguments to %s\r\n", cmd.s);
        eatline(sync_in, c);
        continue;
    }

 exit:
    cmd_restart(&reserve_list, 0);
}

static void cmd_authenticate(char *mech, char *resp)
{
    int r, sasl_result;
    sasl_ssf_t ssf;
    const char *ssfmsg = NULL;
    const void *val;
    int failedloginpause;

    if (sync_userid) {
        prot_printf(sync_out, "BAD Already authenticated\r\n");
        return;
    }

    r = saslserver(sync_saslconn, mech, resp, "", "+ ", "",
                   sync_in, sync_out, &sasl_result, NULL);

    if (r) {
        const char *errorstring = NULL;
        const char *userid = "-notset-";

        switch (r) {
        case IMAP_SASL_CANCEL:
            prot_printf(sync_out,
                        "BAD Client canceled authentication\r\n");
            break;
        case IMAP_SASL_PROTERR:
            errorstring = prot_error(sync_in);

            prot_printf(sync_out,
                        "NO Error reading client response: %s\r\n",
                        errorstring ? errorstring : "");
            break;
        default:
            /* failed authentication */
            errorstring = sasl_errstring(sasl_result, NULL, NULL);

            if (r != SASL_NOUSER)
                sasl_getprop(sync_saslconn, SASL_USERNAME, (const void **) &userid);

            syslog(LOG_NOTICE, "badlogin: %s %s (%s) [%s]",
                   sync_clienthost, mech, userid, sasl_errdetail(sync_saslconn));

            failedloginpause = config_getduration(IMAPOPT_FAILEDLOGINPAUSE, 's');
            if (failedloginpause != 0) {
                sleep(failedloginpause);
            }

            if (errorstring) {
                prot_printf(sync_out, "NO %s\r\n", errorstring);
            } else {
                prot_printf(sync_out, "NO Error authenticating\r\n");
            }
        }

        reset_saslconn(&sync_saslconn);
        return;
    }

    /* successful authentication */

    /* get the userid from SASL --- already canonicalized from
     * mysasl_proxy_policy()
     */
    sasl_result = sasl_getprop(sync_saslconn, SASL_USERNAME, &val);
    if (sasl_result != SASL_OK) {
        prot_printf(sync_out, "NO weird SASL error %d SASL_USERNAME\r\n",
                    sasl_result);
        syslog(LOG_ERR, "weird SASL error %d getting SASL_USERNAME",
               sasl_result);
        reset_saslconn(&sync_saslconn);
        return;
    }

    sync_userid = xstrdup((const char *) val);
    proc_register(config_ident, sync_clienthost, sync_userid, NULL, NULL);

    syslog(LOG_NOTICE, "login: %s %s %s%s %s", sync_clienthost, sync_userid,
           mech, sync_starttls_done ? "+TLS" : "", "User logged in");

    sasl_getprop(sync_saslconn, SASL_SSF, &val);
    ssf = *((sasl_ssf_t *) val);

    /* really, we should be doing a sasl_getprop on SASL_SSF_EXTERNAL,
       but the current libsasl doesn't allow that. */
    if (sync_starttls_done) {
        switch(ssf) {
        case 0: ssfmsg = "tls protection"; break;
        case 1: ssfmsg = "tls plus integrity protection"; break;
        default: ssfmsg = "tls plus privacy protection"; break;
        }
    } else {
        switch(ssf) {
        case 0: ssfmsg = "no protection"; break;
        case 1: ssfmsg = "integrity protection"; break;
        default: ssfmsg = "privacy protection"; break;
        }
    }

    prot_printf(sync_out, "OK Success (%s)\r\n", ssfmsg);

    prot_setsasl(sync_in,  sync_saslconn);
    prot_setsasl(sync_out, sync_saslconn);

    /* Create telemetry log */
    sync_logfd = telemetry_log(sync_userid, sync_in, sync_out, 0);
}

#ifdef HAVE_SSL
static void cmd_starttls(void)
{
    int result;

    if (sync_starttls_done == 1) {
        prot_printf(sync_out, "NO %s\r\n",
                    "Already successfully executed STARTTLS");
        return;
    }

    result=tls_init_serverengine("csync",
                                 5,        /* depth to verify */
                                 1,        /* can client auth? */
                                 NULL);

    if (result == -1) {
        syslog(LOG_ERR, "error initializing TLS");
        prot_printf(sync_out, "NO %s\r\n", "Error initializing TLS");
        return;
    }

    prot_printf(sync_out, "OK %s\r\n", "Begin TLS negotiation now");
    /* must flush our buffers before starting tls */
    prot_flush(sync_out);

    result=tls_start_servertls(0, /* read */
                               1, /* write */
                               180, /* 3 minutes */
                               &saslprops,
                               &tls_conn);

    /* if error */
    if (result==-1) {
        prot_printf(sync_out, "NO Starttls failed\r\n");
        syslog(LOG_NOTICE, "STARTTLS failed: %s", sync_clienthost);
        return;
    }

    /* tell SASL about the negotiated layer */
    result = saslprops_set_tls(&saslprops, sync_saslconn);
    if (result != SASL_OK) {
        fatal("saslprops_set_tls() failed: cmd_starttls()", EX_TEMPFAIL);
    }

    /* tell the prot layer about our new layers */
    prot_settls(sync_in, tls_conn);
    prot_settls(sync_out, tls_conn);

    sync_starttls_done = 1;

    dobanner();
}
#else
static void cmd_starttls(void)
{
    fatal("cmd_starttls() called, but no OpenSSL", EX_SOFTWARE);
}
#endif /* HAVE_SSL */

#ifdef HAVE_ZLIB
static void cmd_compress(char *alg)
{
    if (sync_compress_done) {
        prot_printf(sync_out, "NO Compression already active: %s\r\n", alg);
        return;
    }
    if (strcasecmp(alg, "DEFLATE")) {
        prot_printf(sync_out, "NO Unknown compression algorithm: %s\r\n", alg);
        return;
    }
    if (ZLIB_VERSION[0] != zlibVersion()[0]) {
        prot_printf(sync_out, "NO Error initializing %s "
                    "(incompatible zlib version)\r\n", alg);
        return;
    }
    prot_printf(sync_out, "OK %s active\r\n", alg);
    prot_flush(sync_out);
    prot_setcompress(sync_in);
    prot_setcompress(sync_out);
    sync_compress_done = 1;
}
#else
static void cmd_compress(char *alg __attribute__((unused)))
{
    prot_printf(sync_out, "NO ZLIB not available\r\n");
}
#endif

/* ====================================================================== */

/* partition_list is simple linked list of names used by cmd_restart */

struct partition_list {
    struct partition_list *next;
    char *name;
};

static struct partition_list *
partition_list_add(char *name, struct partition_list *pl)
{
    struct partition_list *p;

    /* Is name already on list? */
    for (p=pl; p; p = p->next) {
        if (!strcmp(p->name, name))
            return(pl);
    }

    /* Add entry to start of list and return new list */
    p = xzmalloc(sizeof(struct partition_list));
    p->next = pl;
    p->name = xstrdup(name);

    return(p);
}

static void
partition_list_free(struct partition_list *current)
{
    while (current) {
        struct partition_list *next = current->next;

        free(current->name);
        free(current);

        current = next;
    }
}

static void cmd_restart(struct sync_reserve_list **reserve_listp, int re_alloc)
{
    struct sync_reserve *res;
    struct sync_reserve_list *l = *reserve_listp;
    struct sync_msgid *msg;
    int hash_size = l->hash_size;
    struct partition_list *p, *pl = NULL;

    for (res = l->head; res; res = res->next) {
        for (msg = res->list->head; msg; msg = msg->next) {
            if (!msg->fname) continue;
            pl = partition_list_add(res->part, pl);
            unlink(msg->fname);
        }
    }
    sync_reserve_list_free(reserve_listp);

    /* Remove all <partition>/sync./<pid> directories referred to above */
    for (p=pl; p ; p = p->next) {
        static char buf[MAX_MAILBOX_PATH];

        snprintf(buf, MAX_MAILBOX_PATH, "%s/sync./%lu",
                 config_partitiondir(p->name), (unsigned long)getpid());
        rmdir(buf);

        if (config_getswitch(IMAPOPT_ARCHIVE_ENABLED)) {
            /* and the archive partition too */
            snprintf(buf, MAX_MAILBOX_PATH, "%s/sync./%lu",
                    config_archivepartitiondir(p->name), (unsigned long)getpid());
            rmdir(buf);
        }
    }
    partition_list_free(pl);

    if (re_alloc)
        *reserve_listp = sync_reserve_list_create(hash_size);
    else
        *reserve_listp = NULL;
}

/******************************************************************************/

static void cmd_apply(struct dlist *kin, struct sync_reserve_list *reserve_list)
{
    struct sync_state sync_state = {
        sync_userid,
        sync_userisadmin,
        sync_authstate,
        &sync_namespace,
        sync_out,
        0 /* flags */
    };

    if (sync_sieve_mailbox_enabled) {
        sync_state.flags |= SYNC_FLAG_SIEVE_MAILBOX;
    }
    if (sync_archive_enabled) {
        sync_state.flags |= SYNC_FLAG_ARCHIVE;
    }

    const char *resp = sync_apply(kin, reserve_list, &sync_state);

    if (sync_state.flags & SYNC_FLAG_SIEVE_MAILBOX) {
        sync_sieve_mailbox_enabled = 1;
    }
    if (sync_state.flags & SYNC_FLAG_ARCHIVE) {
        sync_archive_enabled = 1;
    }

    sync_checkpoint(sync_in);
    prot_printf(sync_out, "%s\r\n", resp);
}

static void cmd_get(struct dlist *kin)
{
    struct sync_state sync_state = {
        sync_userid,
        sync_userisadmin,
        sync_authstate,
        &sync_namespace,
        sync_out,
        0 /* flags */
    };

    if (sync_sieve_mailbox_enabled) {
        sync_state.flags |= SYNC_FLAG_SIEVE_MAILBOX;
    }
    if (sync_archive_enabled) {
        sync_state.flags |= SYNC_FLAG_ARCHIVE;
    }

    const char *resp = sync_get(kin, &sync_state);
    prot_printf(sync_out, "%s\r\n", resp);
}

static void cmd_restore(struct dlist *kin, struct sync_reserve_list *reserve_list)
{
    struct sync_state sync_state = {
        sync_userid,
        sync_userisadmin,
        sync_authstate,
        &sync_namespace,
        sync_out,
        0 /* flags */
    };

    if (sync_sieve_mailbox_enabled) {
        sync_state.flags |= SYNC_FLAG_SIEVE_MAILBOX;
    }
    if (sync_archive_enabled) {
        sync_state.flags |= SYNC_FLAG_ARCHIVE;
    }

    const char *resp = sync_restore(kin, reserve_list, &sync_state);
    sync_checkpoint(sync_in);
    prot_printf(sync_out, "%s\r\n", resp);
}