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