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 <string.h>
48#include <syslog.h>
49#include <unistd.h>
50
51#include "dma.h"
52
53static int
54create_mbox(const char *name)
55{
56	struct sigaction sa, osa;
57	pid_t child, waitchild;
58	int status;
59	int i;
60	long maxfd;
61	int e;
62	int r = -1;
63
64	/*
65	 * We need to enable SIGCHLD temporarily so that waitpid works.
66	 */
67	bzero(&sa, sizeof(sa));
68	sa.sa_handler = SIG_DFL;
69	sigaction(SIGCHLD, &sa, &osa);
70
71	do_timeout(100, 0);
72
73	child = fork();
74	switch (child) {
75	case 0:
76		/* child */
77		maxfd = sysconf(_SC_OPEN_MAX);
78		if (maxfd == -1)
79			maxfd = 1024;	/* what can we do... */
80
81		for (i = 3; i <= maxfd; ++i)
82			close(i);
83
84		execl(LIBEXEC_PATH "/dma-mbox-create", "dma-mbox-create", name, NULL);
85		syslog(LOG_ERR, "cannot execute "LIBEXEC_PATH"/dma-mbox-create: %m");
86		exit(EX_SOFTWARE);
87
88	default:
89		/* parent */
90		waitchild = waitpid(child, &status, 0);
91
92		e = errno;
93
94		do_timeout(0, 0);
95
96		if (waitchild == -1 && e == EINTR) {
97			syslog(LOG_ERR, "hung child while creating mbox `%s': %m", name);
98			break;
99		}
100
101		if (waitchild == -1) {
102			syslog(LOG_ERR, "child disappeared while creating mbox `%s': %m", name);
103			break;
104		}
105
106		if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
107			syslog(LOG_ERR, "error creating mbox `%s'", name);
108			break;
109		}
110
111		/* success */
112		r = 0;
113		break;
114
115	case -1:
116		/* error */
117		syslog(LOG_ERR, "error creating mbox");
118		break;
119	}
120
121	sigaction(SIGCHLD, &osa, NULL);
122
123	return (r);
124}
125
126int
127deliver_local(struct qitem *it)
128{
129	char fn[PATH_MAX+1];
130	char line[1000];
131	const char *sender;
132	const char *newline = "\n";
133	size_t linelen;
134	int tries = 0;
135	int mbox;
136	int error;
137	int hadnl = 0;
138	off_t mboxlen;
139	time_t now = time(NULL);
140
141	error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
142	if (error < 0 || (size_t)error >= sizeof(fn)) {
143		syslog(LOG_NOTICE, "local delivery deferred: %m");
144		return (1);
145	}
146
147retry:
148	/* wait for a maximum of 100s to get the lock to the file */
149	do_timeout(100, 0);
150
151	/* don't use O_CREAT here, because we might be running as the wrong user. */
152	mbox = open_locked(fn, O_WRONLY|O_APPEND);
153	if (mbox < 0) {
154		int e = errno;
155
156		do_timeout(0, 0);
157
158		switch (e) {
159		case EACCES:
160		case ENOENT:
161			/*
162			 * The file does not exist or we can't access it.
163			 * Call dma-mbox-create to create it and fix permissions.
164			 */
165			if (tries > 0 || create_mbox(it->addr) != 0) {
166				syslog(LOG_ERR, "local delivery deferred: can not create `%s'", fn);
167				return (1);
168			}
169			++tries;
170			goto retry;
171
172		case EINTR:
173			syslog(LOG_NOTICE, "local delivery deferred: can not lock `%s'", fn);
174			break;
175
176		default:
177			syslog(LOG_NOTICE, "local delivery deferred: can not open `%s': %m", fn);
178			break;
179		}
180		return (1);
181	}
182	do_timeout(0, 0);
183
184	mboxlen = lseek(mbox, 0, SEEK_END);
185
186	/* New mails start with \nFrom ...., unless we're at the beginning of the mbox */
187	if (mboxlen == 0)
188		newline = "";
189
190	/* If we're bouncing a message, claim it comes from MAILER-DAEMON */
191	sender = it->sender;
192	if (strcmp(sender, "") == 0)
193		sender = "MAILER-DAEMON";
194
195	if (fseek(it->mailf, 0, SEEK_SET) != 0) {
196		syslog(LOG_NOTICE, "local delivery deferred: can not seek: %m");
197		goto out;
198	}
199
200	error = snprintf(line, sizeof(line), "%sFrom %s %s", newline, sender, ctime(&now));
201	if (error < 0 || (size_t)error >= sizeof(line)) {
202		syslog(LOG_NOTICE, "local delivery deferred: can not write header: %m");
203		goto out;
204	}
205	if (write(mbox, line, error) != error)
206		goto wrerror;
207
208	while (!feof(it->mailf)) {
209		if (fgets(line, sizeof(line), it->mailf) == NULL)
210			break;
211		linelen = strlen(line);
212		if (linelen == 0 || line[linelen - 1] != '\n') {
213			syslog(LOG_CRIT, "local delivery failed: corrupted queue file");
214			snprintf(errmsg, sizeof(errmsg), "corrupted queue file");
215			error = -1;
216			goto chop;
217		}
218
219		/*
220		 * mboxro processing:
221		 * - escape lines that start with "From " with a > sign.
222		 * - be reversable by escaping lines that contain an arbitrary
223		 *   number of > signs, followed by "From ", i.e. />*From / in regexp.
224		 * - strict mbox processing only requires escaping after empty lines,
225		 *   yet most MUAs seem to relax this requirement and will treat any
226		 *   line starting with "From " as the beginning of a new mail.
227		 */
228		if ((!MBOX_STRICT || hadnl) &&
229		    strncmp(&line[strspn(line, ">")], "From ", 5) == 0) {
230			const char *gt = ">";
231
232			if (write(mbox, gt, 1) != 1)
233				goto wrerror;
234			hadnl = 0;
235		} else if (strcmp(line, "\n") == 0) {
236			hadnl = 1;
237		} else {
238			hadnl = 0;
239		}
240		if ((size_t)write(mbox, line, linelen) != linelen)
241			goto wrerror;
242	}
243	close(mbox);
244	return (0);
245
246wrerror:
247	syslog(LOG_ERR, "local delivery failed: write error: %m");
248	error = 1;
249chop:
250	if (ftruncate(mbox, mboxlen) != 0)
251		syslog(LOG_WARNING, "error recovering mbox `%s': %m", fn);
252out:
253	close(mbox);
254	return (error);
255}
256