2 * Copyright (c) 2008 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Simon 'corecode' Schubert <corecode@fs.ei.tum.de>.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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
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.
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
34 * $DragonFly: src/libexec/dma/dma.c,v 1.5 2008/09/30 17:47:21 swildner Exp $
37 #include <sys/param.h>
38 #include <sys/queue.h>
40 #include <sys/types.h>
44 #include <openssl/ssl.h>
45 #endif /* HAVE_CRYPTO */
67 static void deliver(struct qitem *);
68 static int add_recp(struct queue *, const char *, const char *, int);
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 struct strlist seenmsg[16][16];
82 static char name[MAXHOSTNAMELEN+1];
90 if (config->mailname != NULL && config->mailname[0] != '\0') {
91 snprintf(name, sizeof(name), "%s", config->mailname);
95 if (config->mailnamefile != NULL && config->mailnamefile[0] != '\0') {
96 fp = fopen(config->mailnamefile, "r");
98 if (fgets(name, sizeof(name), fp) != NULL) {
101 (name[len - 1] == '\r' ||
102 name[len - 1] == '\n'))
104 if (name[0] != '\0') {
112 if (gethostname(name, sizeof(name)) != 0)
113 strcpy(name, "(unknown hostname)");
119 set_from(const char *osender)
124 if ((config->features & VIRTUAL) != 0) {
125 SLIST_FOREACH(v, &virtusers, next) {
126 if (strcmp(v->login, getlogin()) == 0) {
127 sender = strdup(v->address);
136 sender = strdup(osender);
140 if (asprintf(&sender, "%s@%s", getlogin(), hostname()) <= 0)
144 if (strchr(sender, '\n') != NULL) {
156 yyin = fopen(config->aliases, "r");
158 return (0); /* not fatal */
160 return (-1); /* fatal error, probably malloc() */
166 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
168 struct qitem *it, *tit;
175 it = calloc(1, sizeof(*it));
178 it->addr = strdup(str);
179 if (it->addr == NULL)
183 host = strrchr(it->addr, '@');
185 (strcmp(host + 1, hostname()) == 0 ||
186 strcmp(host + 1, "localhost") == 0)) {
189 LIST_FOREACH(tit, &queue->queue, next) {
190 /* weed out duplicate dests */
191 if (strcmp(tit->addr, it->addr) == 0) {
197 LIST_INSERT_HEAD(&queue->queue, it, next);
198 if (strrchr(it->addr, '@') == NULL) {
201 LIST_FOREACH(al, &aliases, next) {
202 if (strcmp(al->alias, it->addr) != 0)
204 SLIST_FOREACH(sit, &al->dests, next) {
205 if (add_recp(queue, sit->str, sender, 1) != 0)
211 LIST_REMOVE(it, next);
213 /* Local destination, check */
214 pw = getpwnam(it->addr);
237 SLIST_FOREACH(t, &tmpfs, next) {
243 gentempf(struct queue *queue)
249 if (snprintf(fn, sizeof(fn), "%s/%s", config->spooldir, "tmp_XXXXXXXXXX") <= 0)
254 if (flock(fd, LOCK_EX) == -1)
257 queue->tmpf = strdup(fn);
258 if (queue->tmpf == NULL) {
262 t = malloc(sizeof(*t));
264 t->str = queue->tmpf;
265 SLIST_INSERT_HEAD(&tmpfs, t, next);
271 open_locked(const char *fname, int flags)
276 fd = open(fname, flags, 0);
279 if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) {
287 return(open(fname, flags|O_EXLOCK));
295 * queue-id1 envelope-to1
296 * queue-id2 envelope-to2
301 * queue ids are unique, formed from the inode of the spool file
302 * and a unique identifier.
305 preparespool(struct queue *queue, const char *sender)
307 char line[1000]; /* by RFC2822 */
314 error = snprintf(line, sizeof(line), "%s\n", sender);
315 if (error < 0 || (size_t)error >= sizeof(line)) {
319 if (write(queue->mailfd, line, error) != error)
322 queuef = fdopen(queue->mailfd, "r+");
327 * Assign queue id to each dest.
329 if (fstat(queue->mailfd, &st) != 0)
331 queue->id = st.st_ino;
332 LIST_FOREACH(it, &queue->queue, next) {
333 if (asprintf(&it->queueid, "%"PRIxMAX".%"PRIxPTR,
334 queue->id, (uintptr_t)it) <= 0)
336 if (asprintf(&it->queuefn, "%s/%s",
337 config->spooldir, it->queueid) <= 0)
339 /* File may not exist yet */
340 if (stat(it->queuefn, &st) == 0)
343 error = snprintf(line, sizeof(line), "%s %s\n",
344 it->queueid, it->addr);
345 if (error < 0 || (size_t)error >= sizeof(line))
347 if (write(queue->mailfd, line, error) != error)
351 if (write(queue->mailfd, line, 1) != 1)
354 hdrlen = lseek(queue->mailfd, 0, SEEK_CUR);
355 LIST_FOREACH(it, &queue->queue, next) {
369 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
372 strcpy(str, "(date fail)");
377 readmail(struct queue *queue, const char *sender, int nodot)
379 char line[1000]; /* by RFC2822 */
383 error = snprintf(line, sizeof(line), "\
384 Received: from %s (uid %d)\n\
385 \t(envelope-from %s)\n\
389 getlogin(), getuid(),
394 if (error < 0 || (size_t)error >= sizeof(line))
396 if (write(queue->mailfd, line, error) != error)
399 while (!feof(stdin)) {
400 if (fgets(line, sizeof(line), stdin) == NULL)
402 linelen = strlen(line);
403 if (linelen == 0 || line[linelen - 1] != '\n') {
404 errno = EINVAL; /* XXX mark permanent errors */
407 if (!nodot && linelen == 2 && line[0] == '.')
409 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
412 if (fsync(queue->mailfd) != 0)
418 linkspool(struct queue *queue)
422 LIST_FOREACH(it, &queue->queue, next) {
423 if (link(queue->tmpf, it->queuefn) != 0)
430 LIST_FOREACH(it, &queue->queue, next) {
436 static struct qitem *
437 go_background(struct queue *queue)
443 if (daemonize && daemon(0, 0) != 0) {
444 syslog(LOG_ERR, "can not daemonize: %m");
449 bzero(&sa, sizeof(sa));
450 sa.sa_flags = SA_NOCLDWAIT;
451 sa.sa_handler = SIG_IGN;
452 sigaction(SIGCHLD, &sa, NULL);
454 LIST_FOREACH(it, &queue->queue, next) {
455 /* No need to fork for the last dest */
456 if (LIST_NEXT(it, next) == NULL)
462 syslog(LOG_ERR, "can not fork: %m");
470 * return and deliver mail
484 syslog(LOG_CRIT, "reached dead code");
489 bounce(struct qitem *it, char *reason)
491 struct queue bounceq;
497 /* Don't bounce bounced mails */
498 if (it->sender[0] == 0) {
499 syslog(LOG_CRIT, "%s: delivery panic: can't bounce a bounce",
504 syslog(LOG_ERR, "%s: delivery failed, bouncing",
507 LIST_INIT(&bounceq.queue);
508 if (add_recp(&bounceq, it->sender, "", 1) != 0)
510 if (gentempf(&bounceq) != 0)
512 if (preparespool(&bounceq, "") != 0)
515 bit = LIST_FIRST(&bounceq.queue);
516 error = fprintf(bit->queuef, "\
517 Received: from MAILER-DAEMON\n\
521 X-Original-To: <%s>\n\
522 From: MAILER-DAEMON <>\n\
524 Subject: Mail delivery failed\n\
525 Message-Id: <%"PRIxMAX"@%s>\n\
528 This is the %s at %s.\n\
530 There was an error delivering your mail to <%s>.\n\
542 bounceq.id, hostname(),
547 config->features & FULLBOUNCE? "Original message follows.":
548 "Message headers follow.");
552 if (fflush(bit->queuef) != 0)
555 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
557 if (config->features & FULLBOUNCE) {
558 while ((pos = fread(line, 1, sizeof(line), it->queuef)) > 0) {
559 if ((size_t)write(bounceq.mailfd, line, pos) != pos)
563 while (!feof(it->queuef)) {
564 if (fgets(line, sizeof(line), it->queuef) == NULL)
568 if ((size_t)write(bounceq.mailfd, line, strlen(line)) != strlen(line))
572 if (fsync(bounceq.mailfd) != 0)
574 if (linkspool(&bounceq) != 0)
581 bit = go_background(&bounceq);
586 syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
592 deliver_local(struct qitem *it, char **errmsg)
600 time_t now = time(NULL);
602 error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
603 if (error < 0 || (size_t)error >= sizeof(fn)) {
604 syslog(LOG_ERR, "%s: local delivery deferred: %m",
609 /* mailx removes users mailspool file if empty, so open with O_CREAT */
610 mbox = open_locked(fn, O_WRONLY | O_APPEND | O_CREAT);
612 syslog(LOG_ERR, "%s: local delivery deferred: can not open `%s': %m",
616 mboxlen = lseek(mbox, 0, SEEK_CUR);
618 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
619 syslog(LOG_ERR, "%s: local delivery deferred: can not seek: %m",
624 error = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
625 if (error < 0 || (size_t)error >= sizeof(line)) {
626 syslog(LOG_ERR, "%s: local delivery deferred: can not write header: %m",
630 if (write(mbox, line, error) != error)
633 while (!feof(it->queuef)) {
634 if (fgets(line, sizeof(line), it->queuef) == NULL)
636 linelen = strlen(line);
637 if (linelen == 0 || line[linelen - 1] != '\n') {
638 syslog(LOG_CRIT, "%s: local delivery failed: corrupted queue file",
640 *errmsg = strdup("corrupted queue file");
645 if (strncmp(line, "From ", 5) == 0) {
646 const char *gt = ">";
648 if (write(mbox, gt, 1) != 1)
651 if ((size_t)write(mbox, line, linelen) != linelen)
655 if (write(mbox, line, 1) != 1)
661 syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
665 if (ftruncate(mbox, mboxlen) != 0)
666 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
673 deliver(struct qitem *it)
676 unsigned int backoff = MIN_RETRY;
677 char *errmsg = strdup("unknown bounce reason");
681 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
682 it->queueid, it->sender, it->addr);
685 syslog(LOG_INFO, "%s: trying delivery",
689 error = deliver_remote(it, &errmsg);
691 error = deliver_local(it, &errmsg);
696 syslog(LOG_INFO, "%s: delivery successful",
701 if (stat(it->queuefn, &st) != 0) {
702 syslog(LOG_ERR, "%s: lost queue file `%s'",
703 it->queueid, it->queuefn);
706 if (gettimeofday(&now, NULL) == 0 &&
707 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
709 "Could not deliver for the last %d seconds. Giving up.",
715 if (backoff > MAX_RETRY)
735 return (c - 'A' + 10);
737 return (c - 'a' + 10);
745 for (i = 0; i < 16; i++)
746 for (j = 0; j < 16; j++)
747 SLIST_INIT(&seenmsg[i][j]);
751 seen(const char *msgid)
758 p = strchr(msgid, '.');
763 i = c2x(msgid[len - 2]);
764 j = c2x(msgid[len - 1]);
765 } else if (len == 1) {
771 if (i < 0 || i >= 16 || j < 0 || j >= 16)
772 errx(1, "INTERNAL ERROR: bad seen code for msgid %s", msgid);
773 SLIST_FOREACH(t, &seenmsg[i][j], next)
774 if (!strncmp(t->str, msgid, len))
776 t = malloc(sizeof(*t));
778 errx(1, "Could not allocate %lu bytes",
779 (unsigned long)(sizeof(*t)));
780 t->str = strdup(msgid);
782 errx(1, "Could not duplicate msgid %s", msgid);
783 SLIST_INSERT_HEAD(&seenmsg[i][j], t, next);
788 load_queue(struct queue *queue, int ignorelock)
792 //struct queue queue, itmqueue;
793 struct queue itmqueue;
804 int fd, locked, seenit;
806 LIST_INIT(&queue->queue);
808 spooldir = opendir(config->spooldir);
809 if (spooldir == NULL)
810 err(1, "reading queue");
813 while ((de = readdir(spooldir)) != NULL) {
819 LIST_INIT(&itmqueue.queue);
821 /* ignore temp files */
822 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
823 de->d_type != DT_REG)
825 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
827 seenit = seen(de->d_name);
829 fd = open_locked(queuefn, O_RDONLY|O_NONBLOCK);
831 /* Ignore locked files */
832 if (errno != EWOULDBLOCK)
834 if (!ignorelock || seenit)
836 fd = open(queuefn, O_RDONLY);
842 queuef = fdopen(fd, "r");
845 if (fgets(line, sizeof(line), queuef) == NULL ||
848 line[strlen(line) - 1] = 0; /* chop newline */
849 sender = strdup(line);
854 if (fgets(line, sizeof(line), queuef) == NULL ||
859 line[strlen(line) - 1] = 0;
860 queueid = strdup(line);
863 addr = strchr(queueid, ' ');
869 if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
871 /* Item has already been delivered? */
872 if (stat(fn, &st) != 0)
874 if (add_recp(&itmqueue, addr, sender, 0) != 0)
876 it = LIST_FIRST(&itmqueue.queue);
878 it->queueid = queueid;
883 if (LIST_EMPTY(&itmqueue.queue)) {
884 warnx("queue file without items: `%s'", queuefn);
887 hdrlen = ftell(queuef);
888 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
890 LIST_REMOVE(it, next);
891 LIST_INSERT_HEAD(&queue->queue, it, next);
896 warn("reading queue: `%s'", queuefn);
912 err(1, "reading queue");
916 run_queue(struct queue *queue)
920 if (LIST_EMPTY(&queue->queue))
923 it = go_background(queue);
929 show_queue(struct queue *queue)
933 if (LIST_EMPTY(&queue->queue)) {
934 printf("Mail queue is empty\n");
938 LIST_FOREACH(it, &queue->queue, next) {
942 To\t: %s\n--\n", it->queueid, it->locked? "*": "", it->sender, it->addr);
950 * - use group permissions
951 * - proper sysexit codes
955 main(int argc, char **argv)
963 int nodot = 0, doqueue = 0, showq = 0;
966 LIST_INIT(&queue.queue);
967 snprintf(tag, 254, "dma");
970 while ((ch = getopt(argc, argv, "A:b:Df:iL:o:O:q:r:")) != -1) {
973 /* -AX is being ignored, except for -A{c,m} */
974 if (optarg[0] == 'c' || optarg[0] == 'm') {
977 /* else FALLTRHOUGH */
979 /* -bX is being ignored, except for -bp */
980 if (optarg[0] == 'p') {
984 /* else FALLTRHOUGH */
990 snprintf(tag, 254, "%s", optarg);
998 /* -oX is being ignored, except for -oi */
999 if (optarg[0] != 'i')
1001 /* else FALLTRHOUGH */
1020 openlog(tag, LOG_PID | LOG_PERROR, LOG_MAIL);
1022 config = malloc(sizeof(struct config));
1024 errx(1, "Cannot allocate enough memory");
1026 memset(config, 0, sizeof(struct config));
1027 if (parse_conf(CONF_PATH, config) < 0) {
1029 errx(1, "reading config file");
1032 if (config->features & VIRTUAL)
1033 if (parse_virtuser(config->virtualpath) < 0)
1034 errx(1, "error reading virtual user file: %s",
1035 config->virtualpath);
1037 if (parse_authfile(config->authpath) < 0)
1038 err(1, "reading SMTP authentication file");
1042 errx(1, "sending mail and displaying queue is"
1043 " mutually exclusive");
1044 load_queue(&lqueue, 1);
1045 show_queue(&lqueue);
1051 errx(1, "sending mail and queue pickup is mutually exclusive");
1052 load_queue(&lqueue, 0);
1057 if (read_aliases() != 0)
1058 err(1, "reading aliases");
1060 if ((sender = set_from(sender)) == NULL)
1061 err(1, "setting from address");
1063 for (i = 0; i < argc; i++) {
1064 if (add_recp(&queue, argv[i], sender, 1) != 0)
1065 errx(1, "invalid recipient `%s'\n", argv[i]);
1068 if (LIST_EMPTY(&queue.queue))
1069 errx(1, "no recipients");
1071 if (gentempf(&queue) != 0)
1072 err(1, "create temp file");
1074 if (preparespool(&queue, sender) != 0)
1075 err(1, "creating spools (1)");
1077 if (readmail(&queue, sender, nodot) != 0)
1078 err(1, "reading mail");
1080 if (linkspool(&queue) != 0)
1081 err(1, "creating spools (2)");
1083 /* From here on the mail is safe. */
1085 if (config->features & DEFER)
1088 it = go_background(&queue);