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