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