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