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 struct strlist seenmsg[16][16];
82 static char name[MAXHOSTNAMELEN+1];
84 if (gethostname(name, sizeof(name)) != 0)
85 strcpy(name, "(unknown hostname)");
91 set_from(const char *osender)
96 if ((config->features & VIRTUAL) != 0) {
97 SLIST_FOREACH(v, &virtusers, next) {
98 if (strcmp(v->login, getlogin()) == 0) {
99 sender = strdup(v->address);
108 sender = strdup(osender);
112 if (asprintf(&sender, "%s@%s", getlogin(), hostname()) <= 0)
116 if (strchr(sender, '\n') != NULL) {
128 yyin = fopen(config->aliases, "r");
130 return (0); /* not fatal */
132 return (-1); /* fatal error, probably malloc() */
138 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
140 struct qitem *it, *tit;
147 it = calloc(1, sizeof(*it));
150 it->addr = strdup(str);
151 if (it->addr == NULL)
155 host = strrchr(it->addr, '@');
157 (strcmp(host + 1, hostname()) == 0 ||
158 strcmp(host + 1, "localhost") == 0)) {
161 LIST_FOREACH(tit, &queue->queue, next) {
162 /* weed out duplicate dests */
163 if (strcmp(tit->addr, it->addr) == 0) {
169 LIST_INSERT_HEAD(&queue->queue, it, next);
170 if (strrchr(it->addr, '@') == NULL) {
173 LIST_FOREACH(al, &aliases, next) {
174 if (strcmp(al->alias, it->addr) != 0)
176 SLIST_FOREACH(sit, &al->dests, next) {
177 if (add_recp(queue, sit->str, sender, 1) != 0)
183 LIST_REMOVE(it, next);
185 /* Local destination, check */
186 pw = getpwnam(it->addr);
209 SLIST_FOREACH(t, &tmpfs, next) {
215 gentempf(struct queue *queue)
221 if (snprintf(fn, sizeof(fn), "%s/%s", config->spooldir, "tmp_XXXXXXXXXX") <= 0)
226 if (flock(fd, LOCK_EX) == -1)
229 queue->tmpf = strdup(fn);
230 if (queue->tmpf == NULL) {
234 t = malloc(sizeof(*t));
236 t->str = queue->tmpf;
237 SLIST_INSERT_HEAD(&tmpfs, t, next);
243 open_locked(const char *fname, int flags)
248 fd = open(fname, flags, 0);
251 if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) {
259 return(open(fname, flags|O_EXLOCK));
267 * queue-id1 envelope-to1
268 * queue-id2 envelope-to2
273 * queue ids are unique, formed from the inode of the spool file
274 * and a unique identifier.
277 preparespool(struct queue *queue, const char *sender)
279 char line[1000]; /* by RFC2822 */
286 error = snprintf(line, sizeof(line), "%s\n", sender);
287 if (error < 0 || (size_t)error >= sizeof(line)) {
291 if (write(queue->mailfd, line, error) != error)
294 queuef = fdopen(queue->mailfd, "r+");
299 * Assign queue id to each dest.
301 if (fstat(queue->mailfd, &st) != 0)
303 queue->id = st.st_ino;
304 LIST_FOREACH(it, &queue->queue, next) {
305 if (asprintf(&it->queueid, "%"PRIxMAX".%"PRIxPTR,
306 queue->id, (uintptr_t)it) <= 0)
308 if (asprintf(&it->queuefn, "%s/%s",
309 config->spooldir, it->queueid) <= 0)
311 /* File may not exist yet */
312 if (stat(it->queuefn, &st) == 0)
315 error = snprintf(line, sizeof(line), "%s %s\n",
316 it->queueid, it->addr);
317 if (error < 0 || (size_t)error >= sizeof(line))
319 if (write(queue->mailfd, line, error) != error)
323 if (write(queue->mailfd, line, 1) != 1)
326 hdrlen = lseek(queue->mailfd, 0, SEEK_CUR);
327 LIST_FOREACH(it, &queue->queue, next) {
341 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
344 strcpy(str, "(date fail)");
349 readmail(struct queue *queue, const char *sender, int nodot)
351 char line[1000]; /* by RFC2822 */
355 error = snprintf(line, sizeof(line), "\
356 Received: from %s (uid %d)\n\
357 \t(envelope-from %s)\n\
361 getlogin(), getuid(),
366 if (error < 0 || (size_t)error >= sizeof(line))
368 if (write(queue->mailfd, line, error) != error)
371 while (!feof(stdin)) {
372 if (fgets(line, sizeof(line), stdin) == NULL)
374 linelen = strlen(line);
375 if (linelen == 0 || line[linelen - 1] != '\n') {
376 errno = EINVAL; /* XXX mark permanent errors */
379 if (!nodot && linelen == 2 && line[0] == '.')
381 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
384 if (fsync(queue->mailfd) != 0)
390 linkspool(struct queue *queue)
394 LIST_FOREACH(it, &queue->queue, next) {
395 if (link(queue->tmpf, it->queuefn) != 0)
402 LIST_FOREACH(it, &queue->queue, next) {
408 static struct qitem *
409 go_background(struct queue *queue)
415 if (daemonize && daemon(0, 0) != 0) {
416 syslog(LOG_ERR, "can not daemonize: %m");
421 bzero(&sa, sizeof(sa));
422 sa.sa_flags = SA_NOCLDWAIT;
423 sa.sa_handler = SIG_IGN;
424 sigaction(SIGCHLD, &sa, NULL);
426 LIST_FOREACH(it, &queue->queue, next) {
427 /* No need to fork for the last dest */
428 if (LIST_NEXT(it, next) == NULL)
434 syslog(LOG_ERR, "can not fork: %m");
442 * return and deliver mail
456 syslog(LOG_CRIT, "reached dead code");
461 bounce(struct qitem *it, const char *reason)
463 struct queue bounceq;
468 /* Don't bounce bounced mails */
469 if (it->sender[0] == 0) {
470 syslog(LOG_CRIT, "%s: delivery panic: can't bounce a bounce",
475 syslog(LOG_ERR, "%s: delivery failed, bouncing",
478 LIST_INIT(&bounceq.queue);
479 if (add_recp(&bounceq, it->sender, "", 1) != 0)
481 if (gentempf(&bounceq) != 0)
483 if (preparespool(&bounceq, "") != 0)
486 bit = LIST_FIRST(&bounceq.queue);
487 error = fprintf(bit->queuef, "\
488 Received: from MAILER-DAEMON\n\
492 X-Original-To: <%s>\n\
493 From: MAILER-DAEMON <>\n\
495 Subject: Mail delivery failed\n\
496 Message-Id: <%"PRIxMAX"@%s>\n\
499 This is the %s at %s.\n\
501 There was an error delivering your mail to <%s>.\n\
505 Message headers follow.\n\
513 bounceq.id, hostname(),
520 if (fflush(bit->queuef) != 0)
523 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
525 while (!feof(it->queuef)) {
526 if (fgets(line, sizeof(line), it->queuef) == NULL)
530 if ((size_t)write(bounceq.mailfd, line, strlen(line)) != strlen(line))
533 if (fsync(bounceq.mailfd) != 0)
535 if (linkspool(&bounceq) != 0)
542 bit = go_background(&bounceq);
547 syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
553 deliver_local(struct qitem *it, const char **errmsg)
561 time_t now = time(NULL);
563 error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
564 if (error < 0 || (size_t)error >= sizeof(fn)) {
565 syslog(LOG_ERR, "%s: local delivery deferred: %m",
570 /* mailx removes users mailspool file if empty, so open with O_CREAT */
571 mbox = open_locked(fn, O_WRONLY | O_APPEND | O_CREAT);
573 syslog(LOG_ERR, "%s: local delivery deferred: can not open `%s': %m",
577 mboxlen = lseek(mbox, 0, SEEK_CUR);
579 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
580 syslog(LOG_ERR, "%s: local delivery deferred: can not seek: %m",
585 error = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
586 if (error < 0 || (size_t)error >= sizeof(line)) {
587 syslog(LOG_ERR, "%s: local delivery deferred: can not write header: %m",
591 if (write(mbox, line, error) != error)
594 while (!feof(it->queuef)) {
595 if (fgets(line, sizeof(line), it->queuef) == NULL)
597 linelen = strlen(line);
598 if (linelen == 0 || line[linelen - 1] != '\n') {
599 syslog(LOG_CRIT, "%s: local delivery failed: corrupted queue file",
601 *errmsg = "corrupted queue file";
606 if (strncmp(line, "From ", 5) == 0) {
607 const char *gt = ">";
609 if (write(mbox, gt, 1) != 1)
612 if ((size_t)write(mbox, line, linelen) != linelen)
616 if (write(mbox, line, 1) != 1)
622 syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
626 if (ftruncate(mbox, mboxlen) != 0)
627 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
634 deliver(struct qitem *it)
637 unsigned int backoff = MIN_RETRY;
638 const char *errmsg = "unknown bounce reason";
642 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
643 it->queueid, it->sender, it->addr);
646 syslog(LOG_INFO, "%s: trying delivery",
650 error = deliver_remote(it, &errmsg);
652 error = deliver_local(it, &errmsg);
657 syslog(LOG_INFO, "%s: delivery successful",
662 if (stat(it->queuefn, &st) != 0) {
663 syslog(LOG_ERR, "%s: lost queue file `%s'",
664 it->queueid, it->queuefn);
667 if (gettimeofday(&now, NULL) == 0 &&
668 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
672 "Could not deliver for the last %d seconds. Giving up.",
679 if (backoff > MAX_RETRY)
699 return (c - 'A' + 10);
701 return (c - 'a' + 10);
709 for (i = 0; i < 16; i++)
710 for (j = 0; j < 16; j++)
711 SLIST_INIT(&seenmsg[i][j]);
715 seen(const char *msgid)
722 p = strchr(msgid, '.');
727 i = c2x(msgid[len - 2]);
728 j = c2x(msgid[len - 1]);
729 } else if (len == 1) {
735 if (i < 0 || i >= 16 || j < 0 || j >= 16)
736 errx(1, "INTERNAL ERROR: bad seen code for msgid %s", msgid);
737 SLIST_FOREACH(t, &seenmsg[i][j], next)
738 if (!strncmp(t->str, msgid, len))
740 t = malloc(sizeof(*t));
742 errx(1, "Could not allocate %lu bytes",
743 (unsigned long)(sizeof(*t)));
744 t->str = strdup(msgid);
746 errx(1, "Could not duplicate msgid %s", msgid);
747 SLIST_INSERT_HEAD(&seenmsg[i][j], t, next);
752 load_queue(struct queue *queue, int ignorelock)
756 //struct queue queue, itmqueue;
757 struct queue itmqueue;
768 int fd, locked, seenit;
770 LIST_INIT(&queue->queue);
772 spooldir = opendir(config->spooldir);
773 if (spooldir == NULL)
774 err(1, "reading queue");
777 while ((de = readdir(spooldir)) != NULL) {
783 LIST_INIT(&itmqueue.queue);
785 /* ignore temp files */
786 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
787 de->d_type != DT_REG)
789 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
791 seenit = seen(de->d_name);
793 fd = open_locked(queuefn, O_RDONLY|O_NONBLOCK);
795 /* Ignore locked files */
796 if (errno != EWOULDBLOCK)
798 if (!ignorelock || seenit)
800 fd = open(queuefn, O_RDONLY);
806 queuef = fdopen(fd, "r");
809 if (fgets(line, sizeof(line), queuef) == NULL ||
812 line[strlen(line) - 1] = 0; /* chop newline */
813 sender = strdup(line);
818 if (fgets(line, sizeof(line), queuef) == NULL ||
823 line[strlen(line) - 1] = 0;
824 queueid = strdup(line);
827 addr = strchr(queueid, ' ');
833 if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
835 /* Item has already been delivered? */
836 if (stat(fn, &st) != 0)
838 if (add_recp(&itmqueue, addr, sender, 0) != 0)
840 it = LIST_FIRST(&itmqueue.queue);
842 it->queueid = queueid;
847 if (LIST_EMPTY(&itmqueue.queue)) {
848 warnx("queue file without items: `%s'", queuefn);
851 hdrlen = ftell(queuef);
852 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
854 LIST_REMOVE(it, next);
855 LIST_INSERT_HEAD(&queue->queue, it, next);
860 warn("reading queue: `%s'", queuefn);
876 err(1, "reading queue");
880 run_queue(struct queue *queue)
884 if (LIST_EMPTY(&queue->queue))
887 it = go_background(queue);
893 show_queue(struct queue *queue)
897 if (LIST_EMPTY(&queue->queue)) {
898 printf("Mail queue is empty\n");
902 LIST_FOREACH(it, &queue->queue, next) {
906 To\t: %s\n--\n", it->queueid, it->locked? "*": "", it->sender, it->addr);
914 * - use group permissions
915 * - proper sysexit codes
919 main(int argc, char **argv)
927 int nodot = 0, doqueue = 0, showq = 0;
930 LIST_INIT(&queue.queue);
931 snprintf(tag, 254, "dma");
934 while ((ch = getopt(argc, argv, "A:b:Df:iL:o:O:q:r:")) != -1) {
937 /* -AX is being ignored, except for -A{c,m} */
938 if (optarg[0] == 'c' || optarg[0] == 'm') {
941 /* else FALLTRHOUGH */
943 /* -bX is being ignored, except for -bp */
944 if (optarg[0] == 'p') {
948 /* else FALLTRHOUGH */
954 snprintf(tag, 254, "%s", optarg);
962 /* -oX is being ignored, except for -oi */
963 if (optarg[0] != 'i')
965 /* else FALLTRHOUGH */
984 openlog(tag, LOG_PID | LOG_PERROR, LOG_MAIL);
986 config = malloc(sizeof(struct config));
988 errx(1, "Cannot allocate enough memory");
990 memset(config, 0, sizeof(struct config));
991 if (parse_conf(CONF_PATH, config) < 0) {
993 errx(1, "reading config file");
996 if (config->features & VIRTUAL)
997 if (parse_virtuser(config->virtualpath) < 0)
998 errx(1, "error reading virtual user file: %s",
999 config->virtualpath);
1001 if (parse_authfile(config->authpath) < 0)
1002 err(1, "reading SMTP authentication file");
1006 errx(1, "sending mail and displaying queue is"
1007 " mutually exclusive");
1008 load_queue(&lqueue, 1);
1009 show_queue(&lqueue);
1015 errx(1, "sending mail and queue pickup is mutually exclusive");
1016 load_queue(&lqueue, 0);
1021 if (read_aliases() != 0)
1022 err(1, "reading aliases");
1024 if ((sender = set_from(sender)) == NULL)
1025 err(1, "setting from address");
1027 for (i = 0; i < argc; i++) {
1028 if (add_recp(&queue, argv[i], sender, 1) != 0)
1029 errx(1, "invalid recipient `%s'\n", argv[i]);
1032 if (LIST_EMPTY(&queue.queue))
1033 errx(1, "no recipients");
1035 if (gentempf(&queue) != 0)
1036 err(1, "create temp file");
1038 if (preparespool(&queue, sender) != 0)
1039 err(1, "creating spools (1)");
1041 if (readmail(&queue, sender, nodot) != 0)
1042 err(1, "reading mail");
1044 if (linkspool(&queue) != 0)
1045 err(1, "creating spools (2)");
1047 /* From here on the mail is safe. */
1049 if (config->features & DEFER)
1052 it = go_background(&queue);