]>
diplodocus.org Git - mdeliver/blob - mdeliver.c
5dd5239756bbb74da3f25f3744052ac323d907a9
1 /* mdeliver.c -- Deliver a message to a Maildir.
5 * This program is in the public domain.
22 #if !defined(HOST_NAME_MAX)
23 #if defined MAXHOSTNAMELEN
24 #define HOST_NAME_MAX MAXHOSTNAMELEN
26 #define HOST_NAME_MAX 64
30 /* holds 2^128 - 1 in decimal, plus '\0' */
33 /* 1 for '\0', 4 for "tmp/", HOST_NAME_MAX for the hostname, and two
34 * LEN_ULONGs for time and pid. */
35 #define TMPNAMLEN 1 + 4 + HOST_NAME_MAX + LEN_ULONG + LEN_ULONG
37 /* Write all of buf, even if write(2) is interrupted. */
39 full_write(int fd
, const char *buf
, size_t nbytes
)
43 /* Loop until nbytes of buf have been written. */
45 /* Keep trying until write succeeds without interruption. */
47 r
= write(fd
, buf
+ w
, nbytes
- w
);
48 } while (r
< 0 && errno
== EINTR
);
61 deliver(char *maildir
, char *newfn
)
63 char fn
[TMPNAMLEN
], host
[HOST_NAME_MAX
+ 1];
64 char *buildfn
; /* used to build up the fn */
73 if (chdir(maildir
) != 0) {
74 err(EX_TEMPFAIL
, "Failed chdir(%s)", maildir
);
78 gethostname(host
, sizeof(host
));
80 for (try = 0; ; try++) {
84 buildfn
= fn
+ sprintf(fn
, "tmp/");
85 buildfn
+= strftime(buildfn
, LEN_ULONG
+ 1, "%s.", t
);
86 buildfn
+= snprintf(buildfn
, LEN_ULONG
+ 1, "%d.", pid
);
87 buildfn
+= sprintf(buildfn
, "%s", host
);
89 if (stat(fn
, &statbuf
) != 0) {
90 if (errno
== ENOENT
) {
96 errx(EX_TEMPFAIL
, "Attempted filename exists.");
102 fd
= open(fn
, O_WRONLY
| O_EXCL
| O_CREAT
, 0644);
104 err(EX_TEMPFAIL
, "Failed open(%s)", fn
);
107 /* From this point, we have a tmp file, so if someting fails we
108 * must try to unlink it before bombing. */
110 while ((r
= read(STDIN_FILENO
, buf
, BUFSIZ
)) > 0) {
111 if (full_write(fd
, buf
, r
) != r
) {
113 err(EX_TEMPFAIL
, "Failed write(%s)", fn
);
119 err(EX_TEMPFAIL
, "Failed fsync(%s)", fn
);
123 err(EX_TEMPFAIL
, "Failed close(%s)", fn
);
127 memcpy(newfn
, "new", 3);
129 if (rename(fn
, newfn
) != 0) {
131 err(EX_TEMPFAIL
, "Failed rename(%s, new)", fn
);
136 main(int argc
, char *argv
[])
138 char newfn
[TMPNAMLEN
];
144 deliver("Maildir", newfn
);
147 if ((pid
= fork()) > 0) {
149 } else if (pid
== 0) {
152 execvp(argv
[0], argv
);
158 /* If we got here fork or exec failed, so try to write an
159 * error message where later mail processors can find it. We
160 * really can't do anything about it if this fails. */
161 memcpy(newfn
, "err", 3);
162 fd
= open(newfn
, O_WRONLY
| O_EXCL
| O_CREAT
, 0644);
163 errfile
= fdopen(fd
, "w");
165 fprintf(errfile
, "%s:%d\n", fail
, errno
);
169 /* Always return 0 because deliver exits if it fails, and if it
170 * succeeds we cannot return a failure code to the MTA. */