summaryrefslogtreecommitdiffstats
path: root/qmail-smtpd.c
blob: 0d3b16df0d87acdd57ccecffaecff56e4179e2a7 (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
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
#include <arpa/inet.h>
#include <sys/time.h>
#include <unistd.h>
#include "sig.h"
#include "stralloc.h"
#include "substdio.h"
#include "alloc.h"
#include "auto_qmail.h"
#include "control.h"
#include "received.h"
#include "constmap.h"
#include "error.h"
#include "ipme.h"
#include "ip.h"
#include "qmail.h"
#include "str.h"
#include "fmt.h"
#include "scan.h"
#include "byte.h"
#include "case.h"
#include "env.h"
#include "now.h"
#include "exit.h"
#include "rcpthosts.h"
#include "timeoutread.h"
#include "timeoutwrite.h"
#include "commands.h"
#include "wait.h"
#include "qregex.h"
#include "strerr.h"
#include "cdb.h"
#include "qmail-spp.h"
#include "dns.h"
#include "base64.h"
#include "open.h"
#include "fd.h"
#include "fork.h"

int spp_val;

#define BMCHECK_BMF 0
#define BMCHECK_BMFNR 1
#define BMCHECK_BMT 2
#define BMCHECK_BMTNR 3
#define BMCHECK_BHELO 4

//#define CRAM_MD5
#define AUTHSLEEP 5

#define MAXHOPS 100
unsigned int databytes = 0;
unsigned int mfchk = 0;
unsigned int greetdelay = 0;
unsigned int drop_pre_greet = 0;
int timeout = 1200;
int recipcount = 0;
unsigned int max_recipcount = 300;

const char *protocol = "SMTP";

char *remoteip;
char *remotehost;
char *remoteinfo;
char *local;
char *relayclient;
static const stralloc *client_get_session_id();

#ifdef TLS
# include <sys/stat.h>
# include "tls.h"
# include "ssl_timeoutio.h"

# define SERVERCERT  "control/servercert.pem"
# define SERVERCERT2 "control/servercert2.pem"

void tls_init();
void tls_nogateway();
int ssl_rfd = -1, ssl_wfd = -1; /* SSL_get_Xfd() are broken */
stralloc proto = {0};
int tls_before_auth = 0;
int tls_require = 0;
#endif

#ifdef SMTPUTF8
# include <idn2.h>
int smtputf8 = 0;
#endif

/* SMTP AUTH */
int flagauth = 0;
char **childargs;

ssize_t safewrite(fd,buf,len) int fd; char *buf; int len;
{
  ssize_t r;
#ifdef TLS
  if (ssl && fd == ssl_wfd)
    r = ssl_timeoutwrite(timeout, ssl_rfd, ssl_wfd, ssl, buf, len);
  else
#endif
  r = timeoutwrite(timeout,fd,buf,len);
  if (r <= 0) _exit(1);
  return r;
}

char ssoutbuf[512];
substdio ssout = SUBSTDIO_FDBUF(safewrite,1,ssoutbuf,sizeof ssoutbuf);

/* write errors to stderr */
char erroutbuf[512];
substdio errout = SUBSTDIO_FDBUF(safewrite,2,erroutbuf,sizeof erroutbuf);

void flush() { substdio_flush(&ssout); }
void out(s) char *s; { substdio_puts(&ssout,s); }

void eflush() {  substdio_flush(&errout); }
void eout(s) char *s; { substdio_puts(&errout,s); }
void enew() { substdio_puts(&errout,"qmail-smtpd: "); }

void die_read() { _exit(1); }

void die_alarm()
{
  enew(); eout("Connection to "); eout(remoteip); eout(" timed out.\n");
  out("451 timeout (#4.4.2)\r\n"); flush(); eflush(); _exit(1);
}
void die_nomem()
{
  enew(); eout("Out of memory while connected to "); eout(remoteip); eout("!\n");
  out("421 out of memory (#4.3.0)\r\n"); flush(); eflush(); _exit(1);
}
void die_control()
{
  enew(); eout("Unable to read controls!\n");
  out("421 unable to read controls (#4.3.0)\r\n"); flush(); eflush(); 
  _exit(1);
}
void die_ipme()
{
  enew(); eout("Unable to figure out my IP addresses!\n");
  out("421 unable to figure out my IP addresses (#4.3.0)\r\n"); flush();
  eflush(); _exit(1);
}
void die_cdb()
{
  enew(); eout("Unable to read cdb user database!\n");
  out("421 unable to read cdb user database (#4.3.0)\r\n"); flush();
  eflush(); _exit(1);
}
void die_sys()
{
  enew(); eout("Unable to read system user database!\n");
  out("421 unable to read system user database (#4.3.0)\r\n"); flush();
  eflush(); _exit(1);
}
void straynewline()
{
  enew(); eout("Stray newline from "); eout(remoteip); eout(".\n");
  out("451 See http://pobox.com/~djb/docs/smtplf.html.\r\n"); flush();
  eflush(); _exit(1);
}
void die_pre_greet() { out("554 SMTP protocol violation\r\n"); flush(); _exit(1); }

int hard_errors = 0;
unsigned int max_hard_errors = 20;
void do_hard_errors() {
  if (++hard_errors < max_hard_errors)
    return;
  enew(); eout("Maximum errors for "); eout(remoteip); eout(" reached. Closing connection\n");
  out("421 too many errors (#4.7.0)\r\n"); flush();
  eflush();
  _exit(1);
}

void err_size() { out("552 sorry, that message size exceeds my databytes limit (#5.3.4)\r\n"); do_hard_errors(); }
void err_bmf() { out("553 sorry, your envelope sender has been denied (#5.7.1)\r\n"); do_hard_errors(); }
void err_bmt() { out("553 sorry, your envelope recipient has been denied (#5.7.1)\r\n"); do_hard_errors(); }
void err_hmf() { out("553 sorry, your envelope sender domain must exist (#5.7.1)\r\n"); do_hard_errors(); }
void err_smf() { out("451 DNS temporary failure (#4.3.0)\r\n"); }
void err_brt() { out("550 sorry, this message is not deliverable (#5.7.1)\r\n"); do_hard_errors(); }
void err_bhelo() { out("553 sorry, your HELO host name has been denied (#5.7.1)\r\n"); do_hard_errors(); }
void err_nogateway()
{
  out("553 sorry, that domain isn't in my list of allowed rcpthosts");
#ifdef TLS
  tls_nogateway();
#endif
  out(" (#5.7.1)\r\n");
  do_hard_errors();
}
void err_badbounce() { out("550 sorry, bounce messages should have a single envelope recipient (#5.7.1)\r\n"); do_hard_errors(); }
void err_unimpl(arg) char *arg; { out("502 unimplemented (#5.5.1)\r\n"); do_hard_errors(); }
void err_syntax() { out("555 syntax error (#5.5.4)\r\n"); do_hard_errors(); }
void err_relay() { out("553 we don't relay (#5.7.1)\r\n"); do_hard_errors(); }
void err_wanthelo() { out("503 HELO/EHLO first (#5.5.1)\r\n"); do_hard_errors(); }
void err_wantmail() { out("503 MAIL first (#5.5.1)\r\n"); do_hard_errors(); }
void err_wantrcpt() { out("503 RCPT first (#5.5.1)\r\n"); do_hard_errors(); }
void err_noop(arg) char *arg; { out("250 ok\r\n"); }
void err_vrfy(arg) char *arg; { out("252 send some mail, i'll try my best\r\n"); }
void err_qqt() { out("451 qqt failure (#4.3.0)\r\n"); }

int err_child() { out("454 oops, problem with child and I can't auth (#4.3.0)\r\n"); return -1; }
int err_fork() { out("454 oops, child won't start and I can't auth (#4.3.0)\r\n"); return -1; }
int err_pipe() { out("454 oops, unable to open pipe and I can't auth (#4.3.0)\r\n"); return -1; }
int err_write() { out("454 oops, unable to write pipe and I can't auth (#4.3.0)\r\n"); return -1; }
void err_authd() { out("503 you're already authenticated (#5.5.0)\r\n"); }
void err_authmail() { out("503 no auth during mail transaction (#5.5.0)\r\n"); do_hard_errors(); }
int err_noauth() { out("504 auth type unimplemented (#5.5.1)\r\n"); do_hard_errors(); return -1; }
int err_noauth2() { out("503 auth not available (#5.3.3)\r\n"); do_hard_errors(); return -1; }
int err_authabrt() { out("501 auth exchange canceled (#5.0.0)\r\n"); return -1; }
int err_input() { out("501 malformed auth input (#5.5.4)\r\n"); return -1; }
int err_wantstarttls() { out("530 Must issue a STARTTLS command first (#5.7.0)\r\n"); return -1; };
void err_authfail() { out("535 authentication failed (#5.7.1)\r\n"); do_hard_errors(); }
void err_nomailbox() { out("554 sorry, no mailbox here by that name (#5.1.1)\r\n"); do_hard_errors(); }
void err_maxrcpt() { out("450 too many recipients (#4.7.1)\r\n"); do_hard_errors(); }

extern void realrcptto_init();
extern void realrcptto_start();
extern int realrcptto();
extern int realrcptto_deny();

stralloc greeting = {0};

void smtp_greet(code) char *code;
{
  substdio_puts(&ssout,code);
  substdio_put(&ssout,greeting.s,greeting.len);
}
void smtp_help(arg) char *arg;
{
  out("214 qmail home page: http://pobox.com/~djb/qmail.html\r\n");
}
void smtp_quit(arg) char *arg;
{
  smtp_greet("221 "); out("\r\n"); flush(); _exit(0);
}

stralloc helohost = {0};
char *fakehelo; /* pointer into helohost, or 0 */

void dohelo(arg) char *arg; {
  if (!stralloc_copys(&helohost,arg)) die_nomem(); 
  if (!stralloc_0(&helohost)) die_nomem(); 
  fakehelo = case_diffs(remotehost,helohost.s) ? helohost.s : 0;
}

int liphostok = 0;
stralloc liphost = {0};

int bmfok = 0;
stralloc bmf = {0};

int bmfnrok = 0;
stralloc bmfnr = {0};

int bmtok = 0;
stralloc bmt = {0};

int bmtnrok = 0;
stralloc bmtnr = {0};

int brtok = 0;
stralloc brt = {0};
struct constmap mapbrt;
int fdmbrt;

int bhelook = 0;
stralloc bhelo = {0};

int logregex = 0;
stralloc matchedregex = {0};

void setup()
{
  char *x;
  unsigned long u;
 
  if (control_init() == -1) die_control();
  if (control_rldef(&greeting,"control/smtpgreeting",1,(char *) 0) != 1)
    die_control();
  liphostok = control_rldef(&liphost,"control/localiphost",1,(char *) 0);
  if (liphostok == -1) die_control();
  if (control_readint(&timeout,"control/timeoutsmtpd") == -1) die_control();
  if (timeout <= 0) timeout = 1;
  if (rcpthosts_init() == -1) die_control();
  if (spp_init() == -1) die_control();

  if (control_readint(&mfchk,"control/mfcheck") == -1) die_control();
  x = env_get("MFCHECK");
  if (x) { scan_ulong(x,&u); mfchk = u; }

  bmfok = control_readfile(&bmf,"control/badmailfrom",0);
  if (bmfok == -1) die_control();

  bmfnrok = control_readfile(&bmfnr,"control/badmailfromnorelay",0);
  if (bmfnrok == -1) die_control();

  bmtok = control_readfile(&bmt,"control/badmailto",0);
  if (bmtok == -1) die_control();

  bmtnrok = control_readfile(&bmtnr,"control/badmailtonorelay",0);
  if (bmtnrok == -1) die_control();

  bhelook = control_readfile(&bhelo, "control/badhelo",0);
  if (bhelook == -1) die_control();
  if (env_get("NOBADHELO")) bhelook = 0;

  if (env_get("LOGREGEX")) logregex = 1;
 

  brtok = control_readfile(&brt,"control/badrcptto",0);
  if (brtok == -1) die_control();
  if (brtok)
    if (!constmap_init(&mapbrt,brt.s,brt.len,0)) die_nomem();
 
  fdmbrt = open_read("control/morebadrcptto.cdb");
  if (fdmbrt == -1) if (errno != error_noent) die_control();


  realrcptto_init();
 
  if (control_readint(&databytes,"control/databytes") == -1) die_control();
  x = env_get("DATABYTES");
  if (x) { scan_ulong(x,&u); databytes = u; }
  if (!(databytes + 1)) --databytes;
 
  x = env_get("GREETDELAY");
  if (x) { scan_ulong(x, &u); greetdelay = u; }
  x = env_get("DROP_PRE_GREET");
  if (x) { scan_ulong(x, &u); drop_pre_greet = u; }

  x = env_get("MAXRCPT");
  if (x) { scan_ulong(x,&u); max_recipcount = u; }

  remoteip = env_get("TCPREMOTEIP");
  if (!remoteip) remoteip = "unknown";
  local = env_get("TCPLOCALHOST");
  if (!local) local = env_get("TCPLOCALIP");
  if (!local) local = "unknown";
  remotehost = env_get("TCPREMOTEHOST");
  if (!remotehost) remotehost = "unknown";
  remoteinfo = env_get("TCPREMOTEINFO");
  relayclient = env_get("RELAYCLIENT");

#ifdef TLS
  if (env_get("TLSBEFOREAUTH")) tls_before_auth = 1;
  if (env_get("TLSREQUIRE")) tls_require = 1;
  if (env_get("SMTPS")) { smtps = 1; tls_init(); }
  else
#endif
  dohelo(remotehost);

  /* generate session */
  (void)client_get_session_id();
}


stralloc addr = {0}; /* will be 0-terminated, if addrparse returns 1 */

int addrparse(arg)
char *arg;
{
  int i;
  char ch;
  char terminator;
  struct ip_address ip;
  int flagesc;
  int flagquoted;
 
  terminator = '>';
  i = str_chr(arg,'<');
  if (arg[i])
    arg += i + 1;
  else { /* partner should go read rfc 821 */
    terminator = ' ';
    arg += str_chr(arg,':');
    if (*arg == ':') ++arg;
    while (*arg == ' ') ++arg;
  }

  /* strip source route */
  if (*arg == '@') while (*arg) if (*arg++ == ':') break;

  if (!stralloc_copys(&addr,"")) die_nomem();
  flagesc = 0;
  flagquoted = 0;
  for (i = 0; (ch = arg[i]); ++i) { /* copy arg to addr, stripping quotes */
    if (flagesc) {
      if (!stralloc_append(&addr,&ch)) die_nomem();
      flagesc = 0;
    }
    else {
      if (!flagquoted && (ch == terminator)) break;
      switch(ch) {
        case '\\': flagesc = 1; break;
        case '"': flagquoted = !flagquoted; break;
        default: if (!stralloc_append(&addr,&ch)) die_nomem();
      }
    }
  }
  /* could check for termination failure here, but why bother? */
  if (!stralloc_append(&addr,"")) die_nomem();

  if (liphostok) {
    i = byte_rchr(addr.s,addr.len,'@');
    if (i < addr.len) /* if not, partner should go read rfc 821 */
      if (addr.s[i + 1] == '[')
        if (!addr.s[i + 1 + ip_scanbracket(addr.s + i + 1,&ip)])
          if (ipme_is(&ip)) {
            addr.len = i + 1;
            if (!stralloc_cat(&addr,&liphost)) die_nomem();
            if (!stralloc_0(&addr)) die_nomem();
          }
  }

  if (addr.len > 900) return 0;
  return 1;
}

#ifdef SMTPUTF8
static int idn_addr_convert(stralloc *addr)
{
  int i = byte_rchr(addr->s, addr->len, '@') + 1;
  if (i < addr->len) {
    char *asciihost = NULL;
    switch (idn2_lookup_u8(addr->s + i, (uint8_t **)&asciihost, IDN2_NFC_INPUT)) {
      case IDN2_OK: break;
      case IDN2_MALLOC: die_nomem();
      default: err_smf(); return 0;
    }
    addr->len = i;
    if (!stralloc_cats(addr, asciihost)) die_nomem();
    if (!stralloc_0(addr)) die_nomem();
  }
  return 1;
}
#endif

static void log_deny(m,f,t) char *m,*f,*t;
{
  enew(); eout(m); eout(" check failed ("); eout(f); eout(") -> (");
  eout(t); eout(") ["); eout(remoteip); eout("] (HELO "); 
  eout(helohost.s); eout(")\n");
  eflush();
} 

int bmcheck(which) int which;
{
  int i = 0;
  int j = 0;
  int x = 0;
  int negate = 0;
  static stralloc bmb = {0};
  static stralloc curregex = {0};

  if (which == BMCHECK_BMF) {
    if (!stralloc_copy(&bmb,&bmf)) die_nomem();
  } else if (which == BMCHECK_BMFNR) {
    if (!stralloc_copy(&bmb,&bmfnr)) die_nomem();
  } else if (which == BMCHECK_BMT) {
    if (!stralloc_copy(&bmb,&bmt)) die_nomem();
  } else if (which == BMCHECK_BMTNR) {
    if (!stralloc_copy(&bmb,&bmtnr)) die_nomem();
  } else if (which == BMCHECK_BHELO) {
    if (!stralloc_copy(&bmb,&bhelo)) die_nomem();
  } else {
    die_control();
  }

  while (j < bmb.len) {
    i = j;
    while ((bmb.s[i] != '\0') && (i < bmb.len)) i++;
    if (bmb.s[j] == '!') {
      negate = 1;
      j++;
    }
    if (!stralloc_copyb(&curregex,bmb.s + j,(i - j))) die_nomem();
    if (!stralloc_0(&curregex)) die_nomem();
    if (which == BMCHECK_BHELO) {
      x = matchregex(helohost.s, curregex.s);
    } else {
      x = matchregex(addr.s, curregex.s);
    }
    if ((negate) && (x == 0)) {
      if (!stralloc_copyb(&matchedregex,bmb.s + j - 1,(i - j + 1))) die_nomem();
      if (!stralloc_0(&matchedregex)) die_nomem();
      return 1;
    }
    if (!(negate) && (x > 0)) {
      if (!stralloc_copyb(&matchedregex,bmb.s + j,(i - j))) die_nomem();
      if (!stralloc_0(&matchedregex)) die_nomem();
      return 1;
    }
    j = i + 1;
    negate = 0;
  }
  return 0;
}

int brtcheck()
{
  int j;
  if (brtok) if (constmap(&mapbrt,addr.s,addr.len - 1)) return 1;
  if (fdmbrt != -1) {
    uint32 dlen;
    j = cdb_seek(fdmbrt, addr.s, addr.len - 1, &dlen);
    if (j == -1) die_control();
    if (j) return j;
  }
  return 0;
}

int mfcheck()
{
  stralloc sa = {0};
  ipalloc ia = {0};
  unsigned int random;
  int j;

  if (!mfchk) return 0;
  random = now() + (getpid() << 16);
  j = byte_rchr(addr.s,addr.len,'@') + 1;
  if (j < addr.len) {
    stralloc_copys(&sa, addr.s + j);
    dns_init(0);
    j = dns_mxip(&ia,&sa,random);
    if (j < 0) return j;
  }
  return 0;
}

int addrallowed()
{
  int r;
  r = rcpthosts(addr.s,str_len(addr.s));
  if (r == -1) die_control();
  return r;
}

int addrrelay()
{
  int j;
  j = addr.len;
  while(--j >= 0)
    if (addr.s[j] == '@') break;
  if (j < 0) j = addr.len;
  while(--j >= 0) {
    if (addr.s[j] == '@') return 1;
    if (addr.s[j] == '%') return 1;
    if (addr.s[j] == '!') return 1;
  }
  return 0;
}

int seenhelo = 0;
int seenmail = 0;
int flagbarfbmf; /* defined if seenmail */
int flagbarfbmt;
int flagbrt; /* defined if any bad rcpts */
int flagbarfbhelo;
int allowed;
int flagsize;
stralloc mailfrom = {0};
stralloc rcptto = {0};
stralloc fuser = {0};
stralloc mfparms = {0};

int mailfrom_size(arg) char *arg;
{
  long r;
  unsigned long sizebytes = 0;

  scan_ulong(arg,&r);
  sizebytes = r;
  if (databytes) if (sizebytes > databytes) return 1;
  return 0;
}

void mailfrom_auth(arg,len) 
char *arg; 
int len;
{
  if (!stralloc_copys(&fuser,"")) die_nomem();
  if (case_starts(arg,"<>")) { if (!stralloc_cats(&fuser,"unknown")) die_nomem(); }
  else 
    while (len) {
      if (*arg == '+') {
        if (case_starts(arg,"+3D")) { arg=arg+2; len=len-2; if (!stralloc_cats(&fuser,"=")) die_nomem(); }
        if (case_starts(arg,"+2B")) { arg=arg+2; len=len-2; if (!stralloc_cats(&fuser,"+")) die_nomem(); }
      }
      else
        if (!stralloc_catb(&fuser,arg,1)) die_nomem();
      arg++; len--;
    }
  if(!stralloc_0(&fuser)) die_nomem();
  if (!remoteinfo) {
    remoteinfo = fuser.s;
    if (!env_unset("TCPREMOTEINFO")) die_read();
    if (!env_put2("TCPREMOTEINFO",remoteinfo)) die_nomem();
  }
}

void mailfrom_parms(arg) char *arg;
{
  int i;
  int len;

    len = str_len(arg);
    if (!stralloc_copys(&mfparms,"")) die_nomem();
    i = byte_chr(arg,len,'>');
    if (i > 4 && i < len) {
      while (len) {
        arg++; len--; 
        if (*arg == ' ' || *arg == '\0' ) {
#ifdef SMTPUTF8
           if (case_starts(mfparms.s,"SMTPUTF8")) smtputf8 = 1;
#endif
           if (case_starts(mfparms.s,"SIZE=")) if (mailfrom_size(mfparms.s+5)) { flagsize = 1; return; }
           /* we do not support this */
           //if (case_starts(mfparms.s,"AUTH=")) mailfrom_auth(mfparms.s+5,mfparms.len-5);
           if (!stralloc_copys(&mfparms,"")) die_nomem();
        }
        else
          if (!stralloc_catb(&mfparms,arg,1)) die_nomem();
      }
    }
}

#define V4MAPPREFIX "::ffff:"
static const stralloc *client_get_session_id()
{
  static stralloc buf = {0}, base64_buf = {0};
  const char *tmp;
  struct timeval tv;
  uint64_t timestamp;
  unsigned int i;
  unsigned long port;
  int family = AF_INET;

  if (base64_buf.s)
    return &base64_buf;

  if (!stralloc_ready(&buf, 24)) die_nomem();

  /* add lowest 48 bits of the timestamp. this gives us a bit less than
     9 years until it wraps */
  gettimeofday(&tv, NULL);
  timestamp = tv.tv_usec + (long long)tv.tv_sec * 1000ULL*1000ULL;
  for (i = 0; i < 48; i += 8)
    buf.s[buf.len++] = (timestamp >> i) & 0xff;

  if ((tmp = getenv("TCPREMOTEPORT")) != NULL && scan_ulong(tmp, &port))
  {
    buf.s[buf.len]   = port & 0xff;
    buf.s[buf.len+1] = (port >> 8) & 0xff;
  }
  buf.len += 2;

  family = ((tmp = getenv("PROTO")) && strcmp(tmp, "TCP6") == 0)
    ? AF_INET6 : AF_INET;
  if ((tmp = getenv("TCPREMOTEIP")))
  {
    if (family == AF_INET6 && !strncmp(tmp, V4MAPPREFIX, strlen(V4MAPPREFIX)))
    {
      tmp += strlen(V4MAPPREFIX);
      family = AF_INET;
    }
    (void)inet_pton(family, tmp, buf.s + buf.len);
    buf.len += (family == AF_INET) ? 4 : 16;
  }

  if (b64encode(&buf, &base64_buf) < 0) die_nomem();
  if (!stralloc_0(&base64_buf)) die_nomem();
  if (!env_put2("SMTPSESSION", base64_buf.s)) die_nomem();
  return &base64_buf;
}

void smtp_helo(arg) char *arg;
{
  if(!spp_helo(arg)) return;
  smtp_greet("250 "); out("\r\n");
  seenmail = 0; seenhelo = 1; dohelo(arg);
  if (bhelook) flagbarfbhelo = bmcheck(BMCHECK_BHELO);
}
void smtp_authout();
/* ESMTP extensions are published here */
void smtp_ehlo(arg) char *arg;
{
#ifdef TLS
  struct stat st;
#endif
  char size[FMT_ULONG];
  size[fmt_ulong(size,(unsigned int) databytes)] = 0;
  if(!spp_helo(arg)) return;
  smtp_greet("250-");
#ifdef TLS
  const char *servercert = env_get("SMTP_SERVERCERT");
  if (!servercert) servercert = SERVERCERT;
  if (!ssl && (stat(servercert, &st) == 0))
    out("\r\n250-STARTTLS");
#endif
#ifdef SMTPUTF8
  out("\r\n250-PIPELINING\r\n250-SMTPUTF8\r\n250-8BITMIME\r\n");
#else
  out("\r\n250-PIPELINING\r\n250-8BITMIME\r\n");
#endif
#if defined(TLS)
  if(!tls_before_auth || (tls_before_auth && ssl)) smtp_authout();
#else
  smtp_authout();
#endif
  out("250 SIZE "); out(size); out("\r\n");
  seenmail = 0; seenhelo = 1; dohelo(arg);
  if (bhelook) flagbarfbhelo = bmcheck(BMCHECK_BHELO);
}
void smtp_rset(arg) char *arg;
{
  spp_rset();
  seenmail = 0;
  out("250 flushed\r\n");
}
void smtp_mail(arg) char *arg;
{
  if (!seenhelo) { err_wanthelo(); return; }
#if defined(TLS)
  if (tls_require && !ssl) { err_wantstarttls(); return; }
#endif
  if (!addrparse(arg)) { err_syntax(); return; }
  flagsize = 0;
  mailfrom_parms(arg);
  if (flagsize) { err_size(); return; }
#ifdef SMTPUTF8
  if (smtputf8) { if (!idn_addr_convert(&addr)) return; }
#endif
  flagbarfbmf = 0; /* bmcheck is skipped for empty envelope senders */
  if ((bmfok) && (addr.len != 1)) flagbarfbmf = bmcheck(BMCHECK_BMF);
  if ((!flagbarfbmf) && (bmfnrok) && (addr.len != 1) && (!relayclient)) {
    flagbarfbmf = bmcheck(BMCHECK_BMFNR);
  }
  switch(mfcheck()) {
    case DNS_HARD:
        strerr_warn4("qmail-smtpd: invalid envelope sender: <",addr.s,"> at ",remoteip,0);
        err_hmf(); return;
    case DNS_SOFT: err_smf(); return;
    case DNS_MEM: die_nomem();
  }
  if (!(spp_val = spp_mail())) return;
  seenmail = 1;
  if (!stralloc_copys(&rcptto,"")) die_nomem();
  if (!stralloc_copys(&mailfrom,addr.s)) die_nomem();
  if (!stralloc_0(&mailfrom)) die_nomem();
  realrcptto_start();
  recipcount = 0;
  out("250 ok\r\n");
}
void smtp_rcpt(arg) char *arg; {
  if (!seenmail) { err_wantmail(); return; }
  if (!addrparse(arg)) { err_syntax(); return; }
  if (!relayclient && addrrelay()) { err_relay(); return; }
  if (recipcount >= max_recipcount) {
    enew(); eout("Too many recipients for "); eout(remoteip); eout(".\n");
    err_maxrcpt();
    return;
  }
  if (flagbarfbhelo) {
    if (logregex) {
      strerr_warn6("qmail-smtpd: badhelo: <",helohost.s,"> at ",remoteip," matches pattern: ",matchedregex.s,0);
    } else {
      strerr_warn4("qmail-smtpd: badhelo: <",helohost.s,"> at ",remoteip,0);
    }
    err_bhelo();
    return;
  }
  if (flagbarfbmf) {
    if (logregex) {
      strerr_warn6("qmail-smtpd: badmailfrom: <",mailfrom.s,"> at ",remoteip," matches pattern: ",matchedregex.s,0);
    } else {
      strerr_warn4("qmail-smtpd: badmailfrom: <",mailfrom.s,"> at ",remoteip,0);
    }
    err_bmf();
    return;
  }
#ifdef SMTPUTF8
  if (smtputf8) { if (!idn_addr_convert(&addr)) return; }
#endif
  if (bmtok) flagbarfbmt = bmcheck(BMCHECK_BMT);
  if ((!flagbarfbmt) && (bmtnrok) && (!relayclient)) {
    flagbarfbmt = bmcheck(BMCHECK_BMTNR);
  }
  if (flagbarfbmt) {
    if (logregex) {
      strerr_warn6("qmail-smtpd: badmailto: <",addr.s,"> at ",remoteip," matches pattern: ",matchedregex.s,0);
    } else {
      strerr_warn4("qmail-smtpd: badmailto: <",addr.s,"> at ",remoteip,0);
    }
    err_bmt();
    return;
  }
  if (!relayclient) allowed = addrallowed();
  else allowed = 1;
  if (relayclient) {
    --addr.len;
    if (!stralloc_cats(&addr,relayclient)) die_nomem();
    if (!stralloc_0(&addr)) die_nomem();
  }
  if (!env_get("RELAYCLIENT") && brtcheck()) { 
    flagbrt = 1; 
    log_deny("BAD RCPT TO", mailfrom.s,addr.s);
  }
  if (!flagauth && !relayclient && !realrcptto(addr.s,1)) {
    err_nomailbox();
    return;
  }
  if (!(spp_val = spp_rcpt(allowed))) return;
  if (!relayclient && spp_val == 1) {
    if (!allowed) {
      strerr_warn6("qmail-smtpd: Attempted relay from ",mailfrom.s," at ",remoteip," to ",addr.s,0);
      err_nogateway();
      return;
    }
  }
  spp_rcpt_accepted();
  if (!stralloc_cats(&rcptto,"T")) die_nomem();
  if (!stralloc_cats(&rcptto,addr.s)) die_nomem();
  if (!stralloc_0(&rcptto)) die_nomem();
  recipcount++;
  out("250 ok\r\n");
}


ssize_t saferead(fd,buf,len) int fd; char *buf; int len;
{
  ssize_t r;
  flush();
#ifdef TLS
  if (ssl && fd == ssl_rfd)
    r = ssl_timeoutread(timeout, ssl_rfd, ssl_wfd, ssl, buf, len);
  else
#endif
  r = timeoutread(timeout,fd,buf,len);
  if (r == -1) if (errno == error_timeout) die_alarm();
  if (r <= 0) die_read();
  return r;
}

char ssinbuf[1024];
substdio ssin = SUBSTDIO_FDBUF(saferead,0,ssinbuf,sizeof ssinbuf);
#ifdef TLS
void flush_io() { ssin.p = 0; flush(); }
#endif

struct qmail qqt;
unsigned int bytestooverflow = 0;

void put(ch)
char *ch;
{
  if (bytestooverflow)
    if (!--bytestooverflow)
      qmail_fail(&qqt);
  qmail_put(&qqt,ch,1);
}

void blast(hops)
int *hops;
{
  char ch;
  int state;
  int flaginheader;
  int pos; /* number of bytes since most recent \n, if fih */
  int flagmaybex; /* 1 if this line might match RECEIVED, if fih */
  int flagmaybey; /* 1 if this line might match \r\n, if fih */
  int flagmaybez; /* 1 if this line might match DELIVERED, if fih */
 
  state = 1;
  *hops = 0;
  flaginheader = 1;
  pos = 0; flagmaybex = flagmaybey = flagmaybez = 1;
  for (;;) {
    substdio_get(&ssin,&ch,1);
    if (flaginheader) {
      if (pos < 9) {
        if (ch != "delivered"[pos]) if (ch != "DELIVERED"[pos]) flagmaybez = 0;
        if (flagmaybez) if (pos == 8) ++*hops;
        if (pos < 8)
          if (ch != "received"[pos]) if (ch != "RECEIVED"[pos]) flagmaybex = 0;
        if (flagmaybex) if (pos == 7) ++*hops;
        if (pos < 2) if (ch != "\r\n"[pos]) flagmaybey = 0;
        if (flagmaybey) if (pos == 1) flaginheader = 0;
        ++pos;
      }
      if (ch == '\n') { pos = 0; flagmaybex = flagmaybey = flagmaybez = 1; }
    }
    switch(state) {
      case 0:
        if (ch == '\n') straynewline();
        if (ch == '\r') { state = 4; continue; }
        break;
      case 1: /* \r\n */
        if (ch == '\n') straynewline();
        if (ch == '.') { state = 2; continue; }
        if (ch == '\r') { state = 4; continue; }
        state = 0;
        break;
      case 2: /* \r\n + . */
        if (ch == '\n') straynewline();
        if (ch == '\r') { state = 3; continue; }
        state = 0;
        break;
      case 3: /* \r\n + .\r */
        if (ch == '\n') return;
        put(".");
        put("\r");
        if (ch == '\r') { state = 4; continue; }
        state = 0;
        break;
      case 4: /* + \r */
        if (ch == '\n') { state = 1; break; }
        if (ch != '\r') { put("\r"); state = 0; }
    }
    put(&ch);
  }
}

char accept_buf[FMT_ULONG];
void acceptmessage(qp) unsigned long qp;
{
  datetime_sec when;
  when = now();
  out("250 ok ");
  accept_buf[fmt_ulong(accept_buf,(unsigned long) when)] = 0;
  out(accept_buf);
  out(" qp ");
  accept_buf[fmt_ulong(accept_buf,qp)] = 0;
  out(accept_buf);
  out("\r\n");
}

void smtp_data(arg) char *arg; {
  int hops;
  unsigned long qp;
  char *qqx;
 
  if (!seenmail) { err_wantmail(); return; }
  if (!rcptto.len) { err_wantrcpt(); return; }
  if (mailfrom.len == 1 && recipcount > 1) { err_badbounce(); return; }
  if (flagbrt) { err_brt(); return; }
  if (!spp_data()) return;
  if (!relayclient && realrcptto_deny()) {
    err_nomailbox();
    return;
  }
  seenmail = 0;
  if (databytes) bytestooverflow = databytes + 1;
  if (qmail_open(&qqt) == -1) { err_qqt(); return; }
  qp = qmail_qp(&qqt);
  out("354 go ahead\r\n");

  if (smtputf8) {
    stralloc utf8proto = {0};
    if (*protocol == 'E') ++protocol;
    if (!stralloc_copys(&utf8proto, "UTF8")) die_nomem();
    if (!stralloc_cats(&utf8proto, protocol)) die_nomem();
    if (!stralloc_0(&utf8proto)) die_nomem();
    protocol = utf8proto.s;
  }

  if (flagauth)
    received_authed(&qqt,protocol,local);
  else
    received(&qqt,protocol,local,remoteip,remotehost,remoteinfo,fakehelo);
  if (!env_get("NOSESSIONHEADER"))
    xsmtpsession(&qqt, (flagauth) ? remoteinfo : NULL, client_get_session_id()->s);
  qmail_put(&qqt,sppheaders.s,sppheaders.len); /* set in qmail-spp.c */
  spp_rset();
  blast(&hops);
  hops = (hops >= MAXHOPS);
  if (hops) qmail_fail(&qqt);
  qmail_from(&qqt,mailfrom.s);
  qmail_put(&qqt,rcptto.s,rcptto.len);
 
  qqx = qmail_close(&qqt);
  if (!*qqx) { acceptmessage(qp); return; }
  if (hops) { out("554 too many hops, this message is looping (#5.4.6)\r\n"); return; }
  if (databytes) if (!bytestooverflow) { err_size(); return; }
  if (*qqx == 'D') out("554 "); else out("451 ");
  out(qqx + 1);
  out("\r\n");
}

/* this file is too long ----------------------------------------- SMTP AUTH */

char unique[FMT_ULONG + FMT_ULONG + 3];
static stralloc authin = {0};   /* input from SMTP client */
static stralloc user = {0};     /* authorization user-id */
static stralloc pass = {0};     /* plain passwd or digest */
static stralloc resp = {0};     /* b64 response */
#ifdef CRAM_MD5
static stralloc chal = {0};     /* plain challenge */
static stralloc slop = {0};     /* b64 challenge */
#endif

char ssauthbuf[512];
char ssauth2buf[512];
substdio ssauth = SUBSTDIO_FDBUF(safewrite,3,ssauthbuf,sizeof(ssauthbuf));
substdio ssauth2 = SUBSTDIO_FDBUF(saferead,4,ssauth2buf,sizeof(ssauth2buf));

void smtp_authout() {
  if (!*childargs) return;
#ifdef CRAM_MD5
  out("250-AUTH LOGIN PLAIN CRAM-MD5\r\n");
#else
  out("250-AUTH LOGIN PLAIN\r\n");
#endif
}

int authgetl(void) {
  int i;

  if (!stralloc_copys(&authin,"")) die_nomem();
  for (;;) {
    if (!stralloc_readyplus(&authin,1)) die_nomem(); /* XXX */
    i = substdio_get(&ssin,authin.s + authin.len,1);
    if (i != 1) die_read();
    if (authin.s[authin.len] == '\n') break;
    ++authin.len;
  }

  if (authin.len > 0) if (authin.s[authin.len - 1] == '\r') --authin.len;
  authin.s[authin.len] = 0;
  if (*authin.s == '*' && *(authin.s + 1) == 0) { return err_authabrt(); }
  if (authin.len == 0) { return err_input(); }
  return authin.len;
}

int authenticate(void)
{
  int child;
  int wstat;
  int pi[2];
  int piauth[2], i, len;
  char *arg;
  static stralloc authout = {0}, authparams = {0};

  if (!stralloc_0(&user)) die_nomem();
  if (!stralloc_0(&pass)) die_nomem();
#ifdef CRAM_MD5
  if (!stralloc_0(&chal)) die_nomem();
#endif

  if (pipe(pi) == -1) return err_pipe();
  if (pipe(piauth) == -1) return err_pipe();
  switch(child = fork()) {
    case -1:
      return err_fork();
    case 0:
      close(pi[1]);
      close(piauth[0]);
      if(fd_copy(3,pi[0]) == -1) return err_pipe();
      if(fd_copy(4,piauth[1]) == -1) return err_pipe();
      sig_pipedefault();
        execvp(*childargs, childargs);
      _exit(1);
  }
  close(pi[0]);
  close(piauth[1]);

  substdio_fdbuf(&ssauth,write,pi[1],ssauthbuf,sizeof ssauthbuf);
  substdio_fdbuf(&ssauth2,read,piauth[0],ssauth2buf,sizeof ssauth2buf);
  if (substdio_put(&ssauth,user.s,user.len) == -1) return err_write();
  if (substdio_put(&ssauth,pass.s,pass.len) == -1) return err_write();
#ifdef CRAM_MD5
  if (substdio_put(&ssauth,chal.s,chal.len) == -1) return err_write();
#endif
  if (substdio_flush(&ssauth) == -1) return err_write();

  close(pi[1]);

  if (!stralloc_copys(&authout, "")) die_nomem();
  for (;;) {
    if (!stralloc_readyplus(&authout, 1)) die_nomem();
    i = substdio_get(&ssauth2, authout.s + authout.len, 1);
    if (i == 0) break;
    ++authout.len;
  }
  authout.s[authout.len] = 0;
  if (substdio_flush(&ssauth2) == -1) return err_write();
  close(piauth[0]);

  if (authout.len > 0) {
    len = authout.len;
    arg = authout.s;
    if (!stralloc_copys(&authparams, "")) die_nomem();
    while (len) {
      if (*arg == '\0') {
        if (case_starts(authparams.s, "USER=") && (authparams.len - 5) > 0) {
          if (!stralloc_copyb(&user, authparams.s + 5, authparams.len - 5)) die_nomem();
          if (!stralloc_0(&user)) die_nomem();
        }
        if (!stralloc_copys(&authparams, "")) die_nomem();
      }
      else
        if (!stralloc_catb(&authparams, arg, 1)) die_nomem();
      arg++;
      len--;
    }
  }

#ifdef CRAM_MD5
  if (!stralloc_copys(&chal,"")) die_nomem();
  if (!stralloc_copys(&slop,"")) die_nomem();
#endif
  byte_zero(ssauthbuf,sizeof ssauthbuf);
  byte_zero(ssauth2buf,sizeof ssauth2buf);
  if (wait_pid(&wstat,child) == -1) return err_child();
  if (wait_crashed(wstat)) return err_child();
  if (wait_exitcode(wstat)) { sleep(AUTHSLEEP); return 1; } /* no */
  return 0; /* yes */
}

int auth_login(arg) char *arg;
{
  int r;

#if defined(TLS)
  if (tls_before_auth && !ssl) return err_wantstarttls();
#endif
  if (*arg) {
    if ((r = b64decode(arg,str_len(arg),&user)) == 1) return err_input();
  }
  else {
    out("334 VXNlcm5hbWU6\r\n"); flush();       /* Username: */
    if (authgetl() < 0) return -1;
    if ((r = b64decode(authin.s,authin.len,&user)) == 1) return err_input();
  }
  if (r == -1) die_nomem();

  out("334 UGFzc3dvcmQ6\r\n"); flush();         /* Password: */

  if (authgetl() < 0) return -1;
  if ((r = b64decode(authin.s,authin.len,&pass)) == 1) return err_input();
  if (r == -1) die_nomem();

  if (!user.len || !pass.len) return err_input();
  return authenticate();
}

int auth_plain(arg) char *arg;
{
  int r, id = 0;

#if defined(TLS)
  if (tls_before_auth && !ssl) return err_wantstarttls();
#endif
  if (*arg) {
    if ((r = b64decode(arg,str_len(arg),&resp)) == 1) return err_input();
  }
  else {
    out("334 \r\n"); flush();
    if (authgetl() < 0) return -1;
    if ((r = b64decode(authin.s,authin.len,&resp)) == 1) return err_input();
  }
  if (r == -1 || !stralloc_0(&resp)) die_nomem();
  while (resp.s[id]) id++;                       /* "authorize-id\0userid\0passwd\0" */

  if (resp.len > id + 1)
    if (!stralloc_copys(&user,resp.s + id + 1)) die_nomem();
  if (resp.len > id + user.len + 2)
    if (!stralloc_copys(&pass,resp.s + id + user.len + 2)) die_nomem();

  if (!user.len || !pass.len) return err_input();
  return authenticate();
}

#ifdef CRAM_MD5
int auth_cram()
{
  int i, r;
  char *s;

#if defined(TLS)
  if (tls_before_auth && !ssl) return err_wantstarttls();
#endif

  s = unique;                                           /* generate challenge */
  s += fmt_uint(s,getpid());
  *s++ = '.';
  s += fmt_ulong(s,(unsigned long) now());
  *s++ = '@';
  *s++ = 0;
  if (!stralloc_copys(&chal,"<")) die_nomem();
  if (!stralloc_cats(&chal,unique)) die_nomem();
  if (!stralloc_cats(&chal,local)) die_nomem();
  if (!stralloc_cats(&chal,">")) die_nomem();
  if (b64encode(&chal,&slop) < 0) die_nomem();
  if (!stralloc_0(&slop)) die_nomem();

  out("334 ");                                          /* "334 base64_challenge \r\n" */
  out(slop.s);
  out("\r\n");
  flush();

  if (authgetl() < 0) return -1;                        /* got response */
  if (r = b64decode(authin.s,authin.len,&resp) == 1) return err_input();
  if (r == -1 || !stralloc_0(&resp)) die_nomem();

  i = str_chr(resp.s,' ');
  s = resp.s + i;
  while (*s == ' ') ++s;
  resp.s[i] = 0;
  if (!stralloc_copys(&user,resp.s)) die_nomem();       /* userid */
  if (!stralloc_copys(&pass,s)) die_nomem();            /* digest */

  if (!user.len || !pass.len) return err_input();
  return authenticate();
}
#endif

struct authcmd {
  char *text;
  int (*fun)();
} authcmds[] = {
  { "login",auth_login }
,  { "plain",auth_plain }
#ifdef CRAM_MD5
, { "cram-md5",auth_cram }
#endif
, { 0,err_noauth }
};

void smtp_auth(arg)
char *arg;
{
  int i;
  char *cmd = arg;

  if (!*childargs) { err_noauth2(); return; }
  if (flagauth) { err_authd(); return; }
  if (seenmail) { err_authmail(); return; }

  if (!stralloc_copys(&user,"")) die_nomem();
  if (!stralloc_copys(&pass,"")) die_nomem();
  if (!stralloc_copys(&resp,"")) die_nomem();
#ifdef CRAM_MD5
  if (!stralloc_copys(&chal,"")) die_nomem();
#endif

  i = str_chr(cmd,' ');
  arg = cmd + i;
  while (*arg == ' ') ++arg;
  cmd[i] = 0;

  for (i = 0;authcmds[i].text;++i)
    if (case_equals(authcmds[i].text,cmd)) break;

  switch (authcmds[i].fun(arg)) {
    case 0:
      if (!spp_auth(authcmds[i].text, user.s)) return;
      flagauth = 1;
      if (ssl) {
        if (!stralloc_copys(&proto, "ESMTPSA (")
            || !stralloc_cats(&proto, SSL_get_cipher(ssl))
            || !stralloc_cats(&proto, " encrypted, authenticated)")) 
          die_nomem();
        if (!stralloc_0(&proto)) die_nomem();
        protocol = proto.s;
      } else {
        protocol = "ESMTPA";
      }
      relayclient = "";
      remoteinfo = user.s;
      if (!env_unset("TCPREMOTEINFO")) die_read();
      if (!env_put2("TCPREMOTEINFO",remoteinfo)) die_nomem();
      if (!env_put2("RELAYCLIENT",relayclient)) die_nomem();
      out("235 ok, go ahead (#2.0.0)\r\n");
      break;
    case 1:
      err_authfail(user.s,authcmds[i].text);
  }
}


/* this file is too long --------------------------------------------- GO ON */

#ifdef TLS
int ssl_verified = 0;
const char *ssl_verify_err = 0;

void smtp_tls(char *arg)
{
  if (ssl) err_unimpl();
  else if (*arg) out("501 Syntax error (no parameters allowed) (#5.5.4)\r\n");
  else tls_init();
}

/* don't want to fail handshake if cert isn't verifiable */
int verify_cb(int preverify_ok, X509_STORE_CTX *ctx) { return 1; }

void tls_nogateway()
{
  /* there may be cases when relayclient is set */
  if (!ssl || relayclient) return;
  out("; no valid cert for gatewaying");
  if (ssl_verify_err) { out(": "); out(ssl_verify_err); }
}
void tls_out(const char *s1, const char *s2)
{
  out("454 TLS "); out(s1);
  if (s2) { out(": "); out(s2); }
  out(" (#4.3.0)\r\n"); flush();
}
void tls_err(const char *s) { tls_out(s, ssl_error()); if (smtps) die_read(); }

void tls_init()
{
  SSL *myssl;
  SSL_CTX *ctx;
  const char *ciphers;
  stralloc saciphers = {0};
  const char *servercert, *servercert2;
  struct stat st;

  /* if set, use servercert selected through SMTP_SERVERCERT env var */
  servercert = env_get("SMTP_SERVERCERT");
  if (!servercert) servercert = SERVERCERT;
  servercert2 = env_get("SMTP_SERVERCERT2");
  if (!servercert2) servercert2 = SERVERCERT2;

  SSL_library_init();

  /* a new SSL context with the bare minimum of options */
  ctx = SSL_CTX_new(TLS_server_method());
  if (!ctx) { tls_err("unable to initialize ctx"); return; }
  int min_ssl_version = (*childargs) ? TLS1_2_VERSION : TLS1_VERSION;
  SSL_CTX_set_min_proto_version(ctx, min_ssl_version);
  SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE |
                           SSL_OP_PRIORITIZE_CHACHA);

  /* set the callback here; SSL_set_verify didn't work before 0.9.6c */
  SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_cb);

  if (!SSL_CTX_use_certificate_chain_file(ctx, servercert))
    { SSL_CTX_free(ctx); tls_err("missing certificate"); return; }

  /* this will also check whether public and private keys match */
  if (!SSL_CTX_use_PrivateKey_file(ctx, servercert, SSL_FILETYPE_PEM))
    { SSL_CTX_free(ctx); tls_err("no valid private key"); return; }

  if (stat(servercert2, &st) == 0) {
    if (!SSL_CTX_use_certificate_chain_file(ctx, servercert2))
      { SSL_CTX_free(ctx); tls_err("invalid alternate certificate"); return; }
    if (!SSL_CTX_use_PrivateKey_file(ctx, servercert2, SSL_FILETYPE_PEM))
      { SSL_CTX_free(ctx); tls_err("no valid alternate private key"); return; }
  }

  /* a new SSL object, with the rest added to it directly to avoid copying */
  myssl = SSL_new(ctx);
  SSL_CTX_free(ctx);
  if (!myssl) { tls_err("unable to initialize ssl"); return; }

  ciphers = env_get("TLSCIPHERS");
  if (!ciphers) {
    if (control_readfile(&saciphers, "control/tlsserverciphers", 0) == -1)
      { SSL_free(myssl); die_control(); }
    if (saciphers.len) { /* convert all '\0's except the last one to ':' */
      int i;
      for (i = 0; i < saciphers.len - 1; ++i)
        if (!saciphers.s[i]) saciphers.s[i] = ':';
      ciphers = saciphers.s;
    }
  }
  if (!ciphers || !*ciphers) ciphers = "DEFAULT";
  SSL_set_cipher_list(myssl, ciphers);
  alloc_free(saciphers.s);

  SSL_set_dh_auto(myssl, 1);
  SSL_set_ecdh_auto(myssl, 1);

  stralloc opensslconf = {0};
  if (control_readfile(&opensslconf, "control/opensslconf", 0) == -1)
    { SSL_free(myssl); die_control(); }
  if (opensslconf.len) {
    SSL_CONF_CTX *cctx = SSL_CONF_CTX_new();
    SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE);
    /* client + server so we can share one single file */
    SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT);
    SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER);
    SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CERTIFICATE);
    SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SHOW_ERRORS);
    SSL_CONF_CTX_set_ssl(cctx, myssl);

    int i, j, next = 0;
    char *cmd, * arg;
    for (i = 0; i < opensslconf.len; i += next) {
      cmd = opensslconf.s + i;
      next = str_len(cmd) + 1;

      j = str_chr(cmd, ' ');
      arg = cmd + j;
      while (*arg == ' ') ++arg;
      cmd[j] = 0;

      if (SSL_CONF_cmd(cctx, cmd, arg) <= 0) {
        enew(); eout("opensslconf \""); eout(cmd); eout(" "); eout(arg);
        eout("\" failed: "); eout(ssl_error()); eout("\n"); eflush();
        tls_out("OpenSSL", "unable to initialize ssl");
        SSL_free(myssl);
        die_read();
      }
    }

    (void)SSL_CONF_CTX_finish(cctx);
  }

  SSL_set_rfd(myssl, ssl_rfd = substdio_fileno(&ssin));
  SSL_set_wfd(myssl, ssl_wfd = substdio_fileno(&ssout));

  if (!smtps) { out("220 ready for tls\r\n"); flush(); }

  if (ssl_timeoutaccept(timeout, ssl_rfd, ssl_wfd, myssl) <= 0) {
    /* neither cleartext nor any other response here is part of a standard */
    const char *err = ssl_error_str();
    ssl_free(myssl); tls_out("connection failed", err); die_read();
  }
  ssl = myssl;
  if (!env_put("SMTPSECURED=1")) die_nomem();

  /* populate the protocol string, used in Received */
  if (!stralloc_copys(&proto, "ESMTPS (")
    || !stralloc_cats(&proto, SSL_get_cipher(ssl))
    || !stralloc_cats(&proto, " encrypted)")) die_nomem();
  if (!stralloc_0(&proto)) die_nomem();
  protocol = proto.s;

  /* have to discard the pre-STARTTLS HELO/EHLO argument, if any */
  dohelo(remotehost);
}

#endif

struct commands smtpcommands[] = {
  { "rcpt", smtp_rcpt, 0 }
, { "mail", smtp_mail, 0 }
, { "data", smtp_data, flush }
, { "auth", smtp_auth, flush }
, { "quit", smtp_quit, flush }
, { "helo", smtp_helo, flush }
, { "ehlo", smtp_ehlo, flush }
, { "rset", smtp_rset, 0 }
, { "help", smtp_help, flush }
#ifdef TLS
, { "starttls", smtp_tls, flush_io }
#endif
, { "noop", err_noop, flush }
, { "vrfy", err_vrfy, flush }
, { 0, err_unimpl, flush }
} ;

void main(argc,argv)
int argc;
char **argv;
{
  int n, m;
  childargs = argv + 1;
  sig_pipeignore();
  if (chdir(auto_qmail) == -1) die_control();
  setup();
  if (ipme_init() != 1) die_ipme();
  if (spp_connect()) {
  if (!relayclient && greetdelay) {
    if (drop_pre_greet) {
      n = timeoutread(greetdelay ? greetdelay : 1, 0, ssinbuf, sizeof(ssinbuf));
      if(n == -1) {
        if (errno != error_timeout)
          strerr_die3sys(1, "GREETDELAY from ", remoteip, ": ");
      } else if (n == 0) {
        strerr_die3x(1, "GREETDELAY from ", remoteip, ": client disconnected");
      } else {
        strerr_warn3("GREETDELAY from ", remoteip, ": client sent data before greeting", 0);
        die_pre_greet();
      }
    }
    else {
      sleep(greetdelay);
      m = 0;
      for (;;) {
        n = timeoutread(0, 0, ssinbuf, sizeof(ssinbuf));
        if (n <= 0)
          break;
        if (n > 0 && m == 0) {
          strerr_warn3("GREETDELAY from ", remoteip, ": client sent data before greeting. ignoring", 0);
          m = 1;
        }
      }
    }
  }
  smtp_greet("220 ");
  out(" ESMTP\r\n");
  }
  if (commands(&ssin,&smtpcommands) == 0) die_read();
  die_nomem();
}