]> git.ipfire.org Git - people/ms/dma.git/blob - local.c
dma: restructure logging
[people/ms/dma.git] / local.c
1 #include <err.h>
2 #include <errno.h>
3 #include <fcntl.h>
4 #include <paths.h>
5 #include <stdint.h>
6 #include <stdio.h>
7 #include <syslog.h>
8 #include <unistd.h>
9
10 #include "dma.h"
11
12 int
13 deliver_local(struct qitem *it, const char **errmsg)
14 {
15 char fn[PATH_MAX+1];
16 char line[1000];
17 size_t linelen;
18 int mbox;
19 int error;
20 off_t mboxlen;
21 time_t now = time(NULL);
22
23 error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
24 if (error < 0 || (size_t)error >= sizeof(fn)) {
25 syslog(LOG_NOTICE, "local delivery deferred: %m");
26 return (1);
27 }
28
29 /* mailx removes users mailspool file if empty, so open with O_CREAT */
30 mbox = open_locked(fn, O_WRONLY | O_APPEND | O_CREAT);
31 if (mbox < 0) {
32 syslog(LOG_NOTICE, "local delivery deferred: can not open `%s': %m", fn);
33 return (1);
34 }
35 mboxlen = lseek(mbox, 0, SEEK_CUR);
36
37 if (fseek(it->mailf, it->hdrlen, SEEK_SET) != 0) {
38 syslog(LOG_NOTICE, "local delivery deferred: can not seek: %m");
39 return (1);
40 }
41
42 error = snprintf(line, sizeof(line), "From %s\t%s", it->sender, ctime(&now));
43 if (error < 0 || (size_t)error >= sizeof(line)) {
44 syslog(LOG_NOTICE, "local delivery deferred: can not write header: %m");
45 return (1);
46 }
47 if (write(mbox, line, error) != error)
48 goto wrerror;
49
50 while (!feof(it->mailf)) {
51 if (fgets(line, sizeof(line), it->mailf) == NULL)
52 break;
53 linelen = strlen(line);
54 if (linelen == 0 || line[linelen - 1] != '\n') {
55 syslog(LOG_CRIT, "local delivery failed: corrupted queue file");
56 *errmsg = "corrupted queue file";
57 error = -1;
58 goto chop;
59 }
60
61 if (strncmp(line, "From ", 5) == 0) {
62 const char *gt = ">";
63
64 if (write(mbox, gt, 1) != 1)
65 goto wrerror;
66 }
67 if ((size_t)write(mbox, line, linelen) != linelen)
68 goto wrerror;
69 }
70 line[0] = '\n';
71 if (write(mbox, line, 1) != 1)
72 goto wrerror;
73 close(mbox);
74 return (0);
75
76 wrerror:
77 syslog(LOG_ERR, "local delivery failed: write error: %m");
78 error = 1;
79 chop:
80 if (ftruncate(mbox, mboxlen) != 0)
81 syslog(LOG_WARNING, "error recovering mbox `%s': %m", fn);
82 close(mbox);
83 return (error);
84 }