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.4 2008/09/16 17:57:22 matthias Exp $
38 #include <sys/param.h>
39 #include <sys/queue.h>
41 #include <sys/socket.h>
43 #include <sys/types.h>
46 #include <openssl/ssl.h>
47 #endif /* HAVE_CRYPTO */
70 static void deliver(struct qitem *, int);
71 static void deliver_smarthost(struct queue *, int);
72 static int add_recp(struct queue *, const char *, const char *, int);
74 struct aliases aliases = LIST_HEAD_INITIALIZER(aliases);
75 static struct strlist tmpfs = SLIST_HEAD_INITIALIZER(tmpfs);
76 struct virtusers virtusers = LIST_HEAD_INITIALIZER(virtusers);
77 struct authusers authusers = LIST_HEAD_INITIALIZER(authusers);
78 static int daemonize = 1;
79 struct config *config;
80 int controlsocket_df, clientsocket_df, controlsocket_wl, clientsocket_wl, semkey;
89 * Try to decrement semaphore as we start communicating with
90 * write_to_local_user()
92 sema.sem_num = SEM_WL;
95 if (semop(semkey, &sema, 1) == -1) {
96 err(1, "semaphore decrement failed");
100 * write_to_local_user() will exit and kill dotforwardhandler(), too
101 * if the corresponding semaphore is zero
102 * otherwise nothing happens
104 write(controlsocket_wl, &null, sizeof(null));
107 * Increment semaphore as we stop communicating with
108 * write_to_local_user()
111 if (semop(semkey, &sema, 1) == -1) {
112 err(1, "semaphore decrement failed");
119 static char name[MAXHOSTNAMELEN+1];
121 if (gethostname(name, sizeof(name)) != 0)
122 strcpy(name, "(unknown hostname)");
128 set_from(const char *osender)
133 if ((config->features & VIRTUAL) != 0) {
134 SLIST_FOREACH(v, &virtusers, next) {
135 if (strcmp(v->login, getlogin()) == 0) {
136 sender = strdup(v->address);
145 sender = strdup(osender);
149 if (asprintf(&sender, "%s@%s", getlogin(), hostname()) <= 0)
153 if (strchr(sender, '\n') != NULL) {
165 yyin = fopen(config->aliases, "r");
167 return(0); /* not fatal */
169 return(-1); /* fatal error, probably malloc() */
175 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
177 struct qitem *it, *tit;
184 it = calloc(1, sizeof(*it));
187 it->addr = strdup(str);
188 if (it->addr == NULL)
192 host = strrchr(it->addr, '@');
194 (strcmp(host + 1, hostname()) == 0 ||
195 strcmp(host + 1, "localhost") == 0)) {
198 LIST_FOREACH(tit, &queue->queue, next) {
199 /* weed out duplicate dests */
200 if (strcmp(tit->addr, it->addr) == 0) {
206 LIST_INSERT_HEAD(&queue->queue, it, next);
207 if (strrchr(it->addr, '@') == NULL) {
208 /* local = 1 means its a username or mailbox */
210 /* only search for aliases and .forward if asked for */
211 /* needed to have the possibility to add an mailbox directly */
213 /* first check /etc/aliases */
214 LIST_FOREACH(al, &aliases, next) {
215 if (strcmp(al->alias, it->addr) != 0)
217 SLIST_FOREACH(sit, &al->dests, next) {
218 if (add_recp(queue, sit->str,
225 LIST_REMOVE(it, next);
227 /* then check .forward of user */
232 /* is the username valid */
233 pw = getpwnam(it->addr);
239 * Try to decrement semaphore as we start
240 * communicating with dotforwardhandler()
242 sema.sem_num = SEM_DF;
245 if (semop(semkey, &sema, 1) == -1) {
246 err(1, "semaphore decrement failed");
249 /* write username to dotforwardhandler */
250 len = strlen(it->addr);
251 write(controlsocket_df, &len, sizeof(len));
252 write(controlsocket_df, it->addr, len);
254 FD_SET(controlsocket_df, &rfds);
256 /* wait for incoming redirects and pipes */
257 while (ret =select(controlsocket_df + 1,
258 &rfds, NULL, NULL, NULL)) {
260 * Receive back list of mailboxnames
261 * and/or emailadresses
265 * increment semaphore because
266 * we stopped communicating
267 * with dotforwardhandler()
270 semop(semkey, &sema, 1);
273 /* read type of .forward entry */
274 read(controlsocket_df, &type, 1);
275 if (type & ENDOFDOTFORWARD) {
276 /* end of .forward */
278 * If there are redirects, then
279 * we do not need the original
283 LIST_REMOVE(it, next);
286 } else if (type & ISMAILBOX) {
287 /* redirect -> user/emailaddress */
289 * FIXME shall there be the possibility to use
290 * usernames instead of mailboxes?
293 read(controlsocket_df, &len, sizeof(len));
294 username = calloc(1, len + 1);
295 read(controlsocket_df, username, len);
297 * Do not further expand since
298 * its remote or local mailbox
300 if (add_recp(queue, username, sender, 0) != 0) {
303 } else if (type & ISPIPE) {
304 /* redirect to a pipe */
306 * Create new qitem and save
310 pit = calloc(1, sizeof(*pit));
313 * Increment semaphore
316 * dotforwardhandler()
319 semop(semkey, &sema, 1);
322 LIST_INSERT_HEAD(&queue->queue, pit, next);
324 * Save username to qitem,
325 * because its overwritten by
328 pit->pipeuser = strdup(it->addr);
329 pit->sender = sender;
330 /* local = 2 means redirect to pipe */
332 read(controlsocket_df, &len, sizeof(len));
333 pit->addr = realloc(pit->addr, len + 1);
334 memset(pit->addr, 0, len + 1);
335 read(controlsocket_df, pit->addr, len);
340 * Increment semaphore because we stopped
341 * communicating with dotforwardhandler()
344 semop(semkey, &sema, 1);
364 SLIST_FOREACH(t, &tmpfs, next) {
370 gentempf(struct queue *queue)
376 if (snprintf(fn, sizeof(fn), "%s/%s", config->spooldir, "tmp_XXXXXXXXXX") <= 0)
383 queue->tmpf = strdup(fn);
384 if (queue->tmpf == NULL) {
388 t = malloc(sizeof(*t));
390 t->str = queue->tmpf;
391 SLIST_INSERT_HEAD(&tmpfs, t, next);
400 * queue-id1 envelope-to1
401 * queue-id2 envelope-to2
406 * queue ids are unique, formed from the inode of the spool file
407 * and a unique identifier.
410 preparespool(struct queue *queue, const char *sender)
412 char line[1000]; /* by RFC2822 */
419 error = snprintf(line, sizeof(line), "%s\n", sender);
420 if (error < 0 || (size_t)error >= sizeof(line)) {
424 if (write(queue->mailfd, line, error) != error)
427 queuef = fdopen(queue->mailfd, "r+");
432 * Assign queue id to each dest.
434 if (fstat(queue->mailfd, &st) != 0)
436 queue->id = st.st_ino;
437 LIST_FOREACH(it, &queue->queue, next) {
438 if (asprintf(&it->queueid, "%"PRIxMAX".%"PRIxPTR,
439 queue->id, (uintptr_t)it) <= 0)
441 if (asprintf(&it->queuefn, "%s/%s",
442 config->spooldir, it->queueid) <= 0)
444 /* File may already exist */
445 if (stat(it->queuefn, &st) == 0) {
446 warn("Spoolfile already exists: %s", it->queuefn);
449 /* Reset errno to avoid confusion */
452 error = snprintf(line, sizeof(line), "%s %s\n",
453 it->queueid, it->addr);
454 if (error < 0 || (size_t)error >= sizeof(line))
456 if (write(queue->mailfd, line, error) != error)
460 if (write(queue->mailfd, line, 1) != 1)
463 hdrlen = lseek(queue->mailfd, 0, SEEK_CUR);
464 LIST_FOREACH(it, &queue->queue, next) {
478 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
481 strcpy(str, "(date fail)");
486 readmail(struct queue *queue, const char *sender, int nodot)
488 char line[1000]; /* by RFC2822 */
492 error = snprintf(line, sizeof(line), "\
493 Received: from %s (uid %d)\n\
494 \t(envelope-from %s)\n\
498 getlogin(), getuid(),
503 if (error < 0 || (size_t)error >= sizeof(line))
505 if (write(queue->mailfd, line, error) != error)
508 while (!feof(stdin)) {
509 if (fgets(line, sizeof(line), stdin) == NULL)
511 linelen = strlen(line);
512 if (linelen == 0 || line[linelen - 1] != '\n') {
513 errno = EINVAL; /* XXX mark permanent errors */
516 if (!nodot && linelen == 2 && line[0] == '.')
518 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
521 if (fsync(queue->mailfd) != 0)
527 linkspool(struct queue *queue)
532 * Only if it is not a pipe delivery
533 * pipe deliveries are only tried once so there
534 * is no need for a spool-file, they use the
538 LIST_FOREACH(it, &queue->queue, next) {
540 * There shall be no files for pipe deliveries since not all
541 * information is saved in the header, so pipe delivery is
542 * tried once and forgotten thereafter.
546 if (link(queue->tmpf, it->queuefn) != 0)
552 LIST_FOREACH(it, &queue->queue, next) {
554 * There are no files for pipe delivery, so they can't be
565 go_background(struct queue *queue, int leavesemaphore)
570 int seen_remote_address = 0;
572 if (daemonize && daemon(0, 0) != 0) {
573 syslog(LOG_ERR, "[go_background] can not daemonize: %m");
577 bzero(&sa, sizeof(sa));
578 sa.sa_flags = SA_NOCLDWAIT;
579 sa.sa_handler = SIG_IGN;
580 sigaction(SIGCHLD, &sa, NULL);
583 LIST_FOREACH(it, &queue->queue, next) {
585 * If smarthost is enabled, the address is remote
586 * set smarthost delivery flag, otherwise deliver it 'normal'.
588 if (config->smarthost != NULL && strlen(config->smarthost) > 0
591 seen_remote_address = 1;
593 * if it is not the last entry, continue
594 * (if it is the last, start delivery in parent
596 if (LIST_NEXT(it, next) != NULL) {
601 * If item is local, we do not need it in the list any
602 * more, so delete it.
604 LIST_REMOVE(it, next);
609 syslog(LOG_ERR, "can not fork: %m");
617 * return and deliver mail
620 if (config->smarthost == NULL || strlen(config->smarthost) == 0 || it->local)
621 if (LIST_NEXT(it, next) == NULL && !seen_remote_address)
622 /* if there is no smarthost-delivery and we are the last item */
623 deliver(it, leavesemaphore);
636 * If it is the last loop and there were remote
637 * addresses, start smarthost delivery.
638 * No need to doublecheck if smarthost is
639 * activated in config file.
641 if (LIST_NEXT(it, next) == NULL) {
642 if (seen_remote_address) {
643 deliver_smarthost(queue, leavesemaphore);
652 syslog(LOG_CRIT, "reached dead code");
657 bounce(struct qitem *it, const char *reason, int leavesemaphore)
659 struct queue bounceq;
665 /* Don't bounce bounced mails */
666 if (it->sender[0] == 0) {
668 * If we are the last bounce, then decrement semaphore
669 * and release children.
671 if (leavesemaphore) {
672 /* semaphore-- (MUST NOT BLOCK BECAUSE ITS POSITIVE) */
673 sema.sem_num = SEM_SIGHUP;
675 sema.sem_flg = IPC_NOWAIT;
676 if (semop(semkey, &sema, 1) == -1) {
677 err(1, "[deliver] semaphore decrement failed");
679 /* release child processes */
682 syslog(LOG_CRIT, "%s: delivery panic: can't bounce a bounce",
687 syslog(LOG_ERR, "%s: delivery failed, bouncing",
690 LIST_INIT(&bounceq.queue);
691 if (add_recp(&bounceq, it->sender, "", 1) != 0)
693 if (gentempf(&bounceq) != 0)
695 if (preparespool(&bounceq, "") != 0)
698 bit = LIST_FIRST(&bounceq.queue);
699 error = fprintf(bit->queuef, "\
700 Received: from MAILER-DAEMON\n\
704 X-Original-To: <%s>\n\
705 From: MAILER-DAEMON <>\n\
707 Subject: Mail delivery failed\n\
708 Message-Id: <%"PRIxMAX"@%s>\n\
711 This is the %s at %s.\n\
713 There was an error delivering your mail to <%s>.\n\
717 Message headers follow.\n\
725 bounceq.id, hostname(),
732 if (fflush(bit->queuef) != 0)
735 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
737 while (!feof(it->queuef)) {
738 if (fgets(line, sizeof(line), it->queuef) == NULL)
742 write(bounceq.mailfd, line, strlen(line));
744 if (fsync(bounceq.mailfd) != 0)
746 if (linkspool(&bounceq) != 0)
753 go_background(&bounceq, leavesemaphore);
758 * If we are the last bounce, then decrement semaphore
759 * and release children.
761 if (leavesemaphore) {
762 /* semaphore-- (MUST NOT BLOCK BECAUSE ITS POSITIVE) */
763 sema.sem_num = SEM_SIGHUP;
765 sema.sem_flg = IPC_NOWAIT;
766 if (semop(semkey, &sema, 1) == -1) {
767 err(1, "[deliver] semaphore decrement failed");
769 /* release child processes */
772 syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
778 deliver_local(struct qitem *it, const char **errmsg)
783 uint8_t mode = 0, fail = 0;
785 time_t now = time(NULL);
791 * Try to decrement semaphore as we start communicating with
792 * write_to_local_user()
794 sema.sem_num = SEM_WL;
797 if (semop(semkey, &sema, 1) == -1) {
798 err(1, "semaphore decrement failed");
802 /* Tell write_to_local_user() the username to drop the privileges */
803 if (it->local == 1) { /* mailbox delivery */
805 } else if (it->local == 2) { /* pipe delivery */
806 username = it->pipeuser;
808 len = strlen(username);
809 write(controlsocket_wl, &len, sizeof(len));
810 write(controlsocket_wl, username, len);
811 read(controlsocket_wl, &fail, sizeof(fail));
814 "%s: local delivery deferred: can not fork and drop privileges `%s': %m",
815 it->queueid, username);
817 * Increment semaphore because we stopped communicating with
818 * write_to_local_user().
821 semop(semkey, &sema, 1);
826 /* Tell write_to_local_user() the delivery mode (write to mailbox || pipe) */
827 if (it->local == 1) { /* mailbox delivery */
829 len = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
830 if (len < 0 || (size_t)len >= sizeof(fn)) {
831 syslog(LOG_ERR, "%s: local delivery deferred: %m",
834 * Increment semaphore because we stopped communicating
835 * with write_to_local_user().
838 semop(semkey, &sema, 1);
841 } else if (it->local == 2) { /* pipe delivery */
843 strncpy(fn, it->addr, sizeof(fn));
846 write(controlsocket_wl, &len, sizeof(len));
847 write(controlsocket_wl, fn, len);
848 write(controlsocket_wl, &mode, sizeof(mode));
849 read(controlsocket_wl, &fail, sizeof(fail));
853 "%s: local delivery deferred: can not (p)open `%s': %m",
854 it->queueid, it->addr);
856 * Increment semaphore because we stopped communicating
857 * with write_to_local_user().
860 semop(semkey, &sema, 1);
865 /* Prepare transfer of mail-data */
866 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
867 syslog(LOG_ERR, "%s: local delivery deferred: can not seek: %m",
870 * Increment semaphore because we stopped communicating
871 * with write_to_local_user().
874 semop(semkey, &sema, 1);
879 /* Send first header line. */
880 linelen = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
881 if (linelen < 0 || (size_t)linelen >= sizeof(line)) {
882 syslog(LOG_ERR, "%s: local delivery deferred: can not write header: %m",
885 * Increment semaphore because we stopped communicating
886 * with write_to_local_user().
889 semop(semkey, &sema, 1);
893 write(controlsocket_wl, &linelen, sizeof(linelen));
894 write(controlsocket_wl, line, linelen);
896 read(controlsocket_wl, &fail, sizeof(fail));
902 /* Read mail data and transfer it to write_to_local_user(). */
903 while (!feof(it->queuef)) {
904 if (fgets(line, sizeof(line), it->queuef) == NULL)
906 linelen = strlen(line);
907 if (linelen == 0 || line[linelen - 1] != '\n') {
909 "%s: local delivery failed: corrupted queue file",
911 *errmsg = "corrupted queue file";
913 /* break receive and write loop at write_to_local_user() */
915 write(controlsocket_wl, &linelen, sizeof(linelen));
916 /* and send error state */
918 write(controlsocket_wl, &linelen, sizeof(linelen));
922 if (strncmp(line, "From ", 5) == 0) {
923 const char *gt = ">";
924 size_t sizeofchar = 1;
926 write(controlsocket_wl, &sizeofchar, sizeof(sizeofchar));
927 write(controlsocket_wl, gt, 1);
928 read(controlsocket_wl, &fail, sizeof(fail));
933 write(controlsocket_wl, &linelen, sizeof(linelen));
934 write(controlsocket_wl, line, linelen);
935 read(controlsocket_wl, &fail, sizeof(fail));
941 /* Send final linebreak */
944 write(controlsocket_wl, &linelen, sizeof(linelen));
945 write(controlsocket_wl, line, linelen);
946 read(controlsocket_wl, &fail, sizeof(fail));
952 /* break receive and write loop in write_to_local_user() */
954 /* send '0' twice, because above we send '0' '1' in case of error */
955 write(controlsocket_wl, &linelen, sizeof(linelen));
956 write(controlsocket_wl, &linelen, sizeof(linelen));
957 read(controlsocket_wl, &fail, sizeof(fail));
964 * Increment semaphore because we stopped communicating
965 * with write_to_local_user().
968 semop(semkey, &sema, 1);
973 syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
977 read(controlsocket_wl, &fail, sizeof(fail));
979 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
983 * Increment semaphore because we stopped communicating
984 * with write_to_local_user().
987 semop(semkey, &sema, 1);
992 deliver(struct qitem *it, int leavesemaphore)
995 unsigned int backoff = MIN_RETRY;
996 const char *errmsg = "unknown bounce reason";
1001 if (it->local == 2) {
1002 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s> command=<%s>",
1003 it->queueid, it->sender, it->pipeuser, it->addr);
1005 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
1006 it->queueid, it->sender, it->addr);
1010 syslog(LOG_INFO, "%s: trying delivery",
1014 * Only increment semaphore, if we are not the last bounce
1015 * because there is still a incremented semaphore from
1016 * the bounced delivery
1018 if (!leavesemaphore) {
1020 * Increment semaphore for each mail we try to deliver.
1021 * When completing the transmit, the semaphore is decremented.
1022 * If the semaphore is zero the other childs know that they
1025 sema.sem_num = SEM_SIGHUP;
1028 if (semop(semkey, &sema, 1) == -1) {
1029 err(1, "[deliver] semaphore increment failed");
1033 error = deliver_local(it, &errmsg);
1035 error = deliver_remote(it, &errmsg, NULL);
1040 /* semaphore-- (MUST NOT BLOCK BECAUSE ITS POSITIVE) */
1041 sema.sem_num = SEM_SIGHUP;
1043 sema.sem_flg = IPC_NOWAIT;
1044 if (semop(semkey, &sema, 1) == -1) {
1045 err(1, "[deliver] semaphore decrement failed");
1047 /* release child processes */
1049 /* Do not try to delete the spool file: pipe mode */
1051 unlink(it->queuefn);
1052 syslog(LOG_INFO, "%s: delivery successful",
1057 /* pipe delivery only tries once, then gives up */
1058 if (it->local == 2) {
1059 /* decrement-- (MUST NOT BLOCK BECAUSE ITS POSITIVE) */
1060 sema.sem_num = SEM_SIGHUP;
1062 sema.sem_flg = IPC_NOWAIT;
1063 if (semop(semkey, &sema, 1) == -1) {
1064 err(1, "[deliver] semaphore decrement failed");
1066 /* release child processes */
1068 syslog(LOG_ERR, "%s: delivery to pipe `%s' failed, giving up",
1069 it->queueid, it->addr);
1072 if (stat(it->queuefn, &st) != 0) {
1073 /* semaphore-- (MUST NOT BLOCK BECAUSE ITS POSITIVE) */
1074 sema.sem_num = SEM_SIGHUP;
1076 sema.sem_flg = IPC_NOWAIT;
1077 if (semop(semkey, &sema, 1) == -1) {
1078 err(1, "[deliver] semaphore decrement failed");
1080 /* release child processes */
1082 syslog(LOG_ERR, "%s: lost queue file `%s'",
1083 it->queueid, it->queuefn);
1086 if (gettimeofday(&now, NULL) == 0 &&
1087 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
1091 "Could not deliver for the last %d seconds. Giving up.",
1098 if (backoff > MAX_RETRY)
1099 backoff = MAX_RETRY;
1108 bounce(it, errmsg, 1);
1113 * deliver_smarthost() is similar to deliver(), but has some differences:
1114 * -deliver_smarthost() works with a queue
1115 * -each entry in this queue has a corresponding file in the spooldir
1116 * -if the mail is sent correctly to a address, delete the corresponding file,
1117 * even if there were errors with other addresses
1118 * -so deliver_remote must tell deliver_smarthost to which addresses it has
1119 * successfully sent the mail
1120 * -this can be done with 3 queues:
1121 * -one queue for sent mails
1122 * -one queue for 4xx addresses (tempfail)
1123 * -one queue for 5xx addresses (permfail)
1124 * -the sent mails are deleted
1125 * -the 4xx are tried again
1126 * -the 5xx are bounced
1130 deliver_smarthost(struct queue *queue, int leavesemaphore)
1132 int error, bounces = 0;
1133 unsigned int backoff = MIN_RETRY;
1134 const char *errmsg = "unknown bounce reason";
1138 struct qitem *it, *tit;
1139 struct queue *queues[4], *bouncequeue, successqueue, tempfailqueue,
1143 * only increment semaphore, if we are not the last bounce
1144 * because there is still a incremented semaphore from
1145 * the bounced delivery
1147 if (!leavesemaphore) {
1149 * Increment semaphore for each mail we try to deliver.
1150 * When completing the transmit, the semaphore is decremented.
1151 * If the semaphore is zero the other childs know that they
1154 sema.sem_num = SEM_SIGHUP;
1157 if (semop(semkey, &sema, 1) == -1) {
1158 err(1, "[deliver] semaphore increment failed");
1163 queues[1] = &successqueue;
1164 queues[2] = &tempfailqueue;
1165 queues[3] = &permfailqueue;
1168 /* initialise 3 empty queues and link it in queues[] */
1169 LIST_INIT(&queues[1]->queue); /* successful sent items */
1170 LIST_INIT(&queues[2]->queue); /* temporary error items */
1171 LIST_INIT(&queues[3]->queue); /* permanent error items */
1173 it = LIST_FIRST(&queues[0]->queue);
1175 syslog(LOG_INFO, "%s: trying delivery",
1178 /* if queuefile of first qitem is gone, the mail can't be sended out */
1179 if (stat(it->queuefn, &st) != 0) {
1180 syslog(LOG_ERR, "%s: lost queue file `%s'",
1181 it->queueid, it->queuefn);
1182 /* semaphore-- (MUST NOT BLOCK BECAUSE ITS POSITIVE) */
1183 sema.sem_num = SEM_SIGHUP;
1185 sema.sem_flg = IPC_NOWAIT;
1186 if (semop(semkey, &sema, 1) == -1) {
1187 err(1, "[deliver] semaphore decrement failed");
1193 error = deliver_remote(it, &errmsg, queues);
1195 /* if there was an error, do nothing with the other 3 queues! */
1199 * If there are permanent errors, bounce items in permanent
1202 if (!LIST_EMPTY(&queues[3]->queue)) {
1208 syslog(LOG_ERR, "can not fork: %m");
1216 * Tell which queue to bounce and set
1217 * errmsg. Child will exit as soon as
1218 * all childs for bounces are spawned.
1219 * So no need to set up a signal handler.
1221 bouncequeue = queues[3];
1222 errmsg = "smarthost sent permanent error (5xx)";
1229 * continue with stuff
1235 /* delete successfully sent items */
1236 if (!LIST_EMPTY(&queues[1]->queue)) {
1237 LIST_FOREACH(tit, &queues[1]->queue, next) {
1238 unlink(tit->queuefn);
1239 LIST_REMOVE(tit, next);
1240 syslog(LOG_INFO, "%s: delivery successful",
1246 /* If the temporary error queue is empty and there was no error, finish */
1247 if (LIST_EMPTY(&queues[2]->queue) && error == 0) {
1248 /* only decrement semaphore if there were no bounces! */
1250 /* semaphore-- (MUST NOT BLOCK BECAUSE ITS POSITIVE) */
1251 sema.sem_num = SEM_SIGHUP;
1253 sema.sem_flg = IPC_NOWAIT;
1254 if (semop(semkey, &sema, 1) == -1) {
1255 err(1, "[deliver] semaphore decrement failed");
1257 /* release child processes */
1262 /* if there are remaining items, set up retry timer */
1266 * if there was an error, do not touch queues[0]!
1267 * and try to deliver all items again
1271 /* wipe out old queue */
1272 if (!LIST_EMPTY(&queues[0]->queue)) {
1273 LIST_FOREACH(tit, &queues[0]->queue, next) {
1274 unlink(tit->queuefn);
1275 LIST_REMOVE(tit, next);
1277 LIST_INIT(&queues[0]->queue);
1279 /* link temporary error queue to queues[0] */
1280 queues[0] = &tempfailqueue;
1281 /* and link queues[2] to wiped out queue */
1285 if (gettimeofday(&now, NULL) == 0 &&
1286 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
1290 "Could not deliver for the last %d seconds. Giving up.",
1294 /* bounce remaining items which have temporary errors */
1295 bouncequeue = queues[2];
1300 if (backoff > MAX_RETRY)
1301 backoff = MAX_RETRY;
1306 LIST_FOREACH(tit, &bouncequeue->queue, next) {
1307 struct sigaction sa;
1309 bzero(&sa, sizeof(sa));
1310 sa.sa_flags = SA_NOCLDWAIT;
1311 sa.sa_handler = SIG_IGN;
1312 sigaction(SIGCHLD, &sa, NULL);
1314 /* fork is needed, because bounce() does not return */
1318 syslog(LOG_ERR, "can not fork: %m");
1329 LIST_REMOVE(tit, next);
1330 if (LIST_NEXT(tit, next) == NULL) {
1332 * For the last bounce, do not increment
1333 * the semaphore when delivering the
1336 bounce(tit, errmsg, 1);
1338 bounce(tit, errmsg, 0);
1350 /* last parent shall exit, too */
1356 load_queue(struct queue *queue)
1360 //struct queue queue, itmqueue;
1361 struct queue itmqueue;
1374 LIST_INIT(&queue->queue);
1376 spooldir = opendir(config->spooldir);
1377 if (spooldir == NULL)
1378 err(1, "reading queue");
1380 while ((de = readdir(spooldir)) != NULL) {
1386 LIST_INIT(&itmqueue.queue);
1388 /* ignore temp files */
1389 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
1390 de->d_type != DT_REG)
1392 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
1394 fd = open(queuefn, O_RDONLY|O_EXLOCK|O_NONBLOCK);
1396 /* Ignore locked files */
1397 if (errno == EWOULDBLOCK)
1402 queuef = fdopen(fd, "r");
1405 if (fgets(line, sizeof(line), queuef) == NULL ||
1408 line[strlen(line) - 1] = 0; /* chop newline */
1409 sender = strdup(line);
1414 if (fgets(line, sizeof(line), queuef) == NULL ||
1417 if (line[0] == '\n')
1419 line[strlen(line) - 1] = 0;
1420 queueid = strdup(line);
1421 if (queueid == NULL)
1423 addr = strchr(queueid, ' ');
1429 if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
1431 /* Item has already been delivered? */
1432 if (stat(fn, &st) != 0)
1434 if (add_recp(&itmqueue, addr, sender, 0) != 0)
1436 it = LIST_FIRST(&itmqueue.queue);
1437 it->queuef = queuef;
1438 it->queueid = queueid;
1442 if (LIST_EMPTY(&itmqueue.queue)) {
1443 warnx("queue file without items: `%s'", queuefn);
1446 hdrlen = ftell(queuef);
1447 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
1448 it->hdrlen = hdrlen;
1449 LIST_REMOVE(it, next);
1450 LIST_INSERT_HEAD(&queue->queue, it, next);
1455 warn("reading queue: `%s'", queuefn);
1459 if (queuefn != NULL)
1463 if (queueid != NULL)
1471 err(1, "reading queue");
1475 run_queue(struct queue *queue)
1478 if (LIST_EMPTY(&queue->queue))
1481 go_background(queue, 0);
1486 show_queue(struct queue *queue)
1490 if (LIST_EMPTY(&queue->queue)) {
1491 printf("Mail queue is empty\n");
1495 LIST_FOREACH(it, &queue->queue, next) {
1499 To\t: %s\n--\n", it->queueid, it->sender, it->addr);
1506 * - alias processing
1507 * - use group permissions
1508 * - proper sysexit codes
1512 parseandexecute(int argc, char **argv)
1514 char *sender = NULL;
1518 struct queue lqueue;
1520 int nodot = 0, doqueue = 0, showq = 0;
1521 uint8_t null = 0, recipient_add_success = 0;
1524 LIST_INIT(&queue.queue);
1525 snprintf(tag, 254, "dma");
1528 while ((ch = getopt(argc, argv, "A:b:Df:iL:o:O:q:r:")) != -1) {
1531 /* -AX is being ignored, except for -A{c,m} */
1532 if (optarg[0] == 'c' || optarg[0] == 'm') {
1535 /* else FALLTRHOUGH */
1537 /* -bX is being ignored, except for -bp */
1538 if (optarg[0] == 'p') {
1542 /* else FALLTRHOUGH */
1548 snprintf(tag, 254, "%s", optarg);
1556 /* -oX is being ignored, except for -oi */
1557 if (optarg[0] != 'i')
1559 /* else FALLTRHOUGH */
1579 openlog(tag, LOG_PID | LOG_PERROR, LOG_MAIL);
1581 config = malloc(sizeof(struct config));
1583 errx(1, "Cannot allocate enough memory");
1585 memset(config, 0, sizeof(struct config));
1586 if (parse_conf(CONF_PATH, config) < 0) {
1589 errx(1, "reading config file");
1592 if (config->features & VIRTUAL)
1593 if (parse_virtuser(config->virtualpath) < 0) {
1595 errx(1, "error reading virtual user file: %s",
1596 config->virtualpath);
1599 if (parse_authfile(config->authpath) < 0) {
1601 err(1, "reading SMTP authentication file");
1606 errx(1, "sending mail and displaying queue is"
1607 " mutually exclusive");
1608 load_queue(&lqueue);
1609 show_queue(&lqueue);
1615 errx(1, "sending mail and queue pickup is mutually exclusive");
1616 load_queue(&lqueue);
1621 if (read_aliases() != 0) {
1623 err(1, "reading aliases");
1626 if ((sender = set_from(sender)) == NULL) {
1628 err(1, "setting from address");
1631 if (gentempf(&queue) != 0) {
1633 err(1, "create temp file");
1636 for (i = 0; i < argc; i++) {
1637 if (add_recp(&queue, argv[i], sender, 1) != 0) {
1639 errx(1, "invalid recipient `%s'\n", argv[i]);
1643 if (LIST_EMPTY(&queue.queue)) {
1645 errx(1, "no recipients");
1648 if (preparespool(&queue, sender) != 0) {
1650 err(1, "creating spools (1)");
1653 if (readmail(&queue, sender, nodot) != 0) {
1655 err(1, "reading mail");
1658 if (linkspool(&queue) != 0) {
1660 err(1, "creating spools (2)");
1663 /* From here on the mail is safe. */
1665 if (config->features & DEFER)
1668 go_background(&queue, 0);
1676 * dotforwardhandler() waits for incoming username
1677 * for each username, the .forward file is read and parsed
1678 * earch entry is given back to add_recp which communicates
1679 * with dotforwardhandler()
1687 uint8_t stmt, namelength;
1690 FD_SET(clientsocket_df, &rfds);
1692 /* wait for incoming usernames */
1693 ret = select(clientsocket_df + 1, &rfds, NULL, NULL, NULL);
1697 while (read(clientsocket_df, &namelength, sizeof(namelength))) {
1699 struct passwd *userentry;
1700 if (namelength == 0) {
1701 /* there will be no more usernames, we can terminate */
1704 /* read username and get homedir */
1705 username = calloc(1, namelength + 1);
1706 read(clientsocket_df, username, namelength);
1707 userentry = getpwnam(username);
1711 if (pid == 0) { /* child */
1714 /* drop privileges to user */
1717 if (initgroups(username, userentry->pw_gid))
1719 if (setgid(userentry->pw_gid))
1721 if (setuid(userentry->pw_uid))
1724 /* read ~/.forward */
1725 dotforward = strdup(userentry->pw_dir);
1726 forward = fopen(strcat(dotforward, "/.forward"), "r");
1727 if (forward == NULL) { /* no dotforward */
1728 stmt = ENDOFDOTFORWARD;
1729 write(clientsocket_df, &stmt, 1);
1734 /* parse ~/.forward */
1735 while (!feof(forward)) { /* each line in ~/.forward */
1736 char *target = NULL;
1737 /* 255 Bytes should be enough for a pipe and a emailaddress */
1740 memset(line, 0, 2048);
1741 fgets(line, sizeof(line), forward);
1742 /* FIXME allow comments? */
1743 if ((target = strtok(line, "\t\n")) != NULL)
1744 if (strncmp(target, "|", 1) == 0) {
1745 /* if first char is a '|', the line is a pipe */
1747 write(clientsocket_df, &stmt, 1);
1748 len = strlen(target);
1749 /* remove the '|' */
1751 /* send result back to add_recp */
1752 write(clientsocket_df, &len, sizeof(len));
1753 write(clientsocket_df, target + 1, len);
1755 /* if first char is not a '|', the line is a mailbox */
1757 write(clientsocket_df, &stmt, 1);
1758 len = strlen(target);
1759 /* send result back to add_recp */
1760 write(clientsocket_df, &len, sizeof(len));
1761 write(clientsocket_df, target, len);
1764 stmt = ENDOFDOTFORWARD;
1765 /* send end of .forward to add_recp */
1766 write(clientsocket_df, &stmt, 1);
1768 } else if (pid < 0) { /* fork failed */
1770 } else { /* parent */
1771 /* parent waits while child is processing .forward */
1772 waitpid(-1, NULL, 0);
1778 * write_to_local_user() writes to a mailbox or
1779 * to a pipe in a user context and communicates with deliver_local()
1782 write_to_local_user() {
1787 /* wait for incoming targets */
1788 while (read(clientsocket_wl, &length, sizeof(length))) {
1790 uint8_t mode, fail = 0;
1791 char fn[PATH_MAX+1];
1798 struct passwd *userentry;
1800 target = calloc(1, length + 1);
1804 /* check if semaphore is '0' */
1805 sema.sem_num = SEM_SIGHUP;
1807 sema.sem_flg = IPC_NOWAIT;
1808 retval = semop(semkey, &sema, 1);
1809 if (retval == 0 || errno == EINVAL) {
1811 * if semaphore is '0' then the last mail is sent
1812 * and there is no need for a write_to_local_user()
1815 * if errno is EINVAL, then someone has removed the semaphore, so we shall exit, too
1822 /* read username and get uid/gid */
1823 read(clientsocket_wl, target, length);
1825 userentry = getpwnam(target);
1829 if (pid == 0) { /* child */
1830 /* drop privileges to user and tell if there is something wrong */
1833 write(clientsocket_wl, &fail, sizeof(fail));
1835 write(clientsocket_wl, &fail, sizeof(fail));
1839 if (initgroups(target, userentry->pw_gid)) {
1841 write(clientsocket_wl, &fail, sizeof(fail));
1843 write(clientsocket_wl, &fail, sizeof(fail));
1847 if (setgid(userentry->pw_gid)) {
1849 write(clientsocket_wl, &fail, sizeof(fail));
1851 write(clientsocket_wl, &fail, sizeof(fail));
1855 if (setuid(userentry->pw_uid)) {
1857 write(clientsocket_wl, &fail, sizeof(fail));
1859 write(clientsocket_wl, &fail, sizeof(fail));
1863 /* and go on with execution outside of if () */
1864 } else if (pid < 0) { /* fork failed */
1866 write(clientsocket_wl, &fail, sizeof(fail));
1868 write(clientsocket_wl, &fail, sizeof(fail));
1871 } else { /* parent */
1874 /* wait for child to finish and continue loop */
1875 waitpid(-1, NULL, 0);
1876 /* check if semaphore is '0' */
1877 sema.sem_num = SEM_SIGHUP;
1879 sema.sem_flg = IPC_NOWAIT;
1880 retval = semop(semkey, &sema, 1);
1881 if (retval == 0 || errno == EINVAL) {
1883 * if semaphore is '0' then the last mail is sent
1884 * and there is no need for a write_to_local_user()
1887 * if errno is EINVAL, then someone has removed the semaphore, so we shall exit, too
1890 } else if (errno != EAGAIN) {
1891 err(1, "[write_to_local_user] semop_op = 0 failed");
1895 /* child code again here */
1896 /* send ack, we are ready to go on with mode and target */
1897 write(clientsocket_wl, &fail, sizeof(fail));
1899 read(clientsocket_wl, &length, sizeof(length));
1900 target = realloc(target, length + 1);
1901 memset(target, 0, length + 1);
1902 read(clientsocket_wl, target, length);
1903 read(clientsocket_wl, &mode, sizeof(mode));
1904 if (mode & ISMAILBOX) {
1905 /* if mode is mailbox, open mailbox */
1906 /* mailx removes users mailspool file if empty, so open with O_CREAT */
1907 mbox = open(target, O_WRONLY | O_EXLOCK | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
1910 write(clientsocket_wl, &fail, sizeof(fail));
1912 write(clientsocket_wl, &fail, sizeof(fail));
1915 mboxlen = lseek(mbox, 0, SEEK_CUR);
1916 } else if (mode & ISPIPE) {
1917 /* if mode is mailbox, popen pipe */
1919 if ((pipe = popen(target, "w")) == NULL) {
1921 write(clientsocket_wl, &fail, sizeof(fail));
1923 write(clientsocket_wl, &fail, sizeof(fail));
1927 /* send ack, we are ready to receive mail contents */
1928 write(clientsocket_wl, &fail, sizeof(fail));
1930 /* write to file/pipe loop */
1931 while (read(clientsocket_wl, &linelen, sizeof(linelen))) {
1933 read(clientsocket_wl, &linelen, sizeof(linelen));
1937 /* if linelen != 0, then there is a error on sender side */
1942 read(clientsocket_wl, line, linelen);
1944 /* write line to target */
1945 if (mode & ISMAILBOX) { /* mailbox delivery */
1946 if ((size_t)write(mbox, line, linelen) != linelen) {
1949 } else if (mode & ISPIPE) { /* pipe delivery */
1950 if (fwrite(line, 1, linelen, pipe) != linelen) {
1955 write(clientsocket_wl, &fail, sizeof(fail));
1958 /* close target after succesfully written last line */
1959 if (mode & ISMAILBOX) { /* mailbox delivery */
1961 } else if (mode & ISPIPE) { /* pipe delivery */
1964 /* send ack and exit */
1965 write(clientsocket_wl, &fail, sizeof(fail));
1969 write(clientsocket_wl, &fail, sizeof(fail));
1972 /* reset mailbox if there was something wrong */
1973 if (mode & ISMAILBOX && ftruncate(mbox, mboxlen) != 0) {
1976 write(clientsocket_wl, &fail, sizeof(fail));
1977 if (mode & ISMAILBOX) { /* mailbox delivery */
1979 } else if (mode & ISPIPE) { /* pipe delivery */
1985 /* release dotforwardhandler out of loop */
1986 write(controlsocket_df, &null, sizeof(null));
1987 /* we do not need the semaphores any more */
1988 semctl(semkey, 0, IPC_RMID, 0);
1993 main(int argc, char **argv)
1996 int sockets1[2], sockets2[2];
1998 struct ipc_perm semperm;
2000 if (geteuid() != 0) {
2001 fprintf(stderr, "This executable must be set setuid root!\n");
2005 /* create socketpair for dotforwardhandler() communication */
2006 if (socketpair(PF_UNIX, SOCK_STREAM, 0, sockets1) != 0) {
2007 err(1,"Socketpair1 creation failed!\n");
2009 /* df is short for DotForwardhandler */
2010 controlsocket_df = sockets1[0];
2011 clientsocket_df = sockets1[1];
2013 /* create socketpair for write_to_local_user() communication */
2014 if (socketpair(PF_UNIX, SOCK_STREAM, 0, sockets2) != 0) {
2015 err(1,"Socketpair2 creation failed!\n");
2017 /* wl is short for Write_to_Local_user */
2018 controlsocket_wl = sockets2[0];
2019 clientsocket_wl = sockets2[1];
2022 * create semaphores:
2023 * -one for exclusive dotforwardhandler communication
2024 * -one for exclusive write_to_local_user communication
2025 * -another for signaling that the queue is completely processed
2027 semkey = semget(IPC_PRIVATE, 3, IPC_CREAT | IPC_EXCL | 0660);
2029 err(1,"[main] Creating semaphores failed");
2032 /* adjust privileges of semaphores */
2034 if ((pw = getpwnam("nobody")) == NULL)
2035 err(1, "Can't get uid of user 'nobody'");
2039 if ((grp = getgrnam("mail")) == NULL)
2040 err(1, "Can't get gid of group 'mail'");
2043 semperm.uid = pw->pw_uid;
2044 semperm.gid = grp->gr_gid;
2045 semperm.mode = 0660;
2046 if (semctl(semkey, SEM_DF, IPC_SET, &semperm) == -1) {
2047 err(1, "[main] semctl(SEM_DF)");
2049 if (semctl(semkey, SEM_WL, IPC_SET, &semperm) == -1) {
2050 err(1, "[main] semctl(SEM_WL)");
2052 if (semctl(semkey, SEM_SIGHUP, IPC_SET, &semperm) == -1) {
2053 err(1, "[main] semctl(SEM_SIGHUP)");
2056 sema.sem_num = SEM_DF;
2059 if (semop(semkey, &sema, 1) == -1) {
2060 err(1, "[main] increment semaphore SEM_DF");
2063 sema.sem_num = SEM_WL;
2066 if (semop(semkey, &sema, 1) == -1) {
2067 err(1, "[main] increment semaphore SEM_WL");
2071 if (pid == 0) { /* part _WITH_ root privileges */
2072 /* fork another process which goes into background */
2073 if (daemonize && daemon(0, 0) != 0) {
2074 syslog(LOG_ERR, "[main] can not daemonize: %m");
2078 /* both processes are running simultaneousily */
2079 if (pid == 0) { /* child */
2080 /* this process handles .forward read requests */
2081 dotforwardhandler();
2083 } else if (pid < 0) {
2084 err(1, "[main] Fork failed!\n");
2086 } else { /* parent */
2087 /* this process writes to mailboxes if needed */
2088 write_to_local_user();
2091 } else if (pid < 0) {
2092 err(1, "Fork failed!\n");
2094 } else { /* part _WITHOUT_ root privileges */
2095 /* drop privileges */
2096 /* FIXME to user mail? */
2098 if (initgroups("nobody", pw->pw_gid) != 0)
2099 err(1, "initgroups");
2101 if (setgid(grp->gr_gid) != 0) /* set to group 'mail' */
2104 if (setgid(6) != 0) /* set to group 'mail' */
2107 if (setuid(pw->pw_uid) != 0) /* set to user 'nobody' */
2110 /* parse command line and execute main mua code */
2111 parseandexecute(argc, argv);
2113 /* release child processes */