4633b0c6d3b9104cd76b7e48336affed7295507e
[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         pid_t pid;
488
489         if (daemonize && daemon(0, 0) != 0) {
490                 syslog(LOG_ERR, "can not daemonize: %m");
491                 exit(1);
492         }
493         daemonize = 0;
494
495         bzero(&sa, sizeof(sa));
496         sa.sa_flags = SA_NOCLDWAIT;
497         sa.sa_handler = SIG_IGN;
498         sigaction(SIGCHLD, &sa, NULL);
499
500         LIST_FOREACH(it, &queue->queue, next) {
501                 /* No need to fork for the last dest */
502                 if (LIST_NEXT(it, next) == NULL)
503                         return (it);
504
505                 pid = fork();
506                 switch (pid) {
507                 case -1:
508                         syslog(LOG_ERR, "can not fork: %m");
509                         exit(1);
510                         break;
511
512                 case 0:
513                         /*
514                          * Child:
515                          *
516                          * return and deliver mail
517                          */
518                         return (it);
519
520                 default:
521                         /*
522                          * Parent:
523                          *
524                          * fork next child
525                          */
526                         break;
527                 }
528         }
529
530         syslog(LOG_CRIT, "reached dead code");
531         exit(1);
532 }
533
534 static void
535 bounce(struct qitem *it, const char *reason)
536 {
537         struct queue bounceq;
538         struct qitem *bit;
539         char line[1000];
540         size_t pos;
541         int error;
542
543         /* Don't bounce bounced mails */
544         if (it->sender[0] == 0) {
545                 syslog(LOG_CRIT, "%s: delivery panic: can't bounce a bounce",
546                        it->queueid);
547                 exit(1);
548         }
549
550         syslog(LOG_ERR, "%s: delivery failed, bouncing",
551                it->queueid);
552
553         LIST_INIT(&bounceq.queue);
554         if (add_recp(&bounceq, it->sender, "", 1) != 0)
555                 goto fail;
556         if (gentempf(&bounceq) != 0)
557                 goto fail;
558         if (preparespool(&bounceq, "") != 0)
559                 goto fail;
560
561         bit = LIST_FIRST(&bounceq.queue);
562         error = fprintf(bit->queuef, "\
563 Received: from MAILER-DAEMON\n\
564 \tid %"PRIxMAX"\n\
565 \tby %s (%s)\n\
566 \t%s\n\
567 X-Original-To: <%s>\n\
568 From: MAILER-DAEMON <>\n\
569 To: %s\n\
570 Subject: Mail delivery failed\n\
571 Message-Id: <%"PRIxMAX"@%s>\n\
572 Date: %s\n\
573 \n\
574 This is the %s at %s.\n\
575 \n\
576 There was an error delivering your mail to <%s>.\n\
577 \n\
578 %s\n\
579 \n\
580 %s\n\
581 \n\
582 ",
583                 bounceq.id,
584                 hostname(), VERSION,
585                 rfc822date(),
586                 it->addr,
587                 it->sender,
588                 bounceq.id, hostname(),
589                 rfc822date(),
590                 VERSION, hostname(),
591                 it->addr,
592                 reason,
593                 config->features & FULLBOUNCE? "Original message follows.":
594                 "Message headers follow.");
595         if (error < 0)
596                 goto fail;
597         if (fflush(bit->queuef) != 0)
598                 goto fail;
599
600         if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
601                 goto fail;
602         if (config->features & FULLBOUNCE) {
603                 while ((pos = fread(line, 1, sizeof(line), it->queuef)) > 0) {
604                         if ((size_t)write(bounceq.mailfd, line, pos) != pos)
605                                 goto fail;
606                 }
607         } else {
608                 while (!feof(it->queuef)) {
609                         if (fgets(line, sizeof(line), it->queuef) == NULL)
610                                 break;
611                         if (line[0] == '\n')
612                                 break;
613                         if ((size_t)write(bounceq.mailfd, line, strlen(line)) != strlen(line))
614                                 goto fail;
615                 }
616         }
617         if (fsync(bounceq.mailfd) != 0)
618                 goto fail;
619         if (linkspool(&bounceq) != 0)
620                 goto fail;
621         /* bounce is safe */
622
623         unlink(it->queuefn);
624         fclose(it->queuef);
625
626         bit = go_background(&bounceq);
627         deliver(bit);
628         /* NOTREACHED */
629
630 fail:
631         syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
632         unlink(it->queuefn);
633         exit(1);
634 }
635
636 static int
637 deliver_local(struct qitem *it, const char **errmsg)
638 {
639         char fn[PATH_MAX+1];
640         char line[1000];
641         size_t linelen;
642         int mbox;
643         int error;
644         off_t mboxlen;
645         time_t now = time(NULL);
646
647         error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
648         if (error < 0 || (size_t)error >= sizeof(fn)) {
649                 syslog(LOG_ERR, "%s: local delivery deferred: %m",
650                        it->queueid);
651                 return (1);
652         }
653
654         /* mailx removes users mailspool file if empty, so open with O_CREAT */
655         mbox = open_locked(fn, O_WRONLY | O_APPEND | O_CREAT);
656         if (mbox < 0) {
657                 syslog(LOG_ERR, "%s: local delivery deferred: can not open `%s': %m",
658                        it->queueid, fn);
659                 return (1);
660         }
661         mboxlen = lseek(mbox, 0, SEEK_CUR);
662
663         if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
664                 syslog(LOG_ERR, "%s: local delivery deferred: can not seek: %m",
665                        it->queueid);
666                 return (1);
667         }
668
669         error = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
670         if (error < 0 || (size_t)error >= sizeof(line)) {
671                 syslog(LOG_ERR, "%s: local delivery deferred: can not write header: %m",
672                        it->queueid);
673                 return (1);
674         }
675         if (write(mbox, line, error) != error)
676                 goto wrerror;
677
678         while (!feof(it->queuef)) {
679                 if (fgets(line, sizeof(line), it->queuef) == NULL)
680                         break;
681                 linelen = strlen(line);
682                 if (linelen == 0 || line[linelen - 1] != '\n') {
683                         syslog(LOG_CRIT, "%s: local delivery failed: corrupted queue file",
684                                it->queueid);
685                         *errmsg = "corrupted queue file";
686                         error = -1;
687                         goto chop;
688                 }
689
690                 if (strncmp(line, "From ", 5) == 0) {
691                         const char *gt = ">";
692
693                         if (write(mbox, gt, 1) != 1)
694                                 goto wrerror;
695                 }
696                 if ((size_t)write(mbox, line, linelen) != linelen)
697                         goto wrerror;
698         }
699         line[0] = '\n';
700         if (write(mbox, line, 1) != 1)
701                 goto wrerror;
702         close(mbox);
703         return (0);
704
705 wrerror:
706         syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
707                it->queueid);
708         error = 1;
709 chop:
710         if (ftruncate(mbox, mboxlen) != 0)
711                 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
712                        it->queueid, fn);
713         close(mbox);
714         return (error);
715 }
716
717 static void
718 deliver(struct qitem *it)
719 {
720         int error;
721         unsigned int backoff = MIN_RETRY;
722         const char *errmsg = "unknown bounce reason";
723         struct timeval now;
724         struct stat st;
725
726         syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
727                it->queueid, it->sender, it->addr);
728
729 retry:
730         syslog(LOG_INFO, "%s: trying delivery",
731                it->queueid);
732
733         if (it->remote)
734                 error = deliver_remote(it, &errmsg);
735         else
736                 error = deliver_local(it, &errmsg);
737
738         switch (error) {
739         case 0:
740                 unlink(it->queuefn);
741                 syslog(LOG_INFO, "%s: delivery successful",
742                        it->queueid);
743                 exit(0);
744
745         case 1:
746                 if (stat(it->queuefn, &st) != 0) {
747                         syslog(LOG_ERR, "%s: lost queue file `%s'",
748                                it->queueid, it->queuefn);
749                         exit(1);
750                 }
751                 if (gettimeofday(&now, NULL) == 0 &&
752                     (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
753                         asprintf(__DECONST(void *, &errmsg),
754                                  "Could not deliver for the last %d seconds. Giving up.",
755                                  MAX_TIMEOUT);
756                         goto bounce;
757                 }
758                 sleep(backoff);
759                 backoff *= 2;
760                 if (backoff > MAX_RETRY)
761                         backoff = MAX_RETRY;
762                 goto retry;
763
764         case -1:
765         default:
766                 break;
767         }
768
769 bounce:
770         bounce(it, errmsg);
771         /* NOTREACHED */
772 }
773
774 static int
775 c2x(char c)
776 {
777         if (c <= '9')
778                 return (c - '0');
779         else if (c <= 'F')
780                 return (c - 'A' + 10);
781         else
782                 return (c - 'a' + 10);
783 }
784
785 static void
786 seen_init(void)
787 {
788         int i, j;
789
790         for (i = 0; i < 16; i++)
791                 for (j = 0; j < 16; j++)
792                         SLIST_INIT(&seenmsg[i][j]);
793 }
794
795 static int
796 seen(const char *msgid)
797 {
798         const char *p;
799         size_t len;
800         int i, j;
801         struct stritem *t;
802
803         p = strchr(msgid, '.');
804         if (p == NULL)
805                 return (0);
806         len = p - msgid;
807         if (len >= 2) {
808                 i = c2x(msgid[len - 2]);
809                 j = c2x(msgid[len - 1]);
810         } else if (len == 1) {
811                 i = c2x(msgid[0]);
812                 j = 0;
813         } else {
814                 i = j = 0;
815         }
816         if (i < 0 || i >= 16 || j < 0 || j >= 16)
817                 errx(1, "INTERNAL ERROR: bad seen code for msgid %s", msgid);
818         SLIST_FOREACH(t, &seenmsg[i][j], next)
819                 if (!strncmp(t->str, msgid, len))
820                         return (1);
821         t = malloc(sizeof(*t));
822         if (t == NULL)
823                 errx(1, "Could not allocate %lu bytes",
824                     (unsigned long)(sizeof(*t)));
825         t->str = strdup(msgid);
826         if (t->str == NULL)
827                 errx(1, "Could not duplicate msgid %s", msgid);
828         SLIST_INSERT_HEAD(&seenmsg[i][j], t, next);
829         return (0);
830 }
831
832 static void
833 load_queue(struct queue *queue, int ignorelock)
834 {
835         struct stat st;
836         struct qitem *it;
837         //struct queue queue, itmqueue;
838         struct queue itmqueue;
839         DIR *spooldir;
840         struct dirent *de;
841         char line[1000];
842         char *fn;
843         FILE *queuef;
844         char *sender;
845         char *addr;
846         char *queueid;
847         char *queuefn;
848         off_t hdrlen;
849         int fd, locked, seenit;
850
851         LIST_INIT(&queue->queue);
852
853         spooldir = opendir(config->spooldir);
854         if (spooldir == NULL)
855                 err(1, "reading queue");
856
857         seen_init();
858         while ((de = readdir(spooldir)) != NULL) {
859                 sender = NULL;
860                 queuef = NULL;
861                 queueid = NULL;
862                 queuefn = NULL;
863                 fn = NULL;
864                 LIST_INIT(&itmqueue.queue);
865
866                 /* ignore temp files */
867                 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
868                     de->d_type != DT_REG)
869                         continue;
870                 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
871                         goto fail;
872                 seenit = seen(de->d_name);
873                 locked = 0;
874                 fd = open_locked(queuefn, O_RDONLY|O_NONBLOCK);
875                 if (fd < 0) {
876                         /* Ignore locked files */
877                         if (errno != EWOULDBLOCK)
878                                 goto skip_item;
879                         if (!ignorelock || seenit)
880                                 continue;
881                         fd = open(queuefn, O_RDONLY);
882                         if (fd < 0)
883                                 goto skip_item;
884                         locked = 1;
885                 }
886
887                 queuef = fdopen(fd, "r");
888                 if (queuef == NULL)
889                         goto skip_item;
890                 if (fgets(line, sizeof(line), queuef) == NULL ||
891                     line[0] == 0)
892                         goto skip_item;
893                 line[strlen(line) - 1] = 0;     /* chop newline */
894                 sender = strdup(line);
895                 if (sender == NULL)
896                         goto skip_item;
897
898                 for (;;) {
899                         if (fgets(line, sizeof(line), queuef) == NULL ||
900                             line[0] == 0)
901                                 goto skip_item;
902                         if (line[0] == '\n')
903                                 break;
904                         line[strlen(line) - 1] = 0;
905                         queueid = strdup(line);
906                         if (queueid == NULL)
907                                 goto skip_item;
908                         addr = strchr(queueid, ' ');
909                         if (addr == NULL)
910                                 goto skip_item;
911                         *addr++ = 0;
912                         if (fn != NULL)
913                                 free(fn);
914                         if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
915                                 goto skip_item;
916                         /* Item has already been delivered? */
917                         if (stat(fn, &st) != 0)
918                                 continue;
919                         if (add_recp(&itmqueue, addr, sender, 0) != 0)
920                                 goto skip_item;
921                         it = LIST_FIRST(&itmqueue.queue);
922                         it->queuef = queuef;
923                         it->queueid = queueid;
924                         it->queuefn = fn;
925                         it->locked = locked;
926                         fn = NULL;
927                 }
928                 if (LIST_EMPTY(&itmqueue.queue)) {
929                         warnx("queue file without items: `%s'", queuefn);
930                         goto skip_item2;
931                 }
932                 hdrlen = ftell(queuef);
933                 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
934                         it->hdrlen = hdrlen;
935                         LIST_REMOVE(it, next);
936                         LIST_INSERT_HEAD(&queue->queue, it, next);
937                 }
938                 continue;
939
940 skip_item:
941                 warn("reading queue: `%s'", queuefn);
942 skip_item2:
943                 if (sender != NULL)
944                         free(sender);
945                 if (queuefn != NULL)
946                         free(queuefn);
947                 if (fn != NULL)
948                         free(fn);
949                 if (queueid != NULL)
950                         free(queueid);
951                 close(fd);
952         }
953         closedir(spooldir);
954         return;
955
956 fail:
957         err(1, "reading queue");
958 }
959
960 static void
961 run_queue(struct queue *queue)
962 {
963         struct qitem *it;
964
965         if (LIST_EMPTY(&queue->queue))
966                 return;
967
968         it = go_background(queue);
969         deliver(it);
970         /* NOTREACHED */
971 }
972
973 static void
974 show_queue(struct queue *queue)
975 {
976         struct qitem *it;
977
978         if (LIST_EMPTY(&queue->queue)) {
979                 printf("Mail queue is empty\n");
980                 return;
981         }
982
983         LIST_FOREACH(it, &queue->queue, next) {
984                 printf("\
985 ID\t: %s%s\n\
986 From\t: %s\n\
987 To\t: %s\n--\n", it->queueid, it->locked? "*": "", it->sender, it->addr);
988         }
989 }
990
991 /*
992  * TODO:
993  *
994  * - alias processing
995  * - use group permissions
996  * - proper sysexit codes
997  */
998
999 int
1000 main(int argc, char **argv)
1001 {
1002         char *sender = NULL;
1003         char tag[255];
1004         struct qitem *it;
1005         struct queue queue;
1006         struct queue lqueue;
1007         int i, ch;
1008         int nodot = 0, doqueue = 0, showq = 0;
1009
1010         atexit(deltmp);
1011         LIST_INIT(&queue.queue);
1012         snprintf(tag, 254, "dma");
1013
1014         opterr = 0;
1015         while ((ch = getopt(argc, argv, "A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
1016                 switch (ch) {
1017                 case 'A':
1018                         /* -AX is being ignored, except for -A{c,m} */
1019                         if (optarg[0] == 'c' || optarg[0] == 'm') {
1020                                 break;
1021                         }
1022                         /* else FALLTRHOUGH */
1023                 case 'b':
1024                         /* -bX is being ignored, except for -bp */
1025                         if (optarg[0] == 'p') {
1026                                 showq = 1;
1027                                 break;
1028                         }
1029                         /* else FALLTRHOUGH */
1030                 case 'D':
1031                         daemonize = 0;
1032                         break;
1033                 case 'L':
1034                         if (optarg != NULL)
1035                                 snprintf(tag, 254, "%s", optarg);
1036                         break;
1037                 case 'f':
1038                 case 'r':
1039                         sender = optarg;
1040                         break;
1041
1042                 case 'o':
1043                         /* -oX is being ignored, except for -oi */
1044                         if (optarg[0] != 'i')
1045                                 break;
1046                         /* else FALLTRHOUGH */
1047                 case 'O':
1048                         break;
1049                 case 'i':
1050                         nodot = 1;
1051                         break;
1052
1053                 case 'q':
1054                         doqueue = 1;
1055                         break;
1056
1057                 /* Ignored options */
1058                 case 'B':
1059                 case 'C':
1060                 case 'd':
1061                 case 'F':
1062                 case 'h':
1063                 case 'N':
1064                 case 'n':
1065                 case 'R':
1066                 case 'U':
1067                 case 'V':
1068                 case 'v':
1069                 case 'X':
1070                         break;
1071
1072                 default:
1073                         exit(1);
1074                 }
1075         }
1076         argc -= optind;
1077         argv += optind;
1078         opterr = 1;
1079
1080         openlog(tag, LOG_PID | LOG_PERROR, LOG_MAIL);
1081         set_username();
1082
1083         config = malloc(sizeof(struct config));
1084         if (config == NULL)
1085                 errx(1, "Cannot allocate enough memory");
1086
1087         memset(config, 0, sizeof(struct config));
1088         if (parse_conf(CONF_PATH, config) < 0) {
1089                 free(config);
1090                 errx(1, "reading config file");
1091         }
1092
1093         if (config->features & VIRTUAL)
1094                 if (parse_virtuser(config->virtualpath) < 0)
1095                         errx(1, "error reading virtual user file: %s",
1096                                 config->virtualpath);
1097
1098         if (parse_authfile(config->authpath) < 0)
1099                 err(1, "reading SMTP authentication file");
1100
1101         if (showq) {
1102                 if (argc != 0)
1103                         errx(1, "sending mail and displaying queue is"
1104                                 " mutually exclusive");
1105                 load_queue(&lqueue, 1);
1106                 show_queue(&lqueue);
1107                 return (0);
1108         }
1109
1110         if (doqueue) {
1111                 if (argc != 0)
1112                         errx(1, "sending mail and queue pickup is mutually exclusive");
1113                 load_queue(&lqueue, 0);
1114                 run_queue(&lqueue);
1115                 return (0);
1116         }
1117
1118         if (read_aliases() != 0)
1119                 err(1, "reading aliases");
1120
1121         if ((sender = set_from(sender)) == NULL)
1122                 err(1, "setting from address");
1123
1124         for (i = 0; i < argc; i++) {
1125                 if (add_recp(&queue, argv[i], sender, 1) != 0)
1126                         errx(1, "invalid recipient `%s'\n", argv[i]);
1127         }
1128
1129         if (LIST_EMPTY(&queue.queue))
1130                 errx(1, "no recipients");
1131
1132         if (gentempf(&queue) != 0)
1133                 err(1, "create temp file");
1134
1135         if (preparespool(&queue, sender) != 0)
1136                 err(1, "creating spools (1)");
1137
1138         if (readmail(&queue, sender, nodot) != 0)
1139                 err(1, "reading mail");
1140
1141         if (linkspool(&queue) != 0)
1142                 err(1, "creating spools (2)");
1143
1144         /* From here on the mail is safe. */
1145
1146         if (config->features & DEFER)
1147                 return (0);
1148
1149         it = go_background(&queue);
1150         deliver(it);
1151
1152         /* NOTREACHED */
1153         return (0);
1154 }