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