d1f2493abeb21968d54ea417d1baed740e4d3ced
[dragonfly.git] / libexec / dma / 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 <paths.h>
47 #include <pwd.h>
48 #include <signal.h>
49 #include <stdarg.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <syslog.h>
54 #include <unistd.h>
55
56 #include "dma.h"
57
58
59
60 static void deliver(struct qitem *);
61
62 struct aliases aliases = LIST_HEAD_INITIALIZER(aliases);
63 struct strlist tmpfs = SLIST_HEAD_INITIALIZER(tmpfs);
64 struct virtusers virtusers = LIST_HEAD_INITIALIZER(virtusers);
65 struct authusers authusers = LIST_HEAD_INITIALIZER(authusers);
66 struct config *config;
67 const char *username;
68 const char *logident_base;
69
70 static int daemonize = 1;
71
72 static char *
73 set_from(const char *osender)
74 {
75         struct virtuser *v;
76         char *sender;
77
78         if ((config->features & VIRTUAL) != 0) {
79                 SLIST_FOREACH(v, &virtusers, next) {
80                         if (strcmp(v->login, username) == 0) {
81                                 sender = strdup(v->address);
82                                 if (sender == NULL)
83                                         return(NULL);
84                                 goto out;
85                         }
86                 }
87         }
88
89         if (osender) {
90                 sender = strdup(osender);
91                 if (sender == NULL)
92                         return (NULL);
93         } else {
94                 if (asprintf(&sender, "%s@%s", username, hostname()) <= 0)
95                         return (NULL);
96         }
97
98         if (strchr(sender, '\n') != NULL) {
99                 errno = EINVAL;
100                 return (NULL);
101         }
102
103 out:
104         return (sender);
105 }
106
107 static int
108 read_aliases(void)
109 {
110         yyin = fopen(config->aliases, "r");
111         if (yyin == NULL)
112                 return (0);     /* not fatal */
113         if (yyparse())
114                 return (-1);    /* fatal error, probably malloc() */
115         fclose(yyin);
116         return (0);
117 }
118
119 int
120 add_recp(struct queue *queue, const char *str, const char *sender, int expand)
121 {
122         struct qitem *it, *tit;
123         struct stritem *sit;
124         struct alias *al;
125         struct passwd *pw;
126         char *host;
127         int aliased = 0;
128
129         it = calloc(1, sizeof(*it));
130         if (it == NULL)
131                 return (-1);
132         it->addr = strdup(str);
133         if (it->addr == NULL)
134                 return (-1);
135
136         it->sender = sender;
137         host = strrchr(it->addr, '@');
138         if (host != NULL &&
139             (strcmp(host + 1, hostname()) == 0 ||
140              strcmp(host + 1, "localhost") == 0)) {
141                 *host = 0;
142         }
143         LIST_FOREACH(tit, &queue->queue, next) {
144                 /* weed out duplicate dests */
145                 if (strcmp(tit->addr, it->addr) == 0) {
146                         free(it->addr);
147                         free(it);
148                         return (0);
149                 }
150         }
151         LIST_INSERT_HEAD(&queue->queue, it, next);
152         if (strrchr(it->addr, '@') == NULL) {
153                 it->remote = 0;
154                 if (expand) {
155                         LIST_FOREACH(al, &aliases, next) {
156                                 if (strcmp(al->alias, it->addr) != 0)
157                                         continue;
158                                 SLIST_FOREACH(sit, &al->dests, next) {
159                                         if (add_recp(queue, sit->str, sender, 1) != 0)
160                                                 return (-1);
161                                 }
162                                 aliased = 1;
163                         }
164                         if (aliased) {
165                                 LIST_REMOVE(it, next);
166                         } else {
167                                 /* Local destination, check */
168                                 pw = getpwnam(it->addr);
169                                 if (pw == NULL)
170                                         goto out;
171                                 /* XXX read .forward */
172                                 endpwent();
173                         }
174                 }
175         } else {
176                 it->remote = 1;
177         }
178
179         return (0);
180
181 out:
182         free(it->addr);
183         free(it);
184         return (-1);
185 }
186
187 static struct qitem *
188 go_background(struct queue *queue)
189 {
190         struct sigaction sa;
191         struct qitem *it;
192         pid_t pid;
193
194         if (daemonize && daemon(0, 0) != 0) {
195                 syslog(LOG_ERR, "can not daemonize: %m");
196                 exit(1);
197         }
198         daemonize = 0;
199
200         bzero(&sa, sizeof(sa));
201         sa.sa_flags = SA_NOCLDWAIT;
202         sa.sa_handler = SIG_IGN;
203         sigaction(SIGCHLD, &sa, NULL);
204
205         LIST_FOREACH(it, &queue->queue, next) {
206                 /* No need to fork for the last dest */
207                 if (LIST_NEXT(it, next) == NULL)
208                         goto retit;
209
210                 pid = fork();
211                 switch (pid) {
212                 case -1:
213                         syslog(LOG_ERR, "can not fork: %m");
214                         exit(1);
215                         break;
216
217                 case 0:
218                         /*
219                          * Child:
220                          *
221                          * return and deliver mail
222                          */
223 retit:
224                         /*
225                          * If necessary, aquire the queue and * mail files.
226                          * If this fails, we probably were raced by another
227                          * process.
228                          */
229                         setlogident("%s", it->queueid);
230                         if (aquirespool(it) < 0)
231                                 exit(1);
232                         dropspool(queue, it);
233                         return (it);
234
235                 default:
236                         /*
237                          * Parent:
238                          *
239                          * fork next child
240                          */
241                         break;
242                 }
243         }
244
245         syslog(LOG_CRIT, "reached dead code");
246         exit(1);
247 }
248
249 static void
250 deliver(struct qitem *it)
251 {
252         int error;
253         unsigned int backoff = MIN_RETRY;
254         const char *errmsg = "unknown bounce reason";
255         struct timeval now;
256         struct stat st;
257
258 retry:
259         syslog(LOG_INFO, "trying delivery");
260
261         if (it->remote)
262                 error = deliver_remote(it, &errmsg);
263         else
264                 error = deliver_local(it, &errmsg);
265
266         switch (error) {
267         case 0:
268                 delqueue(it);
269                 syslog(LOG_INFO, "delivery successful");
270                 exit(0);
271
272         case 1:
273                 if (stat(it->queuefn, &st) != 0) {
274                         syslog(LOG_ERR, "lost queue file `%s'", it->queuefn);
275                         exit(1);
276                 }
277                 if (gettimeofday(&now, NULL) == 0 &&
278                     (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
279                         asprintf(__DECONST(void *, &errmsg),
280                                  "Could not deliver for the last %d seconds. Giving up.",
281                                  MAX_TIMEOUT);
282                         goto bounce;
283                 }
284                 sleep(backoff);
285                 backoff *= 2;
286                 if (backoff > MAX_RETRY)
287                         backoff = MAX_RETRY;
288                 goto retry;
289
290         case -1:
291         default:
292                 break;
293         }
294
295 bounce:
296         bounce(it, errmsg);
297         /* NOTREACHED */
298 }
299
300 void
301 run_queue(struct queue *queue)
302 {
303         struct qitem *it;
304
305         if (LIST_EMPTY(&queue->queue))
306                 return;
307
308         it = go_background(queue);
309         deliver(it);
310         /* NOTREACHED */
311 }
312
313 static void
314 show_queue(struct queue *queue)
315 {
316         struct qitem *it;
317         int locked = 0; /* XXX */
318
319         if (LIST_EMPTY(&queue->queue)) {
320                 printf("Mail queue is empty\n");
321                 return;
322         }
323
324         LIST_FOREACH(it, &queue->queue, next) {
325                 printf("ID\t: %s%s\n"
326                        "From\t: %s\n"
327                        "To\t: %s\n"
328                        "--\n",
329                        it->queueid,
330                        locked ? "*" : "",
331                        it->sender, it->addr);
332         }
333 }
334
335 /*
336  * TODO:
337  *
338  * - alias processing
339  * - use group permissions
340  * - proper sysexit codes
341  */
342
343 int
344 main(int argc, char **argv)
345 {
346         char *sender = NULL;
347         struct queue queue;
348         int i, ch;
349         int nodot = 0, doqueue = 0, showq = 0;
350
351         atexit(deltmp);
352
353         bzero(&queue, sizeof(queue));
354         LIST_INIT(&queue.queue);
355
356         if (strcmp(argv[0], "mailq") == 0) {
357                 argv++; argc--;
358                 showq = 1;
359                 if (argc != 0)
360                         errx(1, "invalid arguments");
361                 goto skipopts;
362         }
363
364         opterr = 0;
365         while ((ch = getopt(argc, argv, ":A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
366                 switch (ch) {
367                 case 'A':
368                         /* -AX is being ignored, except for -A{c,m} */
369                         if (optarg[0] == 'c' || optarg[0] == 'm') {
370                                 break;
371                         }
372                         /* else FALLTRHOUGH */
373                 case 'b':
374                         /* -bX is being ignored, except for -bp */
375                         if (optarg[0] == 'p') {
376                                 showq = 1;
377                                 break;
378                         }
379                         /* else FALLTRHOUGH */
380                 case 'D':
381                         daemonize = 0;
382                         break;
383                 case 'L':
384                         logident_base = optarg;
385                         break;
386                 case 'f':
387                 case 'r':
388                         sender = optarg;
389                         break;
390
391                 case 'o':
392                         /* -oX is being ignored, except for -oi */
393                         if (optarg[0] != 'i')
394                                 break;
395                         /* else FALLTRHOUGH */
396                 case 'O':
397                         break;
398                 case 'i':
399                         nodot = 1;
400                         break;
401
402                 case 'q':
403                         doqueue = 1;
404                         break;
405
406                 /* Ignored options */
407                 case 'B':
408                 case 'C':
409                 case 'd':
410                 case 'F':
411                 case 'h':
412                 case 'N':
413                 case 'n':
414                 case 'R':
415                 case 'U':
416                 case 'V':
417                 case 'v':
418                 case 'X':
419                         break;
420
421                 case ':':
422                         if (optopt == 'q') {
423                                 doqueue = 1;
424                                 break;
425                         }
426                         /* FALLTHROUGH */
427
428                 default:
429                         fprintf(stderr, "invalid argument: `-%c'\n", optopt);
430                         exit(1);
431                 }
432         }
433         argc -= optind;
434         argv += optind;
435         opterr = 1;
436
437         if (argc != 0 && (showq || doqueue))
438                 errx(1, "sending mail and queue operations are mutually exclusive");
439
440         if (showq + doqueue > 1)
441                 errx(1, "conflicting queue operations");
442
443 skipopts:
444         if (logident_base == NULL)
445                 logident_base = "dma";
446         setlogident(NULL);
447         set_username();
448
449         /* XXX fork root here */
450
451         config = calloc(1, sizeof(*config));
452         if (config == NULL)
453                 errlog(1, NULL);
454
455         if (parse_conf(CONF_PATH) < 0) {
456                 free(config);
457                 errlog(1, "can not read config file");
458         }
459
460         if (config->features & VIRTUAL)
461                 if (parse_virtuser(config->virtualpath) < 0)
462                         errlog(1, "can not read virtual user file `%s'",
463                                 config->virtualpath);
464
465         if (parse_authfile(config->authpath) < 0)
466                 errlog(1, "can not read SMTP authentication file");
467
468         if (showq) {
469                 if (load_queue(&queue) < 0)
470                         errlog(1, "can not load queue");
471                 show_queue(&queue);
472                 return (0);
473         }
474
475         if (doqueue) {
476                 if (load_queue(&queue) < 0)
477                         errlog(1, "can not load queue");
478                 run_queue(&queue);
479                 return (0);
480         }
481
482         if (read_aliases() != 0)
483                 errlog(1, "can not read aliases file `%s'", config->aliases);
484
485         if ((sender = set_from(sender)) == NULL)
486                 errlog(1, NULL);
487
488         for (i = 0; i < argc; i++) {
489                 if (add_recp(&queue, argv[i], sender, 1) != 0)
490                         errlogx(1, "invalid recipient `%s'", argv[i]);
491         }
492
493         if (LIST_EMPTY(&queue.queue))
494                 errlogx(1, "no recipients");
495
496         if (newspoolf(&queue, sender) != 0)
497                 errlog(1, "can not create temp file");
498
499         setlogident("%s", queue.id);
500
501         if (readmail(&queue, sender, nodot) != 0)
502                 errlog(1, "can not read mail");
503
504         if (linkspool(&queue, sender) != 0)
505                 errlog(1, "can not create spools");
506
507         /* From here on the mail is safe. */
508
509         if (config->features & DEFER)
510                 return (0);
511
512         run_queue(&queue);
513
514         /* NOTREACHED */
515         return (0);
516 }