xref: /openbsd/usr.sbin/smtpd/mda_mbox.c (revision 4cfece93)
1 /*	$OpenBSD: mda_mbox.c,v 1.2 2020/02/03 15:41:22 gilles Exp $	*/
2 
3 /*
4  * Copyright (c) 2018 Gilles Chehade <gilles@poolp.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/queue.h>
22 #include <sys/tree.h>
23 #include <sys/socket.h>
24 
25 #include <err.h>
26 #include <errno.h>
27 #include <event.h>
28 #include <fcntl.h>
29 #include <imsg.h>
30 #include <paths.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sysexits.h>
35 #include <unistd.h>
36 #include <limits.h>
37 
38 #include "smtpd.h"
39 
40 
41 void
42 mda_mbox(struct deliver *deliver)
43 {
44 	int		ret;
45 	char		sender[LINE_MAX];
46 	char		*envp[] = {
47 		"HOME=/",
48 		"PATH=" _PATH_DEFPATH,
49 		"LOGNAME=root",
50 		"USER=root",
51 		NULL,
52 	};
53 
54 	if (deliver->sender.user[0] == '\0' &&
55 	    deliver->sender.domain[0] == '\0')
56 		ret = snprintf(sender, sizeof sender, "MAILER-DAEMON");
57 	else
58 		ret = snprintf(sender, sizeof sender, "%s@%s",
59 			       deliver->sender.user, deliver->sender.domain);
60 	if (ret < 0 || (size_t)ret >= sizeof sender)
61 		errx(EX_TEMPFAIL, "sender address too long");
62 
63 	execle(PATH_MAILLOCAL, PATH_MAILLOCAL, "-f",
64 	       sender, deliver->userinfo.username, (char *)NULL, envp);
65 	perror("execl");
66 	_exit(EX_TEMPFAIL);
67 }
68 
69 void
70 mda_mbox_init(struct deliver *deliver)
71 {
72 	int	fd;
73 	int	ret;
74 	char	buffer[LINE_MAX];
75 
76 	ret = snprintf(buffer, sizeof buffer, "%s/%s",
77 	    _PATH_MAILDIR, deliver->userinfo.username);
78 	if (ret < 0 || (size_t)ret >= sizeof buffer)
79 		errx(EX_TEMPFAIL, "mailbox pathname too long");
80 
81 	if ((fd = open(buffer, O_CREAT|O_EXCL, 0)) == -1) {
82 		if (errno == EEXIST)
83 			return;
84 		err(EX_TEMPFAIL, "open");
85 	}
86 
87 	if (fchown(fd, deliver->userinfo.uid, deliver->userinfo.gid) == -1)
88 		err(EX_TEMPFAIL, "fchown");
89 
90 	if (fchmod(fd, S_IRUSR|S_IWUSR) == -1)
91 		err(EX_TEMPFAIL, "fchown");
92 }
93