File: qmail-send.c

package info (click to toggle)
qmail 1.01-5
  • links: PTS
  • area: non-free
  • in suites: hamm
  • size: 2,188 kB
  • ctags: 1,711
  • sloc: ansic: 13,993; makefile: 1,914; perl: 448; sh: 377
file content (1652 lines) | stat: -rw-r--r-- 40,163 bytes parent folder | download
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
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
#include <sys/types.h>
#include <sys/stat.h>
#include "readwrite.h"
#include "sig.h"
#include "direntry.h"
#include "control.h"
#include "select.h"
#include "open.h"
#include "seek.h"
#include "exit.h"
#include "lock.h"
#include "ndelay.h"
#include "now.h"
#include "getln.h"
#include "substdio.h"
#include "alloc.h"
#include "error.h"
#include "stralloc.h"
#include "str.h"
#include "byte.h"
#include "fmt.h"
#include "scan.h"
#include "case.h"
#include "auto_qmail.h"
#include "trigger.h"
#include "newfield.h"
#include "quote.h"
#include "qmail.h"
#include "qsutil.h"
#include "prioq.h"
#include "constmap.h"
#include "fmtqfn.h"
#include "readsubdir.h"

/* critical timing feature #1: if not triggered, do not busy-loop */
/* critical timing feature #2: if triggered, respond within fixed time */
/* important timing feature: when triggered, respond instantly */
#define SLEEP_TODO 1500 /* check todo/ every 25 minutes in any case */
#define SLEEP_FUZZ 1 /* slop a bit on sleeps to avoid zeno effect */
#define SLEEP_FOREVER 86400 /* absolute maximum time spent in select() */
#define SLEEP_CLEANUP 76431 /* time between cleanups */
#define SLEEP_SYSFAIL 123
#define OSSIFIED 129600 /* 36 hours; _must_ exceed q-q's DEATH (24 hours) */

int lifetime = 604800;

stralloc percenthack = {0};
struct constmap mappercenthack;
stralloc locals = {0};
struct constmap maplocals;
stralloc redir = {0};
struct constmap mapredir;
stralloc vdoms = {0};
struct constmap mapvdoms;
stralloc envnoathost = {0};
stralloc bouncefrom = {0};
stralloc bouncehost = {0};
stralloc doublebounceto = {0};
stralloc doublebouncehost = {0};

char strnum2[FMT_ULONG];
char strnum3[FMT_ULONG];

#define CHANNELS 2
char *chanaddr[CHANNELS] = { "local/", "remote/" };
char *channodelmsg[CHANNELS] = {
  "local deliveries will be put on hold\n"
, "remote deliveries will be put on hold\n"
};
char *tochan[CHANNELS] = { " to local ", " to remote " };
int chanfdout[CHANNELS] = { 1, 3 };
int chanfdin[CHANNELS] = { 2, 4 };
int chanskip[CHANNELS] = { 10, 20 };

int flagexitasap = 0; void sigterm() { flagexitasap = 1; }
int flagrunasap = 0; void sigalrm() { flagrunasap = 1; }
int flagreadasap = 0; void sighup() { flagreadasap = 1; }

void cleandied() { log1("alert: oh no! lost qmail-clean connection! dying...\n");
 flagexitasap = 1; }

int flagspawnalive[CHANNELS];
void spawndied(c) int c; { log1("alert: oh no! lost spawn connection! dying...\n");
 flagspawnalive[c] = 0; flagexitasap = 1; }

#define REPORTMAX 10000

datetime_sec recent;


/* this file is too long ----------------------------------------- FILENAMES */

stralloc fn = {0};
stralloc fn2 = {0};
char fnmake_strnum[FMT_ULONG];

void fnmake_init()
{
 while (!stralloc_ready(&fn,FMTQFN)) nomem();
 while (!stralloc_ready(&fn2,FMTQFN)) nomem();
}

void fnmake_info(id) unsigned long id; { fn.len = fmtqfn(fn.s,"info/",id,1); }
void fnmake_todo(id) unsigned long id; { fn.len = fmtqfn(fn.s,"todo/",id,0); }
void fnmake_mess(id) unsigned long id; { fn.len = fmtqfn(fn.s,"mess/",id,1); }
void fnmake_foop(id) unsigned long id; { fn.len = fmtqfn(fn.s,"foop/",id,0); }
void fnmake_split(id) unsigned long id; { fn.len = fmtqfn(fn.s,"",id,1); }
void fnmake2_bounce(id) unsigned long id;
{ fn2.len = fmtqfn(fn2.s,"bounce/",id,0); }
void fnmake_chanaddr(id,c) unsigned long id; int c;
{ fn.len = fmtqfn(fn.s,chanaddr[c],id,1); }


/* this file is too long ----------------------------------------- REWRITING */

stralloc rwline = {0};

/* 1 if by land, 2 if by sea, 0 if out of memory. not allowed to barf. */
/* may trash recip. must set up rwline, between a T and a \0. */
int rewrite(recip)
char *recip;
{
  int i;
  int j;
  char *x;
  static stralloc addr = {0};
  static stralloc domain = {0};

  if (!stralloc_copys(&rwline,"T")) return 0;
  if (!stralloc_copys(&addr,recip)) return 0;

  i = byte_rchr(addr.s,addr.len,'@');
  if (i == addr.len) {
    if (!stralloc_cats(&addr,"@")) return 0;
    if (!stralloc_cat(&addr,&envnoathost)) return 0;
  }

  while (constmap(&mappercenthack,addr.s + i + 1,addr.len - i - 1)) {
    j = byte_rchr(addr.s,i,'%');
    if (j == i) break;
    addr.len = i;
    i = j;
    addr.s[i] = '@';
  }

  if (x = constmap(&mapredir,addr.s,addr.len))
    if (x[str_chr(x,'@')])
      if (!stralloc_copys(&addr,x)) return 0;

  i = byte_rchr(addr.s,addr.len,'@');
  if (!stralloc_copyb(&domain,addr.s + i + 1,addr.len - i - 1)) return 0;
  addr.len = i;

  if (constmap(&maplocals,domain.s,domain.len)) {
    if (!stralloc_cat(&rwline,&addr)) return 0;
    if (!stralloc_cats(&rwline,"@")) return 0;
    if (!stralloc_cat(&rwline,&domain)) return 0;
    if (!stralloc_0(&rwline)) return 0;
    return 1;
  }

  for (i = 0;i <= domain.len;++i)
    if ((i == 0) || (i == domain.len) || (domain.s[i] == '.'))
      if (x = constmap(&mapvdoms,domain.s + i,domain.len - i)) {
        if (!*x) break;
        if (!stralloc_cats(&rwline,x)) return 0;
        if (!stralloc_cats(&rwline,"-")) return 0;
        if (!stralloc_cat(&rwline,&addr)) return 0;
        if (!stralloc_cats(&rwline,"@")) return 0;
        if (!stralloc_cat(&rwline,&domain)) return 0;
        if (!stralloc_0(&rwline)) return 0;
        return 1;
      }
 
  if (!stralloc_cat(&rwline,&addr)) return 0;
  if (!stralloc_cats(&rwline,"@")) return 0;
  if (!stralloc_cat(&rwline,&domain)) return 0;
  if (!stralloc_0(&rwline)) return 0;
  return 2;
}

void senderadd(sa,sender,recip)
stralloc *sa;
char *sender;
char *recip;
{
 int i;
 int j;
 int k;

 i = str_len(sender);
 if (i >= 4)
   if (str_equal(sender + i - 4,"-@[]"))
    {
     j = byte_rchr(sender,i - 4,'@');
     k = str_rchr(recip,'@');
     if (recip[k] && (j + 5 <= i))
      {
       /* owner-@host-@[] -> owner-recipbox=reciphost@host */
       while (!stralloc_catb(sa,sender,j)) nomem();
       while (!stralloc_catb(sa,recip,k)) nomem();
       while (!stralloc_cats(sa,"=")) nomem();
       while (!stralloc_cats(sa,recip + k + 1)) nomem();
       while (!stralloc_cats(sa,"@")) nomem();
       while (!stralloc_catb(sa,sender + j + 1,i - 5 - j)) nomem();
       return;
      }
    }
 while (!stralloc_cats(sa,sender)) nomem();
}


/* this file is too long ---------------------------------------------- INFO */

int getinfo(sa,dt,id)
stralloc *sa;
datetime_sec *dt;
unsigned long id;
{
 int fdinfo;
 struct stat st;
 static stralloc line = {0};
 int match;
 substdio ss;
 char buf[128];

 fnmake_info(id);
 fdinfo = open_read(fn.s);
 if (fdinfo == -1) return 0;
 if (fstat(fdinfo,&st) == -1) { close(fdinfo); return 0; }
 substdio_fdbuf(&ss,read,fdinfo,buf,sizeof(buf));
 if (getln(&ss,&line,&match,'\0') == -1) { close(fdinfo); return 0; }
 close(fdinfo);
 if (!match) return 0;
 if (line.s[0] != 'F') return 0;

 *dt = st.st_mtime;
 while (!stralloc_copys(sa,line.s + 1)) nomem();
 while (!stralloc_0(sa)) nomem();
 return 1;
}


/* this file is too long ------------------------------------- COMMUNICATION */

substdio sstoqc; char sstoqcbuf[1024];
substdio ssfromqc; char ssfromqcbuf[1024];
stralloc comm_buf[CHANNELS] = { {0}, {0} };
int comm_pos[CHANNELS];

void comm_init()
{
 int c;
 substdio_fdbuf(&sstoqc,write,5,sstoqcbuf,sizeof(sstoqcbuf));
 substdio_fdbuf(&ssfromqc,read,6,ssfromqcbuf,sizeof(ssfromqcbuf));
 for (c = 0;c < CHANNELS;++c)
   if (ndelay_on(chanfdout[c]) == -1)
   /* this is so stupid: NDELAY semantics should be default on write */
     spawndied(c); /* drastic, but better than risking deadlock */
}

int comm_canwrite(c)
int c;
{
 /* XXX: could allow a bigger buffer; say 10 recipients */
 if (comm_buf[c].s && comm_buf[c].len) return 0;
 return 1;
}

void comm_write(c,delnum,id,sender,recip)
int c;
int delnum;
unsigned long id;
char *sender;
char *recip;
{
 char ch;
 if (comm_buf[c].s && comm_buf[c].len) return;
 while (!stralloc_copys(&comm_buf[c],"")) nomem();
 ch = delnum;
 while (!stralloc_append(&comm_buf[c],&ch)) nomem();
 fnmake_split(id);
 while (!stralloc_cats(&comm_buf[c],fn.s)) nomem();
 while (!stralloc_0(&comm_buf[c])) nomem();
 senderadd(&comm_buf[c],sender,recip);
 while (!stralloc_0(&comm_buf[c])) nomem();
 while (!stralloc_cats(&comm_buf[c],recip)) nomem();
 while (!stralloc_0(&comm_buf[c])) nomem();
 comm_pos[c] = 0;
}

void comm_selprep(nfds,wfds)
int *nfds;
fd_set *wfds;
{
 int c;
 for (c = 0;c < CHANNELS;++c)
   if (flagspawnalive[c])
     if (comm_buf[c].s && comm_buf[c].len)
      {
       FD_SET(chanfdout[c],wfds);
       if (*nfds <= chanfdout[c])
         *nfds = chanfdout[c] + 1;
      }
}

void comm_do(wfds)
fd_set *wfds;
{
 int c;
 for (c = 0;c < CHANNELS;++c)
   if (flagspawnalive[c])
     if (comm_buf[c].s && comm_buf[c].len)
       if (FD_ISSET(chanfdout[c],wfds))
        {
         int w;
         int len;
         len = comm_buf[c].len;
         w = write(chanfdout[c],comm_buf[c].s + comm_pos[c],len - comm_pos[c]);
         if (w <= 0)
	  {
	   if ((w == -1) && (errno == error_pipe))
	     spawndied(c);
	   else
	     continue; /* kernel select() bug; can't avoid busy-looping */
	  }
	 else
	  {
	   comm_pos[c] += w;
	   if (comm_pos[c] == len)
	     comm_buf[c].len = 0;
	  }
        }
}


/* this file is too long ------------------------------------------ CLEANUPS */

int flagcleanup; /* if 1, cleanupdir is initialized and ready */
readsubdir cleanupdir;
datetime_sec cleanuptime;

void cleanup_init()
{
 flagcleanup = 0;
 cleanuptime = now();
}

void cleanup_selprep(wakeup)
datetime_sec *wakeup;
{
 if (flagcleanup) *wakeup = 0;
 if (*wakeup > cleanuptime) *wakeup = cleanuptime;
}

void cleanup_do()
{
 char ch;
 struct stat st;
 unsigned long id;

 if (!flagcleanup)
  {
   if (recent < cleanuptime) return;
   readsubdir_init(&cleanupdir,"mess",pausedir);
   flagcleanup = 1;
  }

 switch(readsubdir_next(&cleanupdir,&id))
  {
   case 1:
     break;
   case 0:
     flagcleanup = 0;
     cleanuptime = recent + SLEEP_CLEANUP;
   default:
     return;
  }

 fnmake_mess(id);
 if (stat(fn.s,&st) == -1) return; /* probably qmail-queue deleted it */
 if (recent <= st.st_atime + OSSIFIED) return;

 fnmake_info(id);
 if (stat(fn.s,&st) == 0) return;
 if (errno != error_noent) return;
 fnmake_todo(id);
 if (stat(fn.s,&st) == 0) return;
 if (errno != error_noent) return;

 fnmake_foop(id);
 if (substdio_putflush(&sstoqc,fn.s,fn.len) == -1) { cleandied(); return; }
 if (substdio_get(&ssfromqc,&ch,1) != 1) { cleandied(); return; }
 if (ch != '+')
   log3("warning: qmail-clean unable to clean up ",fn.s,"\n");
}


/* this file is too long ----------------------------------- PRIORITY QUEUES */

prioq pqdone = {0}; /* -todo +info; HOPEFULLY -local -remote */
prioq pqchan[CHANNELS] = { {0}, {0} };
/* pqchan 0: -todo +info +local ?remote */
/* pqchan 1: -todo +info ?local +remote */
prioq pqfail = {0}; /* stat() failure; has to be pqadded again */

void pqadd(id)
unsigned long id;
{
 struct prioq_elt pe;
 struct prioq_elt pechan[CHANNELS];
 int flagchan[CHANNELS];
 struct stat st;
 int c;

#define CHECKSTAT if (errno != error_noent) goto fail;

 fnmake_info(id);
 if (stat(fn.s,&st) == -1)
  {
   CHECKSTAT
   return; /* someone yanking our chain */
  }

 fnmake_todo(id);
 if (stat(fn.s,&st) != -1) return; /* look, ma, dad crashed writing info! */
 CHECKSTAT

 for (c = 0;c < CHANNELS;++c)
  {
   fnmake_chanaddr(id,c);
   if (stat(fn.s,&st) == -1) { flagchan[c] = 0; CHECKSTAT }
   else { flagchan[c] = 1; pechan[c].id = id; pechan[c].dt = st.st_mtime; }
  }

 for (c = 0;c < CHANNELS;++c)
   if (flagchan[c])
     while (!prioq_insert(&pqchan[c],&pechan[c])) nomem();

 for (c = 0;c < CHANNELS;++c) if (flagchan[c]) break;
 if (c == CHANNELS)
  {
   pe.id = id; pe.dt = now();
   while (!prioq_insert(&pqdone,&pe)) nomem();
  }

 return;

 fail:
 log3("warning: unable to stat ",fn.s,"; will try again later\n");
 pe.id = id; pe.dt = now() + SLEEP_SYSFAIL;
 while (!prioq_insert(&pqfail,&pe)) nomem();
}

void pqstart()
{
 readsubdir rs;
 int x;
 unsigned long id;

 readsubdir_init(&rs,"info",pausedir);

 while (x = readsubdir_next(&rs,&id))
   if (x > 0)
     pqadd(id);
}

void pqfinish()
{
 int c;
 struct prioq_elt pe;
 time_t ut[2]; /* XXX: more portable than utimbuf, but still worrisome */

 for (c = 0;c < CHANNELS;++c)
   while (prioq_min(&pqchan[c],&pe))
    {
     prioq_delmin(&pqchan[c]);
     fnmake_chanaddr(pe.id,c);
     ut[0] = ut[1] = pe.dt;
     if (utime(fn.s,ut) == -1)
       log3("warning: unable to utime ",fn.s,"; message will be retried too soon\n");
    }
}

void pqrun()
{
 int c;
 int i;
 for (c = 0;c < CHANNELS;++c)
   if (pqchan[c].p)
     if (pqchan[c].len)
       for (i = 0;i < pqchan[c].len;++i)
	 pqchan[c].p[i].dt = recent;
}


/* this file is too long ---------------------------------------------- JOBS */

struct job
 {
  int refs; /* if 0, this struct is unused */
  unsigned long id;
  int channel;
  datetime_sec retry;
  stralloc sender;
  int numtodo;
  int flaghiteof;
  int flagdying;
 }
;

int numjobs;
struct job *jo;

void job_init()
{
 int j;
 while (!(jo = (struct job *) alloc(numjobs * sizeof(struct job)))) nomem();
 for (j = 0;j < numjobs;++j)
  {
   jo[j].refs = 0;
   jo[j].sender.s = 0;
  }
}

int job_avail()
{
 int j;
 for (j = 0;j < numjobs;++j) if (!jo[j].refs) return 1;
 return 0;
}

int job_open(id,channel)
unsigned long id;
int channel;
{
 int j;
 for (j = 0;j < numjobs;++j) if (!jo[j].refs) break;
 if (j == numjobs) return -1;
 jo[j].refs = 1;
 jo[j].id = id;
 jo[j].channel = channel;
 jo[j].numtodo = 0;
 jo[j].flaghiteof = 0;
 return j;
}

void job_close(j)
int j;
{
 struct prioq_elt pe;
 struct stat st;

 if (0 < --jo[j].refs) return;

 pe.id = jo[j].id;
 pe.dt = jo[j].retry;
 if (jo[j].flaghiteof && !jo[j].numtodo)
  {
   fnmake_chanaddr(jo[j].id,jo[j].channel);
   if (unlink(fn.s) == -1)
    {
     log3("warning: unable to unlink ",fn.s,"; will try again later\n");
     pe.dt = now() + SLEEP_SYSFAIL;
    }
   else
    {
     int c;
     for (c = 0;c < CHANNELS;++c) if (c != jo[j].channel)
      {
       fnmake_chanaddr(jo[j].id,c);
       if (stat(fn.s,&st) == 0) return; /* more channels going */
       if (errno != error_noent)
	{
         log3("warning: unable to stat ",fn.s,"\n");
	 break; /* this is the only reason for HOPEFULLY */
	}
      }
     pe.dt = now();
     while (!prioq_insert(&pqdone,&pe)) nomem();
     return;
    }
  }

 while (!prioq_insert(&pqchan[jo[j].channel],&pe)) nomem();
}


/* this file is too long ------------------------------------------- BOUNCES */

char *stripvdomprepend(recip)
char *recip;
{
 int i;
 char *domain;
 int domainlen;
 char *prepend;

 i = str_rchr(recip,'@');
 if (!recip[i]) return recip;
 domain = recip + i + 1;
 domainlen = str_len(domain);

 for (i = 0;i <= domainlen;++i)
   if ((i == 0) || (i == domainlen) || (domain[i] == '.'))
     if (prepend = constmap(&mapvdoms,domain + i,domainlen - i))
      {
       if (!*prepend) break;
       i = str_len(prepend);
       if (str_diffn(recip,prepend,i)) break;
       if (recip[i] != '-') break;
       return recip + i + 1;
      }
 return recip;
}

stralloc bouncetext = {0};

void addbounce(id,recip,report)
unsigned long id;
char *recip;
char *report;
{
 int fd;
 int pos;
 int w;
 while (!stralloc_copys(&bouncetext,"<")) nomem();
 while (!stralloc_cats(&bouncetext,stripvdomprepend(recip))) nomem();
 for (pos = 0;pos < bouncetext.len;++pos)
   if (bouncetext.s[pos] == '\n')
     bouncetext.s[pos] = '_';
 while (!stralloc_cats(&bouncetext,">:\n")) nomem();
 while (!stralloc_cats(&bouncetext,report)) nomem();
 if (report[0])
   if (report[str_len(report) - 1] != '\n')
     while (!stralloc_cats(&bouncetext,"\n")) nomem();
 for (pos = bouncetext.len - 2;pos > 0;--pos)
   if (bouncetext.s[pos] == '\n')
     if (bouncetext.s[pos - 1] == '\n')
       bouncetext.s[pos] = '/';
 while (!stralloc_cats(&bouncetext,"\n")) nomem();
 fnmake2_bounce(id);
 for (;;)
  {
   fd = open_append(fn2.s);
   if (fd != -1) break;
   log1("alert: unable to append to bounce message; HELP! sleeping...\n");
   sleep(10);
  }
 pos = 0;
 while (pos < bouncetext.len)
  {
   w = write(fd,bouncetext.s + pos,bouncetext.len - pos);
   if (w <= 0)
    {
     log1("alert: unable to append to bounce message; HELP! sleeping...\n");
     sleep(10);
    }
   else
     pos += w;
  }
 close(fd);
}

int injectbounce(id)
unsigned long id;
{
 struct qmail qqt;
 struct stat st;
 char *bouncesender;
 char *bouncerecip;
 int r;
 int fd;
 substdio ssread;
 char buf[128];
 char inbuf[128];
 static stralloc sender = {0};
 static stralloc quoted = {0};
 datetime_sec birth;
 unsigned long qp;

 if (!getinfo(&sender,&birth,id)) return 0; /* XXX: print warning */

 /* owner-@host-@[] -> owner-@host */
 if (sender.len >= 5)
   if (str_equal(sender.s + sender.len - 5,"-@[]"))
    {
     sender.len -= 4;
     sender.s[sender.len - 1] = 0;
    }

 fnmake2_bounce(id);
 fnmake_mess(id);
 if (stat(fn2.s,&st) == -1)
  {
   if (errno == error_noent)
     return 1;
   log3("warning: unable to stat ",fn2.s,"\n");
   return 0;
  }
 if (str_equal(sender.s,"#@[]"))
   log3("triple bounce: discarding ",fn2.s,"\n");
 else
  {
   if (qmail_open(&qqt) == -1)
    { log1("warning: unable to start qmail-queue, will try later\n"); return 0; }
   qp = qmail_qp(&qqt);

   if (*sender.s) { bouncesender = ""; bouncerecip = sender.s; }
   else { bouncesender = "#@[]"; bouncerecip = doublebounceto.s; }

   while (!newfield_datemake(now())) nomem();
   qmail_put(&qqt,newfield_date.s,newfield_date.len);
   qmail_puts(&qqt,"From: ");
   while (!quote(&quoted,&bouncefrom)) nomem();
   qmail_put(&qqt,quoted.s,quoted.len);
   qmail_puts(&qqt,"@");
   qmail_put(&qqt,bouncehost.s,bouncehost.len);
   qmail_puts(&qqt,"\nTo: ");
   while (!quote2(&quoted,bouncerecip)) nomem();
   qmail_put(&qqt,quoted.s,quoted.len);
   qmail_puts(&qqt,"\n\
Subject: failure notice\n\
\n\
Hi. This is the qmail-send program at ");
   qmail_put(&qqt,bouncehost.s,bouncehost.len);
   qmail_puts(&qqt,*sender.s ? ".\n\
I'm afraid I wasn't able to deliver your message to the following addresses.\n\
This is a permanent error; I've given up. Sorry it didn't work out.\n\
\n\
" : ".\n\
I tried to deliver a bounce message to this address, but the bounce bounced!\n\
\n\
");

   fd = open_read(fn2.s);
   if (fd == -1)
     qmail_fail(&qqt);
   else
    {
     substdio_fdbuf(&ssread,read,fd,inbuf,sizeof(inbuf));
     while ((r = substdio_get(&ssread,buf,sizeof(buf))) > 0)
       qmail_put(&qqt,buf,r);
     close(fd);
     if (r == -1)
       qmail_fail(&qqt);
    }

   qmail_puts(&qqt,*sender.s ? "--- Below this line is a copy of the message.\n\n" : "--- Below this line is the original bounce.\n\n");
   qmail_puts(&qqt,"Return-Path: <");
   while (!quote2(&quoted,sender.s)) nomem();
   qmail_put(&qqt,quoted.s,quoted.len);
   qmail_puts(&qqt,">\n");

   fd = open_read(fn.s);
   if (fd == -1)
     qmail_fail(&qqt);
   else
    {
     substdio_fdbuf(&ssread,read,fd,inbuf,sizeof(inbuf));
     while ((r = substdio_get(&ssread,buf,sizeof(buf))) > 0)
       qmail_put(&qqt,buf,r);
     close(fd);
     if (r == -1)
       qmail_fail(&qqt);
    }

   qmail_from(&qqt,bouncesender);
   qmail_to(&qqt,bouncerecip);
   if (qmail_close(&qqt))
    { log1("warning: trouble injecting bounce message, will try later\n"); return 0; }

   strnum2[fmt_ulong(strnum2,id)] = 0;
   log2("bounce msg ",strnum2);
   strnum2[fmt_ulong(strnum2,qp)] = 0;
   log3(" qp ",strnum2,"\n");
  }
 if (unlink(fn2.s) == -1)
  {
   log3("warning: unable to unlink ",fn2.s,"\n");
   return 0;
  }
 return 1;
}


/* this file is too long ---------------------------------------- DELIVERIES */

struct del
 {
  int used;
  int j;
  unsigned long delid;
  seek_pos mpos;
  stralloc recip;
 }
;

unsigned long masterdelid = 1;
unsigned int concurrency[CHANNELS] = { 10, 20 };
struct del *d[CHANNELS];
stralloc dline[CHANNELS];
char delbuf[2048];

void del_init()
{
 int c;
 int i;
 for (c = 0;c < CHANNELS;++c)
  {
   flagspawnalive[c] = 1;
   while (!(d[c] = (struct del *) alloc(concurrency[c] * sizeof(struct del))))
     nomem();
   for (i = 0;i < concurrency[c];++i)
    { d[c][i].used = 0; d[c][i].recip.s = 0; }
   dline[c].s = 0;
   while (!stralloc_copys(&dline[c],"")) nomem();
  }
}

int del_canexit()
{
 int i;
 int c;
 for (c = 0;c < CHANNELS;++c)
   if (flagspawnalive[c]) /* if dead, nothing we can do about its jobs */
     for (i = 0;i < concurrency[c];++i)
       if (d[c][i].used) return 0;
 return 1;
}

static int del_lastsaid = 0;

void del_saywhynoexit()
{
 int i;
 int c;
 int n;
 n = 0;
 for (c = 0;c < CHANNELS;++c)
   if (flagspawnalive[c])
     for (i = 0;i < concurrency[c];++i)
       if (d[c][i].used)
	 ++n;
 if (!del_lastsaid || (n < del_lastsaid))
  {
   strnum2[fmt_ulong(strnum2,(unsigned long) n)] = 0;
   log3("number of deliveries left before exiting: ",strnum2,"\n");
   del_lastsaid = n;
  }
}

int del_avail(c)
int c;
{
 int i;

 if (!flagspawnalive[c]) return 0;
 if (!comm_canwrite(c)) return 0;
 for (i = 0;i < concurrency[c];++i) if (!d[c][i].used) return 1;
 return 0;
}

void del_start(j,mpos,recip)
int j;
seek_pos mpos;
char *recip;
{
 int i;
 int c;

 c = jo[j].channel;
 if (!flagspawnalive[c]) return;
 if (!comm_canwrite(c)) return;

 for (i = 0;i < concurrency[c];++i) if (!d[c][i].used) break;
 if (i == concurrency[c]) return;

 if (!stralloc_copys(&d[c][i].recip,recip)) { nomem(); return; }
 if (!stralloc_0(&d[c][i].recip)) { nomem(); return; }
 d[c][i].j = j; ++jo[j].refs;
 d[c][i].delid = masterdelid++;
 d[c][i].mpos = mpos;
 d[c][i].used = 1;

 comm_write(c,i,jo[j].id,jo[j].sender.s,recip);

 strnum2[fmt_ulong(strnum2,d[c][i].delid)] = 0;
 strnum3[fmt_ulong(strnum3,jo[j].id)] = 0;
 log2("starting delivery ",strnum2);
 log3(": msg ",strnum3,tochan[c]);
 logsafe(recip);
 log1("\n");
}

void markdone(c,id,pos)
int c;
unsigned long id;
seek_pos pos;
{
 struct stat st;
 int fd;
 fnmake_chanaddr(id,c);
 for (;;)
  {
   fd = open_write(fn.s);
   if (fd == -1) break;
   if (fstat(fd,&st) == -1) { close(fd); break; }
   if (seek_set(fd,pos) == -1) { close(fd); break; }
   if (write(fd,"D",1) != 1) { close(fd); break; }
   /* further errors -> double delivery without us knowing about it, oh well */
   close(fd);
   return;
  }
 log3("warning: trouble marking ",fn.s,"; message will be delivered twice!\n");
}

void del_dochan(c)
int c;
{
 int r;
 char ch;
 int i;
 int delnum;
 r = read(chanfdin[c],delbuf,sizeof(delbuf));
 if (r == -1) return;
 if (r == 0) { spawndied(c); return; }
 for (i = 0;i < r;++i)
  {
   ch = delbuf[i];
   while (!stralloc_append(&dline[c],&ch)) nomem();
   if (dline[c].len > REPORTMAX)
     dline[c].len = REPORTMAX;
     /* qmail-lspawn and qmail-rspawn are responsible for keeping it short */
     /* but from a security point of view, we don't trust rspawn */
   if (!ch && (dline[c].len > 1))
    {
     delnum = (unsigned int) (unsigned char) dline[c].s[0];
     if ((delnum < 0) || (delnum >= concurrency[c]) || !d[c][delnum].used)
       log1("warning: internal error: delivery report out of range\n");
     else
      {
       strnum3[fmt_ulong(strnum3,d[c][delnum].delid)] = 0;
       if (dline[c].s[1] == 'Z')
	 if (jo[d[c][delnum].j].flagdying)
	  {
	   dline[c].s[1] = 'D';
	   --dline[c].len;
	   while (!stralloc_cats(&dline[c],"I'm not going to try again; this message has been in the queue too long.\n")) nomem();
	   while (!stralloc_0(&dline[c])) nomem();
	  }
       switch(dline[c].s[1])
	{
	 case 'K':
	   log3("delivery ",strnum3,": success: ");
	   logsafe(dline[c].s + 2);
	   log1("\n");
	   markdone(c,jo[d[c][delnum].j].id,d[c][delnum].mpos);
	   --jo[d[c][delnum].j].numtodo;
	   break;
	 case 'Z':
	   log3("delivery ",strnum3,": deferral: ");
	   logsafe(dline[c].s + 2);
	   log1("\n");
	   break;
	 case 'D':
	   log3("delivery ",strnum3,": failure: ");
	   logsafe(dline[c].s + 2);
	   log1("\n");
	   addbounce(jo[d[c][delnum].j].id,d[c][delnum].recip.s,dline[c].s + 2);
	   markdone(c,jo[d[c][delnum].j].id,d[c][delnum].mpos);
	   --jo[d[c][delnum].j].numtodo;
	   break;
	 default:
	   log3("delivery ",strnum3,": report mangled, will defer\n");
	}
       job_close(d[c][delnum].j);
       d[c][delnum].used = 0;
      }
     dline[c].len = 0;
    }
  }
}

void del_selprep(nfds,rfds)
int *nfds;
fd_set *rfds;
{
 int c;
 for (c = 0;c < CHANNELS;++c)
   if (flagspawnalive[c])
    {
     FD_SET(chanfdin[c],rfds);
     if (*nfds <= chanfdin[c])
       *nfds = chanfdin[c] + 1;
    }
}

void del_do(rfds)
fd_set *rfds;
{
 int c;
 for (c = 0;c < CHANNELS;++c)
   if (flagspawnalive[c])
     if (FD_ISSET(chanfdin[c],rfds))
       del_dochan(c);
}


/* this file is too long -------------------------------------------- PASSES */

struct
 {
  unsigned long id; /* if 0, need a new pass */
  int j; /* defined if id; job number */
  int fd; /* defined if id; reading from {local,remote} */
  seek_pos mpos; /* defined if id; mark position */
  substdio ss;
  char buf[128];
 }
pass[CHANNELS];

void pass_init()
{
 int c;
 for (c = 0;c < CHANNELS;++c) pass[c].id = 0;
}

void pass_selprep(wakeup)
datetime_sec *wakeup;
{
 int c;
 struct prioq_elt pe;
 if (flagexitasap) return;
 for (c = 0;c < CHANNELS;++c)
   if (pass[c].id)
     if (del_avail(c))
      { *wakeup = 0; return; }
 if (job_avail())
   for (c = 0;c < CHANNELS;++c)
     if (!pass[c].id)
       if (prioq_min(&pqchan[c],&pe))
         if (*wakeup > pe.dt)
           *wakeup = pe.dt;
 if (prioq_min(&pqfail,&pe))
   if (*wakeup > pe.dt)
     *wakeup = pe.dt;
 if (prioq_min(&pqdone,&pe))
   if (*wakeup > pe.dt)
     *wakeup = pe.dt;
}

static datetime_sec squareroot(x) /* result^2 <= x < (result + 1)^2 */
datetime_sec x; /* assuming: >= 0 */
{
 datetime_sec y;
 datetime_sec yy;
 datetime_sec y21;
 int j;

 y = 0; yy = 0;
 for (j = 15;j >= 0;--j)
  {
   y21 = (y << (j + 1)) + (1 << (j + j));
   if (y21 <= x - yy) { y += (1 << j); yy += y21; }
  }
 return y;
}

datetime_sec nextretry(birth,c)
datetime_sec birth;
int c;
{
 int n;

 if (birth > recent) n = 0;
 else n = squareroot(recent - birth); /* no need to add fuzz to recent */
 n += chanskip[c];
 return birth + n * n;
}

void pass_dochan(c)
int c;
{
 datetime_sec birth;
 struct prioq_elt pe;
 static stralloc line = {0};
 int match;

 if (flagexitasap) return;

 if (!pass[c].id)
  {
   if (!job_avail()) return;
   if (!prioq_min(&pqchan[c],&pe)) return;
   if (pe.dt > recent) return;
   fnmake_chanaddr(pe.id,c);

   prioq_delmin(&pqchan[c]);
   pass[c].mpos = 0;
   pass[c].fd = open_read(fn.s);
   if (pass[c].fd == -1) goto trouble;
   if (!getinfo(&line,&birth,pe.id)) { close(pass[c].fd); goto trouble; }
   pass[c].id = pe.id;
   substdio_fdbuf(&pass[c].ss,read,pass[c].fd,pass[c].buf,sizeof(pass[c].buf));
   pass[c].j = job_open(pe.id,c);
   jo[pass[c].j].retry = nextretry(birth,c);
   jo[pass[c].j].flagdying = (recent > birth + lifetime);
   while (!stralloc_copy(&jo[pass[c].j].sender,&line)) nomem();
  }

 if (!del_avail(c)) return;

 if (getln(&pass[c].ss,&line,&match,'\0') == -1)
  {
   fnmake_chanaddr(pass[c].id,c);
   log3("warning: trouble reading ",fn.s,"; will try again later\n");
   close(pass[c].fd);
   job_close(pass[c].j);
   pass[c].id = 0;
   return;
  }
 if (!match)
  {
   close(pass[c].fd);
   jo[pass[c].j].flaghiteof = 1;
   job_close(pass[c].j);
   pass[c].id = 0;
   return;
  }
 switch(line.s[0])
  {
   case 'T':
     ++jo[pass[c].j].numtodo;
     del_start(pass[c].j,pass[c].mpos,line.s + 1);
     break;
   case 'D':
     break;
   default:
     fnmake_chanaddr(pass[c].id,c);
     log3("warning: unknown record type in ",fn.s,"!\n");
     close(pass[c].fd);
     job_close(pass[c].j);
     pass[c].id = 0;
     return;
  }

 pass[c].mpos += line.len;
 return;

 trouble:
 log3("warning: trouble opening ",fn.s,"; will try again later\n");
 pe.dt = recent + SLEEP_SYSFAIL;
 while (!prioq_insert(&pqchan[c],&pe)) nomem();
}

void messdone(id)
unsigned long id;
{
 char ch;
 int c;
 struct prioq_elt pe;
 struct stat st;

 for (c = 0;c < CHANNELS;++c)
  {
   fnmake_chanaddr(id,c);
   if (stat(fn.s,&st) == 0) return; /* false alarm; consequence of HOPEFULLY */
   if (errno != error_noent)
    {
     log3("warning: unable to stat ",fn.s,"; will try again later\n");
     goto fail;
    }
  }

 fnmake_todo(id);
 if (stat(fn.s,&st) == 0) return;
 if (errno != error_noent)
  {
   log3("warning: unable to stat ",fn.s,"; will try again later\n");
   goto fail;
  }
 
 fnmake_info(id);
 if (stat(fn.s,&st) == -1)
  {
   if (errno == error_noent) return;
   log3("warning: unable to stat ",fn.s,"; will try again later\n");
   goto fail;
  }
 
 /* -todo +info -local -remote ?bounce */
 if (!injectbounce(id))
   goto fail; /* injectbounce() produced error message */

 strnum3[fmt_ulong(strnum3,id)] = 0;
 log3("end msg ",strnum3,"\n");

 /* -todo +info -local -remote -bounce */
 fnmake_info(id);
 if (unlink(fn.s) == -1)
  {
   log3("warning: unable to unlink ",fn.s,"; will try again later\n");
   goto fail;
  }

 /* -todo -info -local -remote -bounce; we can relax */
 fnmake_foop(id);
 if (substdio_putflush(&sstoqc,fn.s,fn.len) == -1) { cleandied(); return; }
 if (substdio_get(&ssfromqc,&ch,1) != 1) { cleandied(); return; }
 if (ch != '+')
   log3("warning: qmail-clean unable to clean up ",fn.s,"\n");

 return;

 fail:
 pe.id = id; pe.dt = now() + SLEEP_SYSFAIL;
 while (!prioq_insert(&pqdone,&pe)) nomem();
}

void pass_do()
{
 int c;
 struct prioq_elt pe;

 for (c = 0;c < CHANNELS;++c) pass_dochan(c);
 if (prioq_min(&pqfail,&pe))
   if (pe.dt <= recent)
    {
     prioq_delmin(&pqfail);
     pqadd(pe.id);
    }
 if (prioq_min(&pqdone,&pe))
   if (pe.dt <= recent)
    {
     prioq_delmin(&pqdone);
     messdone(pe.id);
    }
}


/* this file is too long ---------------------------------------------- TODO */

datetime_sec nexttodorun;
DIR *tododir; /* if 0, have to opendir again */
stralloc todoline = {0};
char todobuf[SUBSTDIO_INSIZE];
char todobufinfo[512];
char todobufchan[CHANNELS][1024];

void todo_init()
{
 tododir = 0;
 nexttodorun = now();
 trigger_set();
}

void todo_selprep(nfds,rfds,wakeup)
int *nfds;
fd_set *rfds;
datetime_sec *wakeup;
{
 if (flagexitasap) return;
 trigger_selprep(nfds,rfds);
 if (tododir) *wakeup = 0;
 if (*wakeup > nexttodorun) *wakeup = nexttodorun;
}

void todo_do(rfds)
fd_set *rfds;
{
 struct stat st;
 substdio ss; int fd;
 substdio ssinfo; int fdinfo;
 substdio sschan[CHANNELS];
 int fdchan[CHANNELS];
 int flagchan[CHANNELS];
 struct prioq_elt pe;
 char ch;
 int match;
 unsigned long id;
 unsigned int len;
 direntry *d;
 int c;
 unsigned long uid;
 unsigned long pid;

 fd = -1;
 fdinfo = -1;
 for (c = 0;c < CHANNELS;++c) fdchan[c] = -1;

 if (flagexitasap) return;

 if (!tododir)
  {
   if (!trigger_pulled(rfds))
     if (recent < nexttodorun)
       return;
   trigger_set();
   tododir = opendir("todo");
   if (!tododir)
    {
     pausedir("todo");
     return;
    }
   nexttodorun = recent + SLEEP_TODO;
  }

 d = readdir(tododir);
 if (!d)
  {
   closedir(tododir);
   tododir = 0;
   return;
  }
 if (str_equal(d->d_name,".")) return;
 if (str_equal(d->d_name,"..")) return;
 len = scan_ulong(d->d_name,&id);
 if (!len || d->d_name[len]) return;

 fnmake_todo(id);

 fd = open_read(fn.s);
 if (fd == -1) { log3("warning: unable to open ",fn.s,"\n"); return; }

 fnmake_mess(id);
 /* just for the statistics */
 if (stat(fn.s,&st) == -1)
  { log3("warning: unable to stat ",fn.s,"\n"); goto fail; }

 for (c = 0;c < CHANNELS;++c)
  {
   fnmake_chanaddr(id,c);
   if (unlink(fn.s) == -1) if (errno != error_noent)
    { log3("warning: unable to unlink ",fn.s,"\n"); goto fail; }
  }

 fnmake_info(id);
 if (unlink(fn.s) == -1) if (errno != error_noent)
  { log3("warning: unable to unlink ",fn.s,"\n"); goto fail; }

 fdinfo = open_excl(fn.s);
 if (fdinfo == -1)
  { log3("warning: unable to create ",fn.s,"\n"); goto fail; }

 strnum3[fmt_ulong(strnum3,id)] = 0;
 log3("new msg ",strnum3,"\n");

 for (c = 0;c < CHANNELS;++c) flagchan[c] = 0;

 substdio_fdbuf(&ss,read,fd,todobuf,sizeof(todobuf));
 substdio_fdbuf(&ssinfo,write,fdinfo,todobufinfo,sizeof(todobufinfo));

 uid = 0;
 pid = 0;

 for (;;)
  {
   if (getln(&ss,&todoline,&match,'\0') == -1)
    {
     /* perhaps we're out of memory, perhaps an I/O error */
     fnmake_todo(id);
     log3("warning: trouble reading ",fn.s,"\n"); goto fail;
    }
   if (!match) break;

   switch(todoline.s[0])
    {
     case 'u':
       scan_ulong(todoline.s + 1,&uid);
       break;
     case 'p':
       scan_ulong(todoline.s + 1,&pid);
       break;
     case 'F':
       if (substdio_putflush(&ssinfo,todoline.s,todoline.len) == -1)
	{
	 fnmake_info(id);
         log3("warning: trouble writing to ",fn.s,"\n"); goto fail;
	}
       log2("info msg ",strnum3);
       strnum2[fmt_ulong(strnum2,(unsigned long) st.st_size)] = 0;
       log2(": bytes ",strnum2);
       log1(" from <"); logsafe(todoline.s + 1);
       strnum2[fmt_ulong(strnum2,pid)] = 0;
       log2("> qp ",strnum2);
       strnum2[fmt_ulong(strnum2,uid)] = 0;
       log2(" uid ",strnum2);
       log1("\n");
       break;
     case 'T':
       switch(rewrite(todoline.s + 1))
	{
	 case 0: nomem(); goto fail;
	 case 2: c = 1; break;
	 default: c = 0; break;
        }
       if (fdchan[c] == -1)
	{
	 fnmake_chanaddr(id,c);
	 fdchan[c] = open_excl(fn.s);
	 if (fdchan[c] == -1)
          { log3("warning: unable to create ",fn.s,"\n"); goto fail; }
	 substdio_fdbuf(&sschan[c]
	   ,write,fdchan[c],todobufchan[c],sizeof(todobufchan[c]));
	 flagchan[c] = 1;
	}
       if (substdio_bput(&sschan[c],rwline.s,rwline.len) == -1)
        {
	 fnmake_chanaddr(id,c);
         log3("warning: trouble writing to ",fn.s,"\n"); goto fail;
        }
       break;
     default:
       fnmake_todo(id);
       log3("warning: unknown record type in ",fn.s,"\n"); goto fail;
    }
  }

 close(fd); fd = -1;

 fnmake_info(id);
 if (substdio_flush(&ssinfo) == -1)
  { log3("warning: trouble writing to ",fn.s,"\n"); goto fail; }
 if (fsync(fdinfo) == -1)
  { log3("warning: trouble fsyncing ",fn.s,"\n"); goto fail; }
 close(fdinfo); fdinfo = -1;

 for (c = 0;c < CHANNELS;++c)
   if (fdchan[c] != -1)
    {
     fnmake_chanaddr(id,c);
     if (substdio_flush(&sschan[c]) == -1)
      { log3("warning: trouble writing to ",fn.s,"\n"); goto fail; }
     if (fsync(fdchan[c]) == -1)
      { log3("warning: trouble fsyncing ",fn.s,"\n"); goto fail; }
     close(fdchan[c]); fdchan[c] = -1;
    }

 fnmake_todo(id);
 if (substdio_putflush(&sstoqc,fn.s,fn.len) == -1) { cleandied(); return; }
 if (substdio_get(&ssfromqc,&ch,1) != 1) { cleandied(); return; }
 if (ch != '+')
  {
   log3("warning: qmail-clean unable to clean up ",fn.s,"\n");
   return;
  }

 pe.id = id; pe.dt = now();
 for (c = 0;c < CHANNELS;++c)
   if (flagchan[c])
     while (!prioq_insert(&pqchan[c],&pe)) nomem();

 for (c = 0;c < CHANNELS;++c) if (flagchan[c]) break;
 if (c == CHANNELS)
   while (!prioq_insert(&pqdone,&pe)) nomem();

 return;

 fail:
 if (fd != -1) close(fd);
 if (fdinfo != -1) close(fdinfo);
 for (c = 0;c < CHANNELS;++c)
   if (fdchan[c] != -1) close(fdchan[c]);
}


/* this file is too long ---------------------------------------------- MAIN */

int getcontrols() { if (control_init() == -1) return 0;
 if (control_readint(&lifetime,"control/queuelifetime") == -1) return 0;
 if (control_readint(&concurrency[0],"control/concurrencylocal") == -1) return 0;
 if (control_readint(&concurrency[1],"control/concurrencyremote") == -1) return 0;
 if (control_rldef(&envnoathost,"control/envnoathost",1,"envnoathost") != 1) return 0;
 if (control_rldef(&bouncefrom,"control/bouncefrom",0,"MAILER-DAEMON") != 1) return 0;
 if (control_rldef(&bouncehost,"control/bouncehost",1,"bouncehost") != 1) return 0;
 if (control_rldef(&doublebouncehost,"control/doublebouncehost",1,"doublebouncehost") != 1) return 0;
 if (control_rldef(&doublebounceto,"control/doublebounceto",0,"postmaster") != 1) return 0;
 if (!stralloc_cats(&doublebounceto,"@")) return 0;
 if (!stralloc_cat(&doublebounceto,&doublebouncehost)) return 0;
 if (!stralloc_0(&doublebounceto)) return 0;
 if (control_readfile(&locals,"control/locals",1) != 1) return 0;
 if (!constmap_init(&maplocals,locals.s,locals.len,0)) return 0;
 switch(control_readfile(&percenthack,"control/percenthack",0))
  {
   case -1: return 0;
   case 0: if (!constmap_init(&mappercenthack,"",0,0)) return 0; break;
   case 1: if (!constmap_init(&mappercenthack,percenthack.s,percenthack.len,0)) return 0; break;
  }
 switch(control_readfile(&redir,"control/recipientmap",0))
  {
   case -1: return 0;
   case 0: if (!constmap_init(&mapredir,"",0,1)) return 0; break;
   case 1: if (!constmap_init(&mapredir,redir.s,redir.len,1)) return 0; break;
  }
 switch(control_readfile(&vdoms,"control/virtualdomains",0))
  {
   case -1: return 0;
   case 0: if (!constmap_init(&mapvdoms,"",0,1)) return 0; break;
   case 1: if (!constmap_init(&mapvdoms,vdoms.s,vdoms.len,1)) return 0; break;
  }
 return 1; }

stralloc newlocals = {0};
stralloc newvdoms = {0};

void regetcontrols()
{
 int r;

 if (control_readfile(&newlocals,"control/locals",1) != 1)
  { log1("alert: unable to reread control/locals\n"); return; }
 r = control_readfile(&newvdoms,"control/virtualdomains",0);
 if (r == -1)
  { log1("alert: unable to reread control/virtualdomains\n"); return; }

 constmap_free(&maplocals);
 constmap_free(&mapvdoms);

 while (!stralloc_copy(&locals,&newlocals)) nomem();
 while (!constmap_init(&maplocals,locals.s,locals.len,0)) nomem();

 if (r)
  {
   while (!stralloc_copy(&vdoms,&newvdoms)) nomem();
   while (!constmap_init(&mapvdoms,vdoms.s,vdoms.len,1)) nomem();
  }
 else
   while (!constmap_init(&mapvdoms,"",0,1)) nomem();
}

void reread()
{
 if (chdir(auto_qmail) == -1)
  {
   log1("alert: unable to reread controls: unable to switch to home directory\n");
   return;
  }
 regetcontrols();
 while (chdir("queue") == -1)
  {
   log1("alert: unable to switch back to queue directory; HELP! sleeping...\n");
   sleep(10);
  }
}

void main()
{
 int fd;
 datetime_sec wakeup;
 fd_set rfds;
 fd_set wfds;
 int nfds;
 struct timeval tv;
 int c;

 if (chdir(auto_qmail) == -1)
  { log1("alert: cannot start: unable to switch to home directory\n"); _exit(111); }
 if (!getcontrols())
  { log1("alert: cannot start: unable to read controls\n"); _exit(111); }
 if (chdir("queue") == -1)
  { log1("alert: cannot start: unable to switch to queue directory\n"); _exit(111); }
 sig_pipeignore();
 sig_termcatch(sigterm);
 sig_alarmcatch(sigalrm);
 sig_hangupcatch(sighup);
 sig_childdefault();
 umask(077);

 fd = open_write("lock/sendmutex");
 if (fd == -1)
  { log1("alert: cannot start: unable to open mutex\n"); _exit(111); }
 if (lock_exnb(fd) == -1)
  { log1("alert: cannot start: qmail-send is already running\n"); _exit(111); }

 numjobs = 0;
 for (c = 0;c < CHANNELS;++c)
  {
   char ch;
   int u;
   int r;
   do
     r = read(chanfdin[c],&ch,1);
   while ((r == -1) && (errno == error_intr));
   if (r < 1)
    { log1("alert: cannot start: hath the daemon spawn no fire?\n"); _exit(111); }
   u = (unsigned int) (unsigned char) ch;
   if (concurrency[c] > u) concurrency[c] = u;
   numjobs += concurrency[c];
  }

 log1("running\n");

 fnmake_init();

 for (c = 0;c < CHANNELS;++c)
   if (!concurrency[c])
     log1(channodelmsg[c]);

 comm_init();

 pqstart();
 job_init();
 del_init();
 pass_init();
 todo_init();
 cleanup_init();

 while (!flagexitasap || !del_canexit())
  {
   if (flagexitasap) del_saywhynoexit();

   recent = now();

   if (flagrunasap) { flagrunasap = 0; pqrun(); }
   if (flagreadasap) { flagreadasap = 0; reread(); }

   wakeup = recent + SLEEP_FOREVER;
   FD_ZERO(&rfds);
   FD_ZERO(&wfds);
   nfds = 1;

   comm_selprep(&nfds,&wfds);
   del_selprep(&nfds,&rfds);
   pass_selprep(&wakeup);
   todo_selprep(&nfds,&rfds,&wakeup);
   cleanup_selprep(&wakeup);

   if (wakeup <= recent) tv.tv_sec = 0;
   else tv.tv_sec = wakeup - recent + SLEEP_FUZZ;
   tv.tv_usec = 0;

   if (select(nfds,&rfds,&wfds,(fd_set *) 0,&tv) == -1)
     if (errno == error_intr)
       ;
     else
       log1("warning: trouble in select\n");
   else
    {
     recent = now();

     comm_do(&wfds);
     del_do(&rfds);
     todo_do(&rfds);
     pass_do();
     cleanup_do();
    }
  }
 pqfinish();
 log1("exiting\n");
 _exit(0);
}