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 const char *username;
78 static struct strlist seenmsg[16][16];
84 static char name[MAXHOSTNAMELEN+1];
92 if (config->mailname != NULL && config->mailname[0] != '\0') {
93 snprintf(name, sizeof(name), "%s", config->mailname);
97 if (config->mailnamefile != NULL && config->mailnamefile[0] != '\0') {
98 fp = fopen(config->mailnamefile, "r");
100 if (fgets(name, sizeof(name), fp) != NULL) {
103 (name[len - 1] == '\r' ||
104 name[len - 1] == '\n'))
106 if (name[0] != '\0') {
114 if (gethostname(name, sizeof(name)) != 0)
115 strcpy(name, "(unknown hostname)");
121 check_username(const char *name, uid_t ckuid)
127 pwd = getpwnam(name);
128 if (pwd == NULL || pwd->pw_uid != ckuid)
140 username = check_username(getlogin(), uid);
141 if (username == NULL)
142 username = check_username(getenv("LOGNAME"), uid);
143 if (username == NULL)
144 username = check_username(getenv("USER"), uid);
145 if (username == NULL) {
147 if (pwd != NULL && pwd->pw_name != NULL &&
148 pwd->pw_name[0] != '\0')
149 username = check_username(strdup(pwd->pw_name), uid);
151 if (username == NULL) {
152 asprintf(&u, "%ld", (long)uid);
155 if (username == NULL)
156 username = "unknown-or-invalid-username";
160 set_from(const char *osender)
165 if ((config->features & VIRTUAL) != 0) {
166 SLIST_FOREACH(v, &virtusers, next) {
167 if (strcmp(v->login, username) == 0) {
168 sender = strdup(v->address);
177 sender = strdup(osender);
181 if (asprintf(&sender, "%s@%s", username, hostname()) <= 0)
185 if (strchr(sender, '\n') != NULL) {
197 yyin = fopen(config->aliases, "r");
199 return (0); /* not fatal */
201 return (-1); /* fatal error, probably malloc() */
207 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
209 struct qitem *it, *tit;
216 it = calloc(1, sizeof(*it));
219 it->addr = strdup(str);
220 if (it->addr == NULL)
224 host = strrchr(it->addr, '@');
226 (strcmp(host + 1, hostname()) == 0 ||
227 strcmp(host + 1, "localhost") == 0)) {
230 LIST_FOREACH(tit, &queue->queue, next) {
231 /* weed out duplicate dests */
232 if (strcmp(tit->addr, it->addr) == 0) {
238 LIST_INSERT_HEAD(&queue->queue, it, next);
239 if (strrchr(it->addr, '@') == NULL) {
242 LIST_FOREACH(al, &aliases, next) {
243 if (strcmp(al->alias, it->addr) != 0)
245 SLIST_FOREACH(sit, &al->dests, next) {
246 if (add_recp(queue, sit->str, sender, 1) != 0)
252 LIST_REMOVE(it, next);
254 /* Local destination, check */
255 pw = getpwnam(it->addr);
278 SLIST_FOREACH(t, &tmpfs, next) {
284 gentempf(struct queue *queue)
290 if (snprintf(fn, sizeof(fn), "%s/%s", config->spooldir, "tmp_XXXXXXXXXX") <= 0)
295 if (flock(fd, LOCK_EX) == -1)
298 queue->tmpf = strdup(fn);
299 if (queue->tmpf == NULL) {
303 t = malloc(sizeof(*t));
305 t->str = queue->tmpf;
306 SLIST_INSERT_HEAD(&tmpfs, t, next);
312 open_locked(const char *fname, int flags)
317 fd = open(fname, flags, 0);
320 if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) {
328 return(open(fname, flags|O_EXLOCK));
336 * queue-id1 envelope-to1
337 * queue-id2 envelope-to2
342 * queue ids are unique, formed from the inode of the spool file
343 * and a unique identifier.
346 preparespool(struct queue *queue, const char *sender)
348 char line[1000]; /* by RFC2822 */
355 error = snprintf(line, sizeof(line), "%s\n", sender);
356 if (error < 0 || (size_t)error >= sizeof(line)) {
360 if (write(queue->mailfd, line, error) != error)
363 queuef = fdopen(queue->mailfd, "r+");
368 * Assign queue id to each dest.
370 if (fstat(queue->mailfd, &st) != 0)
372 queue->id = st.st_ino;
373 LIST_FOREACH(it, &queue->queue, next) {
374 if (asprintf(&it->queueid, "%"PRIxMAX".%"PRIxPTR,
375 queue->id, (uintptr_t)it) <= 0)
377 if (asprintf(&it->queuefn, "%s/%s",
378 config->spooldir, it->queueid) <= 0)
380 /* File may not exist yet */
381 if (stat(it->queuefn, &st) == 0)
384 error = snprintf(line, sizeof(line), "%s %s\n",
385 it->queueid, it->addr);
386 if (error < 0 || (size_t)error >= sizeof(line))
388 if (write(queue->mailfd, line, error) != error)
392 if (write(queue->mailfd, line, 1) != 1)
395 hdrlen = lseek(queue->mailfd, 0, SEEK_CUR);
396 LIST_FOREACH(it, &queue->queue, next) {
410 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
413 strcpy(str, "(date fail)");
418 readmail(struct queue *queue, const char *sender, int nodot)
420 char line[1000]; /* by RFC2822 */
424 error = snprintf(line, sizeof(line), "\
425 Received: from %s (uid %d)\n\
426 \t(envelope-from %s)\n\
435 if (error < 0 || (size_t)error >= sizeof(line))
437 if (write(queue->mailfd, line, error) != error)
440 while (!feof(stdin)) {
441 if (fgets(line, sizeof(line), stdin) == NULL)
443 linelen = strlen(line);
444 if (linelen == 0 || line[linelen - 1] != '\n') {
445 errno = EINVAL; /* XXX mark permanent errors */
448 if (!nodot && linelen == 2 && line[0] == '.')
450 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
453 if (fsync(queue->mailfd) != 0)
459 linkspool(struct queue *queue)
463 LIST_FOREACH(it, &queue->queue, next) {
464 if (link(queue->tmpf, it->queuefn) != 0)
471 LIST_FOREACH(it, &queue->queue, next) {
477 static struct qitem *
478 go_background(struct queue *queue)
484 if (daemonize && daemon(0, 0) != 0) {
485 syslog(LOG_ERR, "can not daemonize: %m");
490 bzero(&sa, sizeof(sa));
491 sa.sa_flags = SA_NOCLDWAIT;
492 sa.sa_handler = SIG_IGN;
493 sigaction(SIGCHLD, &sa, NULL);
495 LIST_FOREACH(it, &queue->queue, next) {
496 /* No need to fork for the last dest */
497 if (LIST_NEXT(it, next) == NULL)
503 syslog(LOG_ERR, "can not fork: %m");
511 * return and deliver mail
525 syslog(LOG_CRIT, "reached dead code");
530 bounce(struct qitem *it, const char *reason)
532 struct queue bounceq;
538 /* Don't bounce bounced mails */
539 if (it->sender[0] == 0) {
540 syslog(LOG_CRIT, "%s: delivery panic: can't bounce a bounce",
545 syslog(LOG_ERR, "%s: delivery failed, bouncing",
548 LIST_INIT(&bounceq.queue);
549 if (add_recp(&bounceq, it->sender, "", 1) != 0)
551 if (gentempf(&bounceq) != 0)
553 if (preparespool(&bounceq, "") != 0)
556 bit = LIST_FIRST(&bounceq.queue);
557 error = fprintf(bit->queuef, "\
558 Received: from MAILER-DAEMON\n\
562 X-Original-To: <%s>\n\
563 From: MAILER-DAEMON <>\n\
565 Subject: Mail delivery failed\n\
566 Message-Id: <%"PRIxMAX"@%s>\n\
569 This is the %s at %s.\n\
571 There was an error delivering your mail to <%s>.\n\
583 bounceq.id, hostname(),
588 config->features & FULLBOUNCE? "Original message follows.":
589 "Message headers follow.");
592 if (fflush(bit->queuef) != 0)
595 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
597 if (config->features & FULLBOUNCE) {
598 while ((pos = fread(line, 1, sizeof(line), it->queuef)) > 0) {
599 if ((size_t)write(bounceq.mailfd, line, pos) != pos)
603 while (!feof(it->queuef)) {
604 if (fgets(line, sizeof(line), it->queuef) == NULL)
608 if ((size_t)write(bounceq.mailfd, line, strlen(line)) != strlen(line))
612 if (fsync(bounceq.mailfd) != 0)
614 if (linkspool(&bounceq) != 0)
621 bit = go_background(&bounceq);
626 syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
632 deliver_local(struct qitem *it, const char **errmsg)
640 time_t now = time(NULL);
642 error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
643 if (error < 0 || (size_t)error >= sizeof(fn)) {
644 syslog(LOG_ERR, "%s: local delivery deferred: %m",
649 /* mailx removes users mailspool file if empty, so open with O_CREAT */
650 mbox = open_locked(fn, O_WRONLY | O_APPEND | O_CREAT);
652 syslog(LOG_ERR, "%s: local delivery deferred: can not open `%s': %m",
656 mboxlen = lseek(mbox, 0, SEEK_CUR);
658 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
659 syslog(LOG_ERR, "%s: local delivery deferred: can not seek: %m",
664 error = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
665 if (error < 0 || (size_t)error >= sizeof(line)) {
666 syslog(LOG_ERR, "%s: local delivery deferred: can not write header: %m",
670 if (write(mbox, line, error) != error)
673 while (!feof(it->queuef)) {
674 if (fgets(line, sizeof(line), it->queuef) == NULL)
676 linelen = strlen(line);
677 if (linelen == 0 || line[linelen - 1] != '\n') {
678 syslog(LOG_CRIT, "%s: local delivery failed: corrupted queue file",
680 *errmsg = "corrupted queue file";
685 if (strncmp(line, "From ", 5) == 0) {
686 const char *gt = ">";
688 if (write(mbox, gt, 1) != 1)
691 if ((size_t)write(mbox, line, linelen) != linelen)
695 if (write(mbox, line, 1) != 1)
701 syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
705 if (ftruncate(mbox, mboxlen) != 0)
706 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
713 deliver(struct qitem *it)
716 unsigned int backoff = MIN_RETRY;
717 const char *errmsg = "unknown bounce reason";
721 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
722 it->queueid, it->sender, it->addr);
725 syslog(LOG_INFO, "%s: trying delivery",
729 error = deliver_remote(it, &errmsg);
731 error = deliver_local(it, &errmsg);
736 syslog(LOG_INFO, "%s: delivery successful",
741 if (stat(it->queuefn, &st) != 0) {
742 syslog(LOG_ERR, "%s: lost queue file `%s'",
743 it->queueid, it->queuefn);
746 if (gettimeofday(&now, NULL) == 0 &&
747 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
748 asprintf(__DECONST(void *, &errmsg),
749 "Could not deliver for the last %d seconds. Giving up.",
755 if (backoff > MAX_RETRY)
775 return (c - 'A' + 10);
777 return (c - 'a' + 10);
785 for (i = 0; i < 16; i++)
786 for (j = 0; j < 16; j++)
787 SLIST_INIT(&seenmsg[i][j]);
791 seen(const char *msgid)
798 p = strchr(msgid, '.');
803 i = c2x(msgid[len - 2]);
804 j = c2x(msgid[len - 1]);
805 } else if (len == 1) {
811 if (i < 0 || i >= 16 || j < 0 || j >= 16)
812 errx(1, "INTERNAL ERROR: bad seen code for msgid %s", msgid);
813 SLIST_FOREACH(t, &seenmsg[i][j], next)
814 if (!strncmp(t->str, msgid, len))
816 t = malloc(sizeof(*t));
818 errx(1, "Could not allocate %lu bytes",
819 (unsigned long)(sizeof(*t)));
820 t->str = strdup(msgid);
822 errx(1, "Could not duplicate msgid %s", msgid);
823 SLIST_INSERT_HEAD(&seenmsg[i][j], t, next);
828 load_queue(struct queue *queue, int ignorelock)
832 //struct queue queue, itmqueue;
833 struct queue itmqueue;
844 int fd, locked, seenit;
846 LIST_INIT(&queue->queue);
848 spooldir = opendir(config->spooldir);
849 if (spooldir == NULL)
850 err(1, "reading queue");
853 while ((de = readdir(spooldir)) != NULL) {
859 LIST_INIT(&itmqueue.queue);
861 /* ignore temp files */
862 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
863 de->d_type != DT_REG)
865 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
867 seenit = seen(de->d_name);
869 fd = open_locked(queuefn, O_RDONLY|O_NONBLOCK);
871 /* Ignore locked files */
872 if (errno != EWOULDBLOCK)
874 if (!ignorelock || seenit)
876 fd = open(queuefn, O_RDONLY);
882 queuef = fdopen(fd, "r");
885 if (fgets(line, sizeof(line), queuef) == NULL ||
888 line[strlen(line) - 1] = 0; /* chop newline */
889 sender = strdup(line);
894 if (fgets(line, sizeof(line), queuef) == NULL ||
899 line[strlen(line) - 1] = 0;
900 queueid = strdup(line);
903 addr = strchr(queueid, ' ');
909 if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
911 /* Item has already been delivered? */
912 if (stat(fn, &st) != 0)
914 if (add_recp(&itmqueue, addr, sender, 0) != 0)
916 it = LIST_FIRST(&itmqueue.queue);
918 it->queueid = queueid;
923 if (LIST_EMPTY(&itmqueue.queue)) {
924 warnx("queue file without items: `%s'", queuefn);
927 hdrlen = ftell(queuef);
928 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
930 LIST_REMOVE(it, next);
931 LIST_INSERT_HEAD(&queue->queue, it, next);
936 warn("reading queue: `%s'", queuefn);
952 err(1, "reading queue");
956 run_queue(struct queue *queue)
960 if (LIST_EMPTY(&queue->queue))
963 it = go_background(queue);
969 show_queue(struct queue *queue)
973 if (LIST_EMPTY(&queue->queue)) {
974 printf("Mail queue is empty\n");
978 LIST_FOREACH(it, &queue->queue, next) {
982 To\t: %s\n--\n", it->queueid, it->locked? "*": "", it->sender, it->addr);
990 * - use group permissions
991 * - proper sysexit codes
995 main(int argc, char **argv)
1001 struct queue lqueue;
1003 int nodot = 0, doqueue = 0, showq = 0;
1006 LIST_INIT(&queue.queue);
1007 snprintf(tag, 254, "dma");
1010 while ((ch = getopt(argc, argv, "A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
1013 /* -AX is being ignored, except for -A{c,m} */
1014 if (optarg[0] == 'c' || optarg[0] == 'm') {
1017 /* else FALLTRHOUGH */
1019 /* -bX is being ignored, except for -bp */
1020 if (optarg[0] == 'p') {
1024 /* else FALLTRHOUGH */
1030 snprintf(tag, 254, "%s", optarg);
1038 /* -oX is being ignored, except for -oi */
1039 if (optarg[0] != 'i')
1041 /* else FALLTRHOUGH */
1052 /* Ignored options */
1075 openlog(tag, LOG_PID | LOG_PERROR, LOG_MAIL);
1078 config = malloc(sizeof(struct config));
1080 errx(1, "Cannot allocate enough memory");
1082 memset(config, 0, sizeof(struct config));
1083 if (parse_conf(CONF_PATH, config) < 0) {
1085 errx(1, "reading config file");
1088 if (config->features & VIRTUAL)
1089 if (parse_virtuser(config->virtualpath) < 0)
1090 errx(1, "error reading virtual user file: %s",
1091 config->virtualpath);
1093 if (parse_authfile(config->authpath) < 0)
1094 err(1, "reading SMTP authentication file");
1098 errx(1, "sending mail and displaying queue is"
1099 " mutually exclusive");
1100 load_queue(&lqueue, 1);
1101 show_queue(&lqueue);
1107 errx(1, "sending mail and queue pickup is mutually exclusive");
1108 load_queue(&lqueue, 0);
1113 if (read_aliases() != 0)
1114 err(1, "reading aliases");
1116 if ((sender = set_from(sender)) == NULL)
1117 err(1, "setting from address");
1119 for (i = 0; i < argc; i++) {
1120 if (add_recp(&queue, argv[i], sender, 1) != 0)
1121 errx(1, "invalid recipient `%s'\n", argv[i]);
1124 if (LIST_EMPTY(&queue.queue))
1125 errx(1, "no recipients");
1127 if (gentempf(&queue) != 0)
1128 err(1, "create temp file");
1130 if (preparespool(&queue, sender) != 0)
1131 err(1, "creating spools (1)");
1133 if (readmail(&queue, sender, nodot) != 0)
1134 err(1, "reading mail");
1136 if (linkspool(&queue) != 0)
1137 err(1, "creating spools (2)");
1139 /* From here on the mail is safe. */
1141 if (config->features & DEFER)
1144 it = go_background(&queue);