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.2 2008/02/03 18:41:40 matthias Exp $
37 #include <sys/param.h>
38 #include <sys/queue.h>
40 #include <sys/types.h>
43 #include <openssl/ssl.h>
44 #endif /* HAVE_CRYPTO */
66 static void deliver(struct qitem *);
67 static int add_recp(struct queue *, const char *, const char *, int);
69 struct aliases aliases = LIST_HEAD_INITIALIZER(aliases);
70 static struct strlist tmpfs = SLIST_HEAD_INITIALIZER(tmpfs);
71 struct virtusers virtusers = LIST_HEAD_INITIALIZER(virtusers);
72 struct authusers authusers = LIST_HEAD_INITIALIZER(authusers);
73 static int daemonize = 1;
74 struct config *config;
79 static char name[MAXHOSTNAMELEN+1];
81 if (gethostname(name, sizeof(name)) != 0)
82 strcpy(name, "(unknown hostname)");
88 set_from(const char *osender)
93 if ((config->features & VIRTUAL) != 0) {
94 SLIST_FOREACH(v, &virtusers, next) {
95 if (strcmp(v->login, getlogin()) == 0) {
96 sender = strdup(v->address);
105 sender = strdup(osender);
109 if (asprintf(&sender, "%s@%s", getlogin(), hostname()) <= 0)
113 if (strchr(sender, '\n') != NULL) {
125 yyin = fopen(config->aliases, "r");
127 return (0); /* not fatal */
129 return (-1); /* fatal error, probably malloc() */
135 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
137 struct qitem *it, *tit;
144 it = calloc(1, sizeof(*it));
147 it->addr = strdup(str);
148 if (it->addr == NULL)
152 host = strrchr(it->addr, '@');
154 (strcmp(host + 1, hostname()) == 0 ||
155 strcmp(host + 1, "localhost") == 0)) {
158 LIST_FOREACH(tit, &queue->queue, next) {
159 /* weed out duplicate dests */
160 if (strcmp(tit->addr, it->addr) == 0) {
166 LIST_INSERT_HEAD(&queue->queue, it, next);
167 if (strrchr(it->addr, '@') == NULL) {
170 LIST_FOREACH(al, &aliases, next) {
171 if (strcmp(al->alias, it->addr) != 0)
173 SLIST_FOREACH(sit, &al->dests, next) {
174 if (add_recp(queue, sit->str, sender, 1) != 0)
180 LIST_REMOVE(it, next);
182 /* Local destination, check */
183 pw = getpwnam(it->addr);
206 SLIST_FOREACH(t, &tmpfs, next) {
212 gentempf(struct queue *queue)
218 if (snprintf(fn, sizeof(fn), "%s/%s", config->spooldir, "tmp_XXXXXXXXXX") <= 0)
224 queue->tmpf = strdup(fn);
225 if (queue->tmpf == NULL) {
229 t = malloc(sizeof(*t));
231 t->str = queue->tmpf;
232 SLIST_INSERT_HEAD(&tmpfs, t, next);
241 * queue-id1 envelope-to1
242 * queue-id2 envelope-to2
247 * queue ids are unique, formed from the inode of the spool file
248 * and a unique identifier.
251 preparespool(struct queue *queue, const char *sender)
253 char line[1000]; /* by RFC2822 */
260 error = snprintf(line, sizeof(line), "%s\n", sender);
261 if (error < 0 || (size_t)error >= sizeof(line)) {
265 if (write(queue->mailfd, line, error) != error)
268 queuef = fdopen(queue->mailfd, "r+");
273 * Assign queue id to each dest.
275 if (fstat(queue->mailfd, &st) != 0)
277 queue->id = st.st_ino;
278 LIST_FOREACH(it, &queue->queue, next) {
279 if (asprintf(&it->queueid, "%"PRIxMAX".%"PRIxPTR,
280 queue->id, (uintptr_t)it) <= 0)
282 if (asprintf(&it->queuefn, "%s/%s",
283 config->spooldir, it->queueid) <= 0)
285 /* File may not exist yet */
286 if (stat(it->queuefn, &st) == 0)
289 error = snprintf(line, sizeof(line), "%s %s\n",
290 it->queueid, it->addr);
291 if (error < 0 || (size_t)error >= sizeof(line))
293 if (write(queue->mailfd, line, error) != error)
297 if (write(queue->mailfd, line, 1) != 1)
300 hdrlen = lseek(queue->mailfd, 0, SEEK_CUR);
301 LIST_FOREACH(it, &queue->queue, next) {
315 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
318 strcpy(str, "(date fail)");
323 readmail(struct queue *queue, const char *sender, int nodot)
325 char line[1000]; /* by RFC2822 */
329 error = snprintf(line, sizeof(line), "\
330 Received: from %s (uid %d)\n\
331 \t(envelope-from %s)\n\
335 getlogin(), getuid(),
340 if (error < 0 || (size_t)error >= sizeof(line))
342 if (write(queue->mailfd, line, error) != error)
345 while (!feof(stdin)) {
346 if (fgets(line, sizeof(line), stdin) == NULL)
348 linelen = strlen(line);
349 if (linelen == 0 || line[linelen - 1] != '\n') {
350 errno = EINVAL; /* XXX mark permanent errors */
353 if (!nodot && linelen == 2 && line[0] == '.')
355 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
358 if (fsync(queue->mailfd) != 0)
364 linkspool(struct queue *queue)
368 LIST_FOREACH(it, &queue->queue, next) {
369 if (link(queue->tmpf, it->queuefn) != 0)
376 LIST_FOREACH(it, &queue->queue, next) {
382 static struct qitem *
383 go_background(struct queue *queue)
389 if (daemonize && daemon(0, 0) != 0) {
390 syslog(LOG_ERR, "can not daemonize: %m");
395 bzero(&sa, sizeof(sa));
396 sa.sa_flags = SA_NOCLDWAIT;
397 sa.sa_handler = SIG_IGN;
398 sigaction(SIGCHLD, &sa, NULL);
400 LIST_FOREACH(it, &queue->queue, next) {
401 /* No need to fork for the last dest */
402 if (LIST_NEXT(it, next) == NULL)
408 syslog(LOG_ERR, "can not fork: %m");
416 * return and deliver mail
430 syslog(LOG_CRIT, "reached dead code");
435 bounce(struct qitem *it, const char *reason)
437 struct queue bounceq;
442 /* Don't bounce bounced mails */
443 if (it->sender[0] == 0) {
444 syslog(LOG_CRIT, "%s: delivery panic: can't bounce a bounce",
449 syslog(LOG_ERR, "%s: delivery failed, bouncing",
452 LIST_INIT(&bounceq.queue);
453 if (add_recp(&bounceq, it->sender, "", 1) != 0)
455 if (gentempf(&bounceq) != 0)
457 if (preparespool(&bounceq, "") != 0)
460 bit = LIST_FIRST(&bounceq.queue);
461 error = fprintf(bit->queuef, "\
462 Received: from MAILER-DAEMON\n\
466 X-Original-To: <%s>\n\
467 From: MAILER-DAEMON <>\n\
469 Subject: Mail delivery failed\n\
470 Message-Id: <%"PRIxMAX"@%s>\n\
473 This is the %s at %s.\n\
475 There was an error delivering your mail to <%s>.\n\
479 Message headers follow.\n\
487 bounceq.id, hostname(),
494 if (fflush(bit->queuef) != 0)
497 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
499 while (!feof(it->queuef)) {
500 if (fgets(line, sizeof(line), it->queuef) == NULL)
504 write(bounceq.mailfd, line, strlen(line));
506 if (fsync(bounceq.mailfd) != 0)
508 if (linkspool(&bounceq) != 0)
515 bit = go_background(&bounceq);
520 syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
526 deliver_local(struct qitem *it, const char **errmsg)
534 time_t now = time(NULL);
536 error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
537 if (error < 0 || (size_t)error >= sizeof(fn)) {
538 syslog(LOG_ERR, "%s: local delivery deferred: %m",
543 /* mailx removes users mailspool file if empty, so open with O_CREAT */
544 mbox = open(fn, O_WRONLY | O_EXLOCK | O_APPEND | O_CREAT);
546 syslog(LOG_ERR, "%s: local delivery deferred: can not open `%s': %m",
550 mboxlen = lseek(mbox, 0, SEEK_CUR);
552 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
553 syslog(LOG_ERR, "%s: local delivery deferred: can not seek: %m",
558 error = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
559 if (error < 0 || (size_t)error >= sizeof(line)) {
560 syslog(LOG_ERR, "%s: local delivery deferred: can not write header: %m",
564 if (write(mbox, line, error) != error)
567 while (!feof(it->queuef)) {
568 if (fgets(line, sizeof(line), it->queuef) == NULL)
570 linelen = strlen(line);
571 if (linelen == 0 || line[linelen - 1] != '\n') {
572 syslog(LOG_CRIT, "%s: local delivery failed: corrupted queue file",
574 *errmsg = "corrupted queue file";
579 if (strncmp(line, "From ", 5) == 0) {
580 const char *gt = ">";
582 if (write(mbox, gt, 1) != 1)
585 if ((size_t)write(mbox, line, linelen) != linelen)
589 if (write(mbox, line, 1) != 1)
595 syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
599 if (ftruncate(mbox, mboxlen) != 0)
600 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
607 deliver(struct qitem *it)
610 unsigned int backoff = MIN_RETRY;
611 const char *errmsg = "unknown bounce reason";
615 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
616 it->queueid, it->sender, it->addr);
619 syslog(LOG_INFO, "%s: trying delivery",
623 error = deliver_remote(it, &errmsg);
625 error = deliver_local(it, &errmsg);
630 syslog(LOG_INFO, "%s: delivery successful",
635 if (stat(it->queuefn, &st) != 0) {
636 syslog(LOG_ERR, "%s: lost queue file `%s'",
637 it->queueid, it->queuefn);
640 if (gettimeofday(&now, NULL) == 0 &&
641 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
645 "Could not deliver for the last %d seconds. Giving up.",
652 if (backoff > MAX_RETRY)
667 load_queue(struct queue *queue)
671 //struct queue queue, itmqueue;
672 struct queue itmqueue;
685 LIST_INIT(&queue->queue);
687 spooldir = opendir(config->spooldir);
688 if (spooldir == NULL)
689 err(1, "reading queue");
691 while ((de = readdir(spooldir)) != NULL) {
697 LIST_INIT(&itmqueue.queue);
699 /* ignore temp files */
700 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
701 de->d_type != DT_REG)
703 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
705 fd = open(queuefn, O_RDONLY|O_EXLOCK|O_NONBLOCK);
707 /* Ignore locked files */
708 if (errno == EWOULDBLOCK)
713 queuef = fdopen(fd, "r");
716 if (fgets(line, sizeof(line), queuef) == NULL ||
719 line[strlen(line) - 1] = 0; /* chop newline */
720 sender = strdup(line);
725 if (fgets(line, sizeof(line), queuef) == NULL ||
730 line[strlen(line) - 1] = 0;
731 queueid = strdup(line);
734 addr = strchr(queueid, ' ');
740 if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
742 /* Item has already been delivered? */
743 if (stat(fn, &st) != 0)
745 if (add_recp(&itmqueue, addr, sender, 0) != 0)
747 it = LIST_FIRST(&itmqueue.queue);
749 it->queueid = queueid;
753 if (LIST_EMPTY(&itmqueue.queue)) {
754 warnx("queue file without items: `%s'", queuefn);
757 hdrlen = ftell(queuef);
758 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
760 LIST_REMOVE(it, next);
761 LIST_INSERT_HEAD(&queue->queue, it, next);
766 warn("reading queue: `%s'", queuefn);
782 err(1, "reading queue");
786 run_queue(struct queue *queue)
789 if (LIST_EMPTY(&queue->queue))
792 it = go_background(queue);
798 show_queue(struct queue *queue)
802 if (LIST_EMPTY(&queue->queue)) {
803 printf("Mail queue is empty\n");
807 LIST_FOREACH(it, &queue->queue, next) {
811 To\t: %s\n--\n", it->queueid, it->sender, it->addr);
819 * - use group permissions
820 * - proper sysexit codes
824 main(int argc, char **argv)
828 char confpath[PATH_MAX];
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));
899 /* Check if the user has its own config files */
900 snprintf(confpath, PATH_MAX, "%s/.dma/dma.conf", getenv("HOME"));
901 if (stat(confpath, &sb) < 0)
902 snprintf(confpath, PATH_MAX, "%s", CONF_PATH);
904 if (parse_conf(confpath, config) < 0) {
906 errx(1, "reading config file");
909 if (config->features & VIRTUAL)
910 if (parse_virtuser(config->virtualpath) < 0)
911 errx(1, "error reading virtual user file: %s",
912 config->virtualpath);
914 if (parse_authfile(config->authpath) < 0)
915 err(1, "reading SMTP authentication file");
919 errx(1, "sending mail and displaying queue is"
920 " mutually exclusive");
928 errx(1, "sending mail and queue pickup is mutually exclusive");
934 if (read_aliases() != 0)
935 err(1, "reading aliases");
937 if ((sender = set_from(sender)) == NULL)
938 err(1, "setting from address");
940 for (i = 0; i < argc; i++) {
941 if (add_recp(&queue, argv[i], sender, 1) != 0)
942 errx(1, "invalid recipient `%s'\n", argv[i]);
945 if (LIST_EMPTY(&queue.queue))
946 errx(1, "no recipients");
948 if (gentempf(&queue) != 0)
949 err(1, "create temp file");
951 if (preparespool(&queue, sender) != 0)
952 err(1, "creating spools (1)");
954 if (readmail(&queue, sender, nodot) != 0)
955 err(1, "reading mail");
957 if (linkspool(&queue) != 0)
958 err(1, "creating spools (2)");
960 /* From here on the mail is safe. */
962 if (config->features & DEFER)
965 it = go_background(&queue);