1/*
2 * Copyright (c) 2008-2014, Simon Schubert <2@0x2c.org>.
3 * Copyright (c) 2008 The DragonFly Project.  All rights reserved.
4 *
5 * This code is derived from software contributed to The DragonFly Project
6 * by Simon Schubert <2@0x2c.org>.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in
16 *    the documentation and/or other materials provided with the
17 *    distribution.
18 * 3. Neither the name of The DragonFly Project nor the names of its
19 *    contributors may be used to endorse or promote products derived
20 *    from this software without specific, prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
26 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36#include <sys/types.h>
37#include <sys/wait.h>
38
39#include <err.h>
40#include <errno.h>
41#include <fcntl.h>
42#include <limits.h>
43#include <paths.h>
44#include <signal.h>
45#include <stdint.h>
46#include <stdio.h>
47#include <strings.h>
48#include <string.h>
49#include <syslog.h>
50#include <unistd.h>
51
52#include "dma.h"
53
54static int
55create_mbox(const char *name)
56{
57	struct sigaction sa, osa;
58	pid_t child, waitchild;
59	int status;
60	int i;
61	long maxfd;
62	int e;
63	int r = -1;
64
65	/*
66	 * We need to enable SIGCHLD temporarily so that waitpid works.
67	 */
68	bzero(&sa, sizeof(sa));
69	sa.sa_handler = SIG_DFL;
70	sigaction(SIGCHLD, &sa, &osa);
71
72	do_timeout(100, 0);
73
74	child = fork();
75	switch (child) {
76	case 0:
77		/* child */
78		maxfd = sysconf(_SC_OPEN_MAX);
79		if (maxfd == -1)
80			maxfd = 1024;	/* what can we do... */
81
82		for (i = 3; i <= maxfd; ++i)
83			close(i);
84
85		execl(LIBEXEC_PATH "/dma-mbox-create", "dma-mbox-create", name, (char *)NULL);
86		syslog(LOG_ERR, "cannot execute "LIBEXEC_PATH"/dma-mbox-create: %m");
87		exit(EX_SOFTWARE);
88
89	default:
90		/* parent */
91		waitchild = waitpid(child, &status, 0);
92
93		e = errno;
94
95		do_timeout(0, 0);
96
97		if (waitchild == -1 && e == EINTR) {
98			syslog(LOG_ERR, "hung child while creating mbox `%s': %m", name);
99			break;
100		}
101
102		if (waitchild == -1) {
103			syslog(LOG_ERR, "child disappeared while creating mbox `%s': %m", name);
104			break;
105		}
106
107		if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
108			syslog(LOG_ERR, "error creating mbox `%s'", name);
109			break;
110		}
111
112		/* success */
113		r = 0;
114		break;
115
116	case -1:
117		/* error */
118		syslog(LOG_ERR, "error creating mbox");
119		break;
120	}
121
122	sigaction(SIGCHLD, &osa, NULL);
123
124	return (r);
125}
126
127int
128deliver_local(struct qitem *it)
129{
130	char fn[PATH_MAX+1];
131	char line[1000];
132	const char *sender;
133	const char *newline = "\n";
134	size_t linelen;
135	int tries = 0;
136	int mbox;
137	int error;
138	int hadnl = 0;
139	off_t mboxlen;
140	time_t now = time(NULL);
141
142	error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
143	if (error < 0 || (size_t)error >= sizeof(fn)) {
144		syslog(LOG_NOTICE, "local delivery deferred: %m");
145		return (1);
146	}
147
148retry:
149	/* wait for a maximum of 100s to get the lock to the file */
150	do_timeout(100, 0);
151
152	/* don't use O_CREAT here, because we might be running as the wrong user. */
153	mbox = open_locked(fn, O_WRONLY|O_APPEND);
154	if (mbox < 0) {
155		int e = errno;
156
157		do_timeout(0, 0);
158
159		switch (e) {
160		case EACCES:
161		case ENOENT:
162			/*
163			 * The file does not exist or we can't access it.
164			 * Call dma-mbox-create to create it and fix permissions.
165			 */
166			if (tries > 0 || create_mbox(it->addr) != 0) {
167				syslog(LOG_ERR, "local delivery deferred: can not create `%s'", fn);
168				return (1);
169			}
170			++tries;
171			goto retry;
172
173		case EINTR:
174			syslog(LOG_NOTICE, "local delivery deferred: can not lock `%s'", fn);
175			break;
176
177		default:
178			syslog(LOG_NOTICE, "local delivery deferred: can not open `%s': %m", fn);
179			break;
180		}
181		return (1);
182	}
183	do_timeout(0, 0);
184
185	mboxlen = lseek(mbox, 0, SEEK_END);
186
187	/* New mails start with \nFrom ...., unless we're at the beginning of the mbox */
188	if (mboxlen == 0)
189		newline = "";
190
191	/* If we're bouncing a message, claim it comes from MAILER-DAEMON */
192	sender = it->sender;
193	if (strcmp(sender, "") == 0)
194		sender = "MAILER-DAEMON";
195
196	if (fseek(it->mailf, 0, SEEK_SET) != 0) {
197		syslog(LOG_NOTICE, "local delivery deferred: can not seek: %m");
198		goto out;
199	}
200
201	error = snprintf(line, sizeof(line), "%sFrom %s %s", newline, sender, ctime(&now));
202	if (error < 0 || (size_t)error >= sizeof(line)) {
203		syslog(LOG_NOTICE, "local delivery deferred: can not write header: %m");
204		goto out;
205	}
206	if (write(mbox, line, error) != error)
207		goto wrerror;
208
209	while (!feof(it->mailf)) {
210		if (fgets(line, sizeof(line), it->mailf) == NULL)
211			break;
212		linelen = strlen(line);
213		if (linelen == 0 || line[linelen - 1] != '\n') {
214			syslog(LOG_CRIT, "local delivery failed: corrupted queue file");
215			snprintf(errmsg, sizeof(errmsg), "corrupted queue file");
216			error = -1;
217			goto chop;
218		}
219
220		/*
221		 * mboxro processing:
222		 * - escape lines that start with "From " with a > sign.
223		 * - be reversible by escaping lines that contain an arbitrary
224		 *   number of > signs, followed by "From ", i.e. />*From / in regexp.
225		 * - strict mbox processing only requires escaping after empty lines,
226		 *   yet most MUAs seem to relax this requirement and will treat any
227		 *   line starting with "From " as the beginning of a new mail.
228		 */
229		if ((!MBOX_STRICT || hadnl) &&
230		    strncmp(&line[strspn(line, ">")], "From ", 5) == 0) {
231			const char *gt = ">";
232
233			if (write(mbox, gt, 1) != 1)
234				goto wrerror;
235			hadnl = 0;
236		} else if (strcmp(line, "\n") == 0) {
237			hadnl = 1;
238		} else {
239			hadnl = 0;
240		}
241		if ((size_t)write(mbox, line, linelen) != linelen)
242			goto wrerror;
243	}
244	close(mbox);
245	return (0);
246
247wrerror:
248	syslog(LOG_ERR, "local delivery failed: write error: %m");
249	error = 1;
250chop:
251	if (ftruncate(mbox, mboxlen) != 0)
252		syslog(LOG_WARNING, "error recovering mbox `%s': %m", fn);
253out:
254	close(mbox);
255	return (error);
256}
257