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.
11 #include <h/dropsbr.h>
21 ** Main entry point to open/create and lock
22 ** a file or maildrop.
25 mbox_open(char *file, uid_t uid, gid_t gid, mode_t mode)
32 /* attempt to open and lock file */
33 for (count = 4; count > 0; count--) {
34 if ((fd = lkopen(file, O_RDWR | O_CREAT | O_NONBLOCK, mode))
37 #if defined(FCNTL_LOCKING) || defined(LOCKF_LOCKING)
51 /* just return error */
56 /* good file descriptor */
63 ** Return if we still failed after 4 attempts,
64 ** or we just want to skip the sanity checks.
69 /* Do sanity checks on maildrop. */
70 if (fstat(fd, &st) == NOTOK) {
72 ** The stat failed. So we make sure file
73 ** has right ownership/modes
75 chown(file, uid, gid);
77 } else if (st.st_size > (off_t) 0) {
80 /* Check/prepare MBOX style maildrop for appending. */
81 if (lseek(fd, (off_t) 0, SEEK_END) == (off_t) NOTOK) {
87 /* if error, attempt to close it */
88 if (status == NOTOK) {
99 ** Append message to end of mbox.
102 mbox_copy(int to, int from)
108 if ((i = dup(from)) == NOTOK)
110 if ((fp = fdopen(i, "r")) == NULL) {
115 for (i = 0; fgets(buffer, sizeof(buffer), fp) != NULL; i++) {
117 ** Check the first line, and make some changes.
121 ** Change the "Return-Path:" field
122 ** (if in first line) back to "From ".
124 if (strncmp(buffer, "Return-Path:", 12)==0) {
125 char tmpbuffer[BUFSIZ];
128 strncpy(tmpbuffer, buffer, sizeof(tmpbuffer));
130 if (!(fp = strchr(ep + 1, ' ')))
131 fp = strchr(ep + 1, '\n');
132 tp = dctime(dlocaltimenow());
133 snprintf(buffer, sizeof(buffer),
135 (int)(fp-ep), ep, tp);
136 } else if (strncmp(buffer, "X-Envelope-From:",
139 ** Change the "X-Envelope-From:" field
140 ** (if first line) back to "From ".
142 char tmpbuffer[BUFSIZ];
145 strncpy(tmpbuffer, buffer, sizeof(tmpbuffer));
147 snprintf(buffer, sizeof(buffer), "From %s",
149 } else if (strncmp(buffer, "From ", 5)!=0) {
151 ** If there is already a "From " line,
152 ** then leave it alone. Else we add one.
154 char tmpbuffer[BUFSIZ];
157 strncpy(tmpbuffer, buffer, sizeof(tmpbuffer));
158 ep = "nobody@nowhere";
159 tp = dctime(dlocaltimenow());
160 snprintf(buffer, sizeof(buffer),
161 "From %s %s%s", ep, tp,
167 ** If this is not first line, and begins with "From ",
168 ** then prepend line with ">". (`mboxo' format is used.)
170 if (i != 0 && strncmp(buffer, "From ", 5) == 0) {
173 if (write(to, buffer, strlen(buffer)) != (int)strlen(buffer)) {
179 if (write(to, "\n", 1) != 1) {
184 lseek(from, (off_t) 0, SEEK_END);
191 ** Close and unlock file/maildrop.
194 mbox_close(char *mailbox, int md)
196 if (lkclose(md, mailbox) == 0)