bf22e8ef44d5baf71c8c14e09352729b27fbcd66
[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         struct queue lqueue;
349         int i, ch;
350         int nodot = 0, doqueue = 0, showq = 0;
351
352         atexit(deltmp);
353         LIST_INIT(&queue.queue);
354
355         if (strcmp(argv[0], "mailq") == 0) {
356                 argv++; argc--;
357                 showq = 1;
358                 if (argc != 0)
359                         errx(1, "invalid arguments");
360                 goto skipopts;
361         }
362
363         opterr = 0;
364         while ((ch = getopt(argc, argv, ":A:b:B:C:d:Df:F:h:iL:N:no:O:q:r:R:UV:vX:")) != -1) {
365                 switch (ch) {
366                 case 'A':
367                         /* -AX is being ignored, except for -A{c,m} */
368                         if (optarg[0] == 'c' || optarg[0] == 'm') {
369                                 break;
370                         }
371                         /* else FALLTRHOUGH */
372                 case 'b':
373                         /* -bX is being ignored, except for -bp */
374                         if (optarg[0] == 'p') {
375                                 showq = 1;
376                                 break;
377                         }
378                         /* else FALLTRHOUGH */
379                 case 'D':
380                         daemonize = 0;
381                         break;
382                 case 'L':
383                         logident_base = optarg;
384                         break;
385                 case 'f':
386                 case 'r':
387                         sender = optarg;
388                         break;
389
390                 case 'o':
391                         /* -oX is being ignored, except for -oi */
392                         if (optarg[0] != 'i')
393                                 break;
394                         /* else FALLTRHOUGH */
395                 case 'O':
396                         break;
397                 case 'i':
398                         nodot = 1;
399                         break;
400
401                 case 'q':
402                         doqueue = 1;
403                         break;
404
405                 /* Ignored options */
406                 case 'B':
407                 case 'C':
408                 case 'd':
409                 case 'F':
410                 case 'h':
411                 case 'N':
412                 case 'n':
413                 case 'R':
414                 case 'U':
415                 case 'V':
416                 case 'v':
417                 case 'X':
418                         break;
419
420                 case ':':
421                         if (optopt == 'q') {
422                                 doqueue = 1;
423                                 break;
424                         }
425                         /* FALLTHROUGH */
426
427                 default:
428                         fprintf(stderr, "invalid argument: `-%c'\n", optopt);
429                         exit(1);
430                 }
431         }
432         argc -= optind;
433         argv += optind;
434         opterr = 1;
435
436         if (argc != 0 && (showq || doqueue))
437                 errx(1, "sending mail and queue operations are mutually exclusive");
438
439         if (showq + doqueue > 1)
440                 errx(1, "conflicting queue operations");
441
442 skipopts:
443         if (logident_base == NULL)
444                 logident_base = "dma";
445         setlogident(NULL);
446         set_username();
447
448         /* XXX fork root here */
449
450         config = calloc(1, sizeof(*config));
451         if (config == NULL)
452                 errlog(1, NULL);
453
454         if (parse_conf(CONF_PATH) < 0) {
455                 free(config);
456                 errlog(1, "can not read config file");
457         }
458
459         if (config->features & VIRTUAL)
460                 if (parse_virtuser(config->virtualpath) < 0)
461                         errlog(1, "can not read virtual user file `%s'",
462                                 config->virtualpath);
463
464         if (parse_authfile(config->authpath) < 0)
465                 errlog(1, "can not read SMTP authentication file");
466
467         if (showq) {
468                 if (load_queue(&lqueue) < 0)
469                         errlog(1, "can not load queue");
470                 show_queue(&lqueue);
471                 return (0);
472         }
473
474         if (doqueue) {
475                 if (load_queue(&lqueue) < 0)
476                         errlog(1, "can not load queue");
477                 run_queue(&lqueue);
478                 return (0);
479         }
480
481         if (read_aliases() != 0)
482                 errlog(1, "can not read aliases file `%s'", config->aliases);
483
484         if ((sender = set_from(sender)) == NULL)
485                 errlog(1, NULL);
486
487         for (i = 0; i < argc; i++) {
488                 if (add_recp(&queue, argv[i], sender, 1) != 0)
489                         errlogx(1, "invalid recipient `%s'", argv[i]);
490         }
491
492         if (LIST_EMPTY(&queue.queue))
493                 errlogx(1, "no recipients");
494
495         if (newspoolf(&queue, sender) != 0)
496                 errlog(1, "can not create temp file");
497
498         setlogident("%s", queue.id);
499
500         if (readmail(&queue, sender, nodot) != 0)
501                 errlog(1, "can not read mail");
502
503         if (linkspool(&queue, sender) != 0)
504                 errlog(1, "can not create spools");
505
506         /* From here on the mail is safe. */
507
508         if (config->features & DEFER)
509                 return (0);
510
511         run_queue(&queue);
512
513         /* NOTREACHED */
514         return (0);
515 }