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
35 #include <sys/param.h>
36 #include <sys/queue.h>
38 #include <sys/types.h>
61 static void deliver(struct qitem *);
63 struct aliases aliases = LIST_HEAD_INITIALIZER(aliases);
64 struct strlist tmpfs = SLIST_HEAD_INITIALIZER(tmpfs);
65 struct virtusers virtusers = LIST_HEAD_INITIALIZER(virtusers);
66 struct authusers authusers = LIST_HEAD_INITIALIZER(authusers);
67 struct config *config;
70 static int daemonize = 1;
71 static const char *logident_base;
76 static char name[MAXHOSTNAMELEN+1];
84 if (config->mailname != NULL && config->mailname[0] != '\0') {
85 snprintf(name, sizeof(name), "%s", config->mailname);
89 if (config->mailnamefile != NULL && config->mailnamefile[0] != '\0') {
90 fp = fopen(config->mailnamefile, "r");
92 if (fgets(name, sizeof(name), fp) != NULL) {
95 (name[len - 1] == '\r' ||
96 name[len - 1] == '\n'))
98 if (name[0] != '\0') {
106 if (gethostname(name, sizeof(name)) != 0)
107 strcpy(name, "(unknown hostname)");
113 setlogident(const char *fmt, ...)
122 vasprintf(&sufx, fmt, ap);
124 asprintf(&tag, "%s[%s]", logident_base, sufx);
130 openlog(tag != NULL ? tag : logident_base, 0, LOG_MAIL);
134 check_username(const char *name, uid_t ckuid)
140 pwd = getpwnam(name);
141 if (pwd == NULL || pwd->pw_uid != ckuid)
154 username = check_username(getlogin(), uid);
155 if (username != NULL)
157 username = check_username(getenv("LOGNAME"), uid);
158 if (username != NULL)
160 username = check_username(getenv("USER"), uid);
161 if (username != NULL)
164 if (pwd != NULL && pwd->pw_name != NULL && pwd->pw_name[0] != '\0' &&
165 (u = strdup(pwd->pw_name)) != NULL) {
166 username = check_username(u, uid);
167 if (username != NULL)
172 asprintf(__DECONST(void *, &username), "%ld", (long)uid);
173 if (username != NULL)
175 username = "unknown-or-invalid-username";
179 set_from(const char *osender)
184 if ((config->features & VIRTUAL) != 0) {
185 SLIST_FOREACH(v, &virtusers, next) {
186 if (strcmp(v->login, username) == 0) {
187 sender = strdup(v->address);
196 sender = strdup(osender);
200 if (asprintf(&sender, "%s@%s", username, hostname()) <= 0)
204 if (strchr(sender, '\n') != NULL) {
216 yyin = fopen(config->aliases, "r");
218 return (0); /* not fatal */
220 return (-1); /* fatal error, probably malloc() */
226 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
228 struct qitem *it, *tit;
235 it = calloc(1, sizeof(*it));
238 it->addr = strdup(str);
239 if (it->addr == NULL)
243 host = strrchr(it->addr, '@');
245 (strcmp(host + 1, hostname()) == 0 ||
246 strcmp(host + 1, "localhost") == 0)) {
249 LIST_FOREACH(tit, &queue->queue, next) {
250 /* weed out duplicate dests */
251 if (strcmp(tit->addr, it->addr) == 0) {
257 LIST_INSERT_HEAD(&queue->queue, it, next);
258 if (strrchr(it->addr, '@') == NULL) {
261 LIST_FOREACH(al, &aliases, next) {
262 if (strcmp(al->alias, it->addr) != 0)
264 SLIST_FOREACH(sit, &al->dests, next) {
265 if (add_recp(queue, sit->str, sender, 1) != 0)
271 LIST_REMOVE(it, next);
273 /* Local destination, check */
274 pw = getpwnam(it->addr);
277 /* XXX read .forward */
298 SLIST_FOREACH(t, &tmpfs, next) {
304 open_locked(const char *fname, int flags, ...)
308 if (flags & O_CREAT) {
311 mode = va_arg(ap, int);
318 fd = open(fname, flags, mode);
321 if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) {
329 return(open(fname, flags|O_EXLOCK, mode));
341 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
344 strcpy(str, "(date fail)");
349 strprefixcmp(const char *str, const char *prefix)
351 return (strncasecmp(str, prefix, strlen(prefix)));
355 readmail(struct queue *queue, const char *sender, int nodot)
357 char line[1000]; /* by RFC2822 */
362 int had_messagid = 0;
365 error = fprintf(queue->mailf,
366 "Received: from %s (uid %d)\n"
367 "\t(envelope-from %s)\n"
376 if ((ssize_t)error < 0)
379 while (!feof(stdin)) {
380 if (fgets(line, sizeof(line), stdin) == NULL)
382 linelen = strlen(line);
383 if (linelen == 0 || line[linelen - 1] != '\n') {
384 errno = EINVAL; /* XXX mark permanent errors */
388 if (strprefixcmp(line, "Date:") == 0)
390 else if (strprefixcmp(line, "Message-Id:") == 0)
392 else if (strprefixcmp(line, "From:") == 0)
395 if (strcmp(line, "\n") == 0 && !had_headers) {
397 while (!had_date || !had_messagid || !had_from) {
400 snprintf(line, sizeof(line), "Date: %s\n", rfc822date());
401 } else if (!had_messagid) {
402 /* XXX better msgid, assign earlier and log? */
404 snprintf(line, sizeof(line), "Message-Id: <%s@%s>\n",
405 queue->id, hostname());
406 } else if (!had_from) {
408 snprintf(line, sizeof(line), "From: <%s>\n", sender);
410 if (fwrite(line, strlen(line), 1, queue->mailf) != 1)
415 if (!nodot && linelen == 2 && line[0] == '.')
417 if (fwrite(line, strlen(line), 1, queue->mailf) != 1)
424 static struct qitem *
425 go_background(struct queue *queue)
431 if (daemonize && daemon(0, 0) != 0) {
432 syslog(LOG_ERR, "can not daemonize: %m");
437 bzero(&sa, sizeof(sa));
438 sa.sa_flags = SA_NOCLDWAIT;
439 sa.sa_handler = SIG_IGN;
440 sigaction(SIGCHLD, &sa, NULL);
442 LIST_FOREACH(it, &queue->queue, next) {
443 /* No need to fork for the last dest */
444 if (LIST_NEXT(it, next) == NULL)
450 syslog(LOG_ERR, "can not fork: %m");
458 * return and deliver mail
462 * If necessary, aquire the queue and * mail files.
463 * If this fails, we probably were raced by another
466 setlogident("%s", it->queueid);
467 if (aquirespool(it) < 0)
469 dropspool(queue, it);
482 syslog(LOG_CRIT, "reached dead code");
487 bounce(struct qitem *it, const char *reason)
489 struct queue bounceq;
495 /* Don't bounce bounced mails */
496 if (it->sender[0] == 0) {
497 syslog(LOG_INFO, "can not bounce a bounce message, discarding");
501 LIST_INIT(&bounceq.queue);
502 if (newspoolf(&bounceq, "") != 0)
505 syslog(LOG_ERR, "delivery failed, bouncing as %s", bounceq.id);
506 setlogident("%s", bounceq.id);
508 error = fprintf(bounceq.mailf,
509 "Received: from MAILER-DAEMON\n"
513 "X-Original-To: <%s>\n"
514 "From: MAILER-DAEMON <>\n"
516 "Subject: Mail delivery failed\n"
517 "Message-Id: <%s@%s>\n"
520 "This is the %s at %s.\n"
522 "There was an error delivering your mail to <%s>.\n"
533 bounceq.id, hostname(),
538 config->features & FULLBOUNCE ?
539 "Original message follows." :
540 "Message headers follow.");
544 if (add_recp(&bounceq, it->sender, "", 1) != 0)
547 if (fseek(it->mailf, it->hdrlen, SEEK_SET) != 0)
549 if (config->features & FULLBOUNCE) {
550 while ((pos = fread(line, 1, sizeof(line), it->mailf)) > 0) {
551 if (fwrite(line, 1, pos, bounceq.mailf) != pos)
555 while (!feof(it->mailf)) {
556 if (fgets(line, sizeof(line), it->mailf) == NULL)
560 if (fwrite(line, strlen(line), 1, bounceq.mailf) != 1)
565 if (linkspool(&bounceq, "MAILER-DAEMON") != 0)
571 bit = go_background(&bounceq);
576 syslog(LOG_CRIT, "error creating bounce: %m");
582 deliver(struct qitem *it)
585 unsigned int backoff = MIN_RETRY;
586 const char *errmsg = "unknown bounce reason";
591 syslog(LOG_INFO, "trying delivery");
594 error = deliver_remote(it, &errmsg);
596 error = deliver_local(it, &errmsg);
601 syslog(LOG_INFO, "delivery successful");
605 if (stat(it->queuefn, &st) != 0) {
606 syslog(LOG_ERR, "lost queue file `%s'", it->queuefn);
609 if (gettimeofday(&now, NULL) == 0 &&
610 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
611 asprintf(__DECONST(void *, &errmsg),
612 "Could not deliver for the last %d seconds. Giving up.",
618 if (backoff > MAX_RETRY)
633 run_queue(struct queue *queue)
637 if (LIST_EMPTY(&queue->queue))
640 it = go_background(queue);
646 show_queue(struct queue *queue)
649 int locked = 0; /* XXX */
651 if (LIST_EMPTY(&queue->queue)) {
652 printf("Mail queue is empty\n");
656 LIST_FOREACH(it, &queue->queue, next) {
657 printf("ID\t: %s%s\n"
663 it->sender, it->addr);
671 * - use group permissions
672 * - proper sysexit codes
676 main(int argc, char **argv)
683 int nodot = 0, doqueue = 0, showq = 0;
686 LIST_INIT(&queue.queue);
688 if (strcmp(argv[0], "mailq") == 0) {
692 errx(1, "invalid arguments");
697 while ((ch = getopt(argc, argv, "A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
700 /* -AX is being ignored, except for -A{c,m} */
701 if (optarg[0] == 'c' || optarg[0] == 'm') {
704 /* else FALLTRHOUGH */
706 /* -bX is being ignored, except for -bp */
707 if (optarg[0] == 'p') {
711 /* else FALLTRHOUGH */
716 logident_base = optarg;
724 /* -oX is being ignored, except for -oi */
725 if (optarg[0] != 'i')
727 /* else FALLTRHOUGH */
738 /* Ignored options */
761 if (argc != 0 && (showq || doqueue))
762 errx(1, "sending mail and queue operations are mutually exclusive");
764 if (showq + doqueue > 1)
765 errx(1, "conflicting queue operations");
768 if (logident_base == NULL)
769 logident_base = "dma";
773 /* XXX fork root here */
775 config = calloc(1, sizeof(*config));
779 if (parse_conf(CONF_PATH) < 0) {
781 err(1, "can not read config file");
784 if (config->features & VIRTUAL)
785 if (parse_virtuser(config->virtualpath) < 0)
786 err(1, "can not read virtual user file `%s'",
787 config->virtualpath);
789 if (parse_authfile(config->authpath) < 0)
790 err(1, "can not read SMTP authentication file");
804 if (read_aliases() != 0)
805 err(1, "can not read aliases file `%s'", config->aliases);
807 if ((sender = set_from(sender)) == NULL)
810 for (i = 0; i < argc; i++) {
811 if (add_recp(&queue, argv[i], sender, 1) != 0)
812 errx(1, "invalid recipient `%s'", argv[i]);
815 if (LIST_EMPTY(&queue.queue))
816 errx(1, "no recipients");
818 if (newspoolf(&queue, sender) != 0)
819 err(1, "can not create temp file");
821 setlogident("%s", queue.id);
823 if (readmail(&queue, sender, nodot) != 0)
824 err(1, "can not read mail");
826 if (linkspool(&queue, sender) != 0)
827 err(1, "can not create spools");
829 /* From here on the mail is safe. */
831 if (config->features & DEFER)
834 it = go_background(&queue);