2 ** dropsbr.c -- append to mbox files
4 ** This code is Copyright (c) 2002, by the authors of nmh. See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
13 #include <h/dropsbr.h>
20 ** Main entry point to open/create and lock
21 ** a file or maildrop.
24 mbox_open(char *file, uid_t uid, gid_t gid, mode_t mode)
31 /* attempt to open and lock file */
32 for (count = 4; count > 0; count--) {
33 if ((fd = lkopen(file, O_RDWR | O_CREAT | O_NONBLOCK, mode))
36 #if defined(FCNTL_LOCKING) || defined(LOCKF_LOCKING)
50 /* just return error */
55 /* good file descriptor */
62 ** Return if we still failed after 4 attempts,
63 ** or we just want to skip the sanity checks.
68 /* Do sanity checks on maildrop. */
69 if (fstat(fd, &st) == NOTOK) {
71 ** The stat failed. So we make sure file
72 ** has right ownership/modes
74 chown(file, uid, gid);
76 } else if (st.st_size > (off_t) 0) {
79 /* Check/prepare MBOX style maildrop for appending. */
80 if (lseek(fd, (off_t) 0, SEEK_END) == (off_t) NOTOK) {
86 /* if error, attempt to close it */
87 if (status == NOTOK) {
98 ** Append message to end of mbox.
101 mbox_copy(int to, int from)
107 if ((i = dup(from)) == NOTOK)
109 if ((fp = fdopen(i, "r")) == NULL) {
114 for (i = 0; fgets(buffer, sizeof(buffer), fp) != NULL; i++) {
116 ** Check the first line, and make some changes.
120 ** Change the "Return-Path:" field
121 ** (if in first line) back to "From ".
123 if (strncmp(buffer, "Return-Path:", 12)==0) {
124 char tmpbuffer[BUFSIZ];
127 strncpy(tmpbuffer, buffer, sizeof(tmpbuffer));
129 if (!(fp = strchr(ep + 1, ' ')))
130 fp = strchr(ep + 1, '\n');
131 tp = dctime(dlocaltimenow());
132 snprintf(buffer, sizeof(buffer),
134 (int)(fp-ep), ep, tp);
135 } else if (strncmp(buffer, "X-Envelope-From:",
138 ** Change the "X-Envelope-From:" field
139 ** (if first line) back to "From ".
141 char tmpbuffer[BUFSIZ];
144 strncpy(tmpbuffer, buffer, sizeof(tmpbuffer));
146 snprintf(buffer, sizeof(buffer), "From %s",
148 } else if (strncmp(buffer, "From ", 5)!=0) {
150 ** If there is already a "From " line,
151 ** then leave it alone. Else we add one.
153 char tmpbuffer[BUFSIZ];
156 strncpy(tmpbuffer, buffer, sizeof(tmpbuffer));
157 ep = "nobody@nowhere";
158 tp = dctime(dlocaltimenow());
159 snprintf(buffer, sizeof(buffer),
160 "From %s %s%s", ep, tp,
166 ** If this is not first line, and begins with "From ",
167 ** then prepend line with ">". (`mboxo' format is used.)
169 if (i != 0 && strncmp(buffer, "From ", 5) == 0) {
172 if (write(to, buffer, strlen(buffer)) != (int)strlen(buffer)) {
178 if (write(to, "\n", 1) != 1) {
183 lseek(from, (off_t) 0, SEEK_END);
190 ** Close and unlock file/maildrop.
193 mbox_close(char *mailbox, int md)
195 if (lkclose(md, mailbox) == 0)