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 readmail(struct queue *queue, const char *sender, int nodot)
428 char line[1000]; /* by RFC2822 */
432 error = snprintf(line, sizeof(line), "\
433 Received: from %s (uid %d)\n\
434 \t(envelope-from %s)\n\
443 if (error < 0 || (size_t)error >= sizeof(line))
445 if (write(queue->mailfd, line, error) != error)
448 while (!feof(stdin)) {
449 if (fgets(line, sizeof(line), stdin) == NULL)
451 linelen = strlen(line);
452 if (linelen == 0 || line[linelen - 1] != '\n') {
453 errno = EINVAL; /* XXX mark permanent errors */
456 if (!nodot && linelen == 2 && line[0] == '.')
458 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
461 if (fsync(queue->mailfd) != 0)
467 linkspool(struct queue *queue)
471 LIST_FOREACH(it, &queue->queue, next) {
472 if (link(queue->tmpf, it->queuefn) != 0)
479 LIST_FOREACH(it, &queue->queue, next) {
485 static struct qitem *
486 go_background(struct queue *queue)
493 if (daemonize && daemon(0, 0) != 0) {
494 syslog(LOG_ERR, "can not daemonize: %m");
499 bzero(&sa, sizeof(sa));
500 sa.sa_flags = SA_NOCLDWAIT;
501 sa.sa_handler = SIG_IGN;
502 sigaction(SIGCHLD, &sa, NULL);
504 LIST_FOREACH(it, &queue->queue, next) {
505 /* No need to fork for the last dest */
506 if (LIST_NEXT(it, next) == NULL)
512 syslog(LOG_ERR, "can not fork: %m");
520 * return and deliver mail
523 * We have to prevent sharing of fds between children, so
524 * we have to re-open the queue file.
526 newqf = fopen(it->queuefn, "r");
528 syslog(LOG_ERR, "can not re-open queue file `%s': %m",
546 syslog(LOG_CRIT, "reached dead code");
551 bounce(struct qitem *it, const char *reason)
553 struct queue bounceq;
559 /* Don't bounce bounced mails */
560 if (it->sender[0] == 0) {
561 syslog(LOG_INFO, "%s: can not bounce a bounce message, discarding",
566 syslog(LOG_ERR, "%s: delivery failed, bouncing",
569 LIST_INIT(&bounceq.queue);
570 if (add_recp(&bounceq, it->sender, "", 1) != 0)
572 if (gentempf(&bounceq) != 0)
574 if (preparespool(&bounceq, "") != 0)
577 bit = LIST_FIRST(&bounceq.queue);
578 error = fprintf(bit->queuef, "\
579 Received: from MAILER-DAEMON\n\
583 X-Original-To: <%s>\n\
584 From: MAILER-DAEMON <>\n\
586 Subject: Mail delivery failed\n\
587 Message-Id: <%"PRIxMAX"@%s>\n\
590 This is the %s at %s.\n\
592 There was an error delivering your mail to <%s>.\n\
604 bounceq.id, hostname(),
609 config->features & FULLBOUNCE? "Original message follows.":
610 "Message headers follow.");
613 if (fflush(bit->queuef) != 0)
616 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
618 if (config->features & FULLBOUNCE) {
619 while ((pos = fread(line, 1, sizeof(line), it->queuef)) > 0) {
620 if ((size_t)write(bounceq.mailfd, line, pos) != pos)
624 while (!feof(it->queuef)) {
625 if (fgets(line, sizeof(line), it->queuef) == NULL)
629 if ((size_t)write(bounceq.mailfd, line, strlen(line)) != strlen(line))
633 if (fsync(bounceq.mailfd) != 0)
635 if (linkspool(&bounceq) != 0)
642 bit = go_background(&bounceq);
647 syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
653 deliver_local(struct qitem *it, const char **errmsg)
661 time_t now = time(NULL);
663 error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
664 if (error < 0 || (size_t)error >= sizeof(fn)) {
665 syslog(LOG_NOTICE, "%s: local delivery deferred: %m",
670 /* mailx removes users mailspool file if empty, so open with O_CREAT */
671 mbox = open_locked(fn, O_WRONLY | O_APPEND | O_CREAT);
673 syslog(LOG_NOTICE, "%s: local delivery deferred: can not open `%s': %m",
677 mboxlen = lseek(mbox, 0, SEEK_CUR);
679 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
680 syslog(LOG_NOTICE, "%s: local delivery deferred: can not seek: %m",
685 error = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
686 if (error < 0 || (size_t)error >= sizeof(line)) {
687 syslog(LOG_NOTICE, "%s: local delivery deferred: can not write header: %m",
691 if (write(mbox, line, error) != error)
694 while (!feof(it->queuef)) {
695 if (fgets(line, sizeof(line), it->queuef) == NULL)
697 linelen = strlen(line);
698 if (linelen == 0 || line[linelen - 1] != '\n') {
699 syslog(LOG_CRIT, "%s: local delivery failed: corrupted queue file",
701 *errmsg = "corrupted queue file";
706 if (strncmp(line, "From ", 5) == 0) {
707 const char *gt = ">";
709 if (write(mbox, gt, 1) != 1)
712 if ((size_t)write(mbox, line, linelen) != linelen)
716 if (write(mbox, line, 1) != 1)
722 syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
726 if (ftruncate(mbox, mboxlen) != 0)
727 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
734 deliver(struct qitem *it)
737 unsigned int backoff = MIN_RETRY;
738 const char *errmsg = "unknown bounce reason";
742 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
743 it->queueid, it->sender, it->addr);
746 syslog(LOG_INFO, "%s: trying delivery",
750 error = deliver_remote(it, &errmsg);
752 error = deliver_local(it, &errmsg);
757 syslog(LOG_INFO, "%s: delivery successful",
762 if (stat(it->queuefn, &st) != 0) {
763 syslog(LOG_ERR, "%s: lost queue file `%s'",
764 it->queueid, it->queuefn);
767 if (gettimeofday(&now, NULL) == 0 &&
768 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
769 asprintf(__DECONST(void *, &errmsg),
770 "Could not deliver for the last %d seconds. Giving up.",
776 if (backoff > MAX_RETRY)
796 return (c - 'A' + 10);
798 return (c - 'a' + 10);
806 for (i = 0; i < 16; i++)
807 for (j = 0; j < 16; j++)
808 SLIST_INIT(&seenmsg[i][j]);
812 seen(const char *msgid)
819 p = strchr(msgid, '.');
824 i = c2x(msgid[len - 2]);
825 j = c2x(msgid[len - 1]);
826 } else if (len == 1) {
832 if (i < 0 || i >= 16 || j < 0 || j >= 16)
833 errx(1, "INTERNAL ERROR: bad seen code for msgid %s", msgid);
834 SLIST_FOREACH(t, &seenmsg[i][j], next)
835 if (!strncmp(t->str, msgid, len))
837 t = malloc(sizeof(*t));
839 errx(1, "Could not allocate %lu bytes",
840 (unsigned long)(sizeof(*t)));
841 t->str = strdup(msgid);
843 errx(1, "Could not duplicate msgid %s", msgid);
844 SLIST_INSERT_HEAD(&seenmsg[i][j], t, next);
849 load_queue(struct queue *queue, int ignorelock)
853 //struct queue queue, itmqueue;
854 struct queue itmqueue;
865 int fd, locked, seenit;
867 LIST_INIT(&queue->queue);
869 spooldir = opendir(config->spooldir);
870 if (spooldir == NULL)
871 err(1, "reading queue");
874 while ((de = readdir(spooldir)) != NULL) {
880 LIST_INIT(&itmqueue.queue);
882 /* ignore temp files */
883 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
884 de->d_type != DT_REG)
886 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
888 seenit = seen(de->d_name);
890 fd = open_locked(queuefn, O_RDONLY|O_NONBLOCK);
892 /* Ignore locked files */
893 if (errno != EWOULDBLOCK)
895 if (!ignorelock || seenit)
897 fd = open(queuefn, O_RDONLY);
903 queuef = fdopen(fd, "r");
906 if (fgets(line, sizeof(line), queuef) == NULL ||
909 line[strlen(line) - 1] = 0; /* chop newline */
910 sender = strdup(line);
915 if (fgets(line, sizeof(line), queuef) == NULL ||
920 line[strlen(line) - 1] = 0;
921 queueid = strdup(line);
924 addr = strchr(queueid, ' ');
930 if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
932 /* Item has already been delivered? */
933 if (stat(fn, &st) != 0)
935 if (add_recp(&itmqueue, addr, sender, 0) != 0)
937 it = LIST_FIRST(&itmqueue.queue);
939 it->queueid = queueid;
944 if (LIST_EMPTY(&itmqueue.queue)) {
945 warnx("queue file without items: `%s'", queuefn);
948 hdrlen = ftell(queuef);
949 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
951 LIST_REMOVE(it, next);
952 LIST_INSERT_HEAD(&queue->queue, it, next);
957 warn("reading queue: `%s'", queuefn);
973 err(1, "reading queue");
977 run_queue(struct queue *queue)
981 if (LIST_EMPTY(&queue->queue))
984 it = go_background(queue);
990 show_queue(struct queue *queue)
994 if (LIST_EMPTY(&queue->queue)) {
995 printf("Mail queue is empty\n");
999 LIST_FOREACH(it, &queue->queue, next) {
1003 To\t: %s\n--\n", it->queueid, it->locked? "*": "", it->sender, it->addr);
1010 * - alias processing
1011 * - use group permissions
1012 * - proper sysexit codes
1016 main(int argc, char **argv)
1018 char *sender = NULL;
1022 struct queue lqueue;
1024 int nodot = 0, doqueue = 0, showq = 0;
1027 LIST_INIT(&queue.queue);
1028 snprintf(tag, 254, "dma");
1030 if (strcmp(argv[0], "mailq") == 0) {
1034 errx(1, "invalid arguments");
1039 while ((ch = getopt(argc, argv, "A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
1042 /* -AX is being ignored, except for -A{c,m} */
1043 if (optarg[0] == 'c' || optarg[0] == 'm') {
1046 /* else FALLTRHOUGH */
1048 /* -bX is being ignored, except for -bp */
1049 if (optarg[0] == 'p') {
1053 /* else FALLTRHOUGH */
1059 snprintf(tag, 254, "%s", optarg);
1067 /* -oX is being ignored, except for -oi */
1068 if (optarg[0] != 'i')
1070 /* else FALLTRHOUGH */
1081 /* Ignored options */
1105 openlog(tag, LOG_PID, LOG_MAIL);
1108 config = malloc(sizeof(struct config));
1112 memset(config, 0, sizeof(struct config));
1113 if (parse_conf(CONF_PATH, config) < 0) {
1115 err(1, "can not read config file");
1118 if (config->features & VIRTUAL)
1119 if (parse_virtuser(config->virtualpath) < 0)
1120 err(1, "can not read virtual user file `%s'",
1121 config->virtualpath);
1123 if (parse_authfile(config->authpath) < 0)
1124 err(1, "can not read SMTP authentication file");
1128 errx(1, "sending mail and displaying queue is"
1129 " mutually exclusive");
1130 load_queue(&lqueue, 1);
1131 show_queue(&lqueue);
1137 errx(1, "sending mail and queue pickup is mutually exclusive");
1138 load_queue(&lqueue, 0);
1143 if (read_aliases() != 0)
1144 err(1, "can not read aliases file `%s'", config->aliases);
1146 if ((sender = set_from(sender)) == NULL)
1149 for (i = 0; i < argc; i++) {
1150 if (add_recp(&queue, argv[i], sender, 1) != 0)
1151 errx(1, "invalid recipient `%s'", argv[i]);
1154 if (LIST_EMPTY(&queue.queue))
1155 errx(1, "no recipients");
1157 if (gentempf(&queue) != 0)
1158 err(1, "can not create temp file");
1160 if (preparespool(&queue, sender) != 0)
1161 err(1, "can not create spools (1)");
1163 if (readmail(&queue, sender, nodot) != 0)
1164 err(1, "can not read mail");
1166 if (linkspool(&queue) != 0)
1167 err(1, "can not create spools (2)");
1169 /* From here on the mail is safe. */
1171 if (config->features & DEFER)
1174 it = go_background(&queue);