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