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 static int daemonize = 1;
70 struct config *config;
71 static const char *username;
73 static const char *logident_base;
79 static char name[MAXHOSTNAMELEN+1];
87 if (config->mailname != NULL && config->mailname[0] != '\0') {
88 snprintf(name, sizeof(name), "%s", config->mailname);
92 if (config->mailnamefile != NULL && config->mailnamefile[0] != '\0') {
93 fp = fopen(config->mailnamefile, "r");
95 if (fgets(name, sizeof(name), fp) != NULL) {
98 (name[len - 1] == '\r' ||
99 name[len - 1] == '\n'))
101 if (name[0] != '\0') {
109 if (gethostname(name, sizeof(name)) != 0)
110 strcpy(name, "(unknown hostname)");
116 setlogident(const char *fmt, ...)
125 vasprintf(&sufx, fmt, ap);
127 asprintf(&tag, "%s[%s]", logident_base, sufx);
133 openlog(tag != NULL ? tag : logident_base, 0, LOG_MAIL);
137 check_username(const char *name, uid_t ckuid)
143 pwd = getpwnam(name);
144 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 = snprintf(line, sizeof(line),
368 "Received: from %s (uid %d)\n"
369 "\t(envelope-from %s)\n"
378 if (error < 0 || (size_t)error >= sizeof(line))
380 if (write(queue->mailfd, line, error) != error)
383 while (!feof(stdin)) {
384 if (fgets(line, sizeof(line), stdin) == NULL)
386 linelen = strlen(line);
387 if (linelen == 0 || line[linelen - 1] != '\n') {
388 errno = EINVAL; /* XXX mark permanent errors */
392 if (strprefixcmp(line, "Date:") == 0)
394 else if (strprefixcmp(line, "Message-Id:") == 0)
396 else if (strprefixcmp(line, "From:") == 0)
399 if (strcmp(line, "\n") == 0 && !had_headers) {
401 while (!had_date || !had_messagid || !had_from) {
404 snprintf(line, sizeof(line), "Date: %s\n", rfc822date());
405 } else if (!had_messagid) {
406 /* XXX better msgid, assign earlier and log? */
408 snprintf(line, sizeof(line), "Message-Id: <%s@%s>\n",
409 queue->id, hostname());
410 } else if (!had_from) {
412 snprintf(line, sizeof(line), "From: <%s>\n", sender);
414 if ((size_t)write(queue->mailfd, line, strlen(line)) != strlen(line))
419 if (!nodot && linelen == 2 && line[0] == '.')
421 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
424 if (fsync(queue->mailfd) != 0)
427 syslog(LOG_INFO, "new mail from user=%s uid=%d envelope_from=<%s>",
428 username, uid, sender);
433 static struct qitem *
434 go_background(struct queue *queue)
440 if (daemonize && daemon(0, 0) != 0) {
441 syslog(LOG_ERR, "can not daemonize: %m");
446 bzero(&sa, sizeof(sa));
447 sa.sa_flags = SA_NOCLDWAIT;
448 sa.sa_handler = SIG_IGN;
449 sigaction(SIGCHLD, &sa, NULL);
451 LIST_FOREACH(it, &queue->queue, next) {
452 /* No need to fork for the last dest */
453 if (LIST_NEXT(it, next) == NULL) {
454 setlogident("%s", it->queueid);
461 syslog(LOG_ERR, "can not fork: %m");
469 * return and deliver mail
471 setlogident("%s", it->queueid);
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 (add_recp(&bounceq, it->sender, "", 1) != 0)
506 if (newspoolf(&bounceq, "") != 0)
509 syslog(LOG_ERR, "delivery failed, bouncing as %s", bounceq.id);
510 setlogident("%s", bounceq.id);
512 bit = LIST_FIRST(&bounceq.queue);
513 error = fprintf(bit->mailf,
514 "Received: from MAILER-DAEMON\n"
518 "X-Original-To: <%s>\n"
519 "From: MAILER-DAEMON <>\n"
521 "Subject: Mail delivery failed\n"
522 "Message-Id: <%s@%s>\n"
525 "This is the %s at %s.\n"
527 "There was an error delivering your mail to <%s>.\n"
538 bounceq.id, hostname(),
543 config->features & FULLBOUNCE ?
544 "Original message follows." :
545 "Message headers follow.");
548 if (fflush(bit->mailf) != 0)
551 if (fseek(it->mailf, it->hdrlen, SEEK_SET) != 0)
553 if (config->features & FULLBOUNCE) {
554 while ((pos = fread(line, 1, sizeof(line), it->mailf)) > 0) {
555 if ((size_t)write(bounceq.mailfd, line, pos) != pos)
559 while (!feof(it->mailf)) {
560 if (fgets(line, sizeof(line), it->mailf) == NULL)
564 if ((size_t)write(bounceq.mailfd, line, strlen(line)) != strlen(line))
568 if (fsync(bounceq.mailfd) != 0)
570 if (linkspool(&bounceq) != 0)
576 bit = go_background(&bounceq);
581 syslog(LOG_CRIT, "error creating bounce: %m");
587 deliver(struct qitem *it)
590 unsigned int backoff = MIN_RETRY;
591 const char *errmsg = "unknown bounce reason";
596 syslog(LOG_INFO, "trying delivery");
599 error = deliver_remote(it, &errmsg);
601 error = deliver_local(it, &errmsg);
606 syslog(LOG_INFO, "delivery successful");
610 if (stat(it->queuefn, &st) != 0) {
611 syslog(LOG_ERR, "lost queue file `%s'", it->queuefn);
614 if (gettimeofday(&now, NULL) == 0 &&
615 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
616 asprintf(__DECONST(void *, &errmsg),
617 "Could not deliver for the last %d seconds. Giving up.",
623 if (backoff > MAX_RETRY)
638 run_queue(struct queue *queue)
642 if (LIST_EMPTY(&queue->queue))
645 it = go_background(queue);
651 show_queue(struct queue *queue)
655 if (LIST_EMPTY(&queue->queue)) {
656 printf("Mail queue is empty\n");
660 LIST_FOREACH(it, &queue->queue, next) {
661 printf("ID\t: %s%s\n"
666 it->locked ? "*" : "",
667 it->sender, it->addr);
675 * - use group permissions
676 * - proper sysexit codes
680 main(int argc, char **argv)
687 int nodot = 0, doqueue = 0, showq = 0;
690 LIST_INIT(&queue.queue);
692 if (strcmp(argv[0], "mailq") == 0) {
696 errx(1, "invalid arguments");
701 while ((ch = getopt(argc, argv, "A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
704 /* -AX is being ignored, except for -A{c,m} */
705 if (optarg[0] == 'c' || optarg[0] == 'm') {
708 /* else FALLTRHOUGH */
710 /* -bX is being ignored, except for -bp */
711 if (optarg[0] == 'p') {
715 /* else FALLTRHOUGH */
720 logident_base = optarg;
728 /* -oX is being ignored, except for -oi */
729 if (optarg[0] != 'i')
731 /* else FALLTRHOUGH */
742 /* Ignored options */
765 if (argc != 0 && (showq || doqueue))
766 errx(1, "sending mail and queue operations are mutually exclusive");
768 if (showq + doqueue > 1)
769 errx(1, "conflicting queue operations");
772 if (logident_base == NULL)
773 logident_base = "dma";
777 /* XXX fork root here */
779 config = calloc(1, sizeof(*config));
783 if (parse_conf(CONF_PATH) < 0) {
785 err(1, "can not read config file");
788 if (config->features & VIRTUAL)
789 if (parse_virtuser(config->virtualpath) < 0)
790 err(1, "can not read virtual user file `%s'",
791 config->virtualpath);
793 if (parse_authfile(config->authpath) < 0)
794 err(1, "can not read SMTP authentication file");
797 load_queue(&lqueue, 1);
803 load_queue(&lqueue, 0);
808 if (read_aliases() != 0)
809 err(1, "can not read aliases file `%s'", config->aliases);
811 if ((sender = set_from(sender)) == NULL)
814 for (i = 0; i < argc; i++) {
815 if (add_recp(&queue, argv[i], sender, 1) != 0)
816 errx(1, "invalid recipient `%s'", argv[i]);
819 if (LIST_EMPTY(&queue.queue))
820 errx(1, "no recipients");
822 if (newspoolf(&queue, sender) != 0)
823 err(1, "can not create temp file");
825 setlogident("%s", queue.id);
827 if (readmail(&queue, sender, nodot) != 0)
828 err(1, "can not read mail");
830 if (linkspool(&queue) != 0)
831 err(1, "can not create spools");
833 /* From here on the mail is safe. */
835 if (config->features & DEFER)
838 it = go_background(&queue);