dma: add required headers if they are not present
[dragonfly.git] / libexec / dma / dma.c
1 /*
2  * Copyright (c) 2008 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Simon 'corecode' Schubert <corecode@fs.ei.tum.de>.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * $DragonFly: src/libexec/dma/dma.c,v 1.5 2008/09/30 17:47:21 swildner Exp $
35  */
36
37 #include <sys/param.h>
38 #include <sys/queue.h>
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 #include <sys/wait.h>
42
43 #include <dirent.h>
44 #include <err.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <inttypes.h>
48 #include <netdb.h>
49 #include <paths.h>
50 #include <pwd.h>
51 #include <signal.h>
52 #include <stdarg.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <syslog.h>
57 #include <unistd.h>
58
59 #include "dma.h"
60
61
62
63 static void deliver(struct qitem *);
64 static int add_recp(struct queue *, const char *, const char *, int);
65
66 struct aliases aliases = LIST_HEAD_INITIALIZER(aliases);
67 static struct strlist tmpfs = SLIST_HEAD_INITIALIZER(tmpfs);
68 struct virtusers virtusers = LIST_HEAD_INITIALIZER(virtusers);
69 struct authusers authusers = LIST_HEAD_INITIALIZER(authusers);
70 static int daemonize = 1;
71 struct config *config;
72 static const char *username;
73 static uid_t uid;
74 static struct strlist seenmsg[16][16];
75
76
77 char *
78 hostname(void)
79 {
80         static char name[MAXHOSTNAMELEN+1];
81         int initialized = 0;
82         FILE *fp;
83         size_t len;
84
85         if (initialized)
86                 return (name);
87
88         if (config->mailname != NULL && config->mailname[0] != '\0') {
89                 snprintf(name, sizeof(name), "%s", config->mailname);
90                 initialized = 1;
91                 return (name);
92         }
93         if (config->mailnamefile != NULL && config->mailnamefile[0] != '\0') {
94                 fp = fopen(config->mailnamefile, "r");
95                 if (fp != NULL) {
96                         if (fgets(name, sizeof(name), fp) != NULL) {
97                                 len = strlen(name);
98                                 while (len > 0 &&
99                                     (name[len - 1] == '\r' ||
100                                      name[len - 1] == '\n'))
101                                         name[--len] = '\0';
102                                 if (name[0] != '\0') {
103                                         initialized = 1;
104                                         return (name);
105                                 }
106                         }
107                         fclose(fp);
108                 }
109         }
110         if (gethostname(name, sizeof(name)) != 0)
111                 strcpy(name, "(unknown hostname)");
112         initialized = 1;
113         return name;
114 }
115
116 static const char *
117 check_username(const char *name, uid_t ckuid)
118 {
119         struct passwd *pwd;
120
121         if (name == NULL)
122                 return (NULL);
123         pwd = getpwnam(name);
124         if (pwd == NULL || pwd->pw_uid != ckuid)
125                 return (NULL);
126         return (name);
127 }
128
129 static void
130 set_username(void)
131 {
132         struct passwd *pwd;
133         char *u = NULL;
134
135         uid = getuid();
136         username = check_username(getlogin(), uid);
137         if (username != NULL)
138                 return;
139         username = check_username(getenv("LOGNAME"), uid);
140         if (username != NULL)
141                 return;
142         username = check_username(getenv("USER"), uid);
143         if (username != NULL)
144                 return;
145         pwd = getpwuid(uid);
146         if (pwd != NULL && pwd->pw_name != NULL && pwd->pw_name[0] != '\0' &&
147             (u = strdup(pwd->pw_name)) != NULL) {
148                 username = check_username(u, uid);
149                 if (username != NULL)
150                         return;
151                 else
152                         free(u);
153         }
154         asprintf(__DECONST(void *, &username), "%ld", (long)uid);
155         if (username != NULL)
156                 return;
157         username = "unknown-or-invalid-username";
158 }
159
160 static char *
161 set_from(const char *osender)
162 {
163         struct virtuser *v;
164         char *sender;
165
166         if ((config->features & VIRTUAL) != 0) {
167                 SLIST_FOREACH(v, &virtusers, next) {
168                         if (strcmp(v->login, username) == 0) {
169                                 sender = strdup(v->address);
170                                 if (sender == NULL)
171                                         return(NULL);
172                                 goto out;
173                         }
174                 }
175         }
176
177         if (osender) {
178                 sender = strdup(osender);
179                 if (sender == NULL)
180                         return (NULL);
181         } else {
182                 if (asprintf(&sender, "%s@%s", username, hostname()) <= 0)
183                         return (NULL);
184         }
185
186         if (strchr(sender, '\n') != NULL) {
187                 errno = EINVAL;
188                 return (NULL);
189         }
190
191 out:
192         return (sender);
193 }
194
195 static int
196 read_aliases(void)
197 {
198         yyin = fopen(config->aliases, "r");
199         if (yyin == NULL)
200                 return (0);     /* not fatal */
201         if (yyparse())
202                 return (-1);    /* fatal error, probably malloc() */
203         fclose(yyin);
204         return (0);
205 }
206
207 static int
208 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
209 {
210         struct qitem *it, *tit;
211         struct stritem *sit;
212         struct alias *al;
213         struct passwd *pw;
214         char *host;
215         int aliased = 0;
216
217         it = calloc(1, sizeof(*it));
218         if (it == NULL)
219                 return (-1);
220         it->addr = strdup(str);
221         if (it->addr == NULL)
222                 return (-1);
223
224         it->sender = sender;
225         host = strrchr(it->addr, '@');
226         if (host != NULL &&
227             (strcmp(host + 1, hostname()) == 0 ||
228              strcmp(host + 1, "localhost") == 0)) {
229                 *host = 0;
230         }
231         LIST_FOREACH(tit, &queue->queue, next) {
232                 /* weed out duplicate dests */
233                 if (strcmp(tit->addr, it->addr) == 0) {
234                         free(it->addr);
235                         free(it);
236                         return (0);
237                 }
238         }
239         LIST_INSERT_HEAD(&queue->queue, it, next);
240         if (strrchr(it->addr, '@') == NULL) {
241                 it->remote = 0;
242                 if (expand) {
243                         LIST_FOREACH(al, &aliases, next) {
244                                 if (strcmp(al->alias, it->addr) != 0)
245                                         continue;
246                                 SLIST_FOREACH(sit, &al->dests, next) {
247                                         if (add_recp(queue, sit->str, sender, 1) != 0)
248                                                 return (-1);
249                                 }
250                                 aliased = 1;
251                         }
252                         if (aliased) {
253                                 LIST_REMOVE(it, next);
254                         } else {
255                                 /* Local destination, check */
256                                 pw = getpwnam(it->addr);
257                                 if (pw == NULL)
258                                         goto out;
259                                 endpwent();
260                         }
261                 }
262         } else {
263                 it->remote = 1;
264         }
265
266         return (0);
267
268 out:
269         free(it->addr);
270         free(it);
271         return (-1);
272 }
273
274 static void
275 deltmp(void)
276 {
277         struct stritem *t;
278
279         SLIST_FOREACH(t, &tmpfs, next) {
280                 unlink(t->str);
281         }
282 }
283
284 static int
285 gentempf(struct queue *queue)
286 {
287         char fn[PATH_MAX+1];
288         struct stritem *t;
289         int fd;
290
291         if (snprintf(fn, sizeof(fn), "%s/%s", config->spooldir, "tmp_XXXXXXXXXX") <= 0)
292                 return (-1);
293         fd = mkstemp(fn);
294         if (fd < 0)
295                 return (-1);
296         if (flock(fd, LOCK_EX) == -1)
297                 return (-1);
298         queue->mailfd = fd;
299         queue->tmpf = strdup(fn);
300         if (queue->tmpf == NULL) {
301                 unlink(fn);
302                 return (-1);
303         }
304         t = malloc(sizeof(*t));
305         if (t != NULL) {
306                 t->str = queue->tmpf;
307                 SLIST_INSERT_HEAD(&tmpfs, t, next);
308         }
309         return (0);
310 }
311
312 static int
313 open_locked(const char *fname, int flags)
314 {
315 #ifndef O_EXLOCK
316         int fd, save_errno;
317
318         fd = open(fname, flags, 0);
319         if (fd < 0)
320                 return(fd);
321         if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) {
322                 save_errno = errno;
323                 close(fd);
324                 errno = save_errno;
325                 return(-1);
326         }
327         return(fd);
328 #else
329         return(open(fname, flags|O_EXLOCK));
330 #endif
331 }
332
333 /*
334  * spool file format:
335  *
336  * envelope-from
337  * queue-id1 envelope-to1
338  * queue-id2 envelope-to2
339  * ...
340  * <empty line>
341  * mail data
342  *
343  * queue ids are unique, formed from the inode of the spool file
344  * and a unique identifier.
345  */
346 static int
347 preparespool(struct queue *queue, const char *sender)
348 {
349         char line[1000];        /* by RFC2822 */
350         struct stat st;
351         int error;
352         struct qitem *it;
353         FILE *queuef;
354         off_t hdrlen;
355
356         error = snprintf(line, sizeof(line), "%s\n", sender);
357         if (error < 0 || (size_t)error >= sizeof(line)) {
358                 errno = E2BIG;
359                 return (-1);
360         }
361         if (write(queue->mailfd, line, error) != error)
362                 return (-1);
363
364         queuef = fdopen(queue->mailfd, "r+");
365         if (queuef == NULL)
366                 return (-1);
367
368         /*
369          * Assign queue id to each dest.
370          */
371         if (fstat(queue->mailfd, &st) != 0)
372                 return (-1);
373         queue->id = st.st_ino;
374
375         syslog(LOG_INFO, "%"PRIxMAX": new mail from user=%s uid=%d envelope_from=<%s>",
376                queue->id, username, uid, sender);
377
378         LIST_FOREACH(it, &queue->queue, next) {
379                 if (asprintf(&it->queueid, "%"PRIxMAX".%"PRIxPTR,
380                              queue->id, (uintptr_t)it) <= 0)
381                         return (-1);
382                 if (asprintf(&it->queuefn, "%s/%s",
383                              config->spooldir, it->queueid) <= 0)
384                         return (-1);
385                 /* File may not exist yet */
386                 if (stat(it->queuefn, &st) == 0)
387                         return (-1);
388                 it->queuef = queuef;
389                 error = snprintf(line, sizeof(line), "%s %s\n",
390                                it->queueid, it->addr);
391                 if (error < 0 || (size_t)error >= sizeof(line))
392                         return (-1);
393                 if (write(queue->mailfd, line, error) != error)
394                         return (-1);
395
396                 syslog(LOG_INFO, "%"PRIxMAX": mail to=<%s> queued as %s",
397                        queue->id, it->addr, it->queueid);
398         }
399         line[0] = '\n';
400         if (write(queue->mailfd, line, 1) != 1)
401                 return (-1);
402
403         hdrlen = lseek(queue->mailfd, 0, SEEK_CUR);
404         LIST_FOREACH(it, &queue->queue, next) {
405                 it->hdrlen = hdrlen;
406         }
407         return (0);
408 }
409
410 static char *
411 rfc822date(void)
412 {
413         static char str[50];
414         size_t error;
415         time_t now;
416
417         now = time(NULL);
418         error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
419                        localtime(&now));
420         if (error == 0)
421                 strcpy(str, "(date fail)");
422         return (str);
423 }
424
425 static int
426 strprefixcmp(const char *str, const char *prefix)
427 {
428         return (strncasecmp(str, prefix, strlen(prefix)));
429 }
430
431 static int
432 readmail(struct queue *queue, const char *sender, int nodot)
433 {
434         char line[1000];        /* by RFC2822 */
435         size_t linelen;
436         int error;
437         int had_headers = 0;
438         int had_from = 0;
439         int had_messagid = 0;
440         int had_date = 0;
441
442         error = snprintf(line, sizeof(line),
443                 "Received: from %s (uid %d)\n"
444                 "\t(envelope-from %s)\n"
445                 "\tid %"PRIxMAX"\n"
446                 "\tby %s (%s)\n"
447                 "\t%s\n",
448                 username, uid,
449                 sender,
450                 queue->id,
451                 hostname(), VERSION,
452                 rfc822date());
453         if (error < 0 || (size_t)error >= sizeof(line))
454                 return (-1);
455         if (write(queue->mailfd, line, error) != error)
456                 return (-1);
457
458         while (!feof(stdin)) {
459                 if (fgets(line, sizeof(line), stdin) == NULL)
460                         break;
461                 linelen = strlen(line);
462                 if (linelen == 0 || line[linelen - 1] != '\n') {
463                         errno = EINVAL;         /* XXX mark permanent errors */
464                         return (-1);
465                 }
466                 if (!had_headers) {
467                         if (strprefixcmp(line, "Date:") == 0)
468                                 had_date = 1;
469                         else if (strprefixcmp(line, "Message-Id:") == 0)
470                                 had_messagid = 1;
471                         else if (strprefixcmp(line, "From:") == 0)
472                                 had_from = 1;
473                 }
474                 if (strcmp(line, "\n") == 0 && !had_headers) {
475                         had_headers = 1;
476                         while (!had_date || !had_messagid || !had_from) {
477                                 if (!had_date) {
478                                         had_date = 1;
479                                         snprintf(line, sizeof(line), "Date: %s\n", rfc822date());
480                                 } else if (!had_messagid) {
481                                         /* XXX better msgid, assign earlier and log? */
482                                         had_messagid = 1;
483                                         snprintf(line, sizeof(line), "Message-Id: <%"PRIxMAX"@%s>\n",
484                                                  queue->id, hostname());
485                                 } else if (!had_from) {
486                                         had_from = 1;
487                                         snprintf(line, sizeof(line), "From: <%s>\n", sender);
488                                 }
489                                 if ((size_t)write(queue->mailfd, line, strlen(line)) != strlen(line))
490                                         return (-1);
491                         }
492                         strcpy(line, "\n");
493                 }
494                 if (!nodot && linelen == 2 && line[0] == '.')
495                         break;
496                 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
497                         return (-1);
498         }
499         if (fsync(queue->mailfd) != 0)
500                 return (-1);
501         return (0);
502 }
503
504 static int
505 linkspool(struct queue *queue)
506 {
507         struct qitem *it;
508
509         LIST_FOREACH(it, &queue->queue, next) {
510                 if (link(queue->tmpf, it->queuefn) != 0)
511                         goto delfiles;
512         }
513         unlink(queue->tmpf);
514         return (0);
515
516 delfiles:
517         LIST_FOREACH(it, &queue->queue, next) {
518                 unlink(it->queuefn);
519         }
520         return (-1);
521 }
522
523 static struct qitem *
524 go_background(struct queue *queue)
525 {
526         struct sigaction sa;
527         struct qitem *it;
528         FILE *newqf;
529         pid_t pid;
530
531         if (daemonize && daemon(0, 0) != 0) {
532                 syslog(LOG_ERR, "can not daemonize: %m");
533                 exit(1);
534         }
535         daemonize = 0;
536
537         bzero(&sa, sizeof(sa));
538         sa.sa_flags = SA_NOCLDWAIT;
539         sa.sa_handler = SIG_IGN;
540         sigaction(SIGCHLD, &sa, NULL);
541
542         LIST_FOREACH(it, &queue->queue, next) {
543                 /* No need to fork for the last dest */
544                 if (LIST_NEXT(it, next) == NULL)
545                         return (it);
546
547                 pid = fork();
548                 switch (pid) {
549                 case -1:
550                         syslog(LOG_ERR, "can not fork: %m");
551                         exit(1);
552                         break;
553
554                 case 0:
555                         /*
556                          * Child:
557                          *
558                          * return and deliver mail
559                          */
560                         /*
561                          * We have to prevent sharing of fds between children, so
562                          * we have to re-open the queue file.
563                          */
564                         newqf = fopen(it->queuefn, "r");
565                         if (newqf == NULL) {
566                                 syslog(LOG_ERR, "can not re-open queue file `%s': %m",
567                                        it->queuefn);
568                                 exit(1);
569                         }
570                         fclose(it->queuef);
571                         it->queuef = newqf;
572                         return (it);
573
574                 default:
575                         /*
576                          * Parent:
577                          *
578                          * fork next child
579                          */
580                         break;
581                 }
582         }
583
584         syslog(LOG_CRIT, "reached dead code");
585         exit(1);
586 }
587
588 static void
589 bounce(struct qitem *it, const char *reason)
590 {
591         struct queue bounceq;
592         struct qitem *bit;
593         char line[1000];
594         size_t pos;
595         int error;
596
597         /* Don't bounce bounced mails */
598         if (it->sender[0] == 0) {
599                 syslog(LOG_INFO, "%s: can not bounce a bounce message, discarding",
600                        it->queueid);
601                 exit(1);
602         }
603
604         syslog(LOG_ERR, "%s: delivery failed, bouncing",
605                it->queueid);
606
607         LIST_INIT(&bounceq.queue);
608         if (add_recp(&bounceq, it->sender, "", 1) != 0)
609                 goto fail;
610         if (gentempf(&bounceq) != 0)
611                 goto fail;
612         if (preparespool(&bounceq, "") != 0)
613                 goto fail;
614
615         bit = LIST_FIRST(&bounceq.queue);
616         error = fprintf(bit->queuef,
617                 "Received: from MAILER-DAEMON\n"
618                 "\tid %"PRIxMAX"\n"
619                 "\tby %s (%s)\n"
620                 "\t%s\n"
621                 "X-Original-To: <%s>\n"
622                 "From: MAILER-DAEMON <>\n"
623                 "To: %s\n"
624                 "Subject: Mail delivery failed\n"
625                 "Message-Id: <%"PRIxMAX"@%s>\n"
626                 "Date: %s\n"
627                 "\n"
628                 "This is the %s at %s.\n"
629                 "\n"
630                 "There was an error delivering your mail to <%s>.\n"
631                 "\n"
632                 "%s\n"
633                 "\n"
634                 "%s\n"
635                 "\n",
636                 bounceq.id,
637                 hostname(), VERSION,
638                 rfc822date(),
639                 it->addr,
640                 it->sender,
641                 bounceq.id, hostname(),
642                 rfc822date(),
643                 VERSION, hostname(),
644                 it->addr,
645                 reason,
646                 config->features & FULLBOUNCE ?
647                     "Original message follows." :
648                     "Message headers follow.");
649         if (error < 0)
650                 goto fail;
651         if (fflush(bit->queuef) != 0)
652                 goto fail;
653
654         if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
655                 goto fail;
656         if (config->features & FULLBOUNCE) {
657                 while ((pos = fread(line, 1, sizeof(line), it->queuef)) > 0) {
658                         if ((size_t)write(bounceq.mailfd, line, pos) != pos)
659                                 goto fail;
660                 }
661         } else {
662                 while (!feof(it->queuef)) {
663                         if (fgets(line, sizeof(line), it->queuef) == NULL)
664                                 break;
665                         if (line[0] == '\n')
666                                 break;
667                         if ((size_t)write(bounceq.mailfd, line, strlen(line)) != strlen(line))
668                                 goto fail;
669                 }
670         }
671         if (fsync(bounceq.mailfd) != 0)
672                 goto fail;
673         if (linkspool(&bounceq) != 0)
674                 goto fail;
675         /* bounce is safe */
676
677         unlink(it->queuefn);
678         fclose(it->queuef);
679
680         bit = go_background(&bounceq);
681         deliver(bit);
682         /* NOTREACHED */
683
684 fail:
685         syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
686         unlink(it->queuefn);
687         exit(1);
688 }
689
690 static int
691 deliver_local(struct qitem *it, const char **errmsg)
692 {
693         char fn[PATH_MAX+1];
694         char line[1000];
695         size_t linelen;
696         int mbox;
697         int error;
698         off_t mboxlen;
699         time_t now = time(NULL);
700
701         error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
702         if (error < 0 || (size_t)error >= sizeof(fn)) {
703                 syslog(LOG_NOTICE, "%s: local delivery deferred: %m",
704                        it->queueid);
705                 return (1);
706         }
707
708         /* mailx removes users mailspool file if empty, so open with O_CREAT */
709         mbox = open_locked(fn, O_WRONLY | O_APPEND | O_CREAT);
710         if (mbox < 0) {
711                 syslog(LOG_NOTICE, "%s: local delivery deferred: can not open `%s': %m",
712                        it->queueid, fn);
713                 return (1);
714         }
715         mboxlen = lseek(mbox, 0, SEEK_CUR);
716
717         if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
718                 syslog(LOG_NOTICE, "%s: local delivery deferred: can not seek: %m",
719                        it->queueid);
720                 return (1);
721         }
722
723         error = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
724         if (error < 0 || (size_t)error >= sizeof(line)) {
725                 syslog(LOG_NOTICE, "%s: local delivery deferred: can not write header: %m",
726                        it->queueid);
727                 return (1);
728         }
729         if (write(mbox, line, error) != error)
730                 goto wrerror;
731
732         while (!feof(it->queuef)) {
733                 if (fgets(line, sizeof(line), it->queuef) == NULL)
734                         break;
735                 linelen = strlen(line);
736                 if (linelen == 0 || line[linelen - 1] != '\n') {
737                         syslog(LOG_CRIT, "%s: local delivery failed: corrupted queue file",
738                                it->queueid);
739                         *errmsg = "corrupted queue file";
740                         error = -1;
741                         goto chop;
742                 }
743
744                 if (strncmp(line, "From ", 5) == 0) {
745                         const char *gt = ">";
746
747                         if (write(mbox, gt, 1) != 1)
748                                 goto wrerror;
749                 }
750                 if ((size_t)write(mbox, line, linelen) != linelen)
751                         goto wrerror;
752         }
753         line[0] = '\n';
754         if (write(mbox, line, 1) != 1)
755                 goto wrerror;
756         close(mbox);
757         return (0);
758
759 wrerror:
760         syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
761                it->queueid);
762         error = 1;
763 chop:
764         if (ftruncate(mbox, mboxlen) != 0)
765                 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
766                        it->queueid, fn);
767         close(mbox);
768         return (error);
769 }
770
771 static void
772 deliver(struct qitem *it)
773 {
774         int error;
775         unsigned int backoff = MIN_RETRY;
776         const char *errmsg = "unknown bounce reason";
777         struct timeval now;
778         struct stat st;
779
780         syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
781                it->queueid, it->sender, it->addr);
782
783 retry:
784         syslog(LOG_INFO, "%s: trying delivery",
785                it->queueid);
786
787         if (it->remote)
788                 error = deliver_remote(it, &errmsg);
789         else
790                 error = deliver_local(it, &errmsg);
791
792         switch (error) {
793         case 0:
794                 unlink(it->queuefn);
795                 syslog(LOG_INFO, "%s: delivery successful",
796                        it->queueid);
797                 exit(0);
798
799         case 1:
800                 if (stat(it->queuefn, &st) != 0) {
801                         syslog(LOG_ERR, "%s: lost queue file `%s'",
802                                it->queueid, it->queuefn);
803                         exit(1);
804                 }
805                 if (gettimeofday(&now, NULL) == 0 &&
806                     (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
807                         asprintf(__DECONST(void *, &errmsg),
808                                  "Could not deliver for the last %d seconds. Giving up.",
809                                  MAX_TIMEOUT);
810                         goto bounce;
811                 }
812                 sleep(backoff);
813                 backoff *= 2;
814                 if (backoff > MAX_RETRY)
815                         backoff = MAX_RETRY;
816                 goto retry;
817
818         case -1:
819         default:
820                 break;
821         }
822
823 bounce:
824         bounce(it, errmsg);
825         /* NOTREACHED */
826 }
827
828 static int
829 c2x(char c)
830 {
831         if (c <= '9')
832                 return (c - '0');
833         else if (c <= 'F')
834                 return (c - 'A' + 10);
835         else
836                 return (c - 'a' + 10);
837 }
838
839 static void
840 seen_init(void)
841 {
842         int i, j;
843
844         for (i = 0; i < 16; i++)
845                 for (j = 0; j < 16; j++)
846                         SLIST_INIT(&seenmsg[i][j]);
847 }
848
849 static int
850 seen(const char *msgid)
851 {
852         const char *p;
853         size_t len;
854         int i, j;
855         struct stritem *t;
856
857         p = strchr(msgid, '.');
858         if (p == NULL)
859                 return (0);
860         len = p - msgid;
861         if (len >= 2) {
862                 i = c2x(msgid[len - 2]);
863                 j = c2x(msgid[len - 1]);
864         } else if (len == 1) {
865                 i = c2x(msgid[0]);
866                 j = 0;
867         } else {
868                 i = j = 0;
869         }
870         if (i < 0 || i >= 16 || j < 0 || j >= 16)
871                 errx(1, "INTERNAL ERROR: bad seen code for msgid %s", msgid);
872         SLIST_FOREACH(t, &seenmsg[i][j], next)
873                 if (!strncmp(t->str, msgid, len))
874                         return (1);
875         t = malloc(sizeof(*t));
876         if (t == NULL)
877                 errx(1, "Could not allocate %lu bytes",
878                     (unsigned long)(sizeof(*t)));
879         t->str = strdup(msgid);
880         if (t->str == NULL)
881                 errx(1, "Could not duplicate msgid %s", msgid);
882         SLIST_INSERT_HEAD(&seenmsg[i][j], t, next);
883         return (0);
884 }
885
886 static void
887 load_queue(struct queue *queue, int ignorelock)
888 {
889         struct stat st;
890         struct qitem *it;
891         //struct queue queue, itmqueue;
892         struct queue itmqueue;
893         DIR *spooldir;
894         struct dirent *de;
895         char line[1000];
896         char *fn;
897         FILE *queuef;
898         char *sender;
899         char *addr;
900         char *queueid;
901         char *queuefn;
902         off_t hdrlen;
903         int fd, locked, seenit;
904
905         LIST_INIT(&queue->queue);
906
907         spooldir = opendir(config->spooldir);
908         if (spooldir == NULL)
909                 err(1, "reading queue");
910
911         seen_init();
912         while ((de = readdir(spooldir)) != NULL) {
913                 sender = NULL;
914                 queuef = NULL;
915                 queueid = NULL;
916                 queuefn = NULL;
917                 fn = NULL;
918                 LIST_INIT(&itmqueue.queue);
919
920                 /* ignore temp files */
921                 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
922                     de->d_type != DT_REG)
923                         continue;
924                 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
925                         goto fail;
926                 seenit = seen(de->d_name);
927                 locked = 0;
928                 fd = open_locked(queuefn, O_RDONLY|O_NONBLOCK);
929                 if (fd < 0) {
930                         /* Ignore locked files */
931                         if (errno != EWOULDBLOCK)
932                                 goto skip_item;
933                         if (!ignorelock || seenit)
934                                 continue;
935                         fd = open(queuefn, O_RDONLY);
936                         if (fd < 0)
937                                 goto skip_item;
938                         locked = 1;
939                 }
940
941                 queuef = fdopen(fd, "r");
942                 if (queuef == NULL)
943                         goto skip_item;
944                 if (fgets(line, sizeof(line), queuef) == NULL ||
945                     line[0] == 0)
946                         goto skip_item;
947                 line[strlen(line) - 1] = 0;     /* chop newline */
948                 sender = strdup(line);
949                 if (sender == NULL)
950                         goto skip_item;
951
952                 for (;;) {
953                         if (fgets(line, sizeof(line), queuef) == NULL ||
954                             line[0] == 0)
955                                 goto skip_item;
956                         if (line[0] == '\n')
957                                 break;
958                         line[strlen(line) - 1] = 0;
959                         queueid = strdup(line);
960                         if (queueid == NULL)
961                                 goto skip_item;
962                         addr = strchr(queueid, ' ');
963                         if (addr == NULL)
964                                 goto skip_item;
965                         *addr++ = 0;
966                         if (fn != NULL)
967                                 free(fn);
968                         if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
969                                 goto skip_item;
970                         /* Item has already been delivered? */
971                         if (stat(fn, &st) != 0)
972                                 continue;
973                         if (add_recp(&itmqueue, addr, sender, 0) != 0)
974                                 goto skip_item;
975                         it = LIST_FIRST(&itmqueue.queue);
976                         it->queuef = queuef;
977                         it->queueid = queueid;
978                         it->queuefn = fn;
979                         it->locked = locked;
980                         fn = NULL;
981                 }
982                 if (LIST_EMPTY(&itmqueue.queue)) {
983                         warnx("queue file without items: `%s'", queuefn);
984                         goto skip_item2;
985                 }
986                 hdrlen = ftell(queuef);
987                 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
988                         it->hdrlen = hdrlen;
989                         LIST_REMOVE(it, next);
990                         LIST_INSERT_HEAD(&queue->queue, it, next);
991                 }
992                 continue;
993
994 skip_item:
995                 warn("reading queue: `%s'", queuefn);
996 skip_item2:
997                 if (sender != NULL)
998                         free(sender);
999                 if (queuefn != NULL)
1000                         free(queuefn);
1001                 if (fn != NULL)
1002                         free(fn);
1003                 if (queueid != NULL)
1004                         free(queueid);
1005                 close(fd);
1006         }
1007         closedir(spooldir);
1008         return;
1009
1010 fail:
1011         err(1, "reading queue");
1012 }
1013
1014 static void
1015 run_queue(struct queue *queue)
1016 {
1017         struct qitem *it;
1018
1019         if (LIST_EMPTY(&queue->queue))
1020                 return;
1021
1022         it = go_background(queue);
1023         deliver(it);
1024         /* NOTREACHED */
1025 }
1026
1027 static void
1028 show_queue(struct queue *queue)
1029 {
1030         struct qitem *it;
1031
1032         if (LIST_EMPTY(&queue->queue)) {
1033                 printf("Mail queue is empty\n");
1034                 return;
1035         }
1036
1037         LIST_FOREACH(it, &queue->queue, next) {
1038                 printf("ID\t: %s%s\n"
1039                        "From\t: %s\n"
1040                        "To\t: %s\n"
1041                        "--\n",
1042                        it->queueid,
1043                        it->locked ? "*" : "",
1044                        it->sender, it->addr);
1045         }
1046 }
1047
1048 /*
1049  * TODO:
1050  *
1051  * - alias processing
1052  * - use group permissions
1053  * - proper sysexit codes
1054  */
1055
1056 int
1057 main(int argc, char **argv)
1058 {
1059         char *sender = NULL;
1060         char tag[255];
1061         struct qitem *it;
1062         struct queue queue;
1063         struct queue lqueue;
1064         int i, ch;
1065         int nodot = 0, doqueue = 0, showq = 0;
1066
1067         atexit(deltmp);
1068         LIST_INIT(&queue.queue);
1069         snprintf(tag, 254, "dma");
1070
1071         if (strcmp(argv[0], "mailq") == 0) {
1072                 argv++; argc--;
1073                 showq = 1;
1074                 if (argc != 0)
1075                         errx(1, "invalid arguments");
1076                 goto skipopts;
1077         }
1078
1079         opterr = 0;
1080         while ((ch = getopt(argc, argv, "A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
1081                 switch (ch) {
1082                 case 'A':
1083                         /* -AX is being ignored, except for -A{c,m} */
1084                         if (optarg[0] == 'c' || optarg[0] == 'm') {
1085                                 break;
1086                         }
1087                         /* else FALLTRHOUGH */
1088                 case 'b':
1089                         /* -bX is being ignored, except for -bp */
1090                         if (optarg[0] == 'p') {
1091                                 showq = 1;
1092                                 break;
1093                         }
1094                         /* else FALLTRHOUGH */
1095                 case 'D':
1096                         daemonize = 0;
1097                         break;
1098                 case 'L':
1099                         if (optarg != NULL)
1100                                 snprintf(tag, 254, "%s", optarg);
1101                         break;
1102                 case 'f':
1103                 case 'r':
1104                         sender = optarg;
1105                         break;
1106
1107                 case 'o':
1108                         /* -oX is being ignored, except for -oi */
1109                         if (optarg[0] != 'i')
1110                                 break;
1111                         /* else FALLTRHOUGH */
1112                 case 'O':
1113                         break;
1114                 case 'i':
1115                         nodot = 1;
1116                         break;
1117
1118                 case 'q':
1119                         doqueue = 1;
1120                         break;
1121
1122                 /* Ignored options */
1123                 case 'B':
1124                 case 'C':
1125                 case 'd':
1126                 case 'F':
1127                 case 'h':
1128                 case 'N':
1129                 case 'n':
1130                 case 'R':
1131                 case 'U':
1132                 case 'V':
1133                 case 'v':
1134                 case 'X':
1135                         break;
1136
1137                 default:
1138                         exit(1);
1139                 }
1140         }
1141         argc -= optind;
1142         argv += optind;
1143         opterr = 1;
1144
1145 skipopts:
1146         openlog(tag, LOG_PID, LOG_MAIL);
1147         set_username();
1148
1149         config = malloc(sizeof(struct config));
1150         if (config == NULL)
1151                 err(1, NULL);
1152
1153         memset(config, 0, sizeof(struct config));
1154         if (parse_conf(CONF_PATH, config) < 0) {
1155                 free(config);
1156                 err(1, "can not read config file");
1157         }
1158
1159         if (config->features & VIRTUAL)
1160                 if (parse_virtuser(config->virtualpath) < 0)
1161                         err(1, "can not read virtual user file `%s'",
1162                                 config->virtualpath);
1163
1164         if (parse_authfile(config->authpath) < 0)
1165                 err(1, "can not read SMTP authentication file");
1166
1167         if (showq) {
1168                 if (argc != 0)
1169                         errx(1, "sending mail and displaying queue is"
1170                                 " mutually exclusive");
1171                 load_queue(&lqueue, 1);
1172                 show_queue(&lqueue);
1173                 return (0);
1174         }
1175
1176         if (doqueue) {
1177                 if (argc != 0)
1178                         errx(1, "sending mail and queue pickup is mutually exclusive");
1179                 load_queue(&lqueue, 0);
1180                 run_queue(&lqueue);
1181                 return (0);
1182         }
1183
1184         if (read_aliases() != 0)
1185                 err(1, "can not read aliases file `%s'", config->aliases);
1186
1187         if ((sender = set_from(sender)) == NULL)
1188                 err(1, NULL);
1189
1190         for (i = 0; i < argc; i++) {
1191                 if (add_recp(&queue, argv[i], sender, 1) != 0)
1192                         errx(1, "invalid recipient `%s'", argv[i]);
1193         }
1194
1195         if (LIST_EMPTY(&queue.queue))
1196                 errx(1, "no recipients");
1197
1198         if (gentempf(&queue) != 0)
1199                 err(1, "can not create temp file");
1200
1201         if (preparespool(&queue, sender) != 0)
1202                 err(1, "can not create spools (1)");
1203
1204         if (readmail(&queue, sender, nodot) != 0)
1205                 err(1, "can not read mail");
1206
1207         if (linkspool(&queue) != 0)
1208                 err(1, "can not create spools (2)");
1209
1210         /* From here on the mail is safe. */
1211
1212         if (config->features & DEFER)
1213                 return (0);
1214
1215         it = go_background(&queue);
1216         deliver(it);
1217
1218         /* NOTREACHED */
1219         return (0);
1220 }