]> git.ipfire.org Git - people/ms/dma.git/blob - dma.c
implement queue flushing prod
[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 pw = getpwnam(DMA_ROOT_USER);
427 if (pw == NULL)
428 err(1, "cannot drop root privileges");
429
430 if (setuid(pw->pw_uid) != 0)
431 err(1, "cannot drop root privileges");
432
433 if (geteuid() == 0 || getuid() == 0)
434 errx(1, "cannot drop root privileges");
435 }
436
437 atexit(deltmp);
438 init_random();
439
440 bzero(&queue, sizeof(queue));
441 LIST_INIT(&queue.queue);
442
443 if (strcmp(argv[0], "mailq") == 0) {
444 argv++; argc--;
445 showq = 1;
446 if (argc != 0)
447 errx(1, "invalid arguments");
448 goto skipopts;
449 }
450
451 opterr = 0;
452 while ((ch = getopt(argc, argv, ":A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:tUV:vX:")) != -1) {
453 switch (ch) {
454 case 'A':
455 /* -AX is being ignored, except for -A{c,m} */
456 if (optarg[0] == 'c' || optarg[0] == 'm') {
457 break;
458 }
459 /* else FALLTRHOUGH */
460 case 'b':
461 /* -bX is being ignored, except for -bp */
462 if (optarg[0] == 'p') {
463 showq = 1;
464 break;
465 } else if (optarg[0] == 'q') {
466 queue_only = 1;
467 break;
468 }
469 /* else FALLTRHOUGH */
470 case 'D':
471 daemonize = 0;
472 break;
473 case 'L':
474 logident_base = optarg;
475 break;
476 case 'f':
477 case 'r':
478 sender = optarg;
479 break;
480
481 case 't':
482 recp_from_header = 1;
483 break;
484
485 case 'o':
486 /* -oX is being ignored, except for -oi */
487 if (optarg[0] != 'i')
488 break;
489 /* else FALLTRHOUGH */
490 case 'O':
491 break;
492 case 'i':
493 nodot = 1;
494 break;
495
496 case 'q':
497 /* Don't let getopt slup up other arguments */
498 if (optarg && *optarg == '-')
499 optind--;
500 doqueue = 1;
501 break;
502
503 /* Ignored options */
504 case 'B':
505 case 'C':
506 case 'd':
507 case 'F':
508 case 'h':
509 case 'N':
510 case 'n':
511 case 'R':
512 case 'U':
513 case 'V':
514 case 'v':
515 case 'X':
516 break;
517
518 case ':':
519 if (optopt == 'q') {
520 doqueue = 1;
521 break;
522 }
523 /* FALLTHROUGH */
524
525 default:
526 fprintf(stderr, "invalid argument: `-%c'\n", optopt);
527 exit(1);
528 }
529 }
530 argc -= optind;
531 argv += optind;
532 opterr = 1;
533
534 if (argc != 0 && (showq || doqueue))
535 errx(1, "sending mail and queue operations are mutually exclusive");
536
537 if (showq + doqueue > 1)
538 errx(1, "conflicting queue operations");
539
540 skipopts:
541 if (logident_base == NULL)
542 logident_base = "dma";
543 setlogident(NULL);
544
545 act.sa_handler = sighup_handler;
546 act.sa_flags = 0;
547 sigemptyset(&act.sa_mask);
548 if (sigaction(SIGHUP, &act, NULL) != 0)
549 syslog(LOG_WARNING, "can not set signal handler: %m");
550
551 parse_conf(CONF_PATH "/dma.conf");
552
553 if (config.authpath != NULL)
554 parse_authfile(config.authpath);
555
556 if (showq) {
557 if (load_queue(&queue) < 0)
558 errlog(1, "can not load queue");
559 show_queue(&queue);
560 return (0);
561 }
562
563 if (doqueue) {
564 flushqueue_signal();
565 if (load_queue(&queue) < 0)
566 errlog(1, "can not load queue");
567 run_queue(&queue);
568 return (0);
569 }
570
571 if (read_aliases() != 0)
572 errlog(1, "can not read aliases file `%s'", config.aliases);
573
574 if ((sender = set_from(&queue, sender)) == NULL)
575 errlog(1, NULL);
576
577 if (newspoolf(&queue) != 0)
578 errlog(1, "can not create temp file");
579
580 setlogident("%s", queue.id);
581
582 for (i = 0; i < argc; i++) {
583 if (add_recp(&queue, argv[i], EXPAND_WILDCARD) != 0)
584 errlogx(1, "invalid recipient `%s'", argv[i]);
585 }
586
587 if (LIST_EMPTY(&queue.queue) && !recp_from_header)
588 errlogx(1, "no recipients");
589
590 if (readmail(&queue, nodot, recp_from_header) != 0)
591 errlog(1, "can not read mail");
592
593 if (LIST_EMPTY(&queue.queue))
594 errlogx(1, "no recipients");
595
596 if (linkspool(&queue) != 0)
597 errlog(1, "can not create spools");
598
599 /* From here on the mail is safe. */
600
601 if (config.features & DEFER || queue_only)
602 return (0);
603
604 run_queue(&queue);
605
606 /* NOTREACHED */
607 return (0);
608 }