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>
24 ** Main entry point to open/create and lock
25 ** a file or maildrop.
28 mbox_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) {
102 ** Append message to end of mbox.
105 mbox_copy(int to, int from)
111 if ((i = dup(from)) == NOTOK)
113 if ((fp = fdopen(i, "r")) == NULL) {
118 for (i = 0; fgets(buffer, sizeof(buffer), fp) != NULL; i++) {
120 ** Check the first line, and make some changes.
124 ** Change the "Return-Path:" field
125 ** (if in first line) back to "From ".
127 if (strncmp(buffer, "Return-Path:", 12)==0) {
128 char tmpbuffer[BUFSIZ];
131 strncpy(tmpbuffer, buffer, sizeof(tmpbuffer));
133 if (!(fp = strchr(ep + 1, ' ')))
134 fp = strchr(ep + 1, '\n');
135 tp = dctime(dlocaltimenow());
136 snprintf(buffer, sizeof(buffer),
138 (int)(fp-ep), ep, tp);
139 } else if (strncmp(buffer, "X-Envelope-From:",
142 ** Change the "X-Envelope-From:" field
143 ** (if first line) back to "From ".
145 char tmpbuffer[BUFSIZ];
148 strncpy(tmpbuffer, buffer, sizeof(tmpbuffer));
150 snprintf(buffer, sizeof(buffer), "From %s",
152 } else if (strncmp(buffer, "From ", 5)!=0) {
154 ** If there is already a "From " line,
155 ** then leave it alone. Else we add one.
157 char tmpbuffer[BUFSIZ];
160 strncpy(tmpbuffer, buffer, sizeof(tmpbuffer));
161 ep = "nobody@nowhere";
162 tp = dctime(dlocaltimenow());
163 snprintf(buffer, sizeof(buffer),
164 "From %s %s%s", ep, tp,
170 ** If this is not first line, and begins with "From ",
171 ** then prepend line with ">". (`mboxo' format is used.)
173 if (i != 0 && strncmp(buffer, "From ", 5) == 0) {
176 if (write(to, buffer, strlen(buffer)) != strlen(buffer)) {
182 if (write(to, "\n", 1) != 1) {
187 lseek(from, (off_t) 0, SEEK_END);
194 ** Close and unlock file/maildrop.
197 mbox_close(char *mailbox, int md)
199 if (lkclose(md, mailbox) == 0)