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;
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 check_username(const char *name, uid_t ckuid)
121 pwd = getpwnam(name);
122 if (pwd == NULL || pwd->pw_uid != ckuid)
134 username = check_username(getlogin(), uid);
135 if (username != NULL)
137 username = check_username(getenv("LOGNAME"), uid);
138 if (username != NULL)
140 username = check_username(getenv("USER"), uid);
141 if (username != NULL)
144 if (pwd != NULL && pwd->pw_name != NULL && pwd->pw_name[0] != '\0' &&
145 (u = strdup(pwd->pw_name)) != NULL) {
146 username = check_username(u, uid);
147 if (username != NULL)
152 asprintf(__DECONST(void *, &username), "%ld", (long)uid);
153 if (username != NULL)
155 username = "unknown-or-invalid-username";
159 set_from(const char *osender)
164 if ((config->features & VIRTUAL) != 0) {
165 SLIST_FOREACH(v, &virtusers, next) {
166 if (strcmp(v->login, username) == 0) {
167 sender = strdup(v->address);
176 sender = strdup(osender);
180 if (asprintf(&sender, "%s@%s", username, hostname()) <= 0)
184 if (strchr(sender, '\n') != NULL) {
196 yyin = fopen(config->aliases, "r");
198 return (0); /* not fatal */
200 return (-1); /* fatal error, probably malloc() */
206 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
208 struct qitem *it, *tit;
215 it = calloc(1, sizeof(*it));
218 it->addr = strdup(str);
219 if (it->addr == NULL)
223 host = strrchr(it->addr, '@');
225 (strcmp(host + 1, hostname()) == 0 ||
226 strcmp(host + 1, "localhost") == 0)) {
229 LIST_FOREACH(tit, &queue->queue, next) {
230 /* weed out duplicate dests */
231 if (strcmp(tit->addr, it->addr) == 0) {
237 LIST_INSERT_HEAD(&queue->queue, it, next);
238 if (strrchr(it->addr, '@') == NULL) {
241 LIST_FOREACH(al, &aliases, next) {
242 if (strcmp(al->alias, it->addr) != 0)
244 SLIST_FOREACH(sit, &al->dests, next) {
245 if (add_recp(queue, sit->str, sender, 1) != 0)
251 LIST_REMOVE(it, next);
253 /* Local destination, check */
254 pw = getpwnam(it->addr);
257 /* XXX read .forward */
278 SLIST_FOREACH(t, &tmpfs, next) {
284 open_locked(const char *fname, int flags, ...)
288 if (flags & O_CREAT) {
291 mode = va_arg(ap, int);
298 fd = open(fname, flags, mode);
301 if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) {
309 return(open(fname, flags|O_EXLOCK, mode));
321 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
324 strcpy(str, "(date fail)");
329 strprefixcmp(const char *str, const char *prefix)
331 return (strncasecmp(str, prefix, strlen(prefix)));
335 readmail(struct queue *queue, const char *sender, int nodot)
337 char line[1000]; /* by RFC2822 */
342 int had_messagid = 0;
345 error = snprintf(line, sizeof(line),
346 "Received: from %s (uid %d)\n"
347 "\t(envelope-from %s)\n"
356 if (error < 0 || (size_t)error >= sizeof(line))
358 if (write(queue->mailfd, line, error) != error)
361 while (!feof(stdin)) {
362 if (fgets(line, sizeof(line), stdin) == NULL)
364 linelen = strlen(line);
365 if (linelen == 0 || line[linelen - 1] != '\n') {
366 errno = EINVAL; /* XXX mark permanent errors */
370 if (strprefixcmp(line, "Date:") == 0)
372 else if (strprefixcmp(line, "Message-Id:") == 0)
374 else if (strprefixcmp(line, "From:") == 0)
377 if (strcmp(line, "\n") == 0 && !had_headers) {
379 while (!had_date || !had_messagid || !had_from) {
382 snprintf(line, sizeof(line), "Date: %s\n", rfc822date());
383 } else if (!had_messagid) {
384 /* XXX better msgid, assign earlier and log? */
386 snprintf(line, sizeof(line), "Message-Id: <%"PRIxMAX"@%s>\n",
387 queue->id, hostname());
388 } else if (!had_from) {
390 snprintf(line, sizeof(line), "From: <%s>\n", sender);
392 if ((size_t)write(queue->mailfd, line, strlen(line)) != strlen(line))
397 if (!nodot && linelen == 2 && line[0] == '.')
399 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
402 if (fsync(queue->mailfd) != 0)
407 static struct qitem *
408 go_background(struct queue *queue)
414 if (daemonize && daemon(0, 0) != 0) {
415 syslog(LOG_ERR, "can not daemonize: %m");
420 bzero(&sa, sizeof(sa));
421 sa.sa_flags = SA_NOCLDWAIT;
422 sa.sa_handler = SIG_IGN;
423 sigaction(SIGCHLD, &sa, NULL);
425 LIST_FOREACH(it, &queue->queue, next) {
426 /* No need to fork for the last dest */
427 if (LIST_NEXT(it, next) == NULL)
433 syslog(LOG_ERR, "can not fork: %m");
441 * return and deliver mail
455 syslog(LOG_CRIT, "reached dead code");
460 bounce(struct qitem *it, const char *reason)
462 struct queue bounceq;
468 /* Don't bounce bounced mails */
469 if (it->sender[0] == 0) {
470 syslog(LOG_INFO, "%s: can not bounce a bounce message, discarding",
475 syslog(LOG_ERR, "%s: delivery failed, bouncing",
478 LIST_INIT(&bounceq.queue);
479 if (add_recp(&bounceq, it->sender, "", 1) != 0)
481 if (newspoolf(&bounceq, "") != 0)
483 bit = LIST_FIRST(&bounceq.queue);
484 error = fprintf(bit->mailf,
485 "Received: from MAILER-DAEMON\n"
489 "X-Original-To: <%s>\n"
490 "From: MAILER-DAEMON <>\n"
492 "Subject: Mail delivery failed\n"
493 "Message-Id: <%"PRIxMAX"@%s>\n"
496 "This is the %s at %s.\n"
498 "There was an error delivering your mail to <%s>.\n"
509 bounceq.id, hostname(),
514 config->features & FULLBOUNCE ?
515 "Original message follows." :
516 "Message headers follow.");
519 if (fflush(bit->mailf) != 0)
522 if (fseek(it->mailf, it->hdrlen, SEEK_SET) != 0)
524 if (config->features & FULLBOUNCE) {
525 while ((pos = fread(line, 1, sizeof(line), it->mailf)) > 0) {
526 if ((size_t)write(bounceq.mailfd, line, pos) != pos)
530 while (!feof(it->mailf)) {
531 if (fgets(line, sizeof(line), it->mailf) == NULL)
535 if ((size_t)write(bounceq.mailfd, line, strlen(line)) != strlen(line))
539 if (fsync(bounceq.mailfd) != 0)
541 if (linkspool(&bounceq) != 0)
547 bit = go_background(&bounceq);
552 syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
558 deliver(struct qitem *it)
561 unsigned int backoff = MIN_RETRY;
562 const char *errmsg = "unknown bounce reason";
566 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
567 it->queueid, it->sender, it->addr);
570 syslog(LOG_INFO, "%s: trying delivery",
574 error = deliver_remote(it, &errmsg);
576 error = deliver_local(it, &errmsg);
581 syslog(LOG_INFO, "%s: delivery successful",
586 if (stat(it->queuefn, &st) != 0) {
587 syslog(LOG_ERR, "%s: lost queue file `%s'",
588 it->queueid, it->queuefn);
591 if (gettimeofday(&now, NULL) == 0 &&
592 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
593 asprintf(__DECONST(void *, &errmsg),
594 "Could not deliver for the last %d seconds. Giving up.",
600 if (backoff > MAX_RETRY)
615 run_queue(struct queue *queue)
619 if (LIST_EMPTY(&queue->queue))
622 it = go_background(queue);
628 show_queue(struct queue *queue)
632 if (LIST_EMPTY(&queue->queue)) {
633 printf("Mail queue is empty\n");
637 LIST_FOREACH(it, &queue->queue, next) {
638 printf("ID\t: %s%s\n"
643 it->locked ? "*" : "",
644 it->sender, it->addr);
652 * - use group permissions
653 * - proper sysexit codes
657 main(int argc, char **argv)
660 const char *tag = "dma";
665 int nodot = 0, doqueue = 0, showq = 0;
668 LIST_INIT(&queue.queue);
670 if (strcmp(argv[0], "mailq") == 0) {
674 errx(1, "invalid arguments");
679 while ((ch = getopt(argc, argv, "A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
682 /* -AX is being ignored, except for -A{c,m} */
683 if (optarg[0] == 'c' || optarg[0] == 'm') {
686 /* else FALLTRHOUGH */
688 /* -bX is being ignored, except for -bp */
689 if (optarg[0] == 'p') {
693 /* else FALLTRHOUGH */
706 /* -oX is being ignored, except for -oi */
707 if (optarg[0] != 'i')
709 /* else FALLTRHOUGH */
720 /* Ignored options */
743 if (argc != 0 && (showq || doqueue))
744 errx(1, "sending mail and queue operations are mutually exclusive");
746 if (showq + doqueue > 1)
747 errx(1, "conflicting queue operations");
750 openlog(tag, LOG_PID, LOG_MAIL);
753 /* XXX fork root here */
755 config = calloc(1, sizeof(*config));
759 if (parse_conf(CONF_PATH) < 0) {
761 err(1, "can not read config file");
764 if (config->features & VIRTUAL)
765 if (parse_virtuser(config->virtualpath) < 0)
766 err(1, "can not read virtual user file `%s'",
767 config->virtualpath);
769 if (parse_authfile(config->authpath) < 0)
770 err(1, "can not read SMTP authentication file");
773 load_queue(&lqueue, 1);
779 load_queue(&lqueue, 0);
784 if (read_aliases() != 0)
785 err(1, "can not read aliases file `%s'", config->aliases);
787 if ((sender = set_from(sender)) == NULL)
790 for (i = 0; i < argc; i++) {
791 if (add_recp(&queue, argv[i], sender, 1) != 0)
792 errx(1, "invalid recipient `%s'", argv[i]);
795 if (LIST_EMPTY(&queue.queue))
796 errx(1, "no recipients");
798 if (newspoolf(&queue, sender) != 0)
799 err(1, "can not create temp file");
801 if (readmail(&queue, sender, nodot) != 0)
802 err(1, "can not read mail");
804 if (linkspool(&queue) != 0)
805 err(1, "can not create spools");
807 /* From here on the mail is safe. */
809 if (config->features & DEFER)
812 it = go_background(&queue);