dma: lock temp files on creation
[dragonfly.git] / libexec / dma / dma.c
CommitLineData
f67beddd
MS
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 *
bc7baf1d 34 * $DragonFly: src/libexec/dma/dma.c,v 1.5 2008/09/30 17:47:21 swildner Exp $
f67beddd
MS
35 */
36
37#include <sys/param.h>
38#include <sys/queue.h>
39#include <sys/stat.h>
40#include <sys/types.h>
bc7baf1d 41#include <sys/wait.h>
f67beddd
MS
42
43#ifdef HAVE_CRYPTO
44#include <openssl/ssl.h>
45#endif /* HAVE_CRYPTO */
46
47#include <dirent.h>
48#include <err.h>
49#include <errno.h>
50#include <fcntl.h>
51#include <inttypes.h>
52#include <netdb.h>
53#include <paths.h>
54#include <pwd.h>
55#include <signal.h>
56#include <stdarg.h>
57#include <stdio.h>
58#include <stdlib.h>
59#include <string.h>
60#include <syslog.h>
61#include <unistd.h>
62
63#include "dma.h"
64
65
66
4a23bd3d 67static void deliver(struct qitem *);
f67beddd
MS
68static int add_recp(struct queue *, const char *, const char *, int);
69
70struct aliases aliases = LIST_HEAD_INITIALIZER(aliases);
71static struct strlist tmpfs = SLIST_HEAD_INITIALIZER(tmpfs);
72struct virtusers virtusers = LIST_HEAD_INITIALIZER(virtusers);
73struct authusers authusers = LIST_HEAD_INITIALIZER(authusers);
74static int daemonize = 1;
75struct config *config;
4b331f9f 76static struct strlist seenmsg[16][16];
f67beddd 77
144b337d 78
f67beddd
MS
79char *
80hostname(void)
81{
82 static char name[MAXHOSTNAMELEN+1];
83
84 if (gethostname(name, sizeof(name)) != 0)
85 strcpy(name, "(unknown hostname)");
86
87 return name;
88}
89
90static char *
91set_from(const char *osender)
92{
93 struct virtuser *v;
94 char *sender;
95
96 if ((config->features & VIRTUAL) != 0) {
97 SLIST_FOREACH(v, &virtusers, next) {
98 if (strcmp(v->login, getlogin()) == 0) {
99 sender = strdup(v->address);
100 if (sender == NULL)
101 return(NULL);
102 goto out;
103 }
104 }
105 }
106
107 if (osender) {
108 sender = strdup(osender);
109 if (sender == NULL)
4a23bd3d 110 return (NULL);
f67beddd
MS
111 } else {
112 if (asprintf(&sender, "%s@%s", getlogin(), hostname()) <= 0)
4a23bd3d 113 return (NULL);
f67beddd
MS
114 }
115
116 if (strchr(sender, '\n') != NULL) {
117 errno = EINVAL;
4a23bd3d 118 return (NULL);
f67beddd
MS
119 }
120
121out:
4a23bd3d 122 return (sender);
f67beddd
MS
123}
124
125static int
126read_aliases(void)
127{
128 yyin = fopen(config->aliases, "r");
129 if (yyin == NULL)
4a23bd3d 130 return (0); /* not fatal */
f67beddd 131 if (yyparse())
4a23bd3d 132 return (-1); /* fatal error, probably malloc() */
f67beddd 133 fclose(yyin);
4a23bd3d 134 return (0);
f67beddd
MS
135}
136
137static int
138add_recp(struct queue *queue, const char *str, const char *sender, int expand)
139{
140 struct qitem *it, *tit;
141 struct stritem *sit;
142 struct alias *al;
143 struct passwd *pw;
144 char *host;
145 int aliased = 0;
146
147 it = calloc(1, sizeof(*it));
148 if (it == NULL)
4a23bd3d 149 return (-1);
f67beddd
MS
150 it->addr = strdup(str);
151 if (it->addr == NULL)
4a23bd3d 152 return (-1);
f67beddd
MS
153
154 it->sender = sender;
155 host = strrchr(it->addr, '@');
156 if (host != NULL &&
157 (strcmp(host + 1, hostname()) == 0 ||
158 strcmp(host + 1, "localhost") == 0)) {
159 *host = 0;
160 }
161 LIST_FOREACH(tit, &queue->queue, next) {
162 /* weed out duplicate dests */
163 if (strcmp(tit->addr, it->addr) == 0) {
164 free(it->addr);
165 free(it);
4a23bd3d 166 return (0);
f67beddd
MS
167 }
168 }
169 LIST_INSERT_HEAD(&queue->queue, it, next);
170 if (strrchr(it->addr, '@') == NULL) {
4a23bd3d 171 it->remote = 0;
f67beddd
MS
172 if (expand) {
173 LIST_FOREACH(al, &aliases, next) {
174 if (strcmp(al->alias, it->addr) != 0)
175 continue;
176 SLIST_FOREACH(sit, &al->dests, next) {
4a23bd3d
MS
177 if (add_recp(queue, sit->str, sender, 1) != 0)
178 return (-1);
f67beddd
MS
179 }
180 aliased = 1;
181 }
182 if (aliased) {
183 LIST_REMOVE(it, next);
184 } else {
4a23bd3d 185 /* Local destination, check */
f67beddd
MS
186 pw = getpwnam(it->addr);
187 if (pw == NULL)
188 goto out;
4a23bd3d 189 endpwent();
f67beddd
MS
190 }
191 }
192 } else {
4a23bd3d 193 it->remote = 1;
f67beddd
MS
194 }
195
4a23bd3d 196 return (0);
f67beddd
MS
197
198out:
199 free(it->addr);
200 free(it);
4a23bd3d 201 return (-1);
f67beddd
MS
202}
203
204static void
205deltmp(void)
206{
207 struct stritem *t;
208
209 SLIST_FOREACH(t, &tmpfs, next) {
210 unlink(t->str);
211 }
212}
213
214static int
215gentempf(struct queue *queue)
216{
217 char fn[PATH_MAX+1];
218 struct stritem *t;
219 int fd;
220
221 if (snprintf(fn, sizeof(fn), "%s/%s", config->spooldir, "tmp_XXXXXXXXXX") <= 0)
4a23bd3d 222 return (-1);
f67beddd
MS
223 fd = mkstemp(fn);
224 if (fd < 0)
4a23bd3d 225 return (-1);
855166ca
SS
226 if (flock(fd, LOCK_EX) == -1)
227 return (-1);
f67beddd
MS
228 queue->mailfd = fd;
229 queue->tmpf = strdup(fn);
230 if (queue->tmpf == NULL) {
231 unlink(fn);
4a23bd3d 232 return (-1);
f67beddd
MS
233 }
234 t = malloc(sizeof(*t));
235 if (t != NULL) {
236 t->str = queue->tmpf;
237 SLIST_INSERT_HEAD(&tmpfs, t, next);
238 }
4a23bd3d 239 return (0);
f67beddd
MS
240}
241
144b337d
SS
242static int
243open_locked(const char *fname, int flags)
244{
245#ifndef O_EXLOCK
246 int fd, save_errno;
247
248 fd = open(fname, flags, 0);
249 if (fd < 0)
250 return(fd);
251 if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) {
252 save_errno = errno;
253 close(fd);
254 errno = save_errno;
255 return(-1);
256 }
257 return(fd);
258#else
259 return(open(fname, flags|O_EXLOCK));
260#endif
261}
262
f67beddd
MS
263/*
264 * spool file format:
265 *
266 * envelope-from
267 * queue-id1 envelope-to1
268 * queue-id2 envelope-to2
269 * ...
270 * <empty line>
271 * mail data
272 *
273 * queue ids are unique, formed from the inode of the spool file
274 * and a unique identifier.
275 */
276static int
277preparespool(struct queue *queue, const char *sender)
278{
279 char line[1000]; /* by RFC2822 */
280 struct stat st;
281 int error;
282 struct qitem *it;
283 FILE *queuef;
284 off_t hdrlen;
285
286 error = snprintf(line, sizeof(line), "%s\n", sender);
287 if (error < 0 || (size_t)error >= sizeof(line)) {
288 errno = E2BIG;
4a23bd3d 289 return (-1);
f67beddd
MS
290 }
291 if (write(queue->mailfd, line, error) != error)
4a23bd3d 292 return (-1);
f67beddd
MS
293
294 queuef = fdopen(queue->mailfd, "r+");
295 if (queuef == NULL)
4a23bd3d 296 return (-1);
f67beddd
MS
297
298 /*
299 * Assign queue id to each dest.
300 */
301 if (fstat(queue->mailfd, &st) != 0)
4a23bd3d 302 return (-1);
f67beddd
MS
303 queue->id = st.st_ino;
304 LIST_FOREACH(it, &queue->queue, next) {
305 if (asprintf(&it->queueid, "%"PRIxMAX".%"PRIxPTR,
306 queue->id, (uintptr_t)it) <= 0)
4a23bd3d 307 return (-1);
f67beddd
MS
308 if (asprintf(&it->queuefn, "%s/%s",
309 config->spooldir, it->queueid) <= 0)
4a23bd3d
MS
310 return (-1);
311 /* File may not exist yet */
312 if (stat(it->queuefn, &st) == 0)
313 return (-1);
f67beddd
MS
314 it->queuef = queuef;
315 error = snprintf(line, sizeof(line), "%s %s\n",
316 it->queueid, it->addr);
317 if (error < 0 || (size_t)error >= sizeof(line))
4a23bd3d 318 return (-1);
f67beddd 319 if (write(queue->mailfd, line, error) != error)
4a23bd3d 320 return (-1);
f67beddd
MS
321 }
322 line[0] = '\n';
323 if (write(queue->mailfd, line, 1) != 1)
4a23bd3d 324 return (-1);
f67beddd
MS
325
326 hdrlen = lseek(queue->mailfd, 0, SEEK_CUR);
327 LIST_FOREACH(it, &queue->queue, next) {
328 it->hdrlen = hdrlen;
329 }
4a23bd3d 330 return (0);
f67beddd
MS
331}
332
333static char *
334rfc822date(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)");
4a23bd3d 345 return (str);
f67beddd
MS
346}
347
348static int
349readmail(struct queue *queue, const char *sender, int nodot)
350{
351 char line[1000]; /* by RFC2822 */
352 size_t linelen;
353 int error;
354
355 error = snprintf(line, sizeof(line), "\
356Received: from %s (uid %d)\n\
357\t(envelope-from %s)\n\
358\tid %"PRIxMAX"\n\
359\tby %s (%s)\n\
360\t%s\n",
361 getlogin(), getuid(),
362 sender,
363 queue->id,
364 hostname(), VERSION,
365 rfc822date());
366 if (error < 0 || (size_t)error >= sizeof(line))
4a23bd3d 367 return (-1);
f67beddd 368 if (write(queue->mailfd, line, error) != error)
4a23bd3d 369 return (-1);
f67beddd
MS
370
371 while (!feof(stdin)) {
372 if (fgets(line, sizeof(line), stdin) == NULL)
373 break;
374 linelen = strlen(line);
375 if (linelen == 0 || line[linelen - 1] != '\n') {
376 errno = EINVAL; /* XXX mark permanent errors */
4a23bd3d 377 return (-1);
f67beddd
MS
378 }
379 if (!nodot && linelen == 2 && line[0] == '.')
380 break;
381 if ((size_t)write(queue->mailfd, line, linelen) != linelen)
4a23bd3d 382 return (-1);
f67beddd
MS
383 }
384 if (fsync(queue->mailfd) != 0)
4a23bd3d
MS
385 return (-1);
386 return (0);
f67beddd
MS
387}
388
389static int
390linkspool(struct queue *queue)
391{
392 struct qitem *it;
393
394 LIST_FOREACH(it, &queue->queue, next) {
395 if (link(queue->tmpf, it->queuefn) != 0)
396 goto delfiles;
397 }
4a23bd3d
MS
398 unlink(queue->tmpf);
399 return (0);
f67beddd
MS
400
401delfiles:
402 LIST_FOREACH(it, &queue->queue, next) {
403 unlink(it->queuefn);
404 }
4a23bd3d 405 return (-1);
f67beddd
MS
406}
407
4a23bd3d
MS
408static struct qitem *
409go_background(struct queue *queue)
f67beddd
MS
410{
411 struct sigaction sa;
412 struct qitem *it;
413 pid_t pid;
414
415 if (daemonize && daemon(0, 0) != 0) {
4a23bd3d 416 syslog(LOG_ERR, "can not daemonize: %m");
f67beddd
MS
417 exit(1);
418 }
419 daemonize = 0;
4a23bd3d 420
f67beddd
MS
421 bzero(&sa, sizeof(sa));
422 sa.sa_flags = SA_NOCLDWAIT;
423 sa.sa_handler = SIG_IGN;
424 sigaction(SIGCHLD, &sa, NULL);
425
4dcaa51b 426 LIST_FOREACH(it, &queue->queue, next) {
4a23bd3d
MS
427 /* No need to fork for the last dest */
428 if (LIST_NEXT(it, next) == NULL)
429 return (it);
430
f67beddd
MS
431 pid = fork();
432 switch (pid) {
433 case -1:
434 syslog(LOG_ERR, "can not fork: %m");
435 exit(1);
436 break;
437
438 case 0:
439 /*
440 * Child:
441 *
442 * return and deliver mail
443 */
4a23bd3d 444 return (it);
f67beddd
MS
445
446 default:
447 /*
448 * Parent:
449 *
450 * fork next child
451 */
452 break;
453 }
454 }
455
456 syslog(LOG_CRIT, "reached dead code");
457 exit(1);
458}
459
460static void
4a23bd3d 461bounce(struct qitem *it, const char *reason)
f67beddd
MS
462{
463 struct queue bounceq;
464 struct qitem *bit;
465 char line[1000];
466 int error;
467
468 /* Don't bounce bounced mails */
469 if (it->sender[0] == 0) {
470 syslog(LOG_CRIT, "%s: delivery panic: can't bounce a bounce",
4a23bd3d 471 it->queueid);
f67beddd
MS
472 exit(1);
473 }
474
475 syslog(LOG_ERR, "%s: delivery failed, bouncing",
476 it->queueid);
477
478 LIST_INIT(&bounceq.queue);
479 if (add_recp(&bounceq, it->sender, "", 1) != 0)
480 goto fail;
481 if (gentempf(&bounceq) != 0)
482 goto fail;
483 if (preparespool(&bounceq, "") != 0)
484 goto fail;
485
486 bit = LIST_FIRST(&bounceq.queue);
487 error = fprintf(bit->queuef, "\
488Received: from MAILER-DAEMON\n\
489\tid %"PRIxMAX"\n\
490\tby %s (%s)\n\
491\t%s\n\
492X-Original-To: <%s>\n\
493From: MAILER-DAEMON <>\n\
494To: %s\n\
495Subject: Mail delivery failed\n\
496Message-Id: <%"PRIxMAX"@%s>\n\
497Date: %s\n\
498\n\
499This is the %s at %s.\n\
500\n\
501There was an error delivering your mail to <%s>.\n\
502\n\
503%s\n\
504\n\
505Message headers follow.\n\
506\n\
507",
508 bounceq.id,
509 hostname(), VERSION,
510 rfc822date(),
511 it->addr,
512 it->sender,
513 bounceq.id, hostname(),
514 rfc822date(),
515 VERSION, hostname(),
516 it->addr,
517 reason);
518 if (error < 0)
519 goto fail;
520 if (fflush(bit->queuef) != 0)
521 goto fail;
522
523 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0)
524 goto fail;
525 while (!feof(it->queuef)) {
526 if (fgets(line, sizeof(line), it->queuef) == NULL)
527 break;
528 if (line[0] == '\n')
529 break;
2922fd2b
SS
530 if ((size_t)write(bounceq.mailfd, line, strlen(line)) != strlen(line))
531 goto fail;
f67beddd
MS
532 }
533 if (fsync(bounceq.mailfd) != 0)
534 goto fail;
535 if (linkspool(&bounceq) != 0)
536 goto fail;
537 /* bounce is safe */
538
539 unlink(it->queuefn);
540 fclose(it->queuef);
541
4a23bd3d
MS
542 bit = go_background(&bounceq);
543 deliver(bit);
f67beddd
MS
544 /* NOTREACHED */
545
546fail:
547 syslog(LOG_CRIT, "%s: error creating bounce: %m", it->queueid);
548 unlink(it->queuefn);
549 exit(1);
550}
551
552static int
553deliver_local(struct qitem *it, const char **errmsg)
554{
4dcaa51b 555 char fn[PATH_MAX+1];
4a23bd3d
MS
556 char line[1000];
557 size_t linelen;
558 int mbox;
559 int error;
560 off_t mboxlen;
f67beddd 561 time_t now = time(NULL);
4dcaa51b 562
4a23bd3d
MS
563 error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
564 if (error < 0 || (size_t)error >= sizeof(fn)) {
565 syslog(LOG_ERR, "%s: local delivery deferred: %m",
566 it->queueid);
567 return (1);
f67beddd
MS
568 }
569
4a23bd3d 570 /* mailx removes users mailspool file if empty, so open with O_CREAT */
144b337d 571 mbox = open_locked(fn, O_WRONLY | O_APPEND | O_CREAT);
4a23bd3d
MS
572 if (mbox < 0) {
573 syslog(LOG_ERR, "%s: local delivery deferred: can not open `%s': %m",
574 it->queueid, fn);
575 return (1);
f67beddd 576 }
4a23bd3d 577 mboxlen = lseek(mbox, 0, SEEK_CUR);
f67beddd
MS
578
579 if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
580 syslog(LOG_ERR, "%s: local delivery deferred: can not seek: %m",
581 it->queueid);
4a23bd3d 582 return (1);
f67beddd
MS
583 }
584
4a23bd3d
MS
585 error = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
586 if (error < 0 || (size_t)error >= sizeof(line)) {
f67beddd
MS
587 syslog(LOG_ERR, "%s: local delivery deferred: can not write header: %m",
588 it->queueid);
4a23bd3d 589 return (1);
f67beddd 590 }
4a23bd3d 591 if (write(mbox, line, error) != error)
f67beddd
MS
592 goto wrerror;
593
594 while (!feof(it->queuef)) {
595 if (fgets(line, sizeof(line), it->queuef) == NULL)
596 break;
597 linelen = strlen(line);
598 if (linelen == 0 || line[linelen - 1] != '\n') {
4a23bd3d
MS
599 syslog(LOG_CRIT, "%s: local delivery failed: corrupted queue file",
600 it->queueid);
f67beddd 601 *errmsg = "corrupted queue file";
4a23bd3d 602 error = -1;
f67beddd
MS
603 goto chop;
604 }
605
606 if (strncmp(line, "From ", 5) == 0) {
607 const char *gt = ">";
608
4a23bd3d 609 if (write(mbox, gt, 1) != 1)
f67beddd
MS
610 goto wrerror;
611 }
4a23bd3d 612 if ((size_t)write(mbox, line, linelen) != linelen)
f67beddd
MS
613 goto wrerror;
614 }
615 line[0] = '\n';
4a23bd3d 616 if (write(mbox, line, 1) != 1)
4dcaa51b 617 goto wrerror;
4a23bd3d
MS
618 close(mbox);
619 return (0);
f67beddd
MS
620
621wrerror:
622 syslog(LOG_ERR, "%s: local delivery failed: write error: %m",
623 it->queueid);
4a23bd3d 624 error = 1;
f67beddd 625chop:
4a23bd3d 626 if (ftruncate(mbox, mboxlen) != 0)
f67beddd 627 syslog(LOG_WARNING, "%s: error recovering mbox `%s': %m",
4a23bd3d
MS
628 it->queueid, fn);
629 close(mbox);
630 return (error);
f67beddd
MS
631}
632
633static void
4a23bd3d 634deliver(struct qitem *it)
f67beddd
MS
635{
636 int error;
637 unsigned int backoff = MIN_RETRY;
638 const char *errmsg = "unknown bounce reason";
639 struct timeval now;
640 struct stat st;
641
4a23bd3d
MS
642 syslog(LOG_INFO, "%s: mail from=<%s> to=<%s>",
643 it->queueid, it->sender, it->addr);
f67beddd
MS
644
645retry:
646 syslog(LOG_INFO, "%s: trying delivery",
647 it->queueid);
648
4a23bd3d
MS
649 if (it->remote)
650 error = deliver_remote(it, &errmsg);
651 else
f67beddd
MS
652 error = deliver_local(it, &errmsg);
653
654 switch (error) {
655 case 0:
4a23bd3d 656 unlink(it->queuefn);
f67beddd
MS
657 syslog(LOG_INFO, "%s: delivery successful",
658 it->queueid);
659 exit(0);
660
661 case 1:
662 if (stat(it->queuefn, &st) != 0) {
663 syslog(LOG_ERR, "%s: lost queue file `%s'",
664 it->queueid, it->queuefn);
665 exit(1);
666 }
667 if (gettimeofday(&now, NULL) == 0 &&
668 (now.tv_sec - st.st_mtimespec.tv_sec > MAX_TIMEOUT)) {
669 char *msg;
670
671 if (asprintf(&msg,
4a23bd3d
MS
672 "Could not deliver for the last %d seconds. Giving up.",
673 MAX_TIMEOUT) > 0)
f67beddd
MS
674 errmsg = msg;
675 goto bounce;
676 }
677 sleep(backoff);
678 backoff *= 2;
679 if (backoff > MAX_RETRY)
680 backoff = MAX_RETRY;
681 goto retry;
682
683 case -1:
684 default:
685 break;
686 }
687
688bounce:
4a23bd3d 689 bounce(it, errmsg);
f67beddd
MS
690 /* NOTREACHED */
691}
692
4b331f9f
SS
693static int
694c2x(char c)
695{
696 if (c <= '9')
697 return (c - '0');
698 else if (c <= 'F')
699 return (c - 'A' + 10);
700 else
701 return (c - 'a' + 10);
702}
703
f67beddd 704static void
4b331f9f
SS
705seen_init(void)
706{
707 int i, j;
708
709 for (i = 0; i < 16; i++)
710 for (j = 0; j < 16; j++)
711 SLIST_INIT(&seenmsg[i][j]);
712}
713
714static int
715seen(const char *msgid)
716{
717 const char *p;
718 size_t len;
719 int i, j;
720 struct stritem *t;
721
722 p = strchr(msgid, '.');
723 if (p == NULL)
724 return (0);
725 len = p - msgid;
726 if (len >= 2) {
727 i = c2x(msgid[len - 2]);
728 j = c2x(msgid[len - 1]);
729 } else if (len == 1) {
730 i = c2x(msgid[0]);
731 j = 0;
732 } else {
733 i = j = 0;
734 }
735 if (i < 0 || i >= 16 || j < 0 || j >= 16)
736 errx(1, "INTERNAL ERROR: bad seen code for msgid %s", msgid);
737 SLIST_FOREACH(t, &seenmsg[i][j], next)
738 if (!strncmp(t->str, msgid, len))
739 return (1);
740 t = malloc(sizeof(*t));
741 if (t == NULL)
742 errx(1, "Could not allocate %lu bytes",
743 (unsigned long)(sizeof(*t)));
744 t->str = strdup(msgid);
745 if (t->str == NULL)
746 errx(1, "Could not duplicate msgid %s", msgid);
747 SLIST_INSERT_HEAD(&seenmsg[i][j], t, next);
748 return (0);
749}
750
751static void
752load_queue(struct queue *queue, int ignorelock)
f67beddd
MS
753{
754 struct stat st;
755 struct qitem *it;
756 //struct queue queue, itmqueue;
757 struct queue itmqueue;
758 DIR *spooldir;
759 struct dirent *de;
760 char line[1000];
761 char *fn;
762 FILE *queuef;
763 char *sender;
764 char *addr;
765 char *queueid;
766 char *queuefn;
767 off_t hdrlen;
4b331f9f 768 int fd, locked, seenit;
f67beddd
MS
769
770 LIST_INIT(&queue->queue);
771
772 spooldir = opendir(config->spooldir);
773 if (spooldir == NULL)
774 err(1, "reading queue");
775
4b331f9f 776 seen_init();
f67beddd
MS
777 while ((de = readdir(spooldir)) != NULL) {
778 sender = NULL;
779 queuef = NULL;
780 queueid = NULL;
781 queuefn = NULL;
782 fn = NULL;
783 LIST_INIT(&itmqueue.queue);
784
785 /* ignore temp files */
786 if (strncmp(de->d_name, "tmp_", 4) == 0 ||
787 de->d_type != DT_REG)
788 continue;
789 if (asprintf(&queuefn, "%s/%s", config->spooldir, de->d_name) < 0)
790 goto fail;
4b331f9f
SS
791 seenit = seen(de->d_name);
792 locked = 0;
144b337d 793 fd = open_locked(queuefn, O_RDONLY|O_NONBLOCK);
f67beddd
MS
794 if (fd < 0) {
795 /* Ignore locked files */
4b331f9f
SS
796 if (errno != EWOULDBLOCK)
797 goto skip_item;
798 if (!ignorelock || seenit)
f67beddd 799 continue;
4b331f9f
SS
800 fd = open(queuefn, O_RDONLY);
801 if (fd < 0)
802 goto skip_item;
803 locked = 1;
f67beddd
MS
804 }
805
806 queuef = fdopen(fd, "r");
807 if (queuef == NULL)
808 goto skip_item;
809 if (fgets(line, sizeof(line), queuef) == NULL ||
810 line[0] == 0)
811 goto skip_item;
812 line[strlen(line) - 1] = 0; /* chop newline */
813 sender = strdup(line);
814 if (sender == NULL)
815 goto skip_item;
816
817 for (;;) {
818 if (fgets(line, sizeof(line), queuef) == NULL ||
819 line[0] == 0)
820 goto skip_item;
821 if (line[0] == '\n')
822 break;
823 line[strlen(line) - 1] = 0;
824 queueid = strdup(line);
825 if (queueid == NULL)
826 goto skip_item;
827 addr = strchr(queueid, ' ');
828 if (addr == NULL)
829 goto skip_item;
830 *addr++ = 0;
831 if (fn != NULL)
832 free(fn);
833 if (asprintf(&fn, "%s/%s", config->spooldir, queueid) < 0)
834 goto skip_item;
835 /* Item has already been delivered? */
836 if (stat(fn, &st) != 0)
837 continue;
838 if (add_recp(&itmqueue, addr, sender, 0) != 0)
839 goto skip_item;
840 it = LIST_FIRST(&itmqueue.queue);
841 it->queuef = queuef;
842 it->queueid = queueid;
843 it->queuefn = fn;
4b331f9f 844 it->locked = locked;
f67beddd
MS
845 fn = NULL;
846 }
847 if (LIST_EMPTY(&itmqueue.queue)) {
848 warnx("queue file without items: `%s'", queuefn);
849 goto skip_item2;
850 }
851 hdrlen = ftell(queuef);
852 while ((it = LIST_FIRST(&itmqueue.queue)) != NULL) {
853 it->hdrlen = hdrlen;
854 LIST_REMOVE(it, next);
855 LIST_INSERT_HEAD(&queue->queue, it, next);
856 }
857 continue;
858
859skip_item:
860 warn("reading queue: `%s'", queuefn);
861skip_item2:
862 if (sender != NULL)
863 free(sender);
864 if (queuefn != NULL)
865 free(queuefn);
866 if (fn != NULL)
867 free(fn);
868 if (queueid != NULL)
869 free(queueid);
870 close(fd);
871 }
872 closedir(spooldir);
873 return;
874
875fail:
876 err(1, "reading queue");
877}
878
879static void
880run_queue(struct queue *queue)
881{
4a23bd3d
MS
882 struct qitem *it;
883
f67beddd
MS
884 if (LIST_EMPTY(&queue->queue))
885 return;
886
4a23bd3d
MS
887 it = go_background(queue);
888 deliver(it);
f67beddd
MS
889 /* NOTREACHED */
890}
891
892static void
893show_queue(struct queue *queue)
894{
895 struct qitem *it;
896
897 if (LIST_EMPTY(&queue->queue)) {
898 printf("Mail queue is empty\n");
899 return;
900 }
901
902 LIST_FOREACH(it, &queue->queue, next) {
903 printf("\
4b331f9f 904ID\t: %s%s\n\
f67beddd 905From\t: %s\n\
4b331f9f 906To\t: %s\n--\n", it->queueid, it->locked? "*": "", it->sender, it->addr);
f67beddd
MS
907 }
908}
909
910/*
911 * TODO:
912 *
913 * - alias processing
914 * - use group permissions
915 * - proper sysexit codes
916 */
917
4a23bd3d
MS
918int
919main(int argc, char **argv)
f67beddd
MS
920{
921 char *sender = NULL;
922 char tag[255];
4a23bd3d 923 struct qitem *it;
f67beddd
MS
924 struct queue queue;
925 struct queue lqueue;
f67beddd
MS
926 int i, ch;
927 int nodot = 0, doqueue = 0, showq = 0;
928
929 atexit(deltmp);
930 LIST_INIT(&queue.queue);
931 snprintf(tag, 254, "dma");
932
ae3c3bbd
MS
933 opterr = 0;
934 while ((ch = getopt(argc, argv, "A:b:Df:iL:o:O:q:r:")) != -1) {
f67beddd
MS
935 switch (ch) {
936 case 'A':
937 /* -AX is being ignored, except for -A{c,m} */
938 if (optarg[0] == 'c' || optarg[0] == 'm') {
939 break;
940 }
941 /* else FALLTRHOUGH */
942 case 'b':
943 /* -bX is being ignored, except for -bp */
944 if (optarg[0] == 'p') {
945 showq = 1;
946 break;
947 }
948 /* else FALLTRHOUGH */
949 case 'D':
950 daemonize = 0;
951 break;
952 case 'L':
953 if (optarg != NULL)
954 snprintf(tag, 254, "%s", optarg);
955 break;
956 case 'f':
957 case 'r':
958 sender = optarg;
959 break;
960
961 case 'o':
962 /* -oX is being ignored, except for -oi */
963 if (optarg[0] != 'i')
964 break;
965 /* else FALLTRHOUGH */
ae3c3bbd
MS
966 case 'O':
967 break;
f67beddd
MS
968 case 'i':
969 nodot = 1;
970 break;
971
972 case 'q':
973 doqueue = 1;
974 break;
975
976 default:
977 exit(1);
978 }
979 }
980 argc -= optind;
981 argv += optind;
ae3c3bbd 982 opterr = 1;
f67beddd
MS
983
984 openlog(tag, LOG_PID | LOG_PERROR, LOG_MAIL);
985
986 config = malloc(sizeof(struct config));
987 if (config == NULL)
988 errx(1, "Cannot allocate enough memory");
989
990 memset(config, 0, sizeof(struct config));
5c4cbc76 991 if (parse_conf(CONF_PATH, config) < 0) {
f67beddd
MS
992 free(config);
993 errx(1, "reading config file");
994 }
995
996 if (config->features & VIRTUAL)
4a23bd3d 997 if (parse_virtuser(config->virtualpath) < 0)
f67beddd
MS
998 errx(1, "error reading virtual user file: %s",
999 config->virtualpath);
1000
4a23bd3d 1001 if (parse_authfile(config->authpath) < 0)
f67beddd
MS
1002 err(1, "reading SMTP authentication file");
1003
1004 if (showq) {
1005 if (argc != 0)
1006 errx(1, "sending mail and displaying queue is"
1007 " mutually exclusive");
4b331f9f 1008 load_queue(&lqueue, 1);
f67beddd 1009 show_queue(&lqueue);
4a23bd3d 1010 return (0);
f67beddd
MS
1011 }
1012
1013 if (doqueue) {
1014 if (argc != 0)
1015 errx(1, "sending mail and queue pickup is mutually exclusive");
4b331f9f 1016 load_queue(&lqueue, 0);
f67beddd 1017 run_queue(&lqueue);
4a23bd3d 1018 return (0);
f67beddd
MS
1019 }
1020
4a23bd3d 1021 if (read_aliases() != 0)
f67beddd
MS
1022 err(1, "reading aliases");
1023
4a23bd3d 1024 if ((sender = set_from(sender)) == NULL)
f67beddd
MS
1025 err(1, "setting from address");
1026
1027 for (i = 0; i < argc; i++) {
4a23bd3d 1028 if (add_recp(&queue, argv[i], sender, 1) != 0)
f67beddd
MS
1029 errx(1, "invalid recipient `%s'\n", argv[i]);
1030 }
1031
4a23bd3d 1032 if (LIST_EMPTY(&queue.queue))
f67beddd
MS
1033 errx(1, "no recipients");
1034
4a23bd3d
MS
1035 if (gentempf(&queue) != 0)
1036 err(1, "create temp file");
1037
1038 if (preparespool(&queue, sender) != 0)
f67beddd
MS
1039 err(1, "creating spools (1)");
1040
4a23bd3d 1041 if (readmail(&queue, sender, nodot) != 0)
f67beddd
MS
1042 err(1, "reading mail");
1043
4a23bd3d 1044 if (linkspool(&queue) != 0)
f67beddd
MS
1045 err(1, "creating spools (2)");
1046
1047 /* From here on the mail is safe. */
1048
1049 if (config->features & DEFER)
4a23bd3d 1050 return (0);
f67beddd 1051
4a23bd3d
MS
1052 it = go_background(&queue);
1053 deliver(it);
f67beddd
MS
1054
1055 /* NOTREACHED */
4a23bd3d 1056 return (0);
4dcaa51b 1057}