summaryrefslogtreecommitdiff
path: root/common/smtppass.c
blob: be9c4ceac0f70ce496be4cb27e999a189d8f4c38 (plain)
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
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
/*
 * Copyright (c) 2004, Nate Nielsen
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above
 *       copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * 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.
 *     * The names of contributors to this software may not be
 *       used to endorse or promote products derived from this
 *       software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 *
 * CONTRIBUTORS
 *  Nate Nielsen <nielsen@memberwebs.com>
 *  Yamamoto Takao <takao@oakat.org>
 */

#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <sys/stat.h>

#include <ctype.h>
#include <paths.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <syslog.h>
#include <signal.h>
#include <errno.h>
#include <err.h>
#include <pthread.h>

#include "usuals.h"
#include "compat.h"
#include "sock_any.h"
#include "clamsmtpd.h"
#include "util.h"

/* -----------------------------------------------------------------------
 *  STRUCTURES
 */

typedef struct clamsmtp_thread
{
    pthread_t tid;      /* Written to by the main thread */
    int fd;             /* The file descriptor or -1 */
}
clamsmtp_thread_t;

/* -----------------------------------------------------------------------
 *  STRINGS
 */

#define KL(s)               ((sizeof(s) - 1) / sizeof(char))

#define CRLF                "\r\n"

#define SMTP_TOOLONG        "500 Line too long" CRLF
#define SMTP_STARTBUSY      "554 Server Busy" CRLF
#define SMTP_STARTFAILED    "554 Local Error" CRLF
#define SMTP_DATAVIRUS      "550 Virus Detected; Content Rejected" CRLF
#define SMTP_DATAINTERMED   "354 Start mail input; end with <CRLF>.<CRLF>" CRLF
#define SMTP_FAILED         "451 Local Error" CRLF
#define SMTP_NOTSUPP        "502 Command not implemented" CRLF
#define SMTP_DATAVIRUSOK    "250 Virus Detected; Discarded Email" CRLF
#define SMTP_OK             "250 Ok" CRLF

#define SMTP_DATA           "DATA" CRLF
#define SMTP_BANNER         "220 clamsmtp" CRLF
#define SMTP_HELO_RSP       "250 clamsmtp" CRLF
#define SMTP_EHLO_RSP       "250-clamsmtp" CRLF
#define SMTP_DELIMS         "\r\n\t :"
#define SMTP_MULTI_DELIMS   " -"

#define ESMTP_PIPELINE      "PIPELINING"
#define ESMTP_TLS           "STARTTLS"
#define ESMTP_CHUNK         "CHUNKING"
#define ESMTP_BINARY        "BINARYMIME"
#define ESMTP_CHECK         "CHECKPOINT"

#define HELO_CMD            "HELO"
#define EHLO_CMD            "EHLO"
#define FROM_CMD            "MAIL FROM"
#define TO_CMD              "RCPT TO"
#define DATA_CMD            "DATA"
#define RSET_CMD            "RSET"
#define STARTTLS_CMD        "STARTTLS"
#define BDAT_CMD            "BDAT"

#define DATA_END_SIG        "." CRLF

#define DATA_RSP            "354"
#define OK_RSP              "250"
#define START_RSP           "220"

#define CLAM_OK             "OK"
#define CLAM_ERROR          "ERROR"
#define CLAM_FOUND          "FOUND"

#define CONNECT_RSP         "PONG"
#define CLAM_SCAN           "SCAN "

#define CLAM_CONNECT        "SESSION\nPING\n"
#define CLAM_DISCONNECT     "END\n"

/* -----------------------------------------------------------------------
 *  DEFAULT SETTINGS
 */

#define DEFAULT_SOCKET  "10025"
#define DEFAULT_PORT    10025
#define DEFAULT_CLAMAV  "/var/run/clamav/clamd"
#define DEFAULT_MAXTHREADS  64
#define DEFAULT_TIMEOUT	180
#define DEFAULT_HEADER  "X-AV-Checked: ClamAV using ClamSMTP"

/* -----------------------------------------------------------------------
 *  GLOBALS
 */

int g_daemonized = 0;                     /* Currently running as a daemon */
int g_debuglevel = LOG_ERR;               /* what gets logged to console */
int g_maxthreads = DEFAULT_MAXTHREADS;    /* The maximum number of threads */
struct timeval g_timeout = { DEFAULT_TIMEOUT, 0 };

struct sockaddr_any g_outaddr;              /* The outgoing address */
const char* g_outname = NULL;
struct sockaddr_any g_clamaddr;             /* Address for connecting to clamd */
const char* g_clamname = DEFAULT_CLAMAV;

char* g_header = DEFAULT_HEADER;            /* The header to add to email */
const char* g_directory = _PATH_TMP;        /* The directory for temp files */
unsigned int g_unique_id = 0x00100000;      /* For connection ids */
int g_bounce = 0;                           /* Send back a reject line */
int g_quarantine = 0;                       /* Leave virus files in temp dir */
int g_debugfiles = 0;                       /* Leave all files in temp dir */

/* For main loop and signal handlers */
int g_quit = 0;

/* The main mutex and condition variables */
pthread_mutex_t g_mutex;
pthread_mutexattr_t g_mutexattr;


/* -----------------------------------------------------------------------
 *  FORWARD DECLARATIONS
 */

static void usage();
static void on_quit(int signal);
static void pid_file(const char* pid, int write);
static void connection_loop(int sock);
static void* thread_main(void* arg);
static int smtp_passthru(clamsmtp_context_t* ctx);
static int connect_clam(clamsmtp_context_t* ctx);
static int disconnect_clam(clamsmtp_context_t* ctx);
static void add_to_logline(char* logline, char* prefix, char* line);
static int avcheck_data(clamsmtp_context_t* ctx, char* logline);
static int quarantine_virus(clamsmtp_context_t* ctx, char* tempname);
static int complete_data_transfer(clamsmtp_context_t* ctx, const char* tempname);
static int transfer_to_file(clamsmtp_context_t* ctx, char* tempname);
static int transfer_from_file(clamsmtp_context_t* ctx, const char* filename);
static int clam_scan_file(clamsmtp_context_t* ctx, const char* tempname, char* logline);
static int read_server_response(clamsmtp_context_t* ctx);
static void read_junk(clamsmtp_context_t* ctx, int fd);


/* ----------------------------------------------------------------------------------
 *  STARTUP ETC...
 */

int main(int argc, char* argv[])
{
    const char* listensock = DEFAULT_SOCKET;
    struct sockaddr_any addr;
    char* pidfile = NULL;
    int daemonize = 1;
    int sock;
    int true = 1;
    int ch = 0;
    char* t;

    /* Parse the arguments nicely */
    while((ch = getopt(argc, argv, "bc:d:D:h:l:m:p:qt:vX")) != -1)
    {
        switch(ch)
        {
        /* Actively reject messages */
        case 'b':
            g_bounce = 1;
            break;

        /* Change the CLAM socket */
        case 'c':
            g_clamname = optarg;
            break;

		/*  Don't daemonize  */
        case 'd':
            daemonize = 0;
            g_debuglevel = strtol(optarg, &t, 10);
            if(*t || g_debuglevel > 4)
                errx(1, "invalid debug log level");
            g_debuglevel += LOG_ERR;
            break;

        /* The directory for the files */
        case 'D':
            g_directory = optarg;
            break;

        /* The header to add */
        case 'h':
            if(strlen(optarg) == 0)
                g_header = NULL;
            else
            {
                g_header = optarg;

                /* Trim off any ending newline chars */
                t = g_header + strlen(g_header);
                while(t > g_header && (*(t - 1) == '\r' || *(t - 1) == '\n'))
                    *(--t) = 0;
            }
            break;

        /* Change our listening port */
        case 'l':
            listensock = optarg;
            break;

        /* The maximum number of threads */
        case 'm':
            g_maxthreads = strtol(optarg, &t, 10);
            if(*t || g_maxthreads <= 1 || g_maxthreads >= 1024)
                  errx(1, "invalid max threads (must be between 1 and 1024");
            break;

        /* Write out a pid file */
        case 'p':
            pidfile = optarg;
            break;

        /* The timeout */
		case 't':
			g_timeout.tv_sec = strtol(optarg, &t, 10);
			if(*t || g_timeout.tv_sec <= 0)
				errx(1, "invalid timeout: %s", optarg);
			break;

        /* Leave virus files in directory */
        case 'q':
            g_quarantine = 1;
            break;

        /* Print version number */
        case 'v':
            printf("clamsmtpd (version %s)\n", VERSION);
            exit(0);
            break;

        /* Leave all files in the tmp directory */
        case 'X':
            g_debugfiles = 1;
            break;

        /* Usage information */
        case '?':
        default:
            usage();
            break;
		}
    }

	argc -= optind;
	argv += optind;

    if(argc != 1)
        usage();

    g_outname = argv[0];

    messagex(NULL, LOG_DEBUG, "starting up...");

    /* Parse all the addresses */
    if(sock_any_pton(listensock, &addr, SANY_OPT_DEFANY | SANY_OPT_DEFPORT(DEFAULT_PORT)) == -1)
        errx(1, "invalid listen socket name or ip: %s", listensock);
    if(sock_any_pton(g_outname, &g_outaddr, SANY_OPT_DEFPORT(25)) == -1)
        errx(1, "invalid connect socket name or ip: %s", g_outname);
    if(sock_any_pton(g_clamname, &g_clamaddr, SANY_OPT_DEFLOCAL) == -1)
        errx(1, "invalid clam socket name: %s", g_clamname);

    if(daemonize)
    {
        /* Fork a daemon nicely here */
        if(daemon(0, 0) == -1)
        {
            message(NULL, LOG_ERR, "couldn't run as daemon");
            exit(1);
        }

        messagex(NULL, LOG_DEBUG, "running as a daemon");
        g_daemonized = 1;

        /* Open the system log */
        openlog("clamsmtpd", 0, LOG_MAIL);
    }

    /* Create the socket */
    sock = socket(SANY_TYPE(addr), SOCK_STREAM, 0);
    if(sock < 0)
      err(1, "couldn't open socket");

    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&true, sizeof(true));

    /* Unlink the socket file if it exists */
    if(SANY_TYPE(addr) == AF_UNIX)
        unlink(listensock);

    if(bind(sock, &SANY_ADDR(addr), SANY_LEN(addr)) != 0)
      err(1, "couldn't bind to address: %s", listensock);

    /* Let 5 connections queue up */
    if(listen(sock, 5) != 0)
      err(1, "couldn't listen on socket");

    messagex(NULL, LOG_DEBUG, "created socket: %s", listensock);

    /* Handle some signals */
    signal(SIGPIPE, SIG_IGN);
    signal(SIGHUP, SIG_IGN);
    signal(SIGINT,  on_quit);
    signal(SIGTERM, on_quit);

    siginterrupt(SIGINT, 1);
    siginterrupt(SIGTERM, 1);

    if(pidfile)
        pid_file(pidfile, 1);

    messagex(NULL, LOG_DEBUG, "accepting connections");

    connection_loop(sock);

    if(pidfile)
        pid_file(pidfile, 0);

    messagex(NULL, LOG_DEBUG, "stopped");

    return 0;
}

static void on_quit(int signal)
{
    g_quit = 1;

    /* fprintf(stderr, "clamsmtpd: got signal to quit\n"); */
}

static void usage()
{
    fprintf(stderr, "usage: clamsmtpd [-bq] [-c clamaddr] [-d debuglevel] [-D tmpdir] [-h header] "
            "[-l listenaddr] [-m maxconn] [-p pidfile] [-t timeout] serveraddr\n");
    fprintf(stderr, "       clamsmtpd -v\n");
    exit(2);
}

static void pid_file(const char* pidfile, int write)
{
    if(write)
    {
        FILE* f = fopen(pidfile, "w");
        if(f == NULL)
        {
            message(NULL, LOG_ERR, "couldn't open pid file: %s", pidfile);
        }
        else
        {
            fprintf(f, "%d\n", (int)getpid());

            if(ferror(f))
                message(NULL, LOG_ERR, "couldn't write to pid file: %s", pidfile);

            fclose(f);
        }

        messagex(NULL, LOG_DEBUG, "wrote pid file: %s", pidfile);
    }

    else
    {
        unlink(pidfile);
        messagex(NULL, LOG_DEBUG, "removed pid file: %s", pidfile);
    }
}


/* ----------------------------------------------------------------------------------
 *  CONNECTION HANDLING
 */

static void connection_loop(int sock)
{
    clamsmtp_thread_t* threads = NULL;
    int fd, i, x, r;

    /* Create the thread buffers */
    threads = (clamsmtp_thread_t*)calloc(g_maxthreads, sizeof(clamsmtp_thread_t));
    if(!threads)
        errx(1, "out of memory");

    /* Create the main mutex and condition variable */
    if(pthread_mutexattr_init(&g_mutexattr) != 0 ||
       pthread_mutexattr_settype(&g_mutexattr, MUTEX_TYPE) ||
       pthread_mutex_init(&g_mutex, &g_mutexattr) != 0)
        errx(1, "threading problem. can't create mutex or condition var");

    /* Now loop and accept the connections */
    while(!g_quit)
    {
        fd = accept(sock, NULL, NULL);
        if(fd == -1)
        {
            switch(errno)
            {
            case EINTR:
            case EAGAIN:
                break;

            case ECONNABORTED:
                message(NULL, LOG_ERR, "couldn't accept a connection");
                break;

            default:
                message(NULL, LOG_ERR, "couldn't accept a connection");
                g_quit = 1;
                break;
            };

            if(g_quit)
                break;

            continue;
        }

        /* Set timeouts on client */
        if(setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &g_timeout, sizeof(g_timeout)) < 0 ||
           setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &g_timeout, sizeof(g_timeout)) < 0)
            message(NULL, LOG_WARNING, "couldn't set timeouts on incoming connection");

        /* Look for thread and also clean up others */
        for(i = 0; i < g_maxthreads; i++)
        {
            /* Find a thread to run or clean up old threads */
            if(threads[i].tid != 0)
            {
                plock();
                    x = threads[i].fd;
                punlock();

                if(x == -1)
                {
                    messagex(NULL, LOG_DEBUG, "cleaning up completed thread");
                    pthread_join(threads[i].tid, NULL);
                    threads[i].tid = 0;
                }
#ifdef _DEBUG
                else
                {
                    /* For debugging connection problems: */
                    messagex(NULL, LOG_DEBUG, "active connection thread: %x", (int)threads[i].tid);
                }
#endif
            }

            /* Start a new thread if neccessary */
            if(fd != -1 && threads[i].tid == 0)
            {
                threads[i].fd = fd;
                r = pthread_create(&(threads[i].tid), NULL, thread_main,
                                   (void*)(threads + i));
                if(r != 0)
                {
                    errno = r;
                    message(NULL, LOG_ERR, "couldn't create thread");
                    g_quit = 1;
                    break;
                }

                messagex(NULL, LOG_DEBUG, "created thread for connection");
                fd = -1;
                break;
            }
        }

        /* Check to make sure we have a thread */
        if(fd != -1)
        {
            messagex(NULL, LOG_ERR, "too many connections open (max %d). sent 554 response", g_maxthreads);

            write(fd, SMTP_STARTBUSY, KL(SMTP_STARTBUSY));
            shutdown(fd, SHUT_RDWR);
            close(fd);
            fd = -1;
        }
    }

    messagex(NULL, LOG_DEBUG, "waiting for threads to quit");

    /* Quit all threads here */
    for(i = 0; i < g_maxthreads; i++)
    {
        /* Clean up quit threads */
        if(threads[i].tid != 0)
        {
            if(threads[i].fd != -1)
            {
                plock();
                    fd = threads[i].fd;
                    threads[i].fd = -1;
                punlock();

                shutdown(fd, SHUT_RDWR);
                close(fd);
            }

            pthread_join(threads[i].tid, NULL);
        }
    }

    /* Close the mutex */
    pthread_mutex_destroy(&g_mutex);
    pthread_mutexattr_destroy(&g_mutexattr);
}

static void* thread_main(void* arg)
{
    clamsmtp_thread_t* thread = (clamsmtp_thread_t*)arg;
    struct sockaddr_any addr;
    struct sockaddr_any* outaddr;
    const char* outname;
    char buf[MAXPATHLEN];
    clamsmtp_context_t ctx;
    int processing = 0;
    int ret = 0;

    ASSERT(thread);

    siginterrupt(SIGINT, 1);
    siginterrupt(SIGTERM, 1);

    memset(&ctx, 0, sizeof(ctx));

    clio_init(&(ctx.server), "SERVER");
    clio_init(&(ctx.client), "CLIENT");
    clio_init(&(ctx.clam),   "CLAM  ");

    plock();
        /* Assign a unique id to the connection */
        ctx.id = g_unique_id++;

        /* Get the client socket */
        ctx.client.fd = thread->fd;
    punlock();

    ASSERT(ctx.client.fd != -1);
    messagex(&ctx, LOG_DEBUG, "processing %d on thread %x", ctx.client.fd, (int)pthread_self());

    memset(&addr, 0, sizeof(addr));
    SANY_LEN(addr) = sizeof(addr);

    /* Get the peer name */
    if(getpeername(ctx.client.fd, &SANY_ADDR(addr), &SANY_LEN(addr)) == -1 ||
       sock_any_ntop(&addr, buf, MAXPATHLEN, SANY_OPT_NOPORT) == -1)
        message(&ctx, LOG_WARNING, "couldn't get peer address");
    else
        messagex(&ctx, LOG_INFO, "accepted connection from: %s", buf);


    /* Create the server connection address */
    outaddr = &g_outaddr;
    outname = g_outname;

    if(SANY_TYPE(*outaddr) == AF_INET &&
       outaddr->s.in.sin_addr.s_addr == 0)
    {
        /* Use the incoming IP as the default */
        in_addr_t in = addr.s.in.sin_addr.s_addr;
        memcpy(&addr, &g_outaddr, sizeof(addr));
        addr.s.in.sin_addr.s_addr = in;

        outaddr = &addr;

        if(sock_any_ntop(outaddr, buf, MAXPATHLEN, 0) != -1)
            outname = buf;
    }


    /* Connect to the server */
    if(clio_connect(&ctx, &(ctx.server), outaddr, outname) == -1)
        RETURN(-1);

    /* ... and to the AV daemon */
    if(connect_clam(&ctx) == -1)
        RETURN(-1);


    /* call the processor */
    processing = 1;
    ret = smtp_passthru(&ctx);

cleanup:

    disconnect_clam(&ctx);

    /* Let the client know about fatal errors */
    if(!processing && ret == -1 && clio_valid(&(ctx.client)))
       clio_write_data(&ctx, &(ctx.client), SMTP_STARTFAILED);

    clio_disconnect(&ctx, &(ctx.client));
    clio_disconnect(&ctx, &(ctx.server));

    /* mark this as done */
    plock();
        thread->fd = -1;
    punlock();

    return (void*)(ret == 0 ? 0 : 1);
}


/* ----------------------------------------------------------------------------------
 *  SMTP HANDLING
 */

static int smtp_passthru(clamsmtp_context_t* ctx)
{
    clio_t* io = NULL;
    char logline[LINE_LENGTH];
    int r, ret = 0;
    int neterror = 0;

    int first_rsp = 1;      /* The first 220 response from server to be filtered */
    int filter_ehlo = 0;    /* Filtering parts of an EHLO extensions response */
    int filter_host = 0;    /* Next response is 250 hostname, which we change */

    ASSERT(clio_valid(&(ctx->clam)) &&
           clio_valid(&(ctx->clam)));
    logline[0] = 0;

    for(;;)
    {
        if(clio_select(ctx, &io) == -1)
        {
            neterror = 1;
            RETURN(-1);
		}

        /* Client has data available, read a line and process */
        if(io == &(ctx->client))
        {
            if(clio_read_line(ctx, &(ctx->client), CLIO_DISCARD) == -1)
                RETURN(-1);

            /* Client disconnected, we're done */
            if(ctx->linelen == 0)
                RETURN(0);

            /* We don't let clients send really long lines */
            if(LINE_TOO_LONG(ctx))
            {
                if(clio_write_data(ctx, &(ctx->client), SMTP_TOOLONG) == -1)
                    RETURN(-1);

                continue;
            }

            /* Only valid after EHLO or HELO commands */
            filter_ehlo = 0;
            filter_host = 0;

            /* Handle the DATA section via our AV checker */
            if(is_first_word(ctx->line, DATA_CMD, KL(DATA_CMD)))
            {
                /* Send back the intermediate response to the client */
                if(clio_write_data(ctx, &(ctx->client), SMTP_DATAINTERMED) == -1)
                    RETURN(-1);

                /*
                 * Now go into avcheck mode. This also handles the eventual
                 * sending of the data to the server, making the av check
                 * transparent
                 */
                if(avcheck_data(ctx, logline) == -1)
                    RETURN(-1);

                /* Print the log out for this email */
                messagex(ctx, LOG_INFO, "%s", logline);

                /* Reset log line */
                logline[0] = 0;

                /* Command handled */
                continue;
            }

            /*
             * We filter out features that we can't support in
             * the EHLO response (ESMTP). See below
             */
            else if(is_first_word(ctx->line, EHLO_CMD, KL(EHLO_CMD)))
            {
                messagex(ctx, LOG_DEBUG, "filtering EHLO response");
                filter_ehlo = 1;
                filter_host = 1;

                /* A new message */
                logline[0] = 0;
            }

            /*
             * We need our response to HELO to be modified in order
             * to prevent complaints about mail loops
             */
            else if(is_first_word(ctx->line, HELO_CMD, KL(HELO_CMD)))
            {
                filter_host = 1;

                /* A new message line */
                logline[0] = 0;
            }

            /*
             * We don't like these commands. Filter them out. We should have
             * filtered out their service extensions earlier in the EHLO response.
             * This is just for errant clients.
             */
            else if(is_first_word(ctx->line, STARTTLS_CMD, KL(STARTTLS_CMD)) ||
                    is_first_word(ctx->line, BDAT_CMD, KL(BDAT_CMD)))
            {
                messagex(ctx, LOG_DEBUG, "ESMTP feature not supported");

                if(clio_write_data(ctx, &(ctx->client), SMTP_NOTSUPP) == -1)
                    RETURN(-1);

                /* Command handled */
                continue;
            }

            /* Append recipients to log line */
            else if((r = check_first_word(ctx->line, FROM_CMD, KL(FROM_CMD), SMTP_DELIMS)) > 0)
                add_to_logline(logline, "from=", ctx->line + r);

            /* Append sender to log line */
            else if((r = check_first_word(ctx->line, TO_CMD, KL(TO_CMD), SMTP_DELIMS)) > 0)
                add_to_logline(logline, "to=", ctx->line + r);

            /* Reset log line */
            else if(is_first_word(ctx->line, RSET_CMD, KL(RSET_CMD)))
                logline[0] = 0;

            /* All other commands just get passed through to server */
            if(clio_write_data(ctx, &(ctx->server), ctx->line) == -1)
                RETURN(-1);

            continue;
        }

        /* Server has data available, read a line and forward */
        if(io == &(ctx->server))
        {
            if(clio_read_line(ctx, &(ctx->server), CLIO_DISCARD) == -1)
                RETURN(-1);

            if(ctx->linelen == 0)
                RETURN(0);

            if(LINE_TOO_LONG(ctx))
                messagex(ctx, LOG_WARNING, "SMTP response line too long. discarded extra");

            /*
             * We intercept the first response we get from the server.
             * This allows us to change header so that it doesn't look
             * to the client server that we're in a wierd loop.
             *
             * In different situations using the local hostname or
             * 'localhost' don't work because the receiving mail server
             * expects one of those to be its own name. We use 'clamsmtp'
             * instead. No properly configured server would have this
             * as their domain name, and RFC 2821 allows us to use
             * an arbitrary but identifying string.
             */
            if(first_rsp)
            {
                first_rsp = 0;

                if(is_first_word(ctx->line, START_RSP, KL(START_RSP)))
                {
                    messagex(ctx, LOG_DEBUG, "intercepting initial response");

                    if(clio_write_data(ctx, &(ctx->client), SMTP_BANNER) == -1)
                        RETURN(-1);

                    /* Command handled */
                    continue;
                }
            }

            /*
             * Certain mail servers (Postfix 1.x in particular) do a loop check
             * on the 250 response after a EHLO or HELO. This is where we
             * filter that to prevent loopback errors.
             */
            if(filter_host)
            {
                filter_host = 0;

                /* Check for a simple '250 xxxx' */
                if(is_first_word(ctx->line, OK_RSP, KL(OK_RSP)))
                {
                    messagex(ctx, LOG_DEBUG, "intercepting host response");

                    if(clio_write_data(ctx, &(ctx->client), SMTP_HELO_RSP) == -1)
                        RETURN(-1);

                    continue;
                }

                /* Check for the continued response '250-xxxx' */
                if(check_first_word(ctx->line, OK_RSP, KL(OK_RSP), SMTP_MULTI_DELIMS) > 0)
                {
                    messagex(ctx, LOG_DEBUG, "intercepting host response");

                    if(clio_write_data(ctx, &(ctx->client), SMTP_EHLO_RSP) == -1)
                        RETURN(-1);

                    continue;
                }
            }

            /*
             * Filter out any EHLO responses that we can't or don't want
             * to support. For example pipelining or TLS.
             */
            if(filter_ehlo)
            {
                if((r = check_first_word(ctx->line, OK_RSP, KL(OK_RSP), SMTP_MULTI_DELIMS)) > 0)
                {
                    char* p = ctx->line + r;
                    if(is_first_word(p, ESMTP_PIPELINE, KL(ESMTP_PIPELINE)) ||
                       is_first_word(p, ESMTP_TLS, KL(ESMTP_TLS)) ||
                       is_first_word(p, ESMTP_CHUNK, KL(ESMTP_CHUNK)) ||
                       is_first_word(p, ESMTP_BINARY, KL(ESMTP_BINARY)) ||
                       is_first_word(p, ESMTP_CHECK, KL(ESMTP_CHECK)))
                    {
                        messagex(ctx, LOG_DEBUG, "filtered ESMTP feature: %s", trim_space(p));
                        continue;
                    }
                }
            }

            if(clio_write_data(ctx, &(ctx->client), ctx->line) == -1)
                RETURN(-1);

            continue;
        }
    }

cleanup:

    if(!neterror && ret == -1 && clio_valid(&(ctx->client)))
       clio_write_data(ctx, &(ctx->client), SMTP_FAILED);

    return ret;
}

static void add_to_logline(char* logline, char* prefix, char* line)
{
    int l = strlen(logline);
    char* t = logline;

    /* Simple optimization */
    logline += l;
    l = LINE_LENGTH - l;

    ASSERT(l >= 0);

    if(t[0] != 0)
        strlcat(logline, ", ", l);

    strlcat(logline, prefix, l);

    /* Skip initial white space */
    line = trim_start(line);

    strlcat(logline, line, l);

    /* Skip later white space */
    trim_end(logline);
}

static int avcheck_data(clamsmtp_context_t* ctx, char* logline)
{
    /*
     * Note that most failures are non fatal in this function.
     * We only return -1 for data connection errors and the like,
     * For most others we actually send a response back to the
     * client letting them know what happened and let the SMTP
     * connection continue.
     */

    char buf[MAXPATHLEN];
    int havefile = 0;
    int r, ret = 0;

    strlcpy(buf, g_directory, MAXPATHLEN);
    strlcat(buf, "/clamsmtpd.XXXXXX", MAXPATHLEN);

    /* transfer_to_file deletes the temp file on failure */
    if((r = transfer_to_file(ctx, buf)) != -1)
    {
        havefile = 1;
        r = clam_scan_file(ctx, buf, logline);
    }

    switch(r)
    {

    /*
     * There was an error tell the client. We haven't notified
     * the server about any of this yet
     */
    case -1:
        if(clio_write_data(ctx, &(ctx->client), SMTP_FAILED))
            RETURN(-1);
        break;

    /*
     * No virus was found. Now we initiate a connection to the server
     * and transfer the file to it.
     */
    case 0:
        if(complete_data_transfer(ctx, buf) == -1)
            RETURN(-1);
        break;

    /*
     * A virus was found, normally we just drop the email. But if
     * requested we can send a simple message back to our client.
     * The server doesn't know data was ever sent, and the client can
     * choose to reset the connection to reuse it if it wants.
     */
    case 1:
        if(clio_write_data(ctx, &(ctx->client),
                           g_bounce ? SMTP_DATAVIRUS : SMTP_DATAVIRUSOK) == -1)
            RETURN(-1);

        /* Any special post operation actions on the virus */
        quarantine_virus(ctx, buf);
        break;

    default:
        ASSERT(0 && "Invalid clam_scan_file return value");
        break;
    };

cleanup:
    if(havefile && !g_debugfiles)
    {
        messagex(ctx, LOG_DEBUG, "deleting temporary file: %s", buf);
        unlink(buf);
    }

    return ret;
}

static int complete_data_transfer(clamsmtp_context_t* ctx, const char* tempname)
{
    ASSERT(ctx);
    ASSERT(tempname);

    /* Ask the server for permission to send data */
    if(clio_write_data(ctx, &(ctx->server), SMTP_DATA) == -1)
        return -1;

    if(read_server_response(ctx) == -1)
        return -1;

    /* If server returns an error then tell the client */
    if(!is_first_word(ctx->line, DATA_RSP, KL(DATA_RSP)))
    {
        if(clio_write_data(ctx, &(ctx->client), ctx->line) == -1)
            return -1;

        messagex(ctx, LOG_DEBUG, "server refused data transfer");

        return 0;
    }

    /* Now pull up the file and send it to the server */
    if(transfer_from_file(ctx, tempname) == -1)
    {
        /* Tell the client it went wrong */
        clio_write_data(ctx, &(ctx->client), SMTP_FAILED);
        return -1;
    }

    /* Okay read the response from the server and echo it to the client */
    if(read_server_response(ctx) == -1)
        return -1;

    if(clio_write_data(ctx, &(ctx->client), ctx->line) == -1)
        return -1;

    return 0;
}

static int read_server_response(clamsmtp_context_t* ctx)
{
    /* Read response line from the server */
    if(clio_read_line(ctx, &(ctx->server), CLIO_DISCARD) == -1)
        return -1;

    if(ctx->linelen == 0)
    {
        messagex(ctx, LOG_ERR, "server disconnected unexpectedly");

        /* Tell the client it went wrong */
        clio_write_data(ctx, &(ctx->client), SMTP_FAILED);
        return 0;
    }

    if(LINE_TOO_LONG(ctx))
        messagex(ctx, LOG_WARNING, "SMTP response line too long. discarded extra");

    return 0;
}


/* ----------------------------------------------------------------------------------
 *  CLAM AV
 */

static int connect_clam(clamsmtp_context_t* ctx)
{
    int ret = 0;

    ASSERT(ctx);
    ASSERT(!clio_valid(&(ctx->clam)));

    if(clio_connect(ctx, &(ctx->clam), &g_clamaddr, g_clamname) == -1)
       RETURN(-1);

    read_junk(ctx, ctx->clam.fd);

    /* Send a session and a check header to ClamAV */

    if(clio_write_data(ctx, &(ctx->clam), "SESSION\n") == -1)
        RETURN(-1);

    read_junk(ctx, ctx->clam.fd);
/*
    if(clio_write_data(ctx, &(ctx->clam), "PING\n") == -1 ||
       clio_read_line(ctx, &(ctx->clam), CLIO_DISCARD | CLIO_TRIM) == -1)
        RETURN(-1);

    if(strcmp(ctx->line, CONNECT_RESPONSE) != 0)
    {
        message(ctx, LOG_ERR, "clamd sent an unexpected response: %s", ctx->line);
        RETURN(-1);
    }
*/

cleanup:

    if(ret < 0)
        clio_disconnect(ctx, &(ctx->clam));

    return ret;
}

static int disconnect_clam(clamsmtp_context_t* ctx)
{
    if(!clio_valid(&(ctx->clam)))
        return 0;

    if(clio_write_data(ctx, &(ctx->clam), CLAM_DISCONNECT) != -1)
        read_junk(ctx, ctx->clam.fd);

    clio_disconnect(ctx, &(ctx->clam));
    return 0;
}

static int clam_scan_file(clamsmtp_context_t* ctx, const char* tempname, char* logline)
{
    int len;

    ASSERT(LINE_LENGTH > MAXPATHLEN + 32);

    strcpy(ctx->line, CLAM_SCAN);
    strcat(ctx->line, tempname);
    strcat(ctx->line, "\n");

    if(clio_write_data(ctx, &(ctx->clam), ctx->line) == -1)
        return -1;

    len = clio_read_line(ctx, &(ctx->clam), CLIO_DISCARD | CLIO_TRIM);
    if(len == 0)
    {
        messagex(ctx, LOG_ERR, "clamd disconnected unexpectedly");
        return -1;
    }

    if(is_last_word(ctx->line, CLAM_OK, KL(CLAM_OK)))
    {
        add_to_logline(logline, "status=", "CLEAN");
        messagex(ctx, LOG_DEBUG, "no virus");
        return 0;
    }

    if(is_last_word(ctx->line, CLAM_FOUND, KL(CLAM_FOUND)))
    {
        len = strlen(tempname);

        if(ctx->linelen > len)
            add_to_logline(logline, "status=VIRUS:", ctx->line + len + 1);
        else
            add_to_logline(logline, "status=", "VIRUS");

        messagex(ctx, LOG_DEBUG, "found virus");
        return 1;
    }

    if(is_last_word(ctx->line, CLAM_ERROR, KL(CLAM_ERROR)))
    {
        messagex(ctx, LOG_ERR, "clamav error: %s", ctx->line);
        add_to_logline(logline, "status=", "CLAMAV-ERROR");
        return -1;
    }

    messagex(ctx, LOG_ERR, "unexepected response from clamd: %s", ctx->line);
    return -1;
}


/* ----------------------------------------------------------------------------------
 *  TEMP FILE HANDLING
 */

static int quarantine_virus(clamsmtp_context_t* ctx, char* tempname)
{
    char buf[MAXPATHLEN];
    char* t;

    if(!g_quarantine)
        return 0;

    strlcpy(buf, g_directory, MAXPATHLEN);
    strlcat(buf, "/virus.", MAXPATHLEN);

    /* Points to null terminator */
    t = buf + strlen(buf);

    /*
     * Yes, I know we're using mktemp. And yet we're doing it in
     * a safe manner due to the link command below not overwriting
     * existing files.
     */
    for(;;)
    {
        /* Null terminate off the ending, and replace with X's for mktemp */
        *t = 0;
        strlcat(buf, "XXXXXX", MAXPATHLEN);

        if(!mktemp(buf))
        {
            message(ctx, LOG_ERR, "couldn't create quarantine file name");
            return -1;
        }

        /* Try to link the file over to the temp */
        if(link(tempname, buf) == -1)
        {
            /* We don't want to allow race conditions */
            if(errno == EEXIST)
            {
                message(ctx, LOG_WARNING, "race condition when quarantining virus file: %s", buf);
                continue;
            }

            message(ctx, LOG_ERR, "couldn't quarantine virus file");
            return -1;
        }

        break;
    }

    messagex(ctx, LOG_INFO, "quarantined virus file as: %s", buf);
    return 0;
}

static int transfer_to_file(clamsmtp_context_t* ctx, char* tempname)
{
    FILE* tfile = NULL;
    int tfd = -1;
    int ended_crlf = 1;     /* If the last line ended with a CRLF */
    int ret = 0;
    int count = 0;

    if((tfd = mkstemp(tempname)) == -1 ||
       (tfile = fdopen(tfd, "w")) == NULL)
    {
        message(ctx, LOG_ERR, "couldn't open temp file");
        RETURN(-1);
    }

    messagex(ctx, LOG_DEBUG, "created temporary file: %s", tempname);

    for(;;)
    {
        switch(clio_read_line(ctx, &(ctx->client), CLIO_QUIET))
        {
        case 0:
            messagex(ctx, LOG_ERR, "unexpected end of data from client");
            RETURN(-1);

        case -1:
            /* Message already printed */
            RETURN(-1);
        };

        if(ended_crlf && strcmp(ctx->line, DATA_END_SIG) == 0)
            break;

        /* We check errors on this later */
        fwrite(ctx->line, 1, ctx->linelen, tfile);

        /* Check if this line ended with a CRLF */
        ended_crlf = (strcmp(CRLF, ctx->line + (ctx->linelen - KL(CRLF))) == 0);
    }

    if(ferror(tfile))
    {
        message(ctx, LOG_ERR, "error writing to temp file: %s", tempname);
        RETURN(-1);
    }

    ret = count;
    messagex(ctx, LOG_DEBUG, "wrote %d bytes to temp file", count);

cleanup:

    if(tfile)
       fclose(tfile);

    if(tfd != -1)
    {
        /* Only close this if not opened as a stream */
        if(tfile == NULL)
            close(tfd);

        if(ret == -1)
        {
            messagex(ctx, LOG_DEBUG, "discarding temporary file");
            unlink(tempname);
        }
    }

    return ret;
}

static int transfer_from_file(clamsmtp_context_t* ctx, const char* filename)
{
    FILE* file = NULL;
    int header = 0;
    int ret = 0;

    file = fopen(filename, "r");
    if(file == NULL)
    {
        message(ctx, LOG_ERR, "couldn't open temporary file: %s", filename);
        RETURN(-1);
    }

    messagex(ctx, LOG_DEBUG, "opened temporary file: %s", filename);

    while(fgets(ctx->line, LINE_LENGTH, file) != NULL)
    {
        if(g_header && !header)
        {
            /*
             * The first blank line we see means the headers are done.
             * At this point we add in our virus checked header.
             */
            if(is_blank_line(ctx->line))
            {
                if(clio_write_data_raw(ctx, &(ctx->server), (char*)g_header, strlen(g_header)) == -1 ||
                   clio_write_data_raw(ctx, &(ctx->server), CRLF, KL(CRLF)) == -1)
                    RETURN(-1);

                header = 1;
            }
        }

        if(clio_write_data_raw(ctx, &(ctx->server), ctx->line, strlen(ctx->line)) == -1)
            RETURN(-1);
    }

    if(ferror(file))
    {
        message(ctx, LOG_ERR, "error reading temporary file: %s", filename);
        RETURN(-1);
    }

    if(clio_write_data(ctx, &(ctx->server), DATA_END_SIG) == -1)
        RETURN(-1);

    messagex(ctx, LOG_DEBUG, "sent email data");

cleanup:

    if(file != NULL)
        fclose(file);

    return ret;
}


/* ----------------------------------------------------------------------------------
 *  NETWORKING
 */

static void read_junk(clamsmtp_context_t* ctx, int fd)
{
    char buf[16];
    const char* t;
    int said = 0;
    int l;

    if(fd == -1)
        return;

    /* Make it non blocking */
    fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);

    for(;;)
    {
        l = read(fd, buf, sizeof(buf) - 1);
        if(l <= 0)
            break;

        buf[l] = 0;
        t = trim_start(buf);

        if(!said && *t)
        {
            messagex(ctx, LOG_DEBUG, "received junk data from daemon");
            said = 1;
        }
    }

    fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) & ~O_NONBLOCK);
}