2 ** dropsbr.c -- create/read/manipulate mail drops
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>
24 ** Main entry point to open/create and lock
25 ** a file or maildrop.
28 mbx_open(char *file, uid_t uid, gid_t gid, mode_t mode)
35 /* attempt to open and lock file */
36 for (count = 4; count > 0; count--) {
37 if ((fd = lkopen(file, O_RDWR | O_CREAT | O_NONBLOCK, mode))
40 #if defined(FCNTL_LOCKING) || defined(LOCKF_LOCKING)
54 /* just return error */
59 /* good file descriptor */
66 ** Return if we still failed after 4 attempts,
67 ** or we just want to skip the sanity checks.
72 /* Do sanity checks on maildrop. */
73 if (fstat(fd, &st) == NOTOK) {
75 ** The stat failed. So we make sure file
76 ** has right ownership/modes
78 chown(file, uid, gid);
80 } else if (st.st_size > (off_t) 0) {
83 /* Check/prepare MBOX style maildrop for appending. */
84 if (lseek(fd, (off_t) 0, SEEK_END) == (off_t) NOTOK) {
90 /* if error, attempt to close it */
91 if (status == NOTOK) {
103 ** Append message to end of file or maildrop.
106 mbx_copy(char *mailbox, int md, int fd, int noisy)
114 pos = (long) lseek(md, (off_t) 0, SEEK_CUR);
116 if ((j = dup(fd)) == NOTOK)
118 if ((fp = fdopen(j, "r")) == NULL) {
122 start = lseek(md, (off_t) 0, SEEK_CUR);
124 for (j = 0; fgets(buffer, sizeof(buffer), fp) != NULL; j++) {
126 ** Check the first line, and make some changes.
130 ** Change the "Return-Path:" field
131 ** (if in first line) back to "From ".
133 if (strncmp(buffer, "Return-Path:", 12)==0) {
134 char tmpbuffer[BUFSIZ];
137 strncpy(tmpbuffer, buffer, sizeof(tmpbuffer));
139 if (!(fp = strchr(ep + 1, ' ')))
140 fp = strchr(ep + 1, '\n');
141 tp = dctime(dlocaltimenow());
142 snprintf(buffer, sizeof(buffer),
144 (int)(fp-ep), ep, tp);
145 } else if (strncmp(buffer, "X-Envelope-From:",
148 ** Change the "X-Envelope-From:" field
149 ** (if first line) back to "From ".
151 char tmpbuffer[BUFSIZ];
154 strncpy(tmpbuffer, buffer, sizeof(tmpbuffer));
156 snprintf(buffer, sizeof(buffer), "From %s",
158 } else if (strncmp(buffer, "From ", 5)!=0) {
160 ** If there is already a "From " line,
161 ** then leave it alone. Else we add one.
163 char tmpbuffer[BUFSIZ];
166 strncpy(tmpbuffer, buffer, sizeof(tmpbuffer));
167 ep = "nobody@nowhere";
168 tp = dctime(dlocaltimenow());
169 snprintf(buffer, sizeof(buffer),
170 "From %s %s%s", ep, tp,
176 ** If this is not first line, and begins with "From ",
177 ** then prepend line with ">".
179 if (j != 0 && strncmp(buffer, "From ", 5) == 0) {
183 if (write(md, buffer, i) != i) {
189 if (write(md, "\n", 1) != 1) {
194 lseek(fd, (off_t) 0, SEEK_END);
195 stop = lseek(md, (off_t) 0, SEEK_CUR);
202 ** Close and unlock file/maildrop.
205 mbx_close(char *mailbox, int md)
207 if (lkclose(md, mailbox) == 0)