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