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;
80 static char name[MAXHOSTNAMELEN+1];
82 if (gethostname(name, sizeof(name)) != 0)
83 strcpy(name, "(unknown hostname)");
89 set_from(const char *osender)
94 if ((config->features & VIRTUAL) != 0) {
95 SLIST_FOREACH(v, &virtusers, next) {
96 if (strcmp(v->login, getlogin()) == 0) {
97 sender = strdup(v->address);
106 sender = strdup(osender);
110 if (asprintf(&sender, "%s@%s", getlogin(), hostname()) <= 0)
114 if (strchr(sender, '\n') != NULL) {
126 yyin = fopen(config->aliases, "r");
128 return (0); /* not fatal */
130 return (-1); /* fatal error, probably malloc() */
136 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
138 struct qitem *it, *tit;
145 it = calloc(1, sizeof(*it));
148 it->addr = strdup(str);
149 if (it->addr == NULL)
153 host = strrchr(it->addr, '@');
155 (strcmp(host + 1, hostname()) == 0 ||
156 strcmp(host + 1, "localhost") == 0)) {
159 LIST_FOREACH(tit, &queue->queue, next) {
160 /* weed out duplicate dests */
161 if (strcmp(tit->addr, it->addr) == 0) {
167 LIST_INSERT_HEAD(&queue->queue, it, next);
168 if (strrchr(it->addr, '@') == NULL) {
171 LIST_FOREACH(al, &aliases, next) {
172 if (strcmp(al->alias, it->addr) != 0)
174 SLIST_FOREACH(sit, &al->dests, next) {
175 if (add_recp(queue, sit->str, sender, 1) != 0)
181 LIST_REMOVE(it, next);
183 /* Local destination, check */
184 pw = getpwnam(it->addr);
207 SLIST_FOREACH(t, &tmpfs, next) {
213 gentempf(struct queue *queue)
219 if (snprintf(fn, sizeof(fn), "%s/%s", config->spooldir, "tmp_XXXXXXXXXX") <= 0)
225 queue->tmpf = strdup(fn);
226 if (queue->tmpf == NULL) {
230 t = malloc(sizeof(*t));
232 t->str = queue->tmpf;
233 SLIST_INSERT_HEAD(&tmpfs, t, next);
242 * queue-id1 envelope-to1
243 * queue-id2 envelope-to2
248 * queue ids are unique, formed from the inode of the spool file
249 * and a unique identifier.
252 preparespool(struct queue *queue, const char *sender)
254 char line[1000]; /* by RFC2822 */
261 error = snprintf(line, sizeof(line), "%s\n", sender);
262 if (error < 0 || (size_t)error >= sizeof(line)) {
266 if (write(queue->mailfd, line, error) != error)
269 queuef = fdopen(queue->mailfd, "r+");
274 * Assign queue id to each dest.
276 if (fstat(queue->mailfd, &st) != 0)
278 queue->id = st.st_ino;
279 LIST_FOREACH(it, &queue->queue, next) {
280 if (asprintf(&it->queueid, "%"PRIxMAX".%"PRIxPTR,
281 queue->id, (uintptr_t)it) <= 0)
283 if (asprintf(&it->queuefn, "%s/%s",
284 config->spooldir, it->queueid) <= 0)
286 /* File may not exist yet */
287 if (stat(it->queuefn, &st) == 0)
290 error = snprintf(line, sizeof(line), "%s %s\n",
291 it->queueid, it->addr);
292 if (error < 0 || (size_t)error >= sizeof(line))
294 if (write(queue->mailfd, line, error) != error)
298 if (write(queue->mailfd, line, 1) != 1)
301 hdrlen = lseek(queue->mailfd, 0, SEEK_CUR);
302 LIST_FOREACH(it, &queue->queue, next) {
316 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
319 strcpy(str, "(date fail)");
324 readmail(struct queue *queue, const char *sender, int nodot)
326 char line[1000]; /* by RFC2822 */
330 error = snprintf(line, sizeof(line), "\
331 Received: from %s (uid %d)\n\
332 \t(envelope-from %s)\n\
336 getlogin(), getuid(),
341 if (error < 0 || (size_t)error >= sizeof(line))
343 if (write(queue->mailfd, line, error) != error)
346 while (!feof(stdin)) {
347 if (fgets(line, sizeof(line), stdin) == NULL)
349 linelen = strlen(line);
350 if (linelen == 0 || line[linelen - 1] != '\n') {
351 errno = EINVAL; /* XXX mark permanent errors */
354 if (!nodot && linelen == 2 && line[0] == '.')
356 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
359 if (fsync(queue->mailfd) != 0)
365 linkspool(struct queue *queue)
369 LIST_FOREACH(it, &queue->queue, next) {
370 if (link(queue->tmpf, it->queuefn) != 0)
377 LIST_FOREACH(it, &queue->queue, next) {
383 static struct qitem *
384 go_background(struct queue *queue)
390 if (daemonize && daemon(0, 0) != 0) {
391 syslog(LOG_ERR, "can not daemonize: %m");
396 bzero(&sa, sizeof(sa));
397 sa.sa_flags = SA_NOCLDWAIT;
398 sa.sa_handler = SIG_IGN;
399 sigaction(SIGCHLD, &sa, NULL);
401 LIST_FOREACH(it, &queue->queue, next) {
402 /* No need to fork for the last dest */
403 if (LIST_NEXT(it, next) == NULL)
409 syslog(LOG_ERR, "can not fork: %m");
417 * return and deliver mail
431 syslog(LOG_CRIT, "reached dead code");
436 bounce(struct qitem *it, const char *reason)
438 struct queue bounceq;
443 /* Don't bounce bounced mails */
444 if (it->sender[0] == 0) {
445 syslog(LOG_CRIT, "%s: delivery panic: can't bounce a bounce",
450 syslog(LOG_ERR, "%s: delivery failed, bouncing",
453 LIST_INIT(&bounceq.queue);
454 if (add_recp(&bounceq, it->sender, "", 1) != 0)
456 if (gentempf(&bounceq) != 0)
458 if (preparespool(&bounceq, "") != 0)
461 bit = LIST_FIRST(&bounceq.queue);
462 error = fprintf(bit->queuef, "\
463 Received: from MAILER-DAEMON\n\
467 X-Original-To: <%s>\n\
468 From: MAILER-DAEMON <>\n\
470 Subject: Mail delivery failed\n\
471 Message-Id: <%"PRIxMAX"@%s>\n\
474 This is the %s at %s.\n\
476 There was an error delivering your mail to <%s>.\n\
480 Message headers follow.\n\
488 bounceq.id, hostname(),
495 if (fflush(bit->queuef) != 0)
498 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
500 while (!feof(it->queuef)) {
501 if (fgets(line, sizeof(line), it->queuef) == NULL)
505 write(bounceq.mailfd, line, strlen(line));
507 if (fsync(bounceq.mailfd) != 0)
509 if (linkspool(&bounceq) != 0)
516 bit = go_background(&bounceq);
521 syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
527 deliver_local(struct qitem *it, const char **errmsg)
535 time_t now = time(NULL);
537 error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
538 if (error < 0 || (size_t)error >= sizeof(fn)) {
539 syslog(LOG_ERR, "%s: local delivery deferred: %m",
544 /* mailx removes users mailspool file if empty, so open with O_CREAT */
545 mbox = open(fn, O_WRONLY | O_EXLOCK | O_APPEND | O_CREAT);
547 syslog(LOG_ERR, "%s: local delivery deferred: can not open `%s': %m",
551 mboxlen = lseek(mbox, 0, SEEK_CUR);
553 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
554 syslog(LOG_ERR, "%s: local delivery deferred: can not seek: %m",
559 error = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
560 if (error < 0 || (size_t)error >= sizeof(line)) {
561 syslog(LOG_ERR, "%s: local delivery deferred: can not write header: %m",
565 if (write(mbox, line, error) != error)
568 while (!feof(it->queuef)) {
569 if (fgets(line, sizeof(line), it->queuef) == NULL)
571 linelen = strlen(line);
572 if (linelen == 0 || line[linelen - 1] != '\n') {
573 syslog(LOG_CRIT, "%s: local delivery failed: corrupted queue file",
575 *errmsg = "corrupted queue file";
580 if (strncmp(line, "From ", 5) == 0) {
581 const char *gt = ">";
583 if (write(mbox, gt, 1) != 1)
586 if ((size_t)write(mbox, line, linelen) != linelen)
590 if (write(mbox, line, 1) != 1)
596 syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
600 if (ftruncate(mbox, mboxlen) != 0)
601 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
608 deliver(struct qitem *it)
611 unsigned int backoff = MIN_RETRY;
612 const char *errmsg = "unknown bounce reason";
616 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
617 it->queueid, it->sender, it->addr);
620 syslog(LOG_INFO, "%s: trying delivery",
624 error = deliver_remote(it, &errmsg);
626 error = deliver_local(it, &errmsg);
631 syslog(LOG_INFO, "%s: delivery successful",
636 if (stat(it->queuefn, &st) != 0) {
637 syslog(LOG_ERR, "%s: lost queue file `%s'",
638 it->queueid, it->queuefn);
641 if (gettimeofday(&now, NULL) == 0 &&
642 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
646 "Could not deliver for the last %d seconds. Giving up.",
653 if (backoff > MAX_RETRY)
668 load_queue(struct queue *queue)
672 //struct queue queue, itmqueue;
673 struct queue itmqueue;
686 LIST_INIT(&queue->queue);
688 spooldir = opendir(config->spooldir);
689 if (spooldir == NULL)
690 err(1, "reading queue");
692 while ((de = readdir(spooldir)) != NULL) {
698 LIST_INIT(&itmqueue.queue);
700 /* ignore temp files */
701 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
702 de->d_type != DT_REG)
704 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
706 fd = open(queuefn, O_RDONLY|O_EXLOCK|O_NONBLOCK);
708 /* Ignore locked files */
709 if (errno == EWOULDBLOCK)
714 queuef = fdopen(fd, "r");
717 if (fgets(line, sizeof(line), queuef) == NULL ||
720 line[strlen(line) - 1] = 0; /* chop newline */
721 sender = strdup(line);
726 if (fgets(line, sizeof(line), queuef) == NULL ||
731 line[strlen(line) - 1] = 0;
732 queueid = strdup(line);
735 addr = strchr(queueid, ' ');
741 if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
743 /* Item has already been delivered? */
744 if (stat(fn, &st) != 0)
746 if (add_recp(&itmqueue, addr, sender, 0) != 0)
748 it = LIST_FIRST(&itmqueue.queue);
750 it->queueid = queueid;
754 if (LIST_EMPTY(&itmqueue.queue)) {
755 warnx("queue file without items: `%s'", queuefn);
758 hdrlen = ftell(queuef);
759 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
761 LIST_REMOVE(it, next);
762 LIST_INSERT_HEAD(&queue->queue, it, next);
767 warn("reading queue: `%s'", queuefn);
783 err(1, "reading queue");
787 run_queue(struct queue *queue)
791 if (LIST_EMPTY(&queue->queue))
794 it = go_background(queue);
800 show_queue(struct queue *queue)
804 if (LIST_EMPTY(&queue->queue)) {
805 printf("Mail queue is empty\n");
809 LIST_FOREACH(it, &queue->queue, next) {
813 To\t: %s\n--\n", it->queueid, it->sender, it->addr);
821 * - use group permissions
822 * - proper sysexit codes
826 main(int argc, char **argv)
834 int nodot = 0, doqueue = 0, showq = 0;
837 LIST_INIT(&queue.queue);
838 snprintf(tag, 254, "dma");
841 while ((ch = getopt(argc, argv, "A:b:Df:iL:o:O:q:r:")) != -1) {
844 /* -AX is being ignored, except for -A{c,m} */
845 if (optarg[0] == 'c' || optarg[0] == 'm') {
848 /* else FALLTRHOUGH */
850 /* -bX is being ignored, except for -bp */
851 if (optarg[0] == 'p') {
855 /* else FALLTRHOUGH */
861 snprintf(tag, 254, "%s", optarg);
869 /* -oX is being ignored, except for -oi */
870 if (optarg[0] != 'i')
872 /* else FALLTRHOUGH */
891 openlog(tag, LOG_PID | LOG_PERROR, LOG_MAIL);
893 config = malloc(sizeof(struct config));
895 errx(1, "Cannot allocate enough memory");
897 memset(config, 0, sizeof(struct config));
898 if (parse_conf(CONF_PATH, config) < 0) {
900 errx(1, "reading config file");
903 if (config->features & VIRTUAL)
904 if (parse_virtuser(config->virtualpath) < 0)
905 errx(1, "error reading virtual user file: %s",
906 config->virtualpath);
908 if (parse_authfile(config->authpath) < 0)
909 err(1, "reading SMTP authentication file");
913 errx(1, "sending mail and displaying queue is"
914 " mutually exclusive");
922 errx(1, "sending mail and queue pickup is mutually exclusive");
928 if (read_aliases() != 0)
929 err(1, "reading aliases");
931 if ((sender = set_from(sender)) == NULL)
932 err(1, "setting from address");
934 for (i = 0; i < argc; i++) {
935 if (add_recp(&queue, argv[i], sender, 1) != 0)
936 errx(1, "invalid recipient `%s'\n", argv[i]);
939 if (LIST_EMPTY(&queue.queue))
940 errx(1, "no recipients");
942 if (gentempf(&queue) != 0)
943 err(1, "create temp file");
945 if (preparespool(&queue, sender) != 0)
946 err(1, "creating spools (1)");
948 if (readmail(&queue, sender, nodot) != 0)
949 err(1, "reading mail");
951 if (linkspool(&queue) != 0)
952 err(1, "creating spools (2)");
954 /* From here on the mail is safe. */
956 if (config->features & DEFER)
959 it = go_background(&queue);