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);
279 SLIST_FOREACH(t, &tmpfs, next) {
285 gentempf(struct queue *queue)
291 if (snprintf(fn, sizeof(fn), "%s/%s", config->spooldir, "tmp_XXXXXXXXXX") <= 0)
296 if (flock(fd, LOCK_EX) == -1)
299 queue->tmpf = strdup(fn);
300 if (queue->tmpf == NULL) {
304 t = malloc(sizeof(*t));
306 t->str = queue->tmpf;
307 SLIST_INSERT_HEAD(&tmpfs, t, next);
313 open_locked(const char *fname, int flags)
318 fd = open(fname, flags, 0);
321 if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) {
329 return(open(fname, flags|O_EXLOCK));
337 * queue-id1 envelope-to1
338 * queue-id2 envelope-to2
343 * queue ids are unique, formed from the inode of the spool file
344 * and a unique identifier.
347 preparespool(struct queue *queue, const char *sender)
349 char line[1000]; /* by RFC2822 */
356 error = snprintf(line, sizeof(line), "%s\n", sender);
357 if (error < 0 || (size_t)error >= sizeof(line)) {
361 if (write(queue->mailfd, line, error) != error)
364 queuef = fdopen(queue->mailfd, "r+");
369 * Assign queue id to each dest.
371 if (fstat(queue->mailfd, &st) != 0)
373 queue->id = st.st_ino;
375 syslog(LOG_INFO, "%"PRIxMAX": new mail from user=%s uid=%d envelope_from=<%s>",
376 queue->id, username, uid, sender);
378 LIST_FOREACH(it, &queue->queue, next) {
379 if (asprintf(&it->queueid, "%"PRIxMAX".%"PRIxPTR,
380 queue->id, (uintptr_t)it) <= 0)
382 if (asprintf(&it->queuefn, "%s/%s",
383 config->spooldir, it->queueid) <= 0)
385 /* File may not exist yet */
386 if (stat(it->queuefn, &st) == 0)
389 error = snprintf(line, sizeof(line), "%s %s\n",
390 it->queueid, it->addr);
391 if (error < 0 || (size_t)error >= sizeof(line))
393 if (write(queue->mailfd, line, error) != error)
396 syslog(LOG_INFO, "%"PRIxMAX": mail to=<%s> queued as %s",
397 queue->id, it->addr, it->queueid);
400 if (write(queue->mailfd, line, 1) != 1)
403 hdrlen = lseek(queue->mailfd, 0, SEEK_CUR);
404 LIST_FOREACH(it, &queue->queue, next) {
418 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
421 strcpy(str, "(date fail)");
426 strprefixcmp(const char *str, const char *prefix)
428 return (strncasecmp(str, prefix, strlen(prefix)));
432 readmail(struct queue *queue, const char *sender, int nodot)
434 char line[1000]; /* by RFC2822 */
439 int had_messagid = 0;
442 error = snprintf(line, sizeof(line),
443 "Received: from %s (uid %d)\n"
444 "\t(envelope-from %s)\n"
453 if (error < 0 || (size_t)error >= sizeof(line))
455 if (write(queue->mailfd, line, error) != error)
458 while (!feof(stdin)) {
459 if (fgets(line, sizeof(line), stdin) == NULL)
461 linelen = strlen(line);
462 if (linelen == 0 || line[linelen - 1] != '\n') {
463 errno = EINVAL; /* XXX mark permanent errors */
467 if (strprefixcmp(line, "Date:") == 0)
469 else if (strprefixcmp(line, "Message-Id:") == 0)
471 else if (strprefixcmp(line, "From:") == 0)
474 if (strcmp(line, "\n") == 0 && !had_headers) {
476 while (!had_date || !had_messagid || !had_from) {
479 snprintf(line, sizeof(line), "Date: %s\n", rfc822date());
480 } else if (!had_messagid) {
481 /* XXX better msgid, assign earlier and log? */
483 snprintf(line, sizeof(line), "Message-Id: <%"PRIxMAX"@%s>\n",
484 queue->id, hostname());
485 } else if (!had_from) {
487 snprintf(line, sizeof(line), "From: <%s>\n", sender);
489 if ((size_t)write(queue->mailfd, line, strlen(line)) != strlen(line))
494 if (!nodot && linelen == 2 && line[0] == '.')
496 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
499 if (fsync(queue->mailfd) != 0)
505 linkspool(struct queue *queue)
509 LIST_FOREACH(it, &queue->queue, next) {
510 if (link(queue->tmpf, it->queuefn) != 0)
517 LIST_FOREACH(it, &queue->queue, next) {
523 static struct qitem *
524 go_background(struct queue *queue)
531 if (daemonize && daemon(0, 0) != 0) {
532 syslog(LOG_ERR, "can not daemonize: %m");
537 bzero(&sa, sizeof(sa));
538 sa.sa_flags = SA_NOCLDWAIT;
539 sa.sa_handler = SIG_IGN;
540 sigaction(SIGCHLD, &sa, NULL);
542 LIST_FOREACH(it, &queue->queue, next) {
543 /* No need to fork for the last dest */
544 if (LIST_NEXT(it, next) == NULL)
550 syslog(LOG_ERR, "can not fork: %m");
558 * return and deliver mail
561 * We have to prevent sharing of fds between children, so
562 * we have to re-open the queue file.
564 newqf = fopen(it->queuefn, "r");
566 syslog(LOG_ERR, "can not re-open queue file `%s': %m",
584 syslog(LOG_CRIT, "reached dead code");
589 bounce(struct qitem *it, const char *reason)
591 struct queue bounceq;
597 /* Don't bounce bounced mails */
598 if (it->sender[0] == 0) {
599 syslog(LOG_INFO, "%s: can not bounce a bounce message, discarding",
604 syslog(LOG_ERR, "%s: delivery failed, bouncing",
607 LIST_INIT(&bounceq.queue);
608 if (add_recp(&bounceq, it->sender, "", 1) != 0)
610 if (gentempf(&bounceq) != 0)
612 if (preparespool(&bounceq, "") != 0)
615 bit = LIST_FIRST(&bounceq.queue);
616 error = fprintf(bit->queuef,
617 "Received: from MAILER-DAEMON\n"
621 "X-Original-To: <%s>\n"
622 "From: MAILER-DAEMON <>\n"
624 "Subject: Mail delivery failed\n"
625 "Message-Id: <%"PRIxMAX"@%s>\n"
628 "This is the %s at %s.\n"
630 "There was an error delivering your mail to <%s>.\n"
641 bounceq.id, hostname(),
646 config->features & FULLBOUNCE ?
647 "Original message follows." :
648 "Message headers follow.");
651 if (fflush(bit->queuef) != 0)
654 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
656 if (config->features & FULLBOUNCE) {
657 while ((pos = fread(line, 1, sizeof(line), it->queuef)) > 0) {
658 if ((size_t)write(bounceq.mailfd, line, pos) != pos)
662 while (!feof(it->queuef)) {
663 if (fgets(line, sizeof(line), it->queuef) == NULL)
667 if ((size_t)write(bounceq.mailfd, line, strlen(line)) != strlen(line))
671 if (fsync(bounceq.mailfd) != 0)
673 if (linkspool(&bounceq) != 0)
680 bit = go_background(&bounceq);
685 syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
691 deliver_local(struct qitem *it, const char **errmsg)
699 time_t now = time(NULL);
701 error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
702 if (error < 0 || (size_t)error >= sizeof(fn)) {
703 syslog(LOG_NOTICE, "%s: local delivery deferred: %m",
708 /* mailx removes users mailspool file if empty, so open with O_CREAT */
709 mbox = open_locked(fn, O_WRONLY | O_APPEND | O_CREAT);
711 syslog(LOG_NOTICE, "%s: local delivery deferred: can not open `%s': %m",
715 mboxlen = lseek(mbox, 0, SEEK_CUR);
717 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
718 syslog(LOG_NOTICE, "%s: local delivery deferred: can not seek: %m",
723 error = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
724 if (error < 0 || (size_t)error >= sizeof(line)) {
725 syslog(LOG_NOTICE, "%s: local delivery deferred: can not write header: %m",
729 if (write(mbox, line, error) != error)
732 while (!feof(it->queuef)) {
733 if (fgets(line, sizeof(line), it->queuef) == NULL)
735 linelen = strlen(line);
736 if (linelen == 0 || line[linelen - 1] != '\n') {
737 syslog(LOG_CRIT, "%s: local delivery failed: corrupted queue file",
739 *errmsg = "corrupted queue file";
744 if (strncmp(line, "From ", 5) == 0) {
745 const char *gt = ">";
747 if (write(mbox, gt, 1) != 1)
750 if ((size_t)write(mbox, line, linelen) != linelen)
754 if (write(mbox, line, 1) != 1)
760 syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
764 if (ftruncate(mbox, mboxlen) != 0)
765 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
772 deliver(struct qitem *it)
775 unsigned int backoff = MIN_RETRY;
776 const char *errmsg = "unknown bounce reason";
780 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
781 it->queueid, it->sender, it->addr);
784 syslog(LOG_INFO, "%s: trying delivery",
788 error = deliver_remote(it, &errmsg);
790 error = deliver_local(it, &errmsg);
795 syslog(LOG_INFO, "%s: delivery successful",
800 if (stat(it->queuefn, &st) != 0) {
801 syslog(LOG_ERR, "%s: lost queue file `%s'",
802 it->queueid, it->queuefn);
805 if (gettimeofday(&now, NULL) == 0 &&
806 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
807 asprintf(__DECONST(void *, &errmsg),
808 "Could not deliver for the last %d seconds. Giving up.",
814 if (backoff > MAX_RETRY)
834 return (c - 'A' + 10);
836 return (c - 'a' + 10);
844 for (i = 0; i < 16; i++)
845 for (j = 0; j < 16; j++)
846 SLIST_INIT(&seenmsg[i][j]);
850 seen(const char *msgid)
857 p = strchr(msgid, '.');
862 i = c2x(msgid[len - 2]);
863 j = c2x(msgid[len - 1]);
864 } else if (len == 1) {
870 if (i < 0 || i >= 16 || j < 0 || j >= 16)
871 errx(1, "INTERNAL ERROR: bad seen code for msgid %s", msgid);
872 SLIST_FOREACH(t, &seenmsg[i][j], next)
873 if (!strncmp(t->str, msgid, len))
875 t = malloc(sizeof(*t));
877 errx(1, "Could not allocate %lu bytes",
878 (unsigned long)(sizeof(*t)));
879 t->str = strdup(msgid);
881 errx(1, "Could not duplicate msgid %s", msgid);
882 SLIST_INSERT_HEAD(&seenmsg[i][j], t, next);
887 load_queue(struct queue *queue, int ignorelock)
891 //struct queue queue, itmqueue;
892 struct queue itmqueue;
903 int fd, locked, seenit;
905 LIST_INIT(&queue->queue);
907 spooldir = opendir(config->spooldir);
908 if (spooldir == NULL)
909 err(1, "reading queue");
912 while ((de = readdir(spooldir)) != NULL) {
918 LIST_INIT(&itmqueue.queue);
920 /* ignore temp files */
921 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
922 de->d_type != DT_REG)
924 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
926 seenit = seen(de->d_name);
928 fd = open_locked(queuefn, O_RDONLY|O_NONBLOCK);
930 /* Ignore locked files */
931 if (errno != EWOULDBLOCK)
933 if (!ignorelock || seenit)
935 fd = open(queuefn, O_RDONLY);
941 queuef = fdopen(fd, "r");
944 if (fgets(line, sizeof(line), queuef) == NULL ||
947 line[strlen(line) - 1] = 0; /* chop newline */
948 sender = strdup(line);
953 if (fgets(line, sizeof(line), queuef) == NULL ||
958 line[strlen(line) - 1] = 0;
959 queueid = strdup(line);
962 addr = strchr(queueid, ' ');
968 if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
970 /* Item has already been delivered? */
971 if (stat(fn, &st) != 0)
973 if (add_recp(&itmqueue, addr, sender, 0) != 0)
975 it = LIST_FIRST(&itmqueue.queue);
977 it->queueid = queueid;
982 if (LIST_EMPTY(&itmqueue.queue)) {
983 warnx("queue file without items: `%s'", queuefn);
986 hdrlen = ftell(queuef);
987 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
989 LIST_REMOVE(it, next);
990 LIST_INSERT_HEAD(&queue->queue, it, next);
995 warn("reading queue: `%s'", queuefn);
1003 if (queueid != NULL)
1011 err(1, "reading queue");
1015 run_queue(struct queue *queue)
1019 if (LIST_EMPTY(&queue->queue))
1022 it = go_background(queue);
1028 show_queue(struct queue *queue)
1032 if (LIST_EMPTY(&queue->queue)) {
1033 printf("Mail queue is empty\n");
1037 LIST_FOREACH(it, &queue->queue, next) {
1038 printf("ID\t: %s%s\n"
1043 it->locked ? "*" : "",
1044 it->sender, it->addr);
1051 * - alias processing
1052 * - use group permissions
1053 * - proper sysexit codes
1057 main(int argc, char **argv)
1059 char *sender = NULL;
1060 const char *tag = "dma";
1063 struct queue lqueue;
1065 int nodot = 0, doqueue = 0, showq = 0;
1068 LIST_INIT(&queue.queue);
1070 if (strcmp(argv[0], "mailq") == 0) {
1074 errx(1, "invalid arguments");
1079 while ((ch = getopt(argc, argv, "A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
1082 /* -AX is being ignored, except for -A{c,m} */
1083 if (optarg[0] == 'c' || optarg[0] == 'm') {
1086 /* else FALLTRHOUGH */
1088 /* -bX is being ignored, except for -bp */
1089 if (optarg[0] == 'p') {
1093 /* else FALLTRHOUGH */
1106 /* -oX is being ignored, except for -oi */
1107 if (optarg[0] != 'i')
1109 /* else FALLTRHOUGH */
1120 /* Ignored options */
1144 openlog(tag, LOG_PID, LOG_MAIL);
1147 config = malloc(sizeof(struct config));
1151 memset(config, 0, sizeof(struct config));
1152 if (parse_conf(CONF_PATH, config) < 0) {
1154 err(1, "can not read config file");
1157 if (config->features & VIRTUAL)
1158 if (parse_virtuser(config->virtualpath) < 0)
1159 err(1, "can not read virtual user file `%s'",
1160 config->virtualpath);
1162 if (parse_authfile(config->authpath) < 0)
1163 err(1, "can not read SMTP authentication file");
1167 errx(1, "sending mail and displaying queue is"
1168 " mutually exclusive");
1169 load_queue(&lqueue, 1);
1170 show_queue(&lqueue);
1176 errx(1, "sending mail and queue pickup is mutually exclusive");
1177 load_queue(&lqueue, 0);
1182 if (read_aliases() != 0)
1183 err(1, "can not read aliases file `%s'", config->aliases);
1185 if ((sender = set_from(sender)) == NULL)
1188 for (i = 0; i < argc; i++) {
1189 if (add_recp(&queue, argv[i], sender, 1) != 0)
1190 errx(1, "invalid recipient `%s'", argv[i]);
1193 if (LIST_EMPTY(&queue.queue))
1194 errx(1, "no recipients");
1196 if (gentempf(&queue) != 0)
1197 err(1, "can not create temp file");
1199 if (preparespool(&queue, sender) != 0)
1200 err(1, "can not create spools (1)");
1202 if (readmail(&queue, sender, nodot) != 0)
1203 err(1, "can not read mail");
1205 if (linkspool(&queue) != 0)
1206 err(1, "can not create spools (2)");
1208 /* From here on the mail is safe. */
1210 if (config->features & DEFER)
1213 it = go_background(&queue);