24 #include "auto_qmail.h"
33 #include "readsubdir.h"
35 /* critical timing feature #1: if not triggered, do not busy-loop */
36 /* critical timing feature #2: if triggered, respond within fixed time */
37 /* important timing feature: when triggered, respond instantly */
38 #define SLEEP_TODO 1500 /* check todo/ every 25 minutes in any case */
39 #define SLEEP_FUZZ 1 /* slop a bit on sleeps to avoid zeno effect */
40 #define SLEEP_FOREVER 86400 /* absolute maximum time spent in select() */
41 #define SLEEP_CLEANUP 76431 /* time between cleanups */
42 #define SLEEP_SYSFAIL 123
43 #define OSSIFIED 129600 /* 36 hours; _must_ exceed q-q's DEATH (24 hours) */
45 int lifetime = 604800;
47 stralloc percenthack = {0};
48 struct constmap mappercenthack;
49 stralloc locals = {0};
50 struct constmap maplocals;
52 struct constmap mapvdoms;
53 stralloc envnoathost = {0};
54 stralloc bouncefrom = {0};
55 stralloc bouncehost = {0};
56 stralloc doublebounceto = {0};
57 stralloc doublebouncehost = {0};
58 stralloc control_idhost = {0};
60 char strnum2[FMT_ULONG];
61 char strnum3[FMT_ULONG];
64 char *chanaddr[CHANNELS] = { "local/", "remote/" };
65 char *chanstatusmsg[CHANNELS] = { " local ", " remote " };
66 char *tochan[CHANNELS] = { " to local ", " to remote " };
67 int chanfdout[CHANNELS] = { 1, 3 };
68 int chanfdin[CHANNELS] = { 2, 4 };
69 int chanskip[CHANNELS] = { 10, 20 };
71 int flagexitasap = 0; void sigterm() { flagexitasap = 1; }
72 int flagrunasap = 0; void sigalrm() { flagrunasap = 1; }
73 int flagreadasap = 0; void sighup() { flagreadasap = 1; }
75 void cleandied() { log1("alert: oh no! lost qmail-clean connection! dying...\n");
78 int flagspawnalive[CHANNELS];
79 void spawndied(c) int c; { log1("alert: oh no! lost spawn connection! dying...\n");
80 flagspawnalive[c] = 0; flagexitasap = 1; }
82 #define REPORTMAX 10000
87 /* this file is too long ----------------------------------------- FILENAMES */
91 char fnmake_strnum[FMT_ULONG];
95 while (!stralloc_ready(&fn,FMTQFN)) nomem();
96 while (!stralloc_ready(&fn2,FMTQFN)) nomem();
99 void fnmake_info(id) unsigned long id; { fn.len = fmtqfn(fn.s,"info/",id,1); }
100 void fnmake_todo(id) unsigned long id; { fn.len = fmtqfn(fn.s,"todo/",id,0); }
101 void fnmake_mess(id) unsigned long id; { fn.len = fmtqfn(fn.s,"mess/",id,1); }
102 void fnmake_foop(id) unsigned long id; { fn.len = fmtqfn(fn.s,"foop/",id,0); }
103 void fnmake_split(id) unsigned long id; { fn.len = fmtqfn(fn.s,"",id,1); }
104 void fnmake2_bounce(id) unsigned long id;
105 { fn2.len = fmtqfn(fn2.s,"bounce/",id,0); }
106 void fnmake_chanaddr(id,c) unsigned long id; int c;
107 { fn.len = fmtqfn(fn.s,chanaddr[c],id,1); }
110 /* this file is too long ----------------------------------------- REWRITING */
112 stralloc rwline = {0};
114 /* 1 if by land, 2 if by sea, 0 if out of memory. not allowed to barf. */
115 /* may trash recip. must set up rwline, between a T and a \0. */
122 static stralloc addr = {0};
125 if (!stralloc_copys(&rwline,"T")) return 0;
126 if (!stralloc_copys(&addr,recip)) return 0;
128 i = byte_rchr(addr.s,addr.len,'@');
130 if (!stralloc_cats(&addr,"@")) return 0;
131 if (!stralloc_cat(&addr,&envnoathost)) return 0;
134 while (constmap(&mappercenthack,addr.s + i + 1,addr.len - i - 1)) {
135 j = byte_rchr(addr.s,i,'%');
142 at = byte_rchr(addr.s,addr.len,'@');
144 if (constmap(&maplocals,addr.s + at + 1,addr.len - at - 1)) {
145 if (!stralloc_cat(&rwline,&addr)) return 0;
146 if (!stralloc_0(&rwline)) return 0;
150 for (i = 0;i <= addr.len;++i)
151 if (!i || (i == at + 1) || (i == addr.len) || ((i > at) && (addr.s[i] == '.')))
152 if (x = constmap(&mapvdoms,addr.s + i,addr.len - i)) {
154 if (!stralloc_cats(&rwline,x)) return 0;
155 if (!stralloc_cats(&rwline,"-")) return 0;
156 if (!stralloc_cat(&rwline,&addr)) return 0;
157 if (!stralloc_0(&rwline)) return 0;
161 if (!stralloc_cat(&rwline,&addr)) return 0;
162 if (!stralloc_0(&rwline)) return 0;
166 void senderadd(sa,sender,recip)
177 if (str_equal(sender + i - 4,"-@[]"))
179 j = byte_rchr(sender,i - 4,'@');
180 k = str_rchr(recip,'@');
181 if (recip[k] && (j + 5 <= i))
183 /* owner-@host-@[] -> owner-recipbox=reciphost@host */
184 while (!stralloc_catb(sa,sender,j)) nomem();
185 while (!stralloc_catb(sa,recip,k)) nomem();
186 while (!stralloc_cats(sa,"=")) nomem();
187 while (!stralloc_cats(sa,recip + k + 1)) nomem();
188 while (!stralloc_cats(sa,"@")) nomem();
189 while (!stralloc_catb(sa,sender + j + 1,i - 5 - j)) nomem();
193 while (!stralloc_cats(sa,sender)) nomem();
197 /* this file is too long ---------------------------------------------- INFO */
199 int getinfo(sa,dt,id)
206 static stralloc line = {0};
212 fdinfo = open_read(fn.s);
213 if (fdinfo == -1) return 0;
214 if (fstat(fdinfo,&st) == -1) { close(fdinfo); return 0; }
215 substdio_fdbuf(&ss,read,fdinfo,buf,sizeof(buf));
216 if (getln(&ss,&line,&match,'\0') == -1) { close(fdinfo); return 0; }
218 if (!match) return 0;
219 if (line.s[0] != 'F') return 0;
222 while (!stralloc_copys(sa,line.s + 1)) nomem();
223 while (!stralloc_0(sa)) nomem();
228 /* this file is too long ------------------------------------- COMMUNICATION */
230 substdio sstoqc; char sstoqcbuf[1024];
231 substdio ssfromqc; char ssfromqcbuf[1024];
232 stralloc comm_buf[CHANNELS] = { {0}, {0} };
233 int comm_pos[CHANNELS];
238 substdio_fdbuf(&sstoqc,write,5,sstoqcbuf,sizeof(sstoqcbuf));
239 substdio_fdbuf(&ssfromqc,read,6,ssfromqcbuf,sizeof(ssfromqcbuf));
240 for (c = 0;c < CHANNELS;++c)
241 if (ndelay_on(chanfdout[c]) == -1)
242 /* this is so stupid: NDELAY semantics should be default on write */
243 spawndied(c); /* drastic, but better than risking deadlock */
249 /* XXX: could allow a bigger buffer; say 10 recipients */
250 if (comm_buf[c].s && comm_buf[c].len) return 0;
254 void comm_write(c,delnum,id,sender,recip)
262 if (comm_buf[c].s && comm_buf[c].len) return;
263 while (!stralloc_copys(&comm_buf[c],"")) nomem();
265 while (!stralloc_append(&comm_buf[c],&ch)) nomem();
267 while (!stralloc_cats(&comm_buf[c],fn.s)) nomem();
268 while (!stralloc_0(&comm_buf[c])) nomem();
269 senderadd(&comm_buf[c],sender,recip);
270 while (!stralloc_0(&comm_buf[c])) nomem();
271 while (!stralloc_cats(&comm_buf[c],recip)) nomem();
272 while (!stralloc_0(&comm_buf[c])) nomem();
276 void comm_selprep(nfds,wfds)
281 for (c = 0;c < CHANNELS;++c)
282 if (flagspawnalive[c])
283 if (comm_buf[c].s && comm_buf[c].len)
285 FD_SET(chanfdout[c],wfds);
286 if (*nfds <= chanfdout[c])
287 *nfds = chanfdout[c] + 1;
295 for (c = 0;c < CHANNELS;++c)
296 if (flagspawnalive[c])
297 if (comm_buf[c].s && comm_buf[c].len)
298 if (FD_ISSET(chanfdout[c],wfds))
302 len = comm_buf[c].len;
303 w = write(chanfdout[c],comm_buf[c].s + comm_pos[c],len - comm_pos[c]);
306 if ((w == -1) && (errno == error_pipe))
309 continue; /* kernel select() bug; can't avoid busy-looping */
314 if (comm_pos[c] == len)
321 /* this file is too long ------------------------------------------ CLEANUPS */
323 int flagcleanup; /* if 1, cleanupdir is initialized and ready */
324 readsubdir cleanupdir;
325 datetime_sec cleanuptime;
333 void cleanup_selprep(wakeup)
334 datetime_sec *wakeup;
336 if (flagcleanup) *wakeup = 0;
337 if (*wakeup > cleanuptime) *wakeup = cleanuptime;
348 if (recent < cleanuptime) return;
349 readsubdir_init(&cleanupdir,"mess",pausedir);
353 switch(readsubdir_next(&cleanupdir,&id))
359 cleanuptime = recent + SLEEP_CLEANUP;
365 if (stat(fn.s,&st) == -1) return; /* probably qmail-queue deleted it */
366 if (recent <= st.st_atime + OSSIFIED) return;
369 if (stat(fn.s,&st) == 0) return;
370 if (errno != error_noent) return;
372 if (stat(fn.s,&st) == 0) return;
373 if (errno != error_noent) return;
376 if (substdio_putflush(&sstoqc,fn.s,fn.len) == -1) { cleandied(); return; }
377 if (substdio_get(&ssfromqc,&ch,1) != 1) { cleandied(); return; }
379 log3("warning: qmail-clean unable to clean up ",fn.s,"\n");
383 /* this file is too long ----------------------------------- PRIORITY QUEUES */
385 prioq pqdone = {0}; /* -todo +info; HOPEFULLY -local -remote */
386 prioq pqchan[CHANNELS] = { {0}, {0} };
387 /* pqchan 0: -todo +info +local ?remote */
388 /* pqchan 1: -todo +info ?local +remote */
389 prioq pqfail = {0}; /* stat() failure; has to be pqadded again */
395 struct prioq_elt pechan[CHANNELS];
396 int flagchan[CHANNELS];
400 #define CHECKSTAT if (errno != error_noent) goto fail;
403 if (stat(fn.s,&st) == -1)
406 return; /* someone yanking our chain */
410 if (stat(fn.s,&st) != -1) return; /* look, ma, dad crashed writing info! */
413 for (c = 0;c < CHANNELS;++c)
415 fnmake_chanaddr(id,c);
416 if (stat(fn.s,&st) == -1) { flagchan[c] = 0; CHECKSTAT }
417 else { flagchan[c] = 1; pechan[c].id = id; pechan[c].dt = st.st_mtime; }
420 for (c = 0;c < CHANNELS;++c)
422 while (!prioq_insert(&pqchan[c],&pechan[c])) nomem();
424 for (c = 0;c < CHANNELS;++c) if (flagchan[c]) break;
427 pe.id = id; pe.dt = now();
428 while (!prioq_insert(&pqdone,&pe)) nomem();
434 log3("warning: unable to stat ",fn.s,"; will try again later\n");
435 pe.id = id; pe.dt = now() + SLEEP_SYSFAIL;
436 while (!prioq_insert(&pqfail,&pe)) nomem();
445 readsubdir_init(&rs,"info",pausedir);
447 while (x = readsubdir_next(&rs,&id))
456 time_t ut[2]; /* XXX: more portable than utimbuf, but still worrisome */
458 for (c = 0;c < CHANNELS;++c)
459 while (prioq_min(&pqchan[c],&pe))
461 prioq_delmin(&pqchan[c]);
462 fnmake_chanaddr(pe.id,c);
463 ut[0] = ut[1] = pe.dt;
464 if (utime(fn.s,ut) == -1)
465 log3("warning: unable to utime ",fn.s,"; message will be retried too soon\n");
473 for (c = 0;c < CHANNELS;++c)
476 for (i = 0;i < pqchan[c].len;++i)
477 pqchan[c].p[i].dt = recent;
481 /* this file is too long ---------------------------------------------- JOBS */
485 int refs; /* if 0, this struct is unused */
502 while (!(jo = (struct job *) alloc(numjobs * sizeof(struct job)))) nomem();
503 for (j = 0;j < numjobs;++j)
513 for (j = 0;j < numjobs;++j) if (!jo[j].refs) return 1;
517 int job_open(id,channel)
522 for (j = 0;j < numjobs;++j) if (!jo[j].refs) break;
523 if (j == numjobs) return -1;
526 jo[j].channel = channel;
528 jo[j].flaghiteof = 0;
538 if (0 < --jo[j].refs) return;
542 if (jo[j].flaghiteof && !jo[j].numtodo)
544 fnmake_chanaddr(jo[j].id,jo[j].channel);
545 if (unlink(fn.s) == -1)
547 log3("warning: unable to unlink ",fn.s,"; will try again later\n");
548 pe.dt = now() + SLEEP_SYSFAIL;
553 for (c = 0;c < CHANNELS;++c) if (c != jo[j].channel)
555 fnmake_chanaddr(jo[j].id,c);
556 if (stat(fn.s,&st) == 0) return; /* more channels going */
557 if (errno != error_noent)
559 log3("warning: unable to stat ",fn.s,"\n");
560 break; /* this is the only reason for HOPEFULLY */
564 while (!prioq_insert(&pqdone,&pe)) nomem();
569 while (!prioq_insert(&pqchan[jo[j].channel],&pe)) nomem();
573 /* this file is too long ------------------------------------------- BOUNCES */
575 char *stripvdomprepend(recip)
583 i = str_rchr(recip,'@');
584 if (!recip[i]) return recip;
585 domain = recip + i + 1;
586 domainlen = str_len(domain);
588 for (i = 0;i <= domainlen;++i)
589 if ((i == 0) || (i == domainlen) || (domain[i] == '.'))
590 if (prepend = constmap(&mapvdoms,domain + i,domainlen - i))
592 if (!*prepend) break;
593 i = str_len(prepend);
594 if (str_diffn(recip,prepend,i)) break;
595 if (recip[i] != '-') break;
596 return recip + i + 1;
601 stralloc bouncetext = {0};
603 void addbounce(id,recip,report)
611 while (!stralloc_copys(&bouncetext,"<")) nomem();
612 while (!stralloc_cats(&bouncetext,stripvdomprepend(recip))) nomem();
613 for (pos = 0;pos < bouncetext.len;++pos)
614 if (bouncetext.s[pos] == '\n')
615 bouncetext.s[pos] = '_';
616 while (!stralloc_cats(&bouncetext,">:\n")) nomem();
617 while (!stralloc_cats(&bouncetext,report)) nomem();
619 if (report[str_len(report) - 1] != '\n')
620 while (!stralloc_cats(&bouncetext,"\n")) nomem();
621 for (pos = bouncetext.len - 2;pos > 0;--pos)
622 if (bouncetext.s[pos] == '\n')
623 if (bouncetext.s[pos - 1] == '\n')
624 bouncetext.s[pos] = '/';
625 while (!stralloc_cats(&bouncetext,"\n")) nomem();
629 fd = open_append(fn2.s);
631 log1("alert: unable to append to bounce message; HELP! sleeping...\n");
635 while (pos < bouncetext.len)
637 w = write(fd,bouncetext.s + pos,bouncetext.len - pos);
640 log1("alert: unable to append to bounce message; HELP! sleeping...\n");
661 static stralloc sender = {0};
662 static stralloc quoted = {0};
666 if (!getinfo(&sender,&birth,id)) return 0; /* XXX: print warning */
668 /* owner-@host-@[] -> owner-@host */
670 if (str_equal(sender.s + sender.len - 5,"-@[]"))
673 sender.s[sender.len - 1] = 0;
678 if (stat(fn2.s,&st) == -1)
680 if (errno == error_noent)
682 log3("warning: unable to stat ",fn2.s,"\n");
685 if (str_equal(sender.s,"#@[]"))
686 log3("triple bounce: discarding ",fn2.s,"\n");
689 if (qmail_open(&qqt) == -1)
690 { log1("warning: unable to start qmail-queue, will try later\n"); return 0; }
693 if (*sender.s) { bouncesender = ""; bouncerecip = sender.s; }
694 else { bouncesender = "#@[]"; bouncerecip = doublebounceto.s; }
696 while (!newfield_datemake(now())) nomem();
697 qmail_put(&qqt,newfield_date.s,newfield_date.len);
698 while (!newfield_msgidmake(control_idhost.s,control_idhost.len,now()))
700 qmail_put(&qqt,newfield_msgid.s,newfield_msgid.len);
701 qmail_puts(&qqt,"From: ");
702 while (!quote("ed,&bouncefrom)) nomem();
703 qmail_put(&qqt,quoted.s,quoted.len);
704 qmail_puts(&qqt,"@");
705 qmail_put(&qqt,bouncehost.s,bouncehost.len);
706 qmail_puts(&qqt,"\nTo: ");
707 while (!quote2("ed,bouncerecip)) nomem();
708 qmail_put(&qqt,quoted.s,quoted.len);
710 Subject: failure notice\n\
712 Hi. This is the qmail-send program at ");
713 qmail_put(&qqt,bouncehost.s,bouncehost.len);
714 qmail_puts(&qqt,*sender.s ? ".\n\
715 I'm afraid I wasn't able to deliver your message to the following addresses.\n\
716 This is a permanent error; I've given up. Sorry it didn't work out.\n\
719 I tried to deliver a bounce message to this address, but the bounce bounced!\n\
723 fd = open_read(fn2.s);
728 substdio_fdbuf(&ssread,read,fd,inbuf,sizeof(inbuf));
729 while ((r = substdio_get(&ssread,buf,sizeof(buf))) > 0)
730 qmail_put(&qqt,buf,r);
736 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");
737 qmail_puts(&qqt,"Return-Path: <");
738 while (!quote2("ed,sender.s)) nomem();
739 qmail_put(&qqt,quoted.s,quoted.len);
740 qmail_puts(&qqt,">\n");
742 fd = open_read(fn.s);
747 substdio_fdbuf(&ssread,read,fd,inbuf,sizeof(inbuf));
748 while ((r = substdio_get(&ssread,buf,sizeof(buf))) > 0)
749 qmail_put(&qqt,buf,r);
755 qmail_from(&qqt,bouncesender);
756 qmail_to(&qqt,bouncerecip);
757 if (*qmail_close(&qqt))
758 { log1("warning: trouble injecting bounce message, will try later\n"); return 0; }
760 strnum2[fmt_ulong(strnum2,id)] = 0;
761 log2("bounce msg ",strnum2);
762 strnum2[fmt_ulong(strnum2,qp)] = 0;
763 log3(" qp ",strnum2,"\n");
765 if (unlink(fn2.s) == -1)
767 log3("warning: unable to unlink ",fn2.s,"\n");
774 /* this file is too long ---------------------------------------- DELIVERIES */
786 unsigned long masterdelid = 1;
787 unsigned int concurrency[CHANNELS] = { 10, 20 };
788 unsigned int concurrencyused[CHANNELS] = { 0, 0 };
789 struct del *d[CHANNELS];
790 stralloc dline[CHANNELS];
798 for (c = 0;c < CHANNELS;++c) {
799 strnum2[fmt_ulong(strnum2,(unsigned long) concurrencyused[c])] = 0;
800 strnum3[fmt_ulong(strnum3,(unsigned long) concurrency[c])] = 0;
801 log2(chanstatusmsg[c],strnum2);
804 if (flagexitasap) log1(" exitasap");
812 for (c = 0;c < CHANNELS;++c)
814 flagspawnalive[c] = 1;
815 while (!(d[c] = (struct del *) alloc(concurrency[c] * sizeof(struct del))))
817 for (i = 0;i < concurrency[c];++i)
818 { d[c][i].used = 0; d[c][i].recip.s = 0; }
820 while (!stralloc_copys(&dline[c],"")) nomem();
828 for (c = 0;c < CHANNELS;++c)
829 if (flagspawnalive[c]) /* if dead, nothing we can do about its jobs */
830 if (concurrencyused[c]) return 0;
837 return flagspawnalive[c] && comm_canwrite(c) && (concurrencyused[c] < concurrency[c]);
840 void del_start(j,mpos,recip)
849 if (!flagspawnalive[c]) return;
850 if (!comm_canwrite(c)) return;
852 for (i = 0;i < concurrency[c];++i) if (!d[c][i].used) break;
853 if (i == concurrency[c]) return;
855 if (!stralloc_copys(&d[c][i].recip,recip)) { nomem(); return; }
856 if (!stralloc_0(&d[c][i].recip)) { nomem(); return; }
857 d[c][i].j = j; ++jo[j].refs;
858 d[c][i].delid = masterdelid++;
860 d[c][i].used = 1; ++concurrencyused[c];
862 comm_write(c,i,jo[j].id,jo[j].sender.s,recip);
864 strnum2[fmt_ulong(strnum2,d[c][i].delid)] = 0;
865 strnum3[fmt_ulong(strnum3,jo[j].id)] = 0;
866 log2("starting delivery ",strnum2);
867 log3(": msg ",strnum3,tochan[c]);
873 void markdone(c,id,pos)
880 fnmake_chanaddr(id,c);
883 fd = open_write(fn.s);
885 if (fstat(fd,&st) == -1) { close(fd); break; }
886 if (seek_set(fd,pos) == -1) { close(fd); break; }
887 if (write(fd,"D",1) != 1) { close(fd); break; }
888 /* further errors -> double delivery without us knowing about it, oh well */
892 log3("warning: trouble marking ",fn.s,"; message will be delivered twice!\n");
902 r = read(chanfdin[c],delbuf,sizeof(delbuf));
904 if (r == 0) { spawndied(c); return; }
905 for (i = 0;i < r;++i)
908 while (!stralloc_append(&dline[c],&ch)) nomem();
909 if (dline[c].len > REPORTMAX)
910 dline[c].len = REPORTMAX;
911 /* qmail-lspawn and qmail-rspawn are responsible for keeping it short */
912 /* but from a security point of view, we don't trust rspawn */
913 if (!ch && (dline[c].len > 1))
915 delnum = (unsigned int) (unsigned char) dline[c].s[0];
916 if ((delnum < 0) || (delnum >= concurrency[c]) || !d[c][delnum].used)
917 log1("warning: internal error: delivery report out of range\n");
920 strnum3[fmt_ulong(strnum3,d[c][delnum].delid)] = 0;
921 if (dline[c].s[1] == 'Z')
922 if (jo[d[c][delnum].j].flagdying)
926 while (!stralloc_cats(&dline[c],"I'm not going to try again; this message has been in the queue too long.\n")) nomem();
927 while (!stralloc_0(&dline[c])) nomem();
929 switch(dline[c].s[1])
932 log3("delivery ",strnum3,": success: ");
933 logsafe(dline[c].s + 2);
935 markdone(c,jo[d[c][delnum].j].id,d[c][delnum].mpos);
936 --jo[d[c][delnum].j].numtodo;
939 log3("delivery ",strnum3,": deferral: ");
940 logsafe(dline[c].s + 2);
944 log3("delivery ",strnum3,": failure: ");
945 logsafe(dline[c].s + 2);
947 addbounce(jo[d[c][delnum].j].id,d[c][delnum].recip.s,dline[c].s + 2);
948 markdone(c,jo[d[c][delnum].j].id,d[c][delnum].mpos);
949 --jo[d[c][delnum].j].numtodo;
952 log3("delivery ",strnum3,": report mangled, will defer\n");
954 job_close(d[c][delnum].j);
955 d[c][delnum].used = 0; --concurrencyused[c];
963 void del_selprep(nfds,rfds)
968 for (c = 0;c < CHANNELS;++c)
969 if (flagspawnalive[c])
971 FD_SET(chanfdin[c],rfds);
972 if (*nfds <= chanfdin[c])
973 *nfds = chanfdin[c] + 1;
981 for (c = 0;c < CHANNELS;++c)
982 if (flagspawnalive[c])
983 if (FD_ISSET(chanfdin[c],rfds))
988 /* this file is too long -------------------------------------------- PASSES */
992 unsigned long id; /* if 0, need a new pass */
993 int j; /* defined if id; job number */
994 int fd; /* defined if id; reading from {local,remote} */
995 seek_pos mpos; /* defined if id; mark position */
1004 for (c = 0;c < CHANNELS;++c) pass[c].id = 0;
1007 void pass_selprep(wakeup)
1008 datetime_sec *wakeup;
1011 struct prioq_elt pe;
1012 if (flagexitasap) return;
1013 for (c = 0;c < CHANNELS;++c)
1016 { *wakeup = 0; return; }
1018 for (c = 0;c < CHANNELS;++c)
1020 if (prioq_min(&pqchan[c],&pe))
1021 if (*wakeup > pe.dt)
1023 if (prioq_min(&pqfail,&pe))
1024 if (*wakeup > pe.dt)
1026 if (prioq_min(&pqdone,&pe))
1027 if (*wakeup > pe.dt)
1031 static datetime_sec squareroot(x) /* result^2 <= x < (result + 1)^2 */
1032 datetime_sec x; /* assuming: >= 0 */
1040 for (j = 15;j >= 0;--j)
1042 y21 = (y << (j + 1)) + (1 << (j + j));
1043 if (y21 <= x - yy) { y += (1 << j); yy += y21; }
1048 datetime_sec nextretry(birth,c)
1054 if (birth > recent) n = 0;
1055 else n = squareroot(recent - birth); /* no need to add fuzz to recent */
1057 return birth + n * n;
1064 struct prioq_elt pe;
1065 static stralloc line = {0};
1068 if (flagexitasap) return;
1072 if (!job_avail()) return;
1073 if (!prioq_min(&pqchan[c],&pe)) return;
1074 if (pe.dt > recent) return;
1075 fnmake_chanaddr(pe.id,c);
1077 prioq_delmin(&pqchan[c]);
1079 pass[c].fd = open_read(fn.s);
1080 if (pass[c].fd == -1) goto trouble;
1081 if (!getinfo(&line,&birth,pe.id)) { close(pass[c].fd); goto trouble; }
1083 substdio_fdbuf(&pass[c].ss,read,pass[c].fd,pass[c].buf,sizeof(pass[c].buf));
1084 pass[c].j = job_open(pe.id,c);
1085 jo[pass[c].j].retry = nextretry(birth,c);
1086 jo[pass[c].j].flagdying = (recent > birth + lifetime);
1087 while (!stralloc_copy(&jo[pass[c].j].sender,&line)) nomem();
1090 if (!del_avail(c)) return;
1092 if (getln(&pass[c].ss,&line,&match,'\0') == -1)
1094 fnmake_chanaddr(pass[c].id,c);
1095 log3("warning: trouble reading ",fn.s,"; will try again later\n");
1097 job_close(pass[c].j);
1104 jo[pass[c].j].flaghiteof = 1;
1105 job_close(pass[c].j);
1112 ++jo[pass[c].j].numtodo;
1113 del_start(pass[c].j,pass[c].mpos,line.s + 1);
1118 fnmake_chanaddr(pass[c].id,c);
1119 log3("warning: unknown record type in ",fn.s,"!\n");
1121 job_close(pass[c].j);
1126 pass[c].mpos += line.len;
1130 log3("warning: trouble opening ",fn.s,"; will try again later\n");
1131 pe.dt = recent + SLEEP_SYSFAIL;
1132 while (!prioq_insert(&pqchan[c],&pe)) nomem();
1140 struct prioq_elt pe;
1143 for (c = 0;c < CHANNELS;++c)
1145 fnmake_chanaddr(id,c);
1146 if (stat(fn.s,&st) == 0) return; /* false alarm; consequence of HOPEFULLY */
1147 if (errno != error_noent)
1149 log3("warning: unable to stat ",fn.s,"; will try again later\n");
1155 if (stat(fn.s,&st) == 0) return;
1156 if (errno != error_noent)
1158 log3("warning: unable to stat ",fn.s,"; will try again later\n");
1163 if (stat(fn.s,&st) == -1)
1165 if (errno == error_noent) return;
1166 log3("warning: unable to stat ",fn.s,"; will try again later\n");
1170 /* -todo +info -local -remote ?bounce */
1171 if (!injectbounce(id))
1172 goto fail; /* injectbounce() produced error message */
1174 strnum3[fmt_ulong(strnum3,id)] = 0;
1175 log3("end msg ",strnum3,"\n");
1177 /* -todo +info -local -remote -bounce */
1179 if (unlink(fn.s) == -1)
1181 log3("warning: unable to unlink ",fn.s,"; will try again later\n");
1185 /* -todo -info -local -remote -bounce; we can relax */
1187 if (substdio_putflush(&sstoqc,fn.s,fn.len) == -1) { cleandied(); return; }
1188 if (substdio_get(&ssfromqc,&ch,1) != 1) { cleandied(); return; }
1190 log3("warning: qmail-clean unable to clean up ",fn.s,"\n");
1195 pe.id = id; pe.dt = now() + SLEEP_SYSFAIL;
1196 while (!prioq_insert(&pqdone,&pe)) nomem();
1202 struct prioq_elt pe;
1204 for (c = 0;c < CHANNELS;++c) pass_dochan(c);
1205 if (prioq_min(&pqfail,&pe))
1206 if (pe.dt <= recent)
1208 prioq_delmin(&pqfail);
1211 if (prioq_min(&pqdone,&pe))
1212 if (pe.dt <= recent)
1214 prioq_delmin(&pqdone);
1220 /* this file is too long ---------------------------------------------- TODO */
1222 datetime_sec nexttodorun;
1223 DIR *tododir; /* if 0, have to opendir again */
1224 stralloc todoline = {0};
1225 char todobuf[SUBSTDIO_INSIZE];
1226 char todobufinfo[512];
1227 char todobufchan[CHANNELS][1024];
1232 nexttodorun = now();
1236 void todo_selprep(nfds,rfds,wakeup)
1239 datetime_sec *wakeup;
1241 if (flagexitasap) return;
1242 trigger_selprep(nfds,rfds);
1243 if (tododir) *wakeup = 0;
1244 if (*wakeup > nexttodorun) *wakeup = nexttodorun;
1251 substdio ss; int fd;
1252 substdio ssinfo; int fdinfo;
1253 substdio sschan[CHANNELS];
1254 int fdchan[CHANNELS];
1255 int flagchan[CHANNELS];
1256 struct prioq_elt pe;
1268 for (c = 0;c < CHANNELS;++c) fdchan[c] = -1;
1270 if (flagexitasap) return;
1274 if (!trigger_pulled(rfds))
1275 if (recent < nexttodorun)
1278 tododir = opendir("todo");
1284 nexttodorun = recent + SLEEP_TODO;
1287 d = readdir(tododir);
1294 if (str_equal(d->d_name,".")) return;
1295 if (str_equal(d->d_name,"..")) return;
1296 len = scan_ulong(d->d_name,&id);
1297 if (!len || d->d_name[len]) return;
1301 fd = open_read(fn.s);
1302 if (fd == -1) { log3("warning: unable to open ",fn.s,"\n"); return; }
1305 /* just for the statistics */
1306 if (stat(fn.s,&st) == -1)
1307 { log3("warning: unable to stat ",fn.s,"\n"); goto fail; }
1309 for (c = 0;c < CHANNELS;++c)
1311 fnmake_chanaddr(id,c);
1312 if (unlink(fn.s) == -1) if (errno != error_noent)
1313 { log3("warning: unable to unlink ",fn.s,"\n"); goto fail; }
1317 if (unlink(fn.s) == -1) if (errno != error_noent)
1318 { log3("warning: unable to unlink ",fn.s,"\n"); goto fail; }
1320 fdinfo = open_excl(fn.s);
1322 { log3("warning: unable to create ",fn.s,"\n"); goto fail; }
1324 strnum3[fmt_ulong(strnum3,id)] = 0;
1325 log3("new msg ",strnum3,"\n");
1327 for (c = 0;c < CHANNELS;++c) flagchan[c] = 0;
1329 substdio_fdbuf(&ss,read,fd,todobuf,sizeof(todobuf));
1330 substdio_fdbuf(&ssinfo,write,fdinfo,todobufinfo,sizeof(todobufinfo));
1337 if (getln(&ss,&todoline,&match,'\0') == -1)
1339 /* perhaps we're out of memory, perhaps an I/O error */
1341 log3("warning: trouble reading ",fn.s,"\n"); goto fail;
1345 switch(todoline.s[0])
1348 scan_ulong(todoline.s + 1,&uid);
1351 scan_ulong(todoline.s + 1,&pid);
1354 if (substdio_putflush(&ssinfo,todoline.s,todoline.len) == -1)
1357 log3("warning: trouble writing to ",fn.s,"\n"); goto fail;
1359 log2("info msg ",strnum3);
1360 strnum2[fmt_ulong(strnum2,(unsigned long) st.st_size)] = 0;
1361 log2(": bytes ",strnum2);
1362 log1(" from <"); logsafe(todoline.s + 1);
1363 strnum2[fmt_ulong(strnum2,pid)] = 0;
1364 log2("> qp ",strnum2);
1365 strnum2[fmt_ulong(strnum2,uid)] = 0;
1366 log2(" uid ",strnum2);
1370 switch(rewrite(todoline.s + 1))
1372 case 0: nomem(); goto fail;
1373 case 2: c = 1; break;
1374 default: c = 0; break;
1376 if (fdchan[c] == -1)
1378 fnmake_chanaddr(id,c);
1379 fdchan[c] = open_excl(fn.s);
1380 if (fdchan[c] == -1)
1381 { log3("warning: unable to create ",fn.s,"\n"); goto fail; }
1382 substdio_fdbuf(&sschan[c]
1383 ,write,fdchan[c],todobufchan[c],sizeof(todobufchan[c]));
1386 if (substdio_bput(&sschan[c],rwline.s,rwline.len) == -1)
1388 fnmake_chanaddr(id,c);
1389 log3("warning: trouble writing to ",fn.s,"\n"); goto fail;
1394 log3("warning: unknown record type in ",fn.s,"\n"); goto fail;
1401 if (substdio_flush(&ssinfo) == -1)
1402 { log3("warning: trouble writing to ",fn.s,"\n"); goto fail; }
1403 if (fsync(fdinfo) == -1)
1404 { log3("warning: trouble fsyncing ",fn.s,"\n"); goto fail; }
1405 close(fdinfo); fdinfo = -1;
1407 for (c = 0;c < CHANNELS;++c)
1408 if (fdchan[c] != -1)
1410 fnmake_chanaddr(id,c);
1411 if (substdio_flush(&sschan[c]) == -1)
1412 { log3("warning: trouble writing to ",fn.s,"\n"); goto fail; }
1413 if (fsync(fdchan[c]) == -1)
1414 { log3("warning: trouble fsyncing ",fn.s,"\n"); goto fail; }
1415 close(fdchan[c]); fdchan[c] = -1;
1419 if (substdio_putflush(&sstoqc,fn.s,fn.len) == -1) { cleandied(); return; }
1420 if (substdio_get(&ssfromqc,&ch,1) != 1) { cleandied(); return; }
1423 log3("warning: qmail-clean unable to clean up ",fn.s,"\n");
1427 pe.id = id; pe.dt = now();
1428 for (c = 0;c < CHANNELS;++c)
1430 while (!prioq_insert(&pqchan[c],&pe)) nomem();
1432 for (c = 0;c < CHANNELS;++c) if (flagchan[c]) break;
1434 while (!prioq_insert(&pqdone,&pe)) nomem();
1439 if (fd != -1) close(fd);
1440 if (fdinfo != -1) close(fdinfo);
1441 for (c = 0;c < CHANNELS;++c)
1442 if (fdchan[c] != -1) close(fdchan[c]);
1446 /* this file is too long ---------------------------------------------- MAIN */
1448 int getcontrols() { if (control_init() == -1) return 0;
1449 if (control_readint(&lifetime,"control/queuelifetime") == -1) return 0;
1450 if (control_readint(&concurrency[0],"control/concurrencylocal") == -1) return 0;
1451 if (control_readint(&concurrency[1],"control/concurrencyremote") == -1) return 0;
1452 if (control_rldef(&envnoathost,"control/envnoathost",1,"envnoathost") != 1) return 0;
1453 if (control_rldef(&bouncefrom,"control/bouncefrom",0,"MAILER-DAEMON") != 1) return 0;
1454 if (control_rldef(&bouncehost,"control/bouncehost",1,"bouncehost") != 1) return 0;
1455 if (control_rldef(&doublebouncehost,"control/doublebouncehost",1,"doublebouncehost") != 1) return 0;
1456 if (control_rldef(&doublebounceto,"control/doublebounceto",0,"postmaster") != 1) return 0;
1457 if (!stralloc_cats(&doublebounceto,"@")) return 0;
1458 if (!stralloc_cat(&doublebounceto,&doublebouncehost)) return 0;
1459 if (!stralloc_0(&doublebounceto)) return 0;
1460 if (control_rldef(&control_idhost, "control/idhost",1,"idhost") != 1)
1462 if (control_readfile(&locals,"control/locals",1) != 1) return 0;
1463 if (!constmap_init(&maplocals,locals.s,locals.len,0)) return 0;
1464 switch(control_readfile(&percenthack,"control/percenthack",0))
1467 case 0: if (!constmap_init(&mappercenthack,"",0,0)) return 0; break;
1468 case 1: if (!constmap_init(&mappercenthack,percenthack.s,percenthack.len,0)) return 0; break;
1470 switch(control_readfile(&vdoms,"control/virtualdomains",0))
1473 case 0: if (!constmap_init(&mapvdoms,"",0,1)) return 0; break;
1474 case 1: if (!constmap_init(&mapvdoms,vdoms.s,vdoms.len,1)) return 0; break;
1478 stralloc newlocals = {0};
1479 stralloc newvdoms = {0};
1481 void regetcontrols()
1485 if (control_readfile(&newlocals,"control/locals",1) != 1)
1486 { log1("alert: unable to reread control/locals\n"); return; }
1487 r = control_readfile(&newvdoms,"control/virtualdomains",0);
1489 { log1("alert: unable to reread control/virtualdomains\n"); return; }
1491 constmap_free(&maplocals);
1492 constmap_free(&mapvdoms);
1494 while (!stralloc_copy(&locals,&newlocals)) nomem();
1495 while (!constmap_init(&maplocals,locals.s,locals.len,0)) nomem();
1499 while (!stralloc_copy(&vdoms,&newvdoms)) nomem();
1500 while (!constmap_init(&mapvdoms,vdoms.s,vdoms.len,1)) nomem();
1503 while (!constmap_init(&mapvdoms,"",0,1)) nomem();
1508 if (chdir(auto_qmail) == -1)
1510 log1("alert: unable to reread controls: unable to switch to home directory\n");
1514 while (chdir("queue") == -1)
1516 log1("alert: unable to switch back to queue directory; HELP! sleeping...\n");
1524 datetime_sec wakeup;
1531 if (chdir(auto_qmail) == -1)
1532 { log1("alert: cannot start: unable to switch to home directory\n"); _exit(111); }
1534 { log1("alert: cannot start: unable to read controls\n"); _exit(111); }
1535 if (chdir("queue") == -1)
1536 { log1("alert: cannot start: unable to switch to queue directory\n"); _exit(111); }
1538 sig_termcatch(sigterm);
1539 sig_alarmcatch(sigalrm);
1540 sig_hangupcatch(sighup);
1544 fd = open_write("lock/sendmutex");
1546 { log1("alert: cannot start: unable to open mutex\n"); _exit(111); }
1547 if (lock_exnb(fd) == -1)
1548 { log1("alert: cannot start: qmail-send is already running\n"); _exit(111); }
1551 for (c = 0;c < CHANNELS;++c)
1557 r = read(chanfdin[c],&ch,1);
1558 while ((r == -1) && (errno == error_intr));
1560 { log1("alert: cannot start: hath the daemon spawn no fire?\n"); _exit(111); }
1561 u = (unsigned int) (unsigned char) ch;
1562 if (concurrency[c] > u) concurrency[c] = u;
1563 numjobs += concurrency[c];
1577 while (!flagexitasap || !del_canexit())
1581 if (flagrunasap) { flagrunasap = 0; pqrun(); }
1582 if (flagreadasap) { flagreadasap = 0; reread(); }
1584 wakeup = recent + SLEEP_FOREVER;
1589 comm_selprep(&nfds,&wfds);
1590 del_selprep(&nfds,&rfds);
1591 pass_selprep(&wakeup);
1592 todo_selprep(&nfds,&rfds,&wakeup);
1593 cleanup_selprep(&wakeup);
1595 if (wakeup <= recent) tv.tv_sec = 0;
1596 else tv.tv_sec = wakeup - recent + SLEEP_FUZZ;
1599 if (select(nfds,&rfds,&wfds,(fd_set *) 0,&tv) == -1)
1600 if (errno == error_intr)
1603 log1("warning: trouble in select\n");
1616 log1("status: exiting\n");