]> git.ipfire.org Git - people/ms/dma.git/blob - dma.c
release dma 0.9
[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 "dfcompat.h"
36
37 #include <sys/param.h>
38 #include <sys/types.h>
39 #include <sys/queue.h>
40 #include <sys/stat.h>
41 #include <sys/time.h>
42 #include <sys/wait.h>
43
44 #include <dirent.h>
45 #include <err.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <inttypes.h>
49 #include <paths.h>
50 #include <pwd.h>
51 #include <signal.h>
52 #include <stdarg.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <syslog.h>
57 #include <unistd.h>
58
59 #include "dma.h"
60
61
62 static void deliver(struct qitem *);
63
64 struct aliases aliases = LIST_HEAD_INITIALIZER(aliases);
65 struct strlist tmpfs = SLIST_HEAD_INITIALIZER(tmpfs);
66 struct authusers authusers = LIST_HEAD_INITIALIZER(authusers);
67 char username[USERNAME_SIZE];
68 uid_t useruid;
69 const char *logident_base;
70 char errmsg[ERRMSG_SIZE];
71
72 static int daemonize = 1;
73 static int doqueue = 0;
74
75 struct config config = {
76 .smarthost = NULL,
77 .port = 25,
78 .aliases = "/etc/aliases",
79 .spooldir = "/var/spool/dma",
80 .authpath = NULL,
81 .certfile = NULL,
82 .features = 0,
83 .mailname = NULL,
84 .masquerade_host = NULL,
85 .masquerade_user = NULL,
86 };
87
88
89 static void
90 sighup_handler(int signo)
91 {
92 (void)signo; /* so that gcc doesn't complain */
93 }
94
95 static char *
96 set_from(struct queue *queue, const char *osender)
97 {
98 char *sender;
99
100 if (osender) {
101 sender = strdup(osender);
102 if (sender == NULL)
103 return (NULL);
104 } else if (getenv("EMAIL") != NULL) {
105 sender = strdup(getenv("EMAIL"));
106 if (sender == NULL)
107 return (NULL);
108 } else {
109 const char *from_user = username;
110 const char *from_host = hostname();
111
112 if (config.masquerade_user)
113 from_user = config.masquerade_user;
114 if (config.masquerade_host)
115 from_host = config.masquerade_host;
116 if (asprintf(&sender, "%s@%s", from_user, from_host) <= 0)
117 return (NULL);
118 }
119
120 if (strchr(sender, '\n') != NULL) {
121 errno = EINVAL;
122 return (NULL);
123 }
124
125 queue->sender = sender;
126 return (sender);
127 }
128
129 static int
130 read_aliases(void)
131 {
132 yyin = fopen(config.aliases, "r");
133 if (yyin == NULL) {
134 /*
135 * Non-existing aliases file is not a fatal error
136 */
137 if (errno == ENOENT)
138 return (0);
139 /* Other problems are. */
140 return (-1);
141 }
142 if (yyparse())
143 return (-1); /* fatal error, probably malloc() */
144 fclose(yyin);
145 return (0);
146 }
147
148 static int
149 do_alias(struct queue *queue, const char *addr)
150 {
151 struct alias *al;
152 struct stritem *sit;
153 int aliased = 0;
154
155 LIST_FOREACH(al, &aliases, next) {
156 if (strcmp(al->alias, addr) != 0)
157 continue;
158 SLIST_FOREACH(sit, &al->dests, next) {
159 if (add_recp(queue, sit->str, EXPAND_ADDR) != 0)
160 return (-1);
161 }
162 aliased = 1;
163 }
164
165 return (aliased);
166 }
167
168 int
169 add_recp(struct queue *queue, const char *str, int expand)
170 {
171 struct qitem *it, *tit;
172 struct passwd *pw;
173 char *host;
174 int aliased = 0;
175
176 it = calloc(1, sizeof(*it));
177 if (it == NULL)
178 return (-1);
179 it->addr = strdup(str);
180 if (it->addr == NULL)
181 return (-1);
182
183 it->sender = queue->sender;
184 host = strrchr(it->addr, '@');
185 if (host != NULL &&
186 (strcmp(host + 1, hostname()) == 0 ||
187 strcmp(host + 1, "localhost") == 0)) {
188 *host = 0;
189 }
190 LIST_FOREACH(tit, &queue->queue, next) {
191 /* weed out duplicate dests */
192 if (strcmp(tit->addr, it->addr) == 0) {
193 free(it->addr);
194 free(it);
195 return (0);
196 }
197 }
198 LIST_INSERT_HEAD(&queue->queue, it, next);
199 if (strrchr(it->addr, '@') == NULL) {
200 it->remote = 0;
201 if (expand) {
202 aliased = do_alias(queue, it->addr);
203 if (!aliased && expand == EXPAND_WILDCARD)
204 aliased = do_alias(queue, "*");
205 if (aliased < 0)
206 return (-1);
207 if (aliased) {
208 LIST_REMOVE(it, next);
209 } else {
210 /* Local destination, check */
211 pw = getpwnam(it->addr);
212 if (pw == NULL)
213 goto out;
214 /* XXX read .forward */
215 endpwent();
216 }
217 }
218 } else {
219 it->remote = 1;
220 }
221
222 return (0);
223
224 out:
225 free(it->addr);
226 free(it);
227 return (-1);
228 }
229
230 static struct qitem *
231 go_background(struct queue *queue)
232 {
233 struct sigaction sa;
234 struct qitem *it;
235 pid_t pid;
236
237 if (daemonize && daemon(0, 0) != 0) {
238 syslog(LOG_ERR, "can not daemonize: %m");
239 exit(1);
240 }
241 daemonize = 0;
242
243 bzero(&sa, sizeof(sa));
244 sa.sa_handler = SIG_IGN;
245 sigaction(SIGCHLD, &sa, NULL);
246
247 LIST_FOREACH(it, &queue->queue, next) {
248 /* No need to fork for the last dest */
249 if (LIST_NEXT(it, next) == NULL)
250 goto retit;
251
252 pid = fork();
253 switch (pid) {
254 case -1:
255 syslog(LOG_ERR, "can not fork: %m");
256 exit(1);
257 break;
258
259 case 0:
260 /*
261 * Child:
262 *
263 * return and deliver mail
264 */
265 retit:
266 /*
267 * If necessary, acquire the queue and * mail files.
268 * If this fails, we probably were raced by another
269 * process. It is okay to be raced if we're supposed
270 * to flush the queue.
271 */
272 setlogident("%s", it->queueid);
273 switch (acquirespool(it)) {
274 case 0:
275 break;
276 case 1:
277 if (doqueue)
278 exit(0);
279 syslog(LOG_WARNING, "could not lock queue file");
280 exit(1);
281 default:
282 exit(1);
283 }
284 dropspool(queue, it);
285 return (it);
286
287 default:
288 /*
289 * Parent:
290 *
291 * fork next child
292 */
293 break;
294 }
295 }
296
297 syslog(LOG_CRIT, "reached dead code");
298 exit(1);
299 }
300
301 static void
302 deliver(struct qitem *it)
303 {
304 int error;
305 unsigned int backoff = MIN_RETRY, slept;
306 struct timeval now;
307 struct stat st;
308
309 snprintf(errmsg, sizeof(errmsg), "unknown bounce reason");
310
311 retry:
312 syslog(LOG_INFO, "trying delivery");
313
314 if (it->remote)
315 error = deliver_remote(it);
316 else
317 error = deliver_local(it);
318
319 switch (error) {
320 case 0:
321 delqueue(it);
322 syslog(LOG_INFO, "delivery successful");
323 exit(0);
324
325 case 1:
326 if (stat(it->queuefn, &st) != 0) {
327 syslog(LOG_ERR, "lost queue file `%s'", it->queuefn);
328 exit(1);
329 }
330 if (gettimeofday(&now, NULL) == 0 &&
331 (now.tv_sec - st.st_mtim.tv_sec > MAX_TIMEOUT)) {
332 snprintf(errmsg, sizeof(errmsg),
333 "Could not deliver for the last %d seconds. Giving up.",
334 MAX_TIMEOUT);
335 goto bounce;
336 }
337 for (slept = 0; slept < backoff;) {
338 slept += SLEEP_TIMEOUT - sleep(SLEEP_TIMEOUT);
339 if (flushqueue_since(slept)) {
340 backoff = MIN_RETRY;
341 goto retry;
342 }
343 }
344 if (slept >= backoff) {
345 /* pick the next backoff between [1.5, 2.5) times backoff */
346 backoff = backoff + backoff / 2 + random() % backoff;
347 if (backoff > MAX_RETRY)
348 backoff = MAX_RETRY;
349 }
350 goto retry;
351
352 case -1:
353 default:
354 break;
355 }
356
357 bounce:
358 bounce(it, errmsg);
359 /* NOTREACHED */
360 }
361
362 void
363 run_queue(struct queue *queue)
364 {
365 struct qitem *it;
366
367 if (LIST_EMPTY(&queue->queue))
368 return;
369
370 it = go_background(queue);
371 deliver(it);
372 /* NOTREACHED */
373 }
374
375 static void
376 show_queue(struct queue *queue)
377 {
378 struct qitem *it;
379 int locked = 0; /* XXX */
380
381 if (LIST_EMPTY(&queue->queue)) {
382 printf("Mail queue is empty\n");
383 return;
384 }
385
386 LIST_FOREACH(it, &queue->queue, next) {
387 printf("ID\t: %s%s\n"
388 "From\t: %s\n"
389 "To\t: %s\n",
390 it->queueid,
391 locked ? "*" : "",
392 it->sender, it->addr);
393
394 if (LIST_NEXT(it, next) != NULL)
395 printf("--\n");
396 }
397 }
398
399 /*
400 * TODO:
401 *
402 * - alias processing
403 * - use group permissions
404 * - proper sysexit codes
405 */
406
407 int
408 main(int argc, char **argv)
409 {
410 struct sigaction act;
411 char *sender = NULL;
412 struct queue queue;
413 int i, ch;
414 int nodot = 0, showq = 0, queue_only = 0;
415 int recp_from_header = 0;
416
417 set_username();
418
419 /*
420 * We never run as root. If called by root, drop permissions
421 * to the mail user.
422 */
423 if (geteuid() == 0 || getuid() == 0) {
424 struct passwd *pw;
425
426 errno = 0;
427 pw = getpwnam(DMA_ROOT_USER);
428 if (pw == NULL) {
429 if (errno == 0)
430 errx(1, "user '%s' not found", DMA_ROOT_USER);
431 else
432 err(1, "cannot drop root privileges");
433 }
434
435 if (setuid(pw->pw_uid) != 0)
436 err(1, "cannot drop root privileges");
437
438 if (geteuid() == 0 || getuid() == 0)
439 errx(1, "cannot drop root privileges");
440 }
441
442 atexit(deltmp);
443 init_random();
444
445 bzero(&queue, sizeof(queue));
446 LIST_INIT(&queue.queue);
447
448 if (strcmp(argv[0], "mailq") == 0) {
449 argv++; argc--;
450 showq = 1;
451 if (argc != 0)
452 errx(1, "invalid arguments");
453 goto skipopts;
454 }
455
456 opterr = 0;
457 while ((ch = getopt(argc, argv, ":A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:tUV:vX:")) != -1) {
458 switch (ch) {
459 case 'A':
460 /* -AX is being ignored, except for -A{c,m} */
461 if (optarg[0] == 'c' || optarg[0] == 'm') {
462 break;
463 }
464 /* else FALLTRHOUGH */
465 case 'b':
466 /* -bX is being ignored, except for -bp */
467 if (optarg[0] == 'p') {
468 showq = 1;
469 break;
470 } else if (optarg[0] == 'q') {
471 queue_only = 1;
472 break;
473 }
474 /* else FALLTRHOUGH */
475 case 'D':
476 daemonize = 0;
477 break;
478 case 'L':
479 logident_base = optarg;
480 break;
481 case 'f':
482 case 'r':
483 sender = optarg;
484 break;
485
486 case 't':
487 recp_from_header = 1;
488 break;
489
490 case 'o':
491 /* -oX is being ignored, except for -oi */
492 if (optarg[0] != 'i')
493 break;
494 /* else FALLTRHOUGH */
495 case 'O':
496 break;
497 case 'i':
498 nodot = 1;
499 break;
500
501 case 'q':
502 /* Don't let getopt slup up other arguments */
503 if (optarg && *optarg == '-')
504 optind--;
505 doqueue = 1;
506 break;
507
508 /* Ignored options */
509 case 'B':
510 case 'C':
511 case 'd':
512 case 'F':
513 case 'h':
514 case 'N':
515 case 'n':
516 case 'R':
517 case 'U':
518 case 'V':
519 case 'v':
520 case 'X':
521 break;
522
523 case ':':
524 if (optopt == 'q') {
525 doqueue = 1;
526 break;
527 }
528 /* FALLTHROUGH */
529
530 default:
531 fprintf(stderr, "invalid argument: `-%c'\n", optopt);
532 exit(1);
533 }
534 }
535 argc -= optind;
536 argv += optind;
537 opterr = 1;
538
539 if (argc != 0 && (showq || doqueue))
540 errx(1, "sending mail and queue operations are mutually exclusive");
541
542 if (showq + doqueue > 1)
543 errx(1, "conflicting queue operations");
544
545 skipopts:
546 if (logident_base == NULL)
547 logident_base = "dma";
548 setlogident(NULL);
549
550 act.sa_handler = sighup_handler;
551 act.sa_flags = 0;
552 sigemptyset(&act.sa_mask);
553 if (sigaction(SIGHUP, &act, NULL) != 0)
554 syslog(LOG_WARNING, "can not set signal handler: %m");
555
556 parse_conf(CONF_PATH "/dma.conf");
557
558 if (config.authpath != NULL)
559 parse_authfile(config.authpath);
560
561 if (showq) {
562 if (load_queue(&queue) < 0)
563 errlog(1, "can not load queue");
564 show_queue(&queue);
565 return (0);
566 }
567
568 if (doqueue) {
569 flushqueue_signal();
570 if (load_queue(&queue) < 0)
571 errlog(1, "can not load queue");
572 run_queue(&queue);
573 return (0);
574 }
575
576 if (read_aliases() != 0)
577 errlog(1, "can not read aliases file `%s'", config.aliases);
578
579 if ((sender = set_from(&queue, sender)) == NULL)
580 errlog(1, NULL);
581
582 if (newspoolf(&queue) != 0)
583 errlog(1, "can not create temp file in `%s'", config.spooldir);
584
585 setlogident("%s", queue.id);
586
587 for (i = 0; i < argc; i++) {
588 if (add_recp(&queue, argv[i], EXPAND_WILDCARD) != 0)
589 errlogx(1, "invalid recipient `%s'", argv[i]);
590 }
591
592 if (LIST_EMPTY(&queue.queue) && !recp_from_header)
593 errlogx(1, "no recipients");
594
595 if (readmail(&queue, nodot, recp_from_header) != 0)
596 errlog(1, "can not read mail");
597
598 if (LIST_EMPTY(&queue.queue))
599 errlogx(1, "no recipients");
600
601 if (linkspool(&queue) != 0)
602 errlog(1, "can not create spools");
603
604 /* From here on the mail is safe. */
605
606 if (config.features & DEFER || queue_only)
607 return (0);
608
609 run_queue(&queue);
610
611 /* NOTREACHED */
612 return (0);
613 }