]> git.ipfire.org Git - people/ms/dma.git/blob - dma.c
cc4f60be19a644a60bd48e22578c93057c2263a4
[people/ms/dma.git] / dma.c
1 /*
2 * Copyright (c) 2008 The DragonFly Project. All rights reserved.
3 *
4 * This code is derived from software contributed to The DragonFly Project
5 * by Simon 'corecode' Schubert <corecode@fs.ei.tum.de>.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
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
16 * distribution.
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.
20 *
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
32 * SUCH DAMAGE.
33 */
34
35 #include <sys/param.h>
36 #include <sys/queue.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40
41 #include <dirent.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <inttypes.h>
46 #include <netdb.h>
47 #include <paths.h>
48 #include <pwd.h>
49 #include <signal.h>
50 #include <stdarg.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <syslog.h>
55 #include <unistd.h>
56
57 #include "dma.h"
58
59
60
61 static void deliver(struct qitem *);
62
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;
68 const char *username;
69
70 static int daemonize = 1;
71 static const char *logident_base;
72
73 const char *
74 hostname(void)
75 {
76 static char name[MAXHOSTNAMELEN+1];
77 int initialized = 0;
78 FILE *fp;
79 size_t len;
80
81 if (initialized)
82 return (name);
83
84 if (config->mailname != NULL && config->mailname[0] != '\0') {
85 snprintf(name, sizeof(name), "%s", config->mailname);
86 initialized = 1;
87 return (name);
88 }
89 if (config->mailnamefile != NULL && config->mailnamefile[0] != '\0') {
90 fp = fopen(config->mailnamefile, "r");
91 if (fp != NULL) {
92 if (fgets(name, sizeof(name), fp) != NULL) {
93 len = strlen(name);
94 while (len > 0 &&
95 (name[len - 1] == '\r' ||
96 name[len - 1] == '\n'))
97 name[--len] = '\0';
98 if (name[0] != '\0') {
99 initialized = 1;
100 return (name);
101 }
102 }
103 fclose(fp);
104 }
105 }
106 if (gethostname(name, sizeof(name)) != 0)
107 strcpy(name, "(unknown hostname)");
108 initialized = 1;
109 return name;
110 }
111
112 static void
113 setlogident(const char *fmt, ...)
114 {
115 char *tag = NULL;
116
117 if (fmt != NULL) {
118 va_list ap;
119 char *sufx;
120
121 va_start(ap, fmt);
122 vasprintf(&sufx, fmt, ap);
123 if (sufx != NULL) {
124 asprintf(&tag, "%s[%s]", logident_base, sufx);
125 free(sufx);
126 }
127 va_end(ap);
128 }
129 closelog();
130 openlog(tag != NULL ? tag : logident_base, 0, LOG_MAIL);
131 }
132
133 static const char *
134 check_username(const char *name, uid_t ckuid)
135 {
136 struct passwd *pwd;
137
138 if (name == NULL)
139 return (NULL);
140 pwd = getpwnam(name);
141 if (pwd == NULL || pwd->pw_uid != ckuid)
142 return (NULL);
143 return (name);
144 }
145
146 static void
147 set_username(void)
148 {
149 struct passwd *pwd;
150 char *u = NULL;
151 uid_t uid;
152
153 uid = getuid();
154 username = check_username(getlogin(), uid);
155 if (username != NULL)
156 return;
157 username = check_username(getenv("LOGNAME"), uid);
158 if (username != NULL)
159 return;
160 username = check_username(getenv("USER"), uid);
161 if (username != NULL)
162 return;
163 pwd = getpwuid(uid);
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)
168 return;
169 else
170 free(u);
171 }
172 asprintf(__DECONST(void *, &username), "%ld", (long)uid);
173 if (username != NULL)
174 return;
175 username = "unknown-or-invalid-username";
176 }
177
178 static char *
179 set_from(const char *osender)
180 {
181 struct virtuser *v;
182 char *sender;
183
184 if ((config->features & VIRTUAL) != 0) {
185 SLIST_FOREACH(v, &virtusers, next) {
186 if (strcmp(v->login, username) == 0) {
187 sender = strdup(v->address);
188 if (sender == NULL)
189 return(NULL);
190 goto out;
191 }
192 }
193 }
194
195 if (osender) {
196 sender = strdup(osender);
197 if (sender == NULL)
198 return (NULL);
199 } else {
200 if (asprintf(&sender, "%s@%s", username, hostname()) <= 0)
201 return (NULL);
202 }
203
204 if (strchr(sender, '\n') != NULL) {
205 errno = EINVAL;
206 return (NULL);
207 }
208
209 out:
210 return (sender);
211 }
212
213 static int
214 read_aliases(void)
215 {
216 yyin = fopen(config->aliases, "r");
217 if (yyin == NULL)
218 return (0); /* not fatal */
219 if (yyparse())
220 return (-1); /* fatal error, probably malloc() */
221 fclose(yyin);
222 return (0);
223 }
224
225 int
226 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
227 {
228 struct qitem *it, *tit;
229 struct stritem *sit;
230 struct alias *al;
231 struct passwd *pw;
232 char *host;
233 int aliased = 0;
234
235 it = calloc(1, sizeof(*it));
236 if (it == NULL)
237 return (-1);
238 it->addr = strdup(str);
239 if (it->addr == NULL)
240 return (-1);
241
242 it->sender = sender;
243 host = strrchr(it->addr, '@');
244 if (host != NULL &&
245 (strcmp(host + 1, hostname()) == 0 ||
246 strcmp(host + 1, "localhost") == 0)) {
247 *host = 0;
248 }
249 LIST_FOREACH(tit, &queue->queue, next) {
250 /* weed out duplicate dests */
251 if (strcmp(tit->addr, it->addr) == 0) {
252 free(it->addr);
253 free(it);
254 return (0);
255 }
256 }
257 LIST_INSERT_HEAD(&queue->queue, it, next);
258 if (strrchr(it->addr, '@') == NULL) {
259 it->remote = 0;
260 if (expand) {
261 LIST_FOREACH(al, &aliases, next) {
262 if (strcmp(al->alias, it->addr) != 0)
263 continue;
264 SLIST_FOREACH(sit, &al->dests, next) {
265 if (add_recp(queue, sit->str, sender, 1) != 0)
266 return (-1);
267 }
268 aliased = 1;
269 }
270 if (aliased) {
271 LIST_REMOVE(it, next);
272 } else {
273 /* Local destination, check */
274 pw = getpwnam(it->addr);
275 if (pw == NULL)
276 goto out;
277 /* XXX read .forward */
278 endpwent();
279 }
280 }
281 } else {
282 it->remote = 1;
283 }
284
285 return (0);
286
287 out:
288 free(it->addr);
289 free(it);
290 return (-1);
291 }
292
293 static void
294 deltmp(void)
295 {
296 struct stritem *t;
297
298 SLIST_FOREACH(t, &tmpfs, next) {
299 unlink(t->str);
300 }
301 }
302
303 int
304 open_locked(const char *fname, int flags, ...)
305 {
306 int mode = 0;
307
308 if (flags & O_CREAT) {
309 va_list ap;
310 va_start(ap, flags);
311 mode = va_arg(ap, int);
312 va_end(ap);
313 }
314
315 #ifndef O_EXLOCK
316 int fd, save_errno;
317
318 fd = open(fname, flags, mode);
319 if (fd < 0)
320 return(fd);
321 if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) {
322 save_errno = errno;
323 close(fd);
324 errno = save_errno;
325 return(-1);
326 }
327 return(fd);
328 #else
329 return(open(fname, flags|O_EXLOCK, mode));
330 #endif
331 }
332
333 static char *
334 rfc822date(void)
335 {
336 static char str[50];
337 size_t error;
338 time_t now;
339
340 now = time(NULL);
341 error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z",
342 localtime(&now));
343 if (error == 0)
344 strcpy(str, "(date fail)");
345 return (str);
346 }
347
348 static int
349 strprefixcmp(const char *str, const char *prefix)
350 {
351 return (strncasecmp(str, prefix, strlen(prefix)));
352 }
353
354 static int
355 readmail(struct queue *queue, const char *sender, int nodot)
356 {
357 char line[1000]; /* by RFC2822 */
358 size_t linelen;
359 size_t error;
360 int had_headers = 0;
361 int had_from = 0;
362 int had_messagid = 0;
363 int had_date = 0;
364
365 error = fprintf(queue->mailf,
366 "Received: from %s (uid %d)\n"
367 "\t(envelope-from %s)\n"
368 "\tid %s\n"
369 "\tby %s (%s)\n"
370 "\t%s\n",
371 username, getuid(),
372 sender,
373 queue->id,
374 hostname(), VERSION,
375 rfc822date());
376 if ((ssize_t)error < 0)
377 return (-1);
378
379 while (!feof(stdin)) {
380 if (fgets(line, sizeof(line), stdin) == NULL)
381 break;
382 linelen = strlen(line);
383 if (linelen == 0 || line[linelen - 1] != '\n') {
384 errno = EINVAL; /* XXX mark permanent errors */
385 return (-1);
386 }
387 if (!had_headers) {
388 if (strprefixcmp(line, "Date:") == 0)
389 had_date = 1;
390 else if (strprefixcmp(line, "Message-Id:") == 0)
391 had_messagid = 1;
392 else if (strprefixcmp(line, "From:") == 0)
393 had_from = 1;
394 }
395 if (strcmp(line, "\n") == 0 && !had_headers) {
396 had_headers = 1;
397 while (!had_date || !had_messagid || !had_from) {
398 if (!had_date) {
399 had_date = 1;
400 snprintf(line, sizeof(line), "Date: %s\n", rfc822date());
401 } else if (!had_messagid) {
402 /* XXX better msgid, assign earlier and log? */
403 had_messagid = 1;
404 snprintf(line, sizeof(line), "Message-Id: <%s@%s>\n",
405 queue->id, hostname());
406 } else if (!had_from) {
407 had_from = 1;
408 snprintf(line, sizeof(line), "From: <%s>\n", sender);
409 }
410 if (fwrite(line, strlen(line), 1, queue->mailf) != 1)
411 return (-1);
412 }
413 strcpy(line, "\n");
414 }
415 if (!nodot && linelen == 2 && line[0] == '.')
416 break;
417 if (fwrite(line, strlen(line), 1, queue->mailf) != 1)
418 return (-1);
419 }
420
421 return (0);
422 }
423
424 static struct qitem *
425 go_background(struct queue *queue)
426 {
427 struct sigaction sa;
428 struct qitem *it;
429 pid_t pid;
430
431 if (daemonize && daemon(0, 0) != 0) {
432 syslog(LOG_ERR, "can not daemonize: %m");
433 exit(1);
434 }
435 daemonize = 0;
436
437 bzero(&sa, sizeof(sa));
438 sa.sa_flags = SA_NOCLDWAIT;
439 sa.sa_handler = SIG_IGN;
440 sigaction(SIGCHLD, &sa, NULL);
441
442 LIST_FOREACH(it, &queue->queue, next) {
443 /* No need to fork for the last dest */
444 if (LIST_NEXT(it, next) == NULL)
445 goto retit;
446
447 pid = fork();
448 switch (pid) {
449 case -1:
450 syslog(LOG_ERR, "can not fork: %m");
451 exit(1);
452 break;
453
454 case 0:
455 /*
456 * Child:
457 *
458 * return and deliver mail
459 */
460 retit:
461 /*
462 * If necessary, aquire the queue and * mail files.
463 * If this fails, we probably were raced by another
464 * process.
465 */
466 setlogident("%s", it->queueid);
467 if (aquirespool(it) < 0)
468 exit(1);
469 dropspool(queue, it);
470 return (it);
471
472 default:
473 /*
474 * Parent:
475 *
476 * fork next child
477 */
478 break;
479 }
480 }
481
482 syslog(LOG_CRIT, "reached dead code");
483 exit(1);
484 }
485
486 static void
487 bounce(struct qitem *it, const char *reason)
488 {
489 struct queue bounceq;
490 struct qitem *bit;
491 char line[1000];
492 size_t pos;
493 int error;
494
495 /* Don't bounce bounced mails */
496 if (it->sender[0] == 0) {
497 syslog(LOG_INFO, "can not bounce a bounce message, discarding");
498 exit(1);
499 }
500
501 LIST_INIT(&bounceq.queue);
502 if (newspoolf(&bounceq, "") != 0)
503 goto fail;
504
505 syslog(LOG_ERR, "delivery failed, bouncing as %s", bounceq.id);
506 setlogident("%s", bounceq.id);
507
508 error = fprintf(bounceq.mailf,
509 "Received: from MAILER-DAEMON\n"
510 "\tid %s\n"
511 "\tby %s (%s)\n"
512 "\t%s\n"
513 "X-Original-To: <%s>\n"
514 "From: MAILER-DAEMON <>\n"
515 "To: %s\n"
516 "Subject: Mail delivery failed\n"
517 "Message-Id: <%s@%s>\n"
518 "Date: %s\n"
519 "\n"
520 "This is the %s at %s.\n"
521 "\n"
522 "There was an error delivering your mail to <%s>.\n"
523 "\n"
524 "%s\n"
525 "\n"
526 "%s\n"
527 "\n",
528 bounceq.id,
529 hostname(), VERSION,
530 rfc822date(),
531 it->addr,
532 it->sender,
533 bounceq.id, hostname(),
534 rfc822date(),
535 VERSION, hostname(),
536 it->addr,
537 reason,
538 config->features & FULLBOUNCE ?
539 "Original message follows." :
540 "Message headers follow.");
541 if (error < 0)
542 goto fail;
543
544 if (add_recp(&bounceq, it->sender, "", 1) != 0)
545 goto fail;
546
547 if (fseek(it->mailf, it->hdrlen, SEEK_SET) != 0)
548 goto fail;
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)
552 goto fail;
553 }
554 } else {
555 while (!feof(it->mailf)) {
556 if (fgets(line, sizeof(line), it->mailf) == NULL)
557 break;
558 if (line[0] == '\n')
559 break;
560 if (fwrite(line, strlen(line), 1, bounceq.mailf) != 1)
561 goto fail;
562 }
563 }
564
565 if (linkspool(&bounceq, "MAILER-DAEMON") != 0)
566 goto fail;
567 /* bounce is safe */
568
569 delqueue(it);
570
571 bit = go_background(&bounceq);
572 deliver(bit);
573 /* NOTREACHED */
574
575 fail:
576 syslog(LOG_CRIT, "error creating bounce: %m");
577 delqueue(it);
578 exit(1);
579 }
580
581 static void
582 deliver(struct qitem *it)
583 {
584 int error;
585 unsigned int backoff = MIN_RETRY;
586 const char *errmsg = "unknown bounce reason";
587 struct timeval now;
588 struct stat st;
589
590 retry:
591 syslog(LOG_INFO, "trying delivery");
592
593 if (it->remote)
594 error = deliver_remote(it, &errmsg);
595 else
596 error = deliver_local(it, &errmsg);
597
598 switch (error) {
599 case 0:
600 delqueue(it);
601 syslog(LOG_INFO, "delivery successful");
602 exit(0);
603
604 case 1:
605 if (stat(it->queuefn, &st) != 0) {
606 syslog(LOG_ERR, "lost queue file `%s'", it->queuefn);
607 exit(1);
608 }
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.",
613 MAX_TIMEOUT);
614 goto bounce;
615 }
616 sleep(backoff);
617 backoff *= 2;
618 if (backoff > MAX_RETRY)
619 backoff = MAX_RETRY;
620 goto retry;
621
622 case -1:
623 default:
624 break;
625 }
626
627 bounce:
628 bounce(it, errmsg);
629 /* NOTREACHED */
630 }
631
632 static void
633 run_queue(struct queue *queue)
634 {
635 struct qitem *it;
636
637 if (LIST_EMPTY(&queue->queue))
638 return;
639
640 it = go_background(queue);
641 deliver(it);
642 /* NOTREACHED */
643 }
644
645 static void
646 show_queue(struct queue *queue)
647 {
648 struct qitem *it;
649 int locked = 0; /* XXX */
650
651 if (LIST_EMPTY(&queue->queue)) {
652 printf("Mail queue is empty\n");
653 return;
654 }
655
656 LIST_FOREACH(it, &queue->queue, next) {
657 printf("ID\t: %s%s\n"
658 "From\t: %s\n"
659 "To\t: %s\n"
660 "--\n",
661 it->queueid,
662 locked ? "*" : "",
663 it->sender, it->addr);
664 }
665 }
666
667 /*
668 * TODO:
669 *
670 * - alias processing
671 * - use group permissions
672 * - proper sysexit codes
673 */
674
675 int
676 main(int argc, char **argv)
677 {
678 char *sender = NULL;
679 struct qitem *it;
680 struct queue queue;
681 struct queue lqueue;
682 int i, ch;
683 int nodot = 0, doqueue = 0, showq = 0;
684
685 atexit(deltmp);
686 LIST_INIT(&queue.queue);
687
688 if (strcmp(argv[0], "mailq") == 0) {
689 argv++; argc--;
690 showq = 1;
691 if (argc != 0)
692 errx(1, "invalid arguments");
693 goto skipopts;
694 }
695
696 opterr = 0;
697 while ((ch = getopt(argc, argv, "A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
698 switch (ch) {
699 case 'A':
700 /* -AX is being ignored, except for -A{c,m} */
701 if (optarg[0] == 'c' || optarg[0] == 'm') {
702 break;
703 }
704 /* else FALLTRHOUGH */
705 case 'b':
706 /* -bX is being ignored, except for -bp */
707 if (optarg[0] == 'p') {
708 showq = 1;
709 break;
710 }
711 /* else FALLTRHOUGH */
712 case 'D':
713 daemonize = 0;
714 break;
715 case 'L':
716 logident_base = optarg;
717 break;
718 case 'f':
719 case 'r':
720 sender = optarg;
721 break;
722
723 case 'o':
724 /* -oX is being ignored, except for -oi */
725 if (optarg[0] != 'i')
726 break;
727 /* else FALLTRHOUGH */
728 case 'O':
729 break;
730 case 'i':
731 nodot = 1;
732 break;
733
734 case 'q':
735 doqueue = 1;
736 break;
737
738 /* Ignored options */
739 case 'B':
740 case 'C':
741 case 'd':
742 case 'F':
743 case 'h':
744 case 'N':
745 case 'n':
746 case 'R':
747 case 'U':
748 case 'V':
749 case 'v':
750 case 'X':
751 break;
752
753 default:
754 exit(1);
755 }
756 }
757 argc -= optind;
758 argv += optind;
759 opterr = 1;
760
761 if (argc != 0 && (showq || doqueue))
762 errx(1, "sending mail and queue operations are mutually exclusive");
763
764 if (showq + doqueue > 1)
765 errx(1, "conflicting queue operations");
766
767 skipopts:
768 if (logident_base == NULL)
769 logident_base = "dma";
770 setlogident(NULL);
771 set_username();
772
773 /* XXX fork root here */
774
775 config = calloc(1, sizeof(*config));
776 if (config == NULL)
777 err(1, NULL);
778
779 if (parse_conf(CONF_PATH) < 0) {
780 free(config);
781 err(1, "can not read config file");
782 }
783
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);
788
789 if (parse_authfile(config->authpath) < 0)
790 err(1, "can not read SMTP authentication file");
791
792 if (showq) {
793 load_queue(&lqueue);
794 show_queue(&lqueue);
795 return (0);
796 }
797
798 if (doqueue) {
799 load_queue(&lqueue);
800 run_queue(&lqueue);
801 return (0);
802 }
803
804 if (read_aliases() != 0)
805 err(1, "can not read aliases file `%s'", config->aliases);
806
807 if ((sender = set_from(sender)) == NULL)
808 err(1, NULL);
809
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]);
813 }
814
815 if (LIST_EMPTY(&queue.queue))
816 errx(1, "no recipients");
817
818 if (newspoolf(&queue, sender) != 0)
819 err(1, "can not create temp file");
820
821 setlogident("%s", queue.id);
822
823 if (readmail(&queue, sender, nodot) != 0)
824 err(1, "can not read mail");
825
826 if (linkspool(&queue, sender) != 0)
827 err(1, "can not create spools");
828
829 /* From here on the mail is safe. */
830
831 if (config->features & DEFER)
832 return (0);
833
834 it = go_background(&queue);
835 deliver(it);
836
837 /* NOTREACHED */
838 return (0);
839 }