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>
63 static void deliver(struct qitem *);
65 struct aliases aliases = LIST_HEAD_INITIALIZER(aliases);
66 struct strlist tmpfs = SLIST_HEAD_INITIALIZER(tmpfs);
67 struct virtusers virtusers = LIST_HEAD_INITIALIZER(virtusers);
68 struct authusers authusers = LIST_HEAD_INITIALIZER(authusers);
69 struct config *config;
72 static int daemonize = 1;
73 static const char *logident_base;
78 static char name[MAXHOSTNAMELEN+1];
86 if (config->mailname != NULL && config->mailname[0] != '\0') {
87 snprintf(name, sizeof(name), "%s", config->mailname);
91 if (config->mailnamefile != NULL && config->mailnamefile[0] != '\0') {
92 fp = fopen(config->mailnamefile, "r");
94 if (fgets(name, sizeof(name), fp) != NULL) {
97 (name[len - 1] == '\r' ||
98 name[len - 1] == '\n'))
100 if (name[0] != '\0') {
108 if (gethostname(name, sizeof(name)) != 0)
109 strcpy(name, "(unknown hostname)");
115 setlogident(const char *fmt, ...)
124 vasprintf(&sufx, fmt, ap);
126 asprintf(&tag, "%s[%s]", logident_base, sufx);
132 openlog(tag != NULL ? tag : logident_base, 0, LOG_MAIL);
136 check_username(const char *name, uid_t ckuid)
142 pwd = getpwnam(name);
143 if (pwd == NULL || pwd->pw_uid != ckuid)
156 username = check_username(getlogin(), uid);
157 if (username != NULL)
159 username = check_username(getenv("LOGNAME"), uid);
160 if (username != NULL)
162 username = check_username(getenv("USER"), uid);
163 if (username != NULL)
166 if (pwd != NULL && pwd->pw_name != NULL && pwd->pw_name[0] != '\0' &&
167 (u = strdup(pwd->pw_name)) != NULL) {
168 username = check_username(u, uid);
169 if (username != NULL)
174 asprintf(__DECONST(void *, &username), "%ld", (long)uid);
175 if (username != NULL)
177 username = "unknown-or-invalid-username";
181 set_from(const char *osender)
186 if ((config->features & VIRTUAL) != 0) {
187 SLIST_FOREACH(v, &virtusers, next) {
188 if (strcmp(v->login, username) == 0) {
189 sender = strdup(v->address);
198 sender = strdup(osender);
202 if (asprintf(&sender, "%s@%s", username, hostname()) <= 0)
206 if (strchr(sender, '\n') != NULL) {
218 yyin = fopen(config->aliases, "r");
220 return (0); /* not fatal */
222 return (-1); /* fatal error, probably malloc() */
228 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
230 struct qitem *it, *tit;
237 it = calloc(1, sizeof(*it));
240 it->addr = strdup(str);
241 if (it->addr == NULL)
245 host = strrchr(it->addr, '@');
247 (strcmp(host + 1, hostname()) == 0 ||
248 strcmp(host + 1, "localhost") == 0)) {
251 LIST_FOREACH(tit, &queue->queue, next) {
252 /* weed out duplicate dests */
253 if (strcmp(tit->addr, it->addr) == 0) {
259 LIST_INSERT_HEAD(&queue->queue, it, next);
260 if (strrchr(it->addr, '@') == NULL) {
263 LIST_FOREACH(al, &aliases, next) {
264 if (strcmp(al->alias, it->addr) != 0)
266 SLIST_FOREACH(sit, &al->dests, next) {
267 if (add_recp(queue, sit->str, sender, 1) != 0)
273 LIST_REMOVE(it, next);
275 /* Local destination, check */
276 pw = getpwnam(it->addr);
279 /* XXX read .forward */
300 SLIST_FOREACH(t, &tmpfs, next) {
306 open_locked(const char *fname, int flags, ...)
310 if (flags & O_CREAT) {
313 mode = va_arg(ap, int);
320 fd = open(fname, flags, mode);
323 if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) {
331 return(open(fname, flags|O_EXLOCK, mode));
343 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
346 strcpy(str, "(date fail)");
351 strprefixcmp(const char *str, const char *prefix)
353 return (strncasecmp(str, prefix, strlen(prefix)));
357 readmail(struct queue *queue, const char *sender, int nodot)
359 char line[1000]; /* by RFC2822 */
364 int had_messagid = 0;
367 error = fprintf(queue->mailf,
368 "Received: from %s (uid %d)\n"
369 "\t(envelope-from %s)\n"
378 if ((ssize_t)error < 0)
381 while (!feof(stdin)) {
382 if (fgets(line, sizeof(line), stdin) == NULL)
384 linelen = strlen(line);
385 if (linelen == 0 || line[linelen - 1] != '\n') {
386 errno = EINVAL; /* XXX mark permanent errors */
390 if (strprefixcmp(line, "Date:") == 0)
392 else if (strprefixcmp(line, "Message-Id:") == 0)
394 else if (strprefixcmp(line, "From:") == 0)
397 if (strcmp(line, "\n") == 0 && !had_headers) {
399 while (!had_date || !had_messagid || !had_from) {
402 snprintf(line, sizeof(line), "Date: %s\n", rfc822date());
403 } else if (!had_messagid) {
404 /* XXX better msgid, assign earlier and log? */
406 snprintf(line, sizeof(line), "Message-Id: <%s@%s>\n",
407 queue->id, hostname());
408 } else if (!had_from) {
410 snprintf(line, sizeof(line), "From: <%s>\n", sender);
412 if (fwrite(line, strlen(line), 1, queue->mailf) != 1)
417 if (!nodot && linelen == 2 && line[0] == '.')
419 if (fwrite(line, strlen(line), 1, queue->mailf) != 1)
426 static struct qitem *
427 go_background(struct queue *queue)
433 if (daemonize && daemon(0, 0) != 0) {
434 syslog(LOG_ERR, "can not daemonize: %m");
439 bzero(&sa, sizeof(sa));
440 sa.sa_flags = SA_NOCLDWAIT;
441 sa.sa_handler = SIG_IGN;
442 sigaction(SIGCHLD, &sa, NULL);
444 LIST_FOREACH(it, &queue->queue, next) {
445 /* No need to fork for the last dest */
446 if (LIST_NEXT(it, next) == NULL)
452 syslog(LOG_ERR, "can not fork: %m");
460 * return and deliver mail
464 * If necessary, aquire the queue and * mail files.
465 * If this fails, we probably were raced by another
468 setlogident("%s", it->queueid);
469 if (aquirespool(it) < 0)
471 dropspool(queue, it);
484 syslog(LOG_CRIT, "reached dead code");
489 bounce(struct qitem *it, const char *reason)
491 struct queue bounceq;
497 /* Don't bounce bounced mails */
498 if (it->sender[0] == 0) {
499 syslog(LOG_INFO, "can not bounce a bounce message, discarding");
503 LIST_INIT(&bounceq.queue);
504 if (newspoolf(&bounceq, "") != 0)
507 syslog(LOG_ERR, "delivery failed, bouncing as %s", bounceq.id);
508 setlogident("%s", bounceq.id);
510 error = fprintf(bounceq.mailf,
511 "Received: from MAILER-DAEMON\n"
515 "X-Original-To: <%s>\n"
516 "From: MAILER-DAEMON <>\n"
518 "Subject: Mail delivery failed\n"
519 "Message-Id: <%s@%s>\n"
522 "This is the %s at %s.\n"
524 "There was an error delivering your mail to <%s>.\n"
535 bounceq.id, hostname(),
540 config->features & FULLBOUNCE ?
541 "Original message follows." :
542 "Message headers follow.");
546 if (add_recp(&bounceq, it->sender, "", 1) != 0)
549 if (fseek(it->mailf, it->hdrlen, SEEK_SET) != 0)
551 if (config->features & FULLBOUNCE) {
552 while ((pos = fread(line, 1, sizeof(line), it->mailf)) > 0) {
553 if (fwrite(line, 1, pos, bounceq.mailf) != pos)
557 while (!feof(it->mailf)) {
558 if (fgets(line, sizeof(line), it->mailf) == NULL)
562 if (fwrite(line, strlen(line), 1, bounceq.mailf) != 1)
567 if (linkspool(&bounceq, "MAILER-DAEMON") != 0)
573 bit = go_background(&bounceq);
578 syslog(LOG_CRIT, "error creating bounce: %m");
584 deliver(struct qitem *it)
587 unsigned int backoff = MIN_RETRY;
588 const char *errmsg = "unknown bounce reason";
593 syslog(LOG_INFO, "trying delivery");
596 error = deliver_remote(it, &errmsg);
598 error = deliver_local(it, &errmsg);
603 syslog(LOG_INFO, "delivery successful");
607 if (stat(it->queuefn, &st) != 0) {
608 syslog(LOG_ERR, "lost queue file `%s'", it->queuefn);
611 if (gettimeofday(&now, NULL) == 0 &&
612 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
613 asprintf(__DECONST(void *, &errmsg),
614 "Could not deliver for the last %d seconds. Giving up.",
620 if (backoff > MAX_RETRY)
635 run_queue(struct queue *queue)
639 if (LIST_EMPTY(&queue->queue))
642 it = go_background(queue);
648 show_queue(struct queue *queue)
651 int locked = 0; /* XXX */
653 if (LIST_EMPTY(&queue->queue)) {
654 printf("Mail queue is empty\n");
658 LIST_FOREACH(it, &queue->queue, next) {
659 printf("ID\t: %s%s\n"
665 it->sender, it->addr);
673 * - use group permissions
674 * - proper sysexit codes
678 main(int argc, char **argv)
685 int nodot = 0, doqueue = 0, showq = 0;
688 LIST_INIT(&queue.queue);
690 if (strcmp(argv[0], "mailq") == 0) {
694 errx(1, "invalid arguments");
699 while ((ch = getopt(argc, argv, "A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
702 /* -AX is being ignored, except for -A{c,m} */
703 if (optarg[0] == 'c' || optarg[0] == 'm') {
706 /* else FALLTRHOUGH */
708 /* -bX is being ignored, except for -bp */
709 if (optarg[0] == 'p') {
713 /* else FALLTRHOUGH */
718 logident_base = optarg;
726 /* -oX is being ignored, except for -oi */
727 if (optarg[0] != 'i')
729 /* else FALLTRHOUGH */
740 /* Ignored options */
763 if (argc != 0 && (showq || doqueue))
764 errx(1, "sending mail and queue operations are mutually exclusive");
766 if (showq + doqueue > 1)
767 errx(1, "conflicting queue operations");
770 if (logident_base == NULL)
771 logident_base = "dma";
775 /* XXX fork root here */
777 config = calloc(1, sizeof(*config));
781 if (parse_conf(CONF_PATH) < 0) {
783 err(1, "can not read config file");
786 if (config->features & VIRTUAL)
787 if (parse_virtuser(config->virtualpath) < 0)
788 err(1, "can not read virtual user file `%s'",
789 config->virtualpath);
791 if (parse_authfile(config->authpath) < 0)
792 err(1, "can not read SMTP authentication file");
806 if (read_aliases() != 0)
807 err(1, "can not read aliases file `%s'", config->aliases);
809 if ((sender = set_from(sender)) == NULL)
812 for (i = 0; i < argc; i++) {
813 if (add_recp(&queue, argv[i], sender, 1) != 0)
814 errx(1, "invalid recipient `%s'", argv[i]);
817 if (LIST_EMPTY(&queue.queue))
818 errx(1, "no recipients");
820 if (newspoolf(&queue, sender) != 0)
821 err(1, "can not create temp file");
823 setlogident("%s", queue.id);
825 if (readmail(&queue, sender, nodot) != 0)
826 err(1, "can not read mail");
828 if (linkspool(&queue, sender) != 0)
829 err(1, "can not create spools");
831 /* From here on the mail is safe. */
833 if (config->features & DEFER)
836 it = go_background(&queue);