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;
81 static char name[MAXHOSTNAMELEN+1];
83 if (gethostname(name, sizeof(name)) != 0)
84 strcpy(name, "(unknown hostname)");
90 set_from(const char *osender)
95 if ((config->features & VIRTUAL) != 0) {
96 SLIST_FOREACH(v, &virtusers, next) {
97 if (strcmp(v->login, getlogin()) == 0) {
98 sender = strdup(v->address);
107 sender = strdup(osender);
111 if (asprintf(&sender, "%s@%s", getlogin(), hostname()) <= 0)
115 if (strchr(sender, '\n') != NULL) {
127 yyin = fopen(config->aliases, "r");
129 return (0); /* not fatal */
131 return (-1); /* fatal error, probably malloc() */
137 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
139 struct qitem *it, *tit;
146 it = calloc(1, sizeof(*it));
149 it->addr = strdup(str);
150 if (it->addr == NULL)
154 host = strrchr(it->addr, '@');
156 (strcmp(host + 1, hostname()) == 0 ||
157 strcmp(host + 1, "localhost") == 0)) {
160 LIST_FOREACH(tit, &queue->queue, next) {
161 /* weed out duplicate dests */
162 if (strcmp(tit->addr, it->addr) == 0) {
168 LIST_INSERT_HEAD(&queue->queue, it, next);
169 if (strrchr(it->addr, '@') == NULL) {
172 LIST_FOREACH(al, &aliases, next) {
173 if (strcmp(al->alias, it->addr) != 0)
175 SLIST_FOREACH(sit, &al->dests, next) {
176 if (add_recp(queue, sit->str, sender, 1) != 0)
182 LIST_REMOVE(it, next);
184 /* Local destination, check */
185 pw = getpwnam(it->addr);
208 SLIST_FOREACH(t, &tmpfs, next) {
214 gentempf(struct queue *queue)
220 if (snprintf(fn, sizeof(fn), "%s/%s", config->spooldir, "tmp_XXXXXXXXXX") <= 0)
226 queue->tmpf = strdup(fn);
227 if (queue->tmpf == NULL) {
231 t = malloc(sizeof(*t));
233 t->str = queue->tmpf;
234 SLIST_INSERT_HEAD(&tmpfs, t, next);
240 open_locked(const char *fname, int flags)
245 fd = open(fname, flags, 0);
248 if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) {
256 return(open(fname, flags|O_EXLOCK));
264 * queue-id1 envelope-to1
265 * queue-id2 envelope-to2
270 * queue ids are unique, formed from the inode of the spool file
271 * and a unique identifier.
274 preparespool(struct queue *queue, const char *sender)
276 char line[1000]; /* by RFC2822 */
283 error = snprintf(line, sizeof(line), "%s\n", sender);
284 if (error < 0 || (size_t)error >= sizeof(line)) {
288 if (write(queue->mailfd, line, error) != error)
291 queuef = fdopen(queue->mailfd, "r+");
296 * Assign queue id to each dest.
298 if (fstat(queue->mailfd, &st) != 0)
300 queue->id = st.st_ino;
301 LIST_FOREACH(it, &queue->queue, next) {
302 if (asprintf(&it->queueid, "%"PRIxMAX".%"PRIxPTR,
303 queue->id, (uintptr_t)it) <= 0)
305 if (asprintf(&it->queuefn, "%s/%s",
306 config->spooldir, it->queueid) <= 0)
308 /* File may not exist yet */
309 if (stat(it->queuefn, &st) == 0)
312 error = snprintf(line, sizeof(line), "%s %s\n",
313 it->queueid, it->addr);
314 if (error < 0 || (size_t)error >= sizeof(line))
316 if (write(queue->mailfd, line, error) != error)
320 if (write(queue->mailfd, line, 1) != 1)
323 hdrlen = lseek(queue->mailfd, 0, SEEK_CUR);
324 LIST_FOREACH(it, &queue->queue, next) {
338 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
341 strcpy(str, "(date fail)");
346 readmail(struct queue *queue, const char *sender, int nodot)
348 char line[1000]; /* by RFC2822 */
352 error = snprintf(line, sizeof(line), "\
353 Received: from %s (uid %d)\n\
354 \t(envelope-from %s)\n\
358 getlogin(), getuid(),
363 if (error < 0 || (size_t)error >= sizeof(line))
365 if (write(queue->mailfd, line, error) != error)
368 while (!feof(stdin)) {
369 if (fgets(line, sizeof(line), stdin) == NULL)
371 linelen = strlen(line);
372 if (linelen == 0 || line[linelen - 1] != '\n') {
373 errno = EINVAL; /* XXX mark permanent errors */
376 if (!nodot && linelen == 2 && line[0] == '.')
378 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
381 if (fsync(queue->mailfd) != 0)
387 linkspool(struct queue *queue)
391 LIST_FOREACH(it, &queue->queue, next) {
392 if (link(queue->tmpf, it->queuefn) != 0)
399 LIST_FOREACH(it, &queue->queue, next) {
405 static struct qitem *
406 go_background(struct queue *queue)
412 if (daemonize && daemon(0, 0) != 0) {
413 syslog(LOG_ERR, "can not daemonize: %m");
418 bzero(&sa, sizeof(sa));
419 sa.sa_flags = SA_NOCLDWAIT;
420 sa.sa_handler = SIG_IGN;
421 sigaction(SIGCHLD, &sa, NULL);
423 LIST_FOREACH(it, &queue->queue, next) {
424 /* No need to fork for the last dest */
425 if (LIST_NEXT(it, next) == NULL)
431 syslog(LOG_ERR, "can not fork: %m");
439 * return and deliver mail
453 syslog(LOG_CRIT, "reached dead code");
458 bounce(struct qitem *it, const char *reason)
460 struct queue bounceq;
465 /* Don't bounce bounced mails */
466 if (it->sender[0] == 0) {
467 syslog(LOG_CRIT, "%s: delivery panic: can't bounce a bounce",
472 syslog(LOG_ERR, "%s: delivery failed, bouncing",
475 LIST_INIT(&bounceq.queue);
476 if (add_recp(&bounceq, it->sender, "", 1) != 0)
478 if (gentempf(&bounceq) != 0)
480 if (preparespool(&bounceq, "") != 0)
483 bit = LIST_FIRST(&bounceq.queue);
484 error = fprintf(bit->queuef, "\
485 Received: from MAILER-DAEMON\n\
489 X-Original-To: <%s>\n\
490 From: MAILER-DAEMON <>\n\
492 Subject: Mail delivery failed\n\
493 Message-Id: <%"PRIxMAX"@%s>\n\
496 This is the %s at %s.\n\
498 There was an error delivering your mail to <%s>.\n\
502 Message headers follow.\n\
510 bounceq.id, hostname(),
517 if (fflush(bit->queuef) != 0)
520 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
522 while (!feof(it->queuef)) {
523 if (fgets(line, sizeof(line), it->queuef) == NULL)
527 write(bounceq.mailfd, line, strlen(line));
529 if (fsync(bounceq.mailfd) != 0)
531 if (linkspool(&bounceq) != 0)
538 bit = go_background(&bounceq);
543 syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
549 deliver_local(struct qitem *it, const char **errmsg)
557 time_t now = time(NULL);
559 error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
560 if (error < 0 || (size_t)error >= sizeof(fn)) {
561 syslog(LOG_ERR, "%s: local delivery deferred: %m",
566 /* mailx removes users mailspool file if empty, so open with O_CREAT */
567 mbox = open_locked(fn, O_WRONLY | O_APPEND | O_CREAT);
569 syslog(LOG_ERR, "%s: local delivery deferred: can not open `%s': %m",
573 mboxlen = lseek(mbox, 0, SEEK_CUR);
575 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
576 syslog(LOG_ERR, "%s: local delivery deferred: can not seek: %m",
581 error = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
582 if (error < 0 || (size_t)error >= sizeof(line)) {
583 syslog(LOG_ERR, "%s: local delivery deferred: can not write header: %m",
587 if (write(mbox, line, error) != error)
590 while (!feof(it->queuef)) {
591 if (fgets(line, sizeof(line), it->queuef) == NULL)
593 linelen = strlen(line);
594 if (linelen == 0 || line[linelen - 1] != '\n') {
595 syslog(LOG_CRIT, "%s: local delivery failed: corrupted queue file",
597 *errmsg = "corrupted queue file";
602 if (strncmp(line, "From ", 5) == 0) {
603 const char *gt = ">";
605 if (write(mbox, gt, 1) != 1)
608 if ((size_t)write(mbox, line, linelen) != linelen)
612 if (write(mbox, line, 1) != 1)
618 syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
622 if (ftruncate(mbox, mboxlen) != 0)
623 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
630 deliver(struct qitem *it)
633 unsigned int backoff = MIN_RETRY;
634 const char *errmsg = "unknown bounce reason";
638 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
639 it->queueid, it->sender, it->addr);
642 syslog(LOG_INFO, "%s: trying delivery",
646 error = deliver_remote(it, &errmsg);
648 error = deliver_local(it, &errmsg);
653 syslog(LOG_INFO, "%s: delivery successful",
658 if (stat(it->queuefn, &st) != 0) {
659 syslog(LOG_ERR, "%s: lost queue file `%s'",
660 it->queueid, it->queuefn);
663 if (gettimeofday(&now, NULL) == 0 &&
664 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
668 "Could not deliver for the last %d seconds. Giving up.",
675 if (backoff > MAX_RETRY)
690 load_queue(struct queue *queue)
694 //struct queue queue, itmqueue;
695 struct queue itmqueue;
708 LIST_INIT(&queue->queue);
710 spooldir = opendir(config->spooldir);
711 if (spooldir == NULL)
712 err(1, "reading queue");
714 while ((de = readdir(spooldir)) != NULL) {
720 LIST_INIT(&itmqueue.queue);
722 /* ignore temp files */
723 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
724 de->d_type != DT_REG)
726 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
728 fd = open_locked(queuefn, O_RDONLY|O_NONBLOCK);
730 /* Ignore locked files */
731 if (errno == EWOULDBLOCK)
736 queuef = fdopen(fd, "r");
739 if (fgets(line, sizeof(line), queuef) == NULL ||
742 line[strlen(line) - 1] = 0; /* chop newline */
743 sender = strdup(line);
748 if (fgets(line, sizeof(line), queuef) == NULL ||
753 line[strlen(line) - 1] = 0;
754 queueid = strdup(line);
757 addr = strchr(queueid, ' ');
763 if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
765 /* Item has already been delivered? */
766 if (stat(fn, &st) != 0)
768 if (add_recp(&itmqueue, addr, sender, 0) != 0)
770 it = LIST_FIRST(&itmqueue.queue);
772 it->queueid = queueid;
776 if (LIST_EMPTY(&itmqueue.queue)) {
777 warnx("queue file without items: `%s'", queuefn);
780 hdrlen = ftell(queuef);
781 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
783 LIST_REMOVE(it, next);
784 LIST_INSERT_HEAD(&queue->queue, it, next);
789 warn("reading queue: `%s'", queuefn);
805 err(1, "reading queue");
809 run_queue(struct queue *queue)
813 if (LIST_EMPTY(&queue->queue))
816 it = go_background(queue);
822 show_queue(struct queue *queue)
826 if (LIST_EMPTY(&queue->queue)) {
827 printf("Mail queue is empty\n");
831 LIST_FOREACH(it, &queue->queue, next) {
835 To\t: %s\n--\n", it->queueid, it->sender, it->addr);
843 * - use group permissions
844 * - proper sysexit codes
848 main(int argc, char **argv)
856 int nodot = 0, doqueue = 0, showq = 0;
859 LIST_INIT(&queue.queue);
860 snprintf(tag, 254, "dma");
863 while ((ch = getopt(argc, argv, "A:b:Df:iL:o:O:q:r:")) != -1) {
866 /* -AX is being ignored, except for -A{c,m} */
867 if (optarg[0] == 'c' || optarg[0] == 'm') {
870 /* else FALLTRHOUGH */
872 /* -bX is being ignored, except for -bp */
873 if (optarg[0] == 'p') {
877 /* else FALLTRHOUGH */
883 snprintf(tag, 254, "%s", optarg);
891 /* -oX is being ignored, except for -oi */
892 if (optarg[0] != 'i')
894 /* else FALLTRHOUGH */
913 openlog(tag, LOG_PID | LOG_PERROR, LOG_MAIL);
915 config = malloc(sizeof(struct config));
917 errx(1, "Cannot allocate enough memory");
919 memset(config, 0, sizeof(struct config));
920 if (parse_conf(CONF_PATH, config) < 0) {
922 errx(1, "reading config file");
925 if (config->features & VIRTUAL)
926 if (parse_virtuser(config->virtualpath) < 0)
927 errx(1, "error reading virtual user file: %s",
928 config->virtualpath);
930 if (parse_authfile(config->authpath) < 0)
931 err(1, "reading SMTP authentication file");
935 errx(1, "sending mail and displaying queue is"
936 " mutually exclusive");
944 errx(1, "sending mail and queue pickup is mutually exclusive");
950 if (read_aliases() != 0)
951 err(1, "reading aliases");
953 if ((sender = set_from(sender)) == NULL)
954 err(1, "setting from address");
956 for (i = 0; i < argc; i++) {
957 if (add_recp(&queue, argv[i], sender, 1) != 0)
958 errx(1, "invalid recipient `%s'\n", argv[i]);
961 if (LIST_EMPTY(&queue.queue))
962 errx(1, "no recipients");
964 if (gentempf(&queue) != 0)
965 err(1, "create temp file");
967 if (preparespool(&queue, sender) != 0)
968 err(1, "creating spools (1)");
970 if (readmail(&queue, sender, nodot) != 0)
971 err(1, "reading mail");
973 if (linkspool(&queue) != 0)
974 err(1, "creating spools (2)");
976 /* From here on the mail is safe. */
978 if (config->features & DEFER)
981 it = go_background(&queue);