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>
63 static void deliver(struct qitem *);
64 static int add_recp(struct queue *, const char *, const char *, int);
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;
74 static struct strlist seenmsg[16][16];
80 static char name[MAXHOSTNAMELEN+1];
88 if (config->mailname != NULL && config->mailname[0] != '\0') {
89 snprintf(name, sizeof(name), "%s", config->mailname);
93 if (config->mailnamefile != NULL && config->mailnamefile[0] != '\0') {
94 fp = fopen(config->mailnamefile, "r");
96 if (fgets(name, sizeof(name), fp) != NULL) {
99 (name[len - 1] == '\r' ||
100 name[len - 1] == '\n'))
102 if (name[0] != '\0') {
110 if (gethostname(name, sizeof(name)) != 0)
111 strcpy(name, "(unknown hostname)");
117 check_username(const char *name, uid_t ckuid)
123 pwd = getpwnam(name);
124 if (pwd == NULL || pwd->pw_uid != ckuid)
136 username = check_username(getlogin(), uid);
137 if (username != NULL)
139 username = check_username(getenv("LOGNAME"), uid);
140 if (username != NULL)
142 username = check_username(getenv("USER"), uid);
143 if (username != NULL)
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)
154 asprintf(__DECONST(void *, &username), "%ld", (long)uid);
155 if (username != NULL)
157 username = "unknown-or-invalid-username";
161 set_from(const char *osender)
166 if ((config->features & VIRTUAL) != 0) {
167 SLIST_FOREACH(v, &virtusers, next) {
168 if (strcmp(v->login, username) == 0) {
169 sender = strdup(v->address);
178 sender = strdup(osender);
182 if (asprintf(&sender, "%s@%s", username, hostname()) <= 0)
186 if (strchr(sender, '\n') != NULL) {
198 yyin = fopen(config->aliases, "r");
200 return (0); /* not fatal */
202 return (-1); /* fatal error, probably malloc() */
208 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
210 struct qitem *it, *tit;
217 it = calloc(1, sizeof(*it));
220 it->addr = strdup(str);
221 if (it->addr == NULL)
225 host = strrchr(it->addr, '@');
227 (strcmp(host + 1, hostname()) == 0 ||
228 strcmp(host + 1, "localhost") == 0)) {
231 LIST_FOREACH(tit, &queue->queue, next) {
232 /* weed out duplicate dests */
233 if (strcmp(tit->addr, it->addr) == 0) {
239 LIST_INSERT_HEAD(&queue->queue, it, next);
240 if (strrchr(it->addr, '@') == NULL) {
243 LIST_FOREACH(al, &aliases, next) {
244 if (strcmp(al->alias, it->addr) != 0)
246 SLIST_FOREACH(sit, &al->dests, next) {
247 if (add_recp(queue, sit->str, sender, 1) != 0)
253 LIST_REMOVE(it, next);
255 /* Local destination, check */
256 pw = getpwnam(it->addr);
259 /* XXX read .forward */
280 SLIST_FOREACH(t, &tmpfs, next) {
286 gentempf(struct queue *queue)
292 if (snprintf(fn, sizeof(fn), "%s/%s", config->spooldir, "tmp_XXXXXXXXXX") <= 0)
297 if (flock(fd, LOCK_EX) == -1)
300 queue->tmpf = strdup(fn);
301 if (queue->tmpf == NULL) {
305 t = malloc(sizeof(*t));
307 t->str = queue->tmpf;
308 SLIST_INSERT_HEAD(&tmpfs, t, next);
314 open_locked(const char *fname, int flags)
319 fd = open(fname, flags, 0);
322 if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) {
330 return(open(fname, flags|O_EXLOCK));
338 * queue-id1 envelope-to1
339 * queue-id2 envelope-to2
344 * queue ids are unique, formed from the inode of the spool file
345 * and a unique identifier.
348 preparespool(struct queue *queue, const char *sender)
350 char line[1000]; /* by RFC2822 */
357 error = snprintf(line, sizeof(line), "%s\n", sender);
358 if (error < 0 || (size_t)error >= sizeof(line)) {
362 if (write(queue->mailfd, line, error) != error)
365 queuef = fdopen(queue->mailfd, "r+");
370 * Assign queue id to each dest.
372 if (fstat(queue->mailfd, &st) != 0)
374 queue->id = st.st_ino;
376 syslog(LOG_INFO, "%"PRIxMAX": new mail from user=%s uid=%d envelope_from=<%s>",
377 queue->id, username, uid, sender);
379 LIST_FOREACH(it, &queue->queue, next) {
380 if (asprintf(&it->queueid, "%"PRIxMAX".%"PRIxPTR,
381 queue->id, (uintptr_t)it) <= 0)
383 if (asprintf(&it->queuefn, "%s/%s",
384 config->spooldir, it->queueid) <= 0)
386 /* File may not exist yet */
387 if (stat(it->queuefn, &st) == 0)
390 error = snprintf(line, sizeof(line), "%s %s\n",
391 it->queueid, it->addr);
392 if (error < 0 || (size_t)error >= sizeof(line))
394 if (write(queue->mailfd, line, error) != error)
397 syslog(LOG_INFO, "%"PRIxMAX": mail to=<%s> queued as %s",
398 queue->id, it->addr, it->queueid);
401 if (write(queue->mailfd, line, 1) != 1)
404 hdrlen = lseek(queue->mailfd, 0, SEEK_CUR);
405 LIST_FOREACH(it, &queue->queue, next) {
419 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
422 strcpy(str, "(date fail)");
427 strprefixcmp(const char *str, const char *prefix)
429 return (strncasecmp(str, prefix, strlen(prefix)));
433 readmail(struct queue *queue, const char *sender, int nodot)
435 char line[1000]; /* by RFC2822 */
440 int had_messagid = 0;
443 error = snprintf(line, sizeof(line),
444 "Received: from %s (uid %d)\n"
445 "\t(envelope-from %s)\n"
454 if (error < 0 || (size_t)error >= sizeof(line))
456 if (write(queue->mailfd, line, error) != error)
459 while (!feof(stdin)) {
460 if (fgets(line, sizeof(line), stdin) == NULL)
462 linelen = strlen(line);
463 if (linelen == 0 || line[linelen - 1] != '\n') {
464 errno = EINVAL; /* XXX mark permanent errors */
468 if (strprefixcmp(line, "Date:") == 0)
470 else if (strprefixcmp(line, "Message-Id:") == 0)
472 else if (strprefixcmp(line, "From:") == 0)
475 if (strcmp(line, "\n") == 0 && !had_headers) {
477 while (!had_date || !had_messagid || !had_from) {
480 snprintf(line, sizeof(line), "Date: %s\n", rfc822date());
481 } else if (!had_messagid) {
482 /* XXX better msgid, assign earlier and log? */
484 snprintf(line, sizeof(line), "Message-Id: <%"PRIxMAX"@%s>\n",
485 queue->id, hostname());
486 } else if (!had_from) {
488 snprintf(line, sizeof(line), "From: <%s>\n", sender);
490 if ((size_t)write(queue->mailfd, line, strlen(line)) != strlen(line))
495 if (!nodot && linelen == 2 && line[0] == '.')
497 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
500 if (fsync(queue->mailfd) != 0)
506 linkspool(struct queue *queue)
510 LIST_FOREACH(it, &queue->queue, next) {
511 if (link(queue->tmpf, it->queuefn) != 0)
518 LIST_FOREACH(it, &queue->queue, next) {
524 static struct qitem *
525 go_background(struct queue *queue)
532 if (daemonize && daemon(0, 0) != 0) {
533 syslog(LOG_ERR, "can not daemonize: %m");
538 bzero(&sa, sizeof(sa));
539 sa.sa_flags = SA_NOCLDWAIT;
540 sa.sa_handler = SIG_IGN;
541 sigaction(SIGCHLD, &sa, NULL);
543 LIST_FOREACH(it, &queue->queue, next) {
544 /* No need to fork for the last dest */
545 if (LIST_NEXT(it, next) == NULL)
551 syslog(LOG_ERR, "can not fork: %m");
559 * return and deliver mail
562 * We have to prevent sharing of fds between children, so
563 * we have to re-open the queue file.
565 newqf = fopen(it->queuefn, "r");
567 syslog(LOG_ERR, "can not re-open queue file `%s': %m",
585 syslog(LOG_CRIT, "reached dead code");
590 bounce(struct qitem *it, const char *reason)
592 struct queue bounceq;
598 /* Don't bounce bounced mails */
599 if (it->sender[0] == 0) {
600 syslog(LOG_INFO, "%s: can not bounce a bounce message, discarding",
605 syslog(LOG_ERR, "%s: delivery failed, bouncing",
608 LIST_INIT(&bounceq.queue);
609 if (add_recp(&bounceq, it->sender, "", 1) != 0)
611 if (gentempf(&bounceq) != 0)
613 if (preparespool(&bounceq, "") != 0)
616 bit = LIST_FIRST(&bounceq.queue);
617 error = fprintf(bit->queuef,
618 "Received: from MAILER-DAEMON\n"
622 "X-Original-To: <%s>\n"
623 "From: MAILER-DAEMON <>\n"
625 "Subject: Mail delivery failed\n"
626 "Message-Id: <%"PRIxMAX"@%s>\n"
629 "This is the %s at %s.\n"
631 "There was an error delivering your mail to <%s>.\n"
642 bounceq.id, hostname(),
647 config->features & FULLBOUNCE ?
648 "Original message follows." :
649 "Message headers follow.");
652 if (fflush(bit->queuef) != 0)
655 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
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)
663 while (!feof(it->queuef)) {
664 if (fgets(line, sizeof(line), it->queuef) == NULL)
668 if ((size_t)write(bounceq.mailfd, line, strlen(line)) != strlen(line))
672 if (fsync(bounceq.mailfd) != 0)
674 if (linkspool(&bounceq) != 0)
681 bit = go_background(&bounceq);
686 syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
692 deliver_local(struct qitem *it, const char **errmsg)
700 time_t now = time(NULL);
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",
709 /* mailx removes users mailspool file if empty, so open with O_CREAT */
710 mbox = open_locked(fn, O_WRONLY | O_APPEND | O_CREAT);
712 syslog(LOG_NOTICE, "%s: local delivery deferred: can not open `%s': %m",
716 mboxlen = lseek(mbox, 0, SEEK_CUR);
718 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
719 syslog(LOG_NOTICE, "%s: local delivery deferred: can not seek: %m",
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",
730 if (write(mbox, line, error) != error)
733 while (!feof(it->queuef)) {
734 if (fgets(line, sizeof(line), it->queuef) == NULL)
736 linelen = strlen(line);
737 if (linelen == 0 || line[linelen - 1] != '\n') {
738 syslog(LOG_CRIT, "%s: local delivery failed: corrupted queue file",
740 *errmsg = "corrupted queue file";
745 if (strncmp(line, "From ", 5) == 0) {
746 const char *gt = ">";
748 if (write(mbox, gt, 1) != 1)
751 if ((size_t)write(mbox, line, linelen) != linelen)
755 if (write(mbox, line, 1) != 1)
761 syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
765 if (ftruncate(mbox, mboxlen) != 0)
766 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
773 deliver(struct qitem *it)
776 unsigned int backoff = MIN_RETRY;
777 const char *errmsg = "unknown bounce reason";
781 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
782 it->queueid, it->sender, it->addr);
785 syslog(LOG_INFO, "%s: trying delivery",
789 error = deliver_remote(it, &errmsg);
791 error = deliver_local(it, &errmsg);
796 syslog(LOG_INFO, "%s: delivery successful",
801 if (stat(it->queuefn, &st) != 0) {
802 syslog(LOG_ERR, "%s: lost queue file `%s'",
803 it->queueid, it->queuefn);
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.",
815 if (backoff > MAX_RETRY)
835 return (c - 'A' + 10);
837 return (c - 'a' + 10);
845 for (i = 0; i < 16; i++)
846 for (j = 0; j < 16; j++)
847 SLIST_INIT(&seenmsg[i][j]);
851 seen(const char *msgid)
858 p = strchr(msgid, '.');
863 i = c2x(msgid[len - 2]);
864 j = c2x(msgid[len - 1]);
865 } else if (len == 1) {
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))
876 t = malloc(sizeof(*t));
878 errx(1, "Could not allocate %lu bytes",
879 (unsigned long)(sizeof(*t)));
880 t->str = strdup(msgid);
882 errx(1, "Could not duplicate msgid %s", msgid);
883 SLIST_INSERT_HEAD(&seenmsg[i][j], t, next);
888 load_queue(struct queue *queue, int ignorelock)
892 //struct queue queue, itmqueue;
893 struct queue itmqueue;
904 int fd, locked, seenit;
906 LIST_INIT(&queue->queue);
908 spooldir = opendir(config->spooldir);
909 if (spooldir == NULL)
910 err(1, "reading queue");
913 while ((de = readdir(spooldir)) != NULL) {
919 LIST_INIT(&itmqueue.queue);
921 /* ignore temp files */
922 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
923 de->d_type != DT_REG)
925 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
927 seenit = seen(de->d_name);
929 fd = open_locked(queuefn, O_RDONLY|O_NONBLOCK);
931 /* Ignore locked files */
932 if (errno != EWOULDBLOCK)
934 if (!ignorelock || seenit)
936 fd = open(queuefn, O_RDONLY);
942 queuef = fdopen(fd, "r");
945 if (fgets(line, sizeof(line), queuef) == NULL ||
948 line[strlen(line) - 1] = 0; /* chop newline */
949 sender = strdup(line);
954 if (fgets(line, sizeof(line), queuef) == NULL ||
959 line[strlen(line) - 1] = 0;
960 queueid = strdup(line);
963 addr = strchr(queueid, ' ');
969 if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
971 /* Item has already been delivered? */
972 if (stat(fn, &st) != 0)
974 if (add_recp(&itmqueue, addr, sender, 0) != 0)
976 it = LIST_FIRST(&itmqueue.queue);
978 it->queueid = queueid;
983 if (LIST_EMPTY(&itmqueue.queue)) {
984 warnx("queue file without items: `%s'", queuefn);
987 hdrlen = ftell(queuef);
988 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
990 LIST_REMOVE(it, next);
991 LIST_INSERT_HEAD(&queue->queue, it, next);
996 warn("reading queue: `%s'", queuefn);
1000 if (queuefn != NULL)
1004 if (queueid != NULL)
1012 err(1, "reading queue");
1016 run_queue(struct queue *queue)
1020 if (LIST_EMPTY(&queue->queue))
1023 it = go_background(queue);
1029 show_queue(struct queue *queue)
1033 if (LIST_EMPTY(&queue->queue)) {
1034 printf("Mail queue is empty\n");
1038 LIST_FOREACH(it, &queue->queue, next) {
1039 printf("ID\t: %s%s\n"
1044 it->locked ? "*" : "",
1045 it->sender, it->addr);
1052 * - alias processing
1053 * - use group permissions
1054 * - proper sysexit codes
1058 main(int argc, char **argv)
1060 char *sender = NULL;
1061 const char *tag = "dma";
1064 struct queue lqueue;
1066 int nodot = 0, doqueue = 0, showq = 0;
1069 LIST_INIT(&queue.queue);
1071 if (strcmp(argv[0], "mailq") == 0) {
1075 errx(1, "invalid arguments");
1080 while ((ch = getopt(argc, argv, "A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
1083 /* -AX is being ignored, except for -A{c,m} */
1084 if (optarg[0] == 'c' || optarg[0] == 'm') {
1087 /* else FALLTRHOUGH */
1089 /* -bX is being ignored, except for -bp */
1090 if (optarg[0] == 'p') {
1094 /* else FALLTRHOUGH */
1107 /* -oX is being ignored, except for -oi */
1108 if (optarg[0] != 'i')
1110 /* else FALLTRHOUGH */
1121 /* Ignored options */
1144 if (argc != 0 && (showq || doqueue))
1145 errx(1, "sending mail and queue operations are mutually exclusive");
1147 if (showq + doqueue > 1)
1148 errx(1, "conflicting queue operations");
1151 openlog(tag, LOG_PID, LOG_MAIL);
1154 /* XXX fork root here */
1156 config = calloc(1, sizeof(*config));
1160 if (parse_conf(CONF_PATH, config) < 0) {
1162 err(1, "can not read config file");
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);
1170 if (parse_authfile(config->authpath) < 0)
1171 err(1, "can not read SMTP authentication file");
1174 load_queue(&lqueue, 1);
1175 show_queue(&lqueue);
1180 load_queue(&lqueue, 0);
1185 if (read_aliases() != 0)
1186 err(1, "can not read aliases file `%s'", config->aliases);
1188 if ((sender = set_from(sender)) == NULL)
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]);
1196 if (LIST_EMPTY(&queue.queue))
1197 errx(1, "no recipients");
1199 if (gentempf(&queue) != 0)
1200 err(1, "can not create temp file");
1202 if (preparespool(&queue, sender) != 0)
1203 err(1, "can not create spools (1)");
1205 if (readmail(&queue, sender, nodot) != 0)
1206 err(1, "can not read mail");
1208 if (linkspool(&queue) != 0)
1209 err(1, "can not create spools (2)");
1211 /* From here on the mail is safe. */
1213 if (config->features & DEFER)
1216 it = go_background(&queue);