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)
143 username = check_username(getenv("LOGNAME"), uid);
144 if (username != NULL)
146 username = check_username(getenv("USER"), uid);
147 if (username != NULL)
150 if (pwd != NULL && pwd->pw_name != NULL && pwd->pw_name[0] != '\0' &&
151 (u = strdup(pwd->pw_name)) != NULL) {
152 username = check_username(u, uid);
153 if (username != NULL)
158 asprintf(__DECONST(void *, &username), "%ld", (long)uid);
159 if (username != NULL)
161 username = "unknown-or-invalid-username";
165 set_from(const char *osender)
170 if ((config->features & VIRTUAL) != 0) {
171 SLIST_FOREACH(v, &virtusers, next) {
172 if (strcmp(v->login, username) == 0) {
173 sender = strdup(v->address);
182 sender = strdup(osender);
186 if (asprintf(&sender, "%s@%s", username, hostname()) <= 0)
190 if (strchr(sender, '\n') != NULL) {
202 yyin = fopen(config->aliases, "r");
204 return (0); /* not fatal */
206 return (-1); /* fatal error, probably malloc() */
212 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
214 struct qitem *it, *tit;
221 it = calloc(1, sizeof(*it));
224 it->addr = strdup(str);
225 if (it->addr == NULL)
229 host = strrchr(it->addr, '@');
231 (strcmp(host + 1, hostname()) == 0 ||
232 strcmp(host + 1, "localhost") == 0)) {
235 LIST_FOREACH(tit, &queue->queue, next) {
236 /* weed out duplicate dests */
237 if (strcmp(tit->addr, it->addr) == 0) {
243 LIST_INSERT_HEAD(&queue->queue, it, next);
244 if (strrchr(it->addr, '@') == NULL) {
247 LIST_FOREACH(al, &aliases, next) {
248 if (strcmp(al->alias, it->addr) != 0)
250 SLIST_FOREACH(sit, &al->dests, next) {
251 if (add_recp(queue, sit->str, sender, 1) != 0)
257 LIST_REMOVE(it, next);
259 /* Local destination, check */
260 pw = getpwnam(it->addr);
283 SLIST_FOREACH(t, &tmpfs, next) {
289 gentempf(struct queue *queue)
295 if (snprintf(fn, sizeof(fn), "%s/%s", config->spooldir, "tmp_XXXXXXXXXX") <= 0)
300 if (flock(fd, LOCK_EX) == -1)
303 queue->tmpf = strdup(fn);
304 if (queue->tmpf == NULL) {
308 t = malloc(sizeof(*t));
310 t->str = queue->tmpf;
311 SLIST_INSERT_HEAD(&tmpfs, t, next);
317 open_locked(const char *fname, int flags)
322 fd = open(fname, flags, 0);
325 if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) {
333 return(open(fname, flags|O_EXLOCK));
341 * queue-id1 envelope-to1
342 * queue-id2 envelope-to2
347 * queue ids are unique, formed from the inode of the spool file
348 * and a unique identifier.
351 preparespool(struct queue *queue, const char *sender)
353 char line[1000]; /* by RFC2822 */
360 error = snprintf(line, sizeof(line), "%s\n", sender);
361 if (error < 0 || (size_t)error >= sizeof(line)) {
365 if (write(queue->mailfd, line, error) != error)
368 queuef = fdopen(queue->mailfd, "r+");
373 * Assign queue id to each dest.
375 if (fstat(queue->mailfd, &st) != 0)
377 queue->id = st.st_ino;
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)
397 if (write(queue->mailfd, line, 1) != 1)
400 hdrlen = lseek(queue->mailfd, 0, SEEK_CUR);
401 LIST_FOREACH(it, &queue->queue, next) {
415 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
418 strcpy(str, "(date fail)");
423 readmail(struct queue *queue, const char *sender, int nodot)
425 char line[1000]; /* by RFC2822 */
429 error = snprintf(line, sizeof(line), "\
430 Received: from %s (uid %d)\n\
431 \t(envelope-from %s)\n\
440 if (error < 0 || (size_t)error >= sizeof(line))
442 if (write(queue->mailfd, line, error) != error)
445 while (!feof(stdin)) {
446 if (fgets(line, sizeof(line), stdin) == NULL)
448 linelen = strlen(line);
449 if (linelen == 0 || line[linelen - 1] != '\n') {
450 errno = EINVAL; /* XXX mark permanent errors */
453 if (!nodot && linelen == 2 && line[0] == '.')
455 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
458 if (fsync(queue->mailfd) != 0)
464 linkspool(struct queue *queue)
468 LIST_FOREACH(it, &queue->queue, next) {
469 if (link(queue->tmpf, it->queuefn) != 0)
476 LIST_FOREACH(it, &queue->queue, next) {
482 static struct qitem *
483 go_background(struct queue *queue)
489 if (daemonize && daemon(0, 0) != 0) {
490 syslog(LOG_ERR, "can not daemonize: %m");
495 bzero(&sa, sizeof(sa));
496 sa.sa_flags = SA_NOCLDWAIT;
497 sa.sa_handler = SIG_IGN;
498 sigaction(SIGCHLD, &sa, NULL);
500 LIST_FOREACH(it, &queue->queue, next) {
501 /* No need to fork for the last dest */
502 if (LIST_NEXT(it, next) == NULL)
508 syslog(LOG_ERR, "can not fork: %m");
516 * return and deliver mail
530 syslog(LOG_CRIT, "reached dead code");
535 bounce(struct qitem *it, const char *reason)
537 struct queue bounceq;
543 /* Don't bounce bounced mails */
544 if (it->sender[0] == 0) {
545 syslog(LOG_CRIT, "%s: delivery panic: can't bounce a bounce",
550 syslog(LOG_ERR, "%s: delivery failed, bouncing",
553 LIST_INIT(&bounceq.queue);
554 if (add_recp(&bounceq, it->sender, "", 1) != 0)
556 if (gentempf(&bounceq) != 0)
558 if (preparespool(&bounceq, "") != 0)
561 bit = LIST_FIRST(&bounceq.queue);
562 error = fprintf(bit->queuef, "\
563 Received: from MAILER-DAEMON\n\
567 X-Original-To: <%s>\n\
568 From: MAILER-DAEMON <>\n\
570 Subject: Mail delivery failed\n\
571 Message-Id: <%"PRIxMAX"@%s>\n\
574 This is the %s at %s.\n\
576 There was an error delivering your mail to <%s>.\n\
588 bounceq.id, hostname(),
593 config->features & FULLBOUNCE? "Original message follows.":
594 "Message headers follow.");
597 if (fflush(bit->queuef) != 0)
600 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
602 if (config->features & FULLBOUNCE) {
603 while ((pos = fread(line, 1, sizeof(line), it->queuef)) > 0) {
604 if ((size_t)write(bounceq.mailfd, line, pos) != pos)
608 while (!feof(it->queuef)) {
609 if (fgets(line, sizeof(line), it->queuef) == NULL)
613 if ((size_t)write(bounceq.mailfd, line, strlen(line)) != strlen(line))
617 if (fsync(bounceq.mailfd) != 0)
619 if (linkspool(&bounceq) != 0)
626 bit = go_background(&bounceq);
631 syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
637 deliver_local(struct qitem *it, const char **errmsg)
645 time_t now = time(NULL);
647 error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
648 if (error < 0 || (size_t)error >= sizeof(fn)) {
649 syslog(LOG_ERR, "%s: local delivery deferred: %m",
654 /* mailx removes users mailspool file if empty, so open with O_CREAT */
655 mbox = open_locked(fn, O_WRONLY | O_APPEND | O_CREAT);
657 syslog(LOG_ERR, "%s: local delivery deferred: can not open `%s': %m",
661 mboxlen = lseek(mbox, 0, SEEK_CUR);
663 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
664 syslog(LOG_ERR, "%s: local delivery deferred: can not seek: %m",
669 error = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
670 if (error < 0 || (size_t)error >= sizeof(line)) {
671 syslog(LOG_ERR, "%s: local delivery deferred: can not write header: %m",
675 if (write(mbox, line, error) != error)
678 while (!feof(it->queuef)) {
679 if (fgets(line, sizeof(line), it->queuef) == NULL)
681 linelen = strlen(line);
682 if (linelen == 0 || line[linelen - 1] != '\n') {
683 syslog(LOG_CRIT, "%s: local delivery failed: corrupted queue file",
685 *errmsg = "corrupted queue file";
690 if (strncmp(line, "From ", 5) == 0) {
691 const char *gt = ">";
693 if (write(mbox, gt, 1) != 1)
696 if ((size_t)write(mbox, line, linelen) != linelen)
700 if (write(mbox, line, 1) != 1)
706 syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
710 if (ftruncate(mbox, mboxlen) != 0)
711 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
718 deliver(struct qitem *it)
721 unsigned int backoff = MIN_RETRY;
722 const char *errmsg = "unknown bounce reason";
726 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
727 it->queueid, it->sender, it->addr);
730 syslog(LOG_INFO, "%s: trying delivery",
734 error = deliver_remote(it, &errmsg);
736 error = deliver_local(it, &errmsg);
741 syslog(LOG_INFO, "%s: delivery successful",
746 if (stat(it->queuefn, &st) != 0) {
747 syslog(LOG_ERR, "%s: lost queue file `%s'",
748 it->queueid, it->queuefn);
751 if (gettimeofday(&now, NULL) == 0 &&
752 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
753 asprintf(__DECONST(void *, &errmsg),
754 "Could not deliver for the last %d seconds. Giving up.",
760 if (backoff > MAX_RETRY)
780 return (c - 'A' + 10);
782 return (c - 'a' + 10);
790 for (i = 0; i < 16; i++)
791 for (j = 0; j < 16; j++)
792 SLIST_INIT(&seenmsg[i][j]);
796 seen(const char *msgid)
803 p = strchr(msgid, '.');
808 i = c2x(msgid[len - 2]);
809 j = c2x(msgid[len - 1]);
810 } else if (len == 1) {
816 if (i < 0 || i >= 16 || j < 0 || j >= 16)
817 errx(1, "INTERNAL ERROR: bad seen code for msgid %s", msgid);
818 SLIST_FOREACH(t, &seenmsg[i][j], next)
819 if (!strncmp(t->str, msgid, len))
821 t = malloc(sizeof(*t));
823 errx(1, "Could not allocate %lu bytes",
824 (unsigned long)(sizeof(*t)));
825 t->str = strdup(msgid);
827 errx(1, "Could not duplicate msgid %s", msgid);
828 SLIST_INSERT_HEAD(&seenmsg[i][j], t, next);
833 load_queue(struct queue *queue, int ignorelock)
837 //struct queue queue, itmqueue;
838 struct queue itmqueue;
849 int fd, locked, seenit;
851 LIST_INIT(&queue->queue);
853 spooldir = opendir(config->spooldir);
854 if (spooldir == NULL)
855 err(1, "reading queue");
858 while ((de = readdir(spooldir)) != NULL) {
864 LIST_INIT(&itmqueue.queue);
866 /* ignore temp files */
867 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
868 de->d_type != DT_REG)
870 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
872 seenit = seen(de->d_name);
874 fd = open_locked(queuefn, O_RDONLY|O_NONBLOCK);
876 /* Ignore locked files */
877 if (errno != EWOULDBLOCK)
879 if (!ignorelock || seenit)
881 fd = open(queuefn, O_RDONLY);
887 queuef = fdopen(fd, "r");
890 if (fgets(line, sizeof(line), queuef) == NULL ||
893 line[strlen(line) - 1] = 0; /* chop newline */
894 sender = strdup(line);
899 if (fgets(line, sizeof(line), queuef) == NULL ||
904 line[strlen(line) - 1] = 0;
905 queueid = strdup(line);
908 addr = strchr(queueid, ' ');
914 if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
916 /* Item has already been delivered? */
917 if (stat(fn, &st) != 0)
919 if (add_recp(&itmqueue, addr, sender, 0) != 0)
921 it = LIST_FIRST(&itmqueue.queue);
923 it->queueid = queueid;
928 if (LIST_EMPTY(&itmqueue.queue)) {
929 warnx("queue file without items: `%s'", queuefn);
932 hdrlen = ftell(queuef);
933 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
935 LIST_REMOVE(it, next);
936 LIST_INSERT_HEAD(&queue->queue, it, next);
941 warn("reading queue: `%s'", queuefn);
957 err(1, "reading queue");
961 run_queue(struct queue *queue)
965 if (LIST_EMPTY(&queue->queue))
968 it = go_background(queue);
974 show_queue(struct queue *queue)
978 if (LIST_EMPTY(&queue->queue)) {
979 printf("Mail queue is empty\n");
983 LIST_FOREACH(it, &queue->queue, next) {
987 To\t: %s\n--\n", it->queueid, it->locked? "*": "", it->sender, it->addr);
995 * - use group permissions
996 * - proper sysexit codes
1000 main(int argc, char **argv)
1002 char *sender = NULL;
1006 struct queue lqueue;
1008 int nodot = 0, doqueue = 0, showq = 0;
1011 LIST_INIT(&queue.queue);
1012 snprintf(tag, 254, "dma");
1015 while ((ch = getopt(argc, argv, "A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
1018 /* -AX is being ignored, except for -A{c,m} */
1019 if (optarg[0] == 'c' || optarg[0] == 'm') {
1022 /* else FALLTRHOUGH */
1024 /* -bX is being ignored, except for -bp */
1025 if (optarg[0] == 'p') {
1029 /* else FALLTRHOUGH */
1035 snprintf(tag, 254, "%s", optarg);
1043 /* -oX is being ignored, except for -oi */
1044 if (optarg[0] != 'i')
1046 /* else FALLTRHOUGH */
1057 /* Ignored options */
1080 openlog(tag, LOG_PID | LOG_PERROR, LOG_MAIL);
1083 config = malloc(sizeof(struct config));
1085 errx(1, "Cannot allocate enough memory");
1087 memset(config, 0, sizeof(struct config));
1088 if (parse_conf(CONF_PATH, config) < 0) {
1090 errx(1, "reading config file");
1093 if (config->features & VIRTUAL)
1094 if (parse_virtuser(config->virtualpath) < 0)
1095 errx(1, "error reading virtual user file: %s",
1096 config->virtualpath);
1098 if (parse_authfile(config->authpath) < 0)
1099 err(1, "reading SMTP authentication file");
1103 errx(1, "sending mail and displaying queue is"
1104 " mutually exclusive");
1105 load_queue(&lqueue, 1);
1106 show_queue(&lqueue);
1112 errx(1, "sending mail and queue pickup is mutually exclusive");
1113 load_queue(&lqueue, 0);
1118 if (read_aliases() != 0)
1119 err(1, "reading aliases");
1121 if ((sender = set_from(sender)) == NULL)
1122 err(1, "setting from address");
1124 for (i = 0; i < argc; i++) {
1125 if (add_recp(&queue, argv[i], sender, 1) != 0)
1126 errx(1, "invalid recipient `%s'\n", argv[i]);
1129 if (LIST_EMPTY(&queue.queue))
1130 errx(1, "no recipients");
1132 if (gentempf(&queue) != 0)
1133 err(1, "create temp file");
1135 if (preparespool(&queue, sender) != 0)
1136 err(1, "creating spools (1)");
1138 if (readmail(&queue, sender, nodot) != 0)
1139 err(1, "reading mail");
1141 if (linkspool(&queue) != 0)
1142 err(1, "creating spools (2)");
1144 /* From here on the mail is safe. */
1146 if (config->features & DEFER)
1149 it = go_background(&queue);