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