2 * Copyright (c) 1998-2004 Sendmail, Inc. and its suppliers.
4 * Copyright (c) 1990, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * By using this file, you agree to the terms and conditions set
8 * forth in the LICENSE file which can be found at the top level of
9 * the sendmail distribution.
18 "@(#) Copyright (c) 1998-2004 Sendmail, Inc. and its suppliers.\n\
19 All rights reserved.\n\
20 Copyright (c) 1990, 1993, 1994\n\
21 The Regents of the University of California. All rights reserved.\n")
23 SM_IDSTR(id, "@(#)$Id: mail.local.c,v 8.256 2008/02/19 07:13:30 gshapiro Exp $")
26 #include <sm/errstring.h>
28 #include <sm/limits.h>
31 # undef EX_OK /* unistd.h may have another use for this */
33 # define LOCKFILE_PMODE 0
35 #include <sm/sysexits.h>
39 #endif /* ! HASHSPOOL */
41 # define HASHSPOOLMD5 0
42 #endif /* ! HASHSPOOLMD5 */
45 ** This is not intended to work on System V derived systems
46 ** such as Solaris or HP-UX, since they use a totally different
47 ** approach to mailboxes (essentially, they have a set-group-ID program
48 ** rather than set-user-ID, and they rely on the ability to "give away"
49 ** files to do their work). IT IS NOT A BUG that this doesn't
50 ** work on such architectures.
57 #include <sys/types.h>
61 # include <sys/socket.h>
62 # include <sys/file.h>
63 # include <netinet/in.h>
64 # include <arpa/nameser.h>
68 #include <sm/string.h>
73 #include <sendmail/pathnames.h>
80 # include <openssl/md5.h>
81 # endif /* HASHSPOOLMD5 */
82 #endif /* HASHSPOOL */
86 ** Override path to mail store at run time (using -p).
87 ** From: Eugene Grosbein of Svyaz Service JSC
88 ** See: http://www.freebsd.org/cgi/query-pr.cgi?pr=bin/114195
89 ** NOTE: Update man page before adding this to a release.
91 #endif /* _FFR_SPOOL_PATH */
95 # define LOCKTO_RM 300 /* timeout for stale lockfile removal */
96 #endif /* ! LOCKTO_RM */
98 # define LOCKTO_GLOB 400 /* global timeout for lockfile creation */
99 #endif /* ! LOCKTO_GLOB */
101 /* define a realloc() which works for NULL pointers */
102 #define REALLOC(ptr, size) (((ptr) == NULL) ? malloc(size) : realloc(ptr, size))
105 ** If you don't have flock, you could try using lockf instead.
109 # define flock(a, b) lockf(a, b, 0)
112 # endif /* LOCK_EX */
113 # define LOCK_EX F_LOCK
114 #endif /* LDA_USE_LOCKF */
117 # include <sys/file.h>
118 #endif /* ! LOCK_EX */
121 ** If you don't have setreuid, and you have saved uids, and you have
122 ** a seteuid() call that doesn't try to emulate using setuid(), then
123 ** you can try defining LDA_USE_SETEUID.
126 #ifdef LDA_USE_SETEUID
127 # define setreuid(r, e) seteuid(e)
128 #endif /* LDA_USE_SETEUID */
130 #ifdef LDA_CONTENTLENGTH
131 # define CONTENTLENGTH 1
132 #endif /* LDA_CONTENTLENGTH */
135 # define INADDRSZ 4 /* size of an IPv4 address in bytes */
136 #endif /* ! INADDRSZ */
139 # include <maillock.h>
140 #endif /* MAILLOCK */
142 #ifndef MAILER_DAEMON
143 # define MAILER_DAEMON "MAILER-DAEMON"
144 #endif /* ! MAILER_DAEMON */
147 char ContentHdr[40] = "Content-Length: ";
150 #endif /* CONTENTLENGTH */
152 bool EightBitMime = true; /* advertise 8BITMIME in LMTP */
153 char ErrBuf[10240]; /* error buffer */
154 int ExitVal = EX_OK; /* sysexits.h error value. */
156 bool nofsync = false;
157 bool HoldErrs = false; /* Hold errors in ErrBuf */
158 bool LMTPMode = false;
159 bool BounceQuota = false; /* permanent error when over quota */
160 bool CloseMBDB = false;
161 char *HomeMailFile = NULL; /* store mail in homedir */
164 int HashType = HASH_NONE;
166 bool StripRcptDomain = true;
167 #else /* HASHSPOOL */
168 # define StripRcptDomain true
169 #endif /* HASHSPOOL */
170 char SpoolPath[MAXPATHLEN];
172 char *parseaddr __P((char *, bool));
173 char *process_recipient __P((char *));
174 void dolmtp __P((void));
175 void deliver __P((int, char *));
176 int e_to_sys __P((int));
177 void notifybiff __P((char *));
178 int store __P((char *, bool *));
179 void usage __P((void));
180 int lockmbox __P((char *));
181 void unlockmbox __P((void));
182 void mailerr __P((const char *, const char *, ...));
183 void flush_error __P((void));
185 const char *hashname __P((char *));
186 #endif /* HASHSPOOL */
189 static void sm_exit __P((int));
198 CloseMBDB = false; /* not really necessary, but ... */
212 char *mbdbname = "pw";
218 /* make sure we have some open file descriptors */
219 for (fd = 10; fd < 30; fd++)
222 /* use a reasonable umask */
226 openlog("mail.local", 0, LOG_MAIL);
227 # else /* LOG_MAIL */
228 openlog("mail.local", 0);
229 # endif /* LOG_MAIL */
233 /* XXX can this be converted to a compile time check? */
234 if (sm_strlcpy(SpoolPath, _PATH_MAILDIR, sizeof(SpoolPath)) >=
237 mailerr("421", "Configuration error: _PATH_MAILDIR too large");
241 while ((ch = getopt(argc, argv, "7BbdD:f:h:r:lH:p:ns")) != -1)
242 #else /* HASHSPOOL */
244 while ((ch = getopt(argc, argv, "7BbdD:f:h:r:lp:s")) != -1)
245 # else /* _FFR_SPOOL_PATH */
246 while ((ch = getopt(argc, argv, "7BbdD:f:h:r:ls")) != -1)
247 # endif /* _FFR_SPOOL_PATH */
248 #endif /* HASHSPOOL */
252 case '7': /* Do not advertise 8BITMIME */
253 EightBitMime = false;
260 case 'b': /* bounce mail when over quota. */
264 case 'd': /* Backward compatible. */
267 case 'D': /* mailbox database type */
272 case 'r': /* Backward compatible. */
275 mailerr(NULL, "Multiple -f options");
282 if (optarg != NULL || *optarg != '\0')
283 HomeMailFile = optarg;
286 mailerr(NULL, "-h: missing filename");
301 if (optarg == NULL || *optarg == '\0')
303 mailerr(NULL, "-H: missing hashinfo");
309 HashType = HASH_USER;
316 # endif /* HASHSPOOLMD5 */
319 mailerr(NULL, "-H: unknown hash type");
322 if (optarg[1] == '\0')
324 mailerr(NULL, "-H: invalid hash depth");
327 HashDepth = atoi(&optarg[1]);
328 if ((HashDepth <= 0) || ((HashDepth * 2) >= MAXPATHLEN))
330 mailerr(NULL, "-H: invalid hash depth");
336 StripRcptDomain = false;
338 #endif /* HASHSPOOL */
340 #if HASHSPOOL || _FFR_SPOOL_PATH
342 if (optarg == NULL || *optarg == '\0')
344 mailerr(NULL, "-p: missing spool path");
347 if (sm_strlcpy(SpoolPath, optarg, sizeof(SpoolPath)) >=
350 mailerr(NULL, "-p: invalid spool path");
354 #endif /* HASHSPOOL || _FFR_SPOOL_PATH */
364 /* initialize biff structures */
368 err = sm_mbdb_initialize(mbdbname);
371 char *errcode = "521";
373 if (err == EX_TEMPFAIL)
376 mailerr(errcode, "Can not open mailbox database %s: %s",
377 mbdbname, sm_strexit(err));
386 mailerr("421", "Users should not be specified in command line if LMTP required");
387 sm_exit(EX_TEMPFAIL);
395 /* Non-LMTP from here on out */
400 ** If from not specified, use the name from getlogin() if the
401 ** uid matches, otherwise, use the name from the password file
402 ** corresponding to the uid.
406 if (from == NULL && ((from = getlogin()) == NULL ||
407 (pw = getpwnam(from)) == NULL ||
409 from = (pw = getpwuid(uid)) != NULL ? pw->pw_name : "???";
412 ** There is no way to distinguish the error status of one delivery
413 ** from the rest of the deliveries. So, if we failed hard on one
414 ** or more deliveries, but had no failures on any of the others, we
415 ** return a hard failure. If we failed temporarily on one or more
416 ** deliveries, we return a temporary failure regardless of the other
417 ** failures. This results in the delivery being reattempted later
418 ** at the expense of repeated failures and multiple deliveries.
422 fd = store(from, NULL);
429 for (; *argv != NULL; ++argv)
453 while (*p != ',' && *p != ':' && *p != '\0')
458 /* Skip over , or : */
465 while (*p != '\0' && *p != '@' && *p != '>')
475 while (*p != '\0' && *p != '\"')
484 if (*p == '\0' || *(p + 1) == '\0')
488 if (*p == '+' && rcpt)
498 while (*p != '\0' && *p != '>')
508 if (*p != '\0' && *p != ' ')
520 mailerr("421 4.3.0", "Memory exhausted");
521 sm_exit(EX_TEMPFAIL);
524 (void) sm_strlcpy(p, s, l);
529 process_recipient(addr)
534 switch (sm_mbdb_lookup(addr, &user))
540 return "550 5.1.1 User unknown";
543 return "451 4.3.0 User database failure; retry later";
546 return "550 5.3.0 User database failure";
555 char *return_path = NULL;
556 char **rcpt_addr = NULL;
559 bool gotlhlo = false;
564 char myhostname[1024];
567 memset(myhostname, '\0', sizeof myhostname);
568 (void) gethostname(myhostname, sizeof myhostname - 1);
569 if (myhostname[0] == '\0')
570 sm_strlcpy(myhostname, "localhost", sizeof myhostname);
572 printf("220 %s LMTP ready\r\n", myhostname);
575 (void) fflush(stdout);
576 if (fgets(buf, sizeof(buf) - 1, stdin) == NULL)
578 p = buf + strlen(buf) - 1;
579 if (p >= buf && *p == '\n')
581 if (p >= buf && *p == '\r')
588 if (sm_strcasecmp(buf, "data") == 0)
594 mailerr("503 5.5.1", "No recipients");
598 msgfd = store(return_path, &inbody);
600 if (msgfd < 0 && !inbody)
606 for (i = 0; i < rcpt_num; i++)
610 /* print error for rcpt */
614 p = strchr(rcpt_addr[i], '+');
617 deliver(msgfd, rcpt_addr[i]);
629 if (sm_strncasecmp(buf, "lhlo ", 5) == 0)
631 /* check for duplicate per RFC 1651 4.2 */
634 mailerr("503", "%s Duplicate LHLO",
639 printf("250-%s\r\n", myhostname);
641 printf("250-8BITMIME\r\n");
642 printf("250-ENHANCEDSTATUSCODES\r\n");
643 printf("250 PIPELINING\r\n");
652 if (sm_strncasecmp(buf, "mail ", 5) == 0)
654 if (return_path != NULL)
657 "Nested MAIL command");
660 if (sm_strncasecmp(buf + 5, "from:", 5) != 0 ||
661 ((return_path = parseaddr(buf + 10,
665 "Syntax error in parameters");
668 printf("250 2.5.0 Ok\r\n");
677 if (sm_strcasecmp(buf, "noop") == 0)
679 printf("250 2.0.0 Ok\r\n");
688 if (sm_strcasecmp(buf, "quit") == 0)
690 printf("221 2.0.0 Bye\r\n");
699 if (sm_strncasecmp(buf, "rcpt ", 5) == 0)
701 if (return_path == NULL)
704 "Need MAIL command");
707 if (rcpt_num >= rcpt_alloc)
709 rcpt_alloc += RCPT_GROW;
710 rcpt_addr = (char **)
711 REALLOC((char *) rcpt_addr,
714 if (rcpt_addr == NULL)
718 sm_exit(EX_TEMPFAIL);
721 if (sm_strncasecmp(buf + 5, "to:", 3) != 0 ||
722 ((rcpt_addr[rcpt_num] = parseaddr(buf + 8,
723 StripRcptDomain)) == NULL))
726 "Syntax error in parameters");
729 err = process_recipient(rcpt_addr[rcpt_num]);
732 mailerr(NULL, "%s", err);
736 printf("250 2.1.5 Ok\r\n");
739 else if (sm_strcasecmp(buf, "rset") == 0)
741 printf("250 2.0.0 Ok\r\n");
745 free(rcpt_addr[--rcpt_num]);
746 if (return_path != NULL)
757 if (sm_strncasecmp(buf, "vrfy ", 5) == 0)
759 printf("252 2.3.3 Try RCPT to attempt delivery\r\n");
768 mailerr("500 5.5.2", "Syntax error");
783 bool eline; /* previous line was empty */
784 bool fullline = true; /* current line is terminated */
785 bool prevfl; /* previous line was terminated */
788 char tmpbuf[sizeof _PATH_LOCTMP + 1];
794 (void) sm_strlcpy(tmpbuf, _PATH_LOCTMP, sizeof tmpbuf);
795 if ((fd = mkstemp(tmpbuf)) < 0 || (fp = fdopen(fd, "w+")) == NULL)
799 mailerr("451 4.3.0", "Unable to open temporary file");
802 (void) unlink(tmpbuf);
806 printf("354 Go ahead\r\n");
807 (void) fflush(stdout);
813 (void) fprintf(fp, "From %s %s", from, ctime(&tval));
818 #endif /* CONTENTLENGTH */
822 while (fgets(line, sizeof(line), stdin) != (char *) NULL)
827 prevfl = fullline; /* preserve state of previous line */
828 while (line[line_len] != '\n' && line_len < sizeof(line) - 2)
832 /* Check for dot-stuffing */
833 if (prevfl && LMTPMode && line[0] == '.')
835 if (line[1] == '\n' ||
836 (line[1] == '\r' && line[2] == '\n'))
838 memcpy(line, line + 1, line_len);
842 /* Check to see if we have the full line from fgets() */
846 if (line[line_len - 1] == '\n')
849 line[line_len - 2] == '\r')
851 line[line_len - 2] = '\n';
852 line[line_len - 1] = '\0';
857 else if (line[line_len - 1] == '\r')
859 /* Did we just miss the CRLF? */
863 line[line_len - 1] = '\n';
867 (void) ungetc(peek, stdin);
874 if (prevfl && line[0] == '\n' && HeaderLength == 0)
878 HeaderLength = ftell(fp);
879 if (HeaderLength <= 0)
882 ** shouldn't happen, unless ftell() is
889 #else /* CONTENTLENGTH */
890 if (prevfl && line[0] == '\n')
892 #endif /* CONTENTLENGTH */
895 if (eline && line[0] == 'F' &&
897 !memcmp(line, "From ", 5))
898 (void) putc('>', fp);
901 /* discard existing "Content-Length:" headers */
902 if (prevfl && HeaderLength == 0 &&
903 (line[0] == 'C' || line[0] == 'c') &&
904 sm_strncasecmp(line, ContentHdr, 15) == 0)
907 ** be paranoid: clear the line
908 ** so no "wrong matches" may occur later
913 #endif /* CONTENTLENGTH */
918 (void) fwrite(line, sizeof(char), line_len, fp);
922 "Temporary file write error");
930 /* check if an error occurred */
936 /* Got a premature EOF -- toss message and exit */
940 /* If message not newline terminated, need an extra. */
941 if (fp != NULL && strchr(line, '\n') == NULL)
942 (void) putc('\n', fp);
948 BodyLength = ftell(fp);
949 if (HeaderLength == 0 && BodyLength > 0) /* empty body */
951 HeaderLength = BodyLength;
955 BodyLength = BodyLength - HeaderLength - 1 ;
957 if (HeaderLength > 0 && BodyLength >= 0)
959 (void) sm_snprintf(line, sizeof line, "%lld\n",
960 (LONGLONG_T) BodyLength);
961 (void) sm_strlcpy(&ContentHdr[16], line,
962 sizeof(ContentHdr) - 16);
965 BodyLength = -1; /* Something is wrong here */
966 #endif /* CONTENTLENGTH */
968 /* Output a newline; note, empty messages are allowed. */
970 (void) putc('\n', fp);
972 if (fp == NULL || fflush(fp) == EOF || ferror(fp) != 0)
974 mailerr("451 4.3.0", "Temporary file write error");
989 char path[MAXPATHLEN];
990 int mbfd = -1, nr = 0, nw, off;
994 off_t curoff, cursize;
998 #endif /* CONTENTLENGTH */
999 char biffmsg[100], buf[8 * 1024];
1003 ** Disallow delivery to unknown names -- special mailboxes can be
1004 ** handled in the sendmail aliases file.
1007 exitval = sm_mbdb_lookup(name, &user);
1014 exitval = EX_UNAVAILABLE;
1015 mailerr("550 5.1.1", "%s: User unknown", name);
1019 mailerr("451 4.3.0", "%s: User database failure; retry later",
1024 exitval = EX_UNAVAILABLE;
1025 mailerr("550 5.3.0", "%s: User database failure", name);
1029 if (exitval != EX_OK)
1031 if (ExitVal != EX_TEMPFAIL)
1039 ** Keep name reasonably short to avoid buffer overruns.
1040 ** This isn't necessary on BSD because of the proper
1041 ** definition of snprintf(), but it can cause problems
1042 ** on other systems.
1043 ** Also, clear out any bogus characters.
1047 if (strlen(name) > 40)
1049 for (p = name; *p != '\0'; p++)
1053 else if (!isprint(*p))
1056 #endif /* !HASHSPOOL */
1059 if (HomeMailFile == NULL)
1061 if (sm_strlcpyn(path, sizeof(path),
1064 #else /* HASHSPOOL */
1066 #endif /* HASHSPOOL */
1070 #endif /* HASHSPOOL */
1071 name) >= sizeof(path))
1073 exitval = EX_UNAVAILABLE;
1074 mailerr("550 5.1.1", "%s: Invalid mailbox path", name);
1078 else if (*user.mbdb_homedir == '\0')
1080 exitval = EX_UNAVAILABLE;
1081 mailerr("550 5.1.1", "%s: User missing home directory", name);
1084 else if (sm_snprintf(path, sizeof(path), "%s/%s",
1085 user.mbdb_homedir, HomeMailFile) >= sizeof(path))
1087 exitval = EX_UNAVAILABLE;
1088 mailerr("550 5.1.1", "%s: Invalid mailbox path", name);
1094 ** If the mailbox is linked or a symlink, fail. There's an obvious
1095 ** race here, that the file was replaced with a symbolic link after
1096 ** the lstat returned, but before the open. We attempt to detect
1097 ** this by comparing the original stat information and information
1098 ** returned by an fstat of the file descriptor returned by the open.
1100 ** NB: this is a symptom of a larger problem, that the mail spooling
1101 ** directory is writeable by the wrong users. If that directory is
1102 ** writeable, system security is compromised for other reasons, and
1103 ** it cannot be fixed here.
1105 ** If we created the mailbox, set the owner/group. If that fails,
1106 ** just return. Another process may have already opened it, so we
1107 ** can't unlink it. Historically, binmail set the owner/group at
1108 ** each mail delivery. We no longer do this, assuming that if the
1109 ** ownership or permissions were changed there was a reason.
1112 ** open(2) should support flock'ing the file.
1118 #else /* MAILLOCK */
1120 #endif /* MAILLOCK */
1121 if ((off = lockmbox(p)) != 0)
1123 if (off == EX_TEMPFAIL || e_to_sys(off) == EX_TEMPFAIL)
1125 ExitVal = EX_TEMPFAIL;
1126 errcode = "451 4.3.0";
1129 errcode = "551 5.3.0";
1131 mailerr(errcode, "lockmailbox %s failed; error code %d %s",
1132 p, off, errno > 0 ? sm_errstring(errno) : "");
1136 if (lstat(path, &sb) < 0)
1139 int mode = S_IRUSR|S_IWUSR;
1140 gid_t gid = user.mbdb_gid;
1145 mode |= S_IRGRP|S_IWGRP;
1146 #endif /* MAILGID */
1148 mbfd = open(path, O_APPEND|O_CREAT|O_EXCL|O_WRONLY,
1152 if (lstat(path, &sb) < 0)
1154 ExitVal = EX_CANTCREAT;
1155 mailerr("550 5.2.0",
1156 "%s: lstat: file changed after open", path);
1161 if (save_errno == EEXIST)
1164 /* open failed, don't try again */
1165 mailerr("450 4.2.0", "%s: %s", path,
1166 sm_errstring(save_errno));
1169 else if (fchown(mbfd, user.mbdb_uid, gid) < 0)
1171 mailerr("451 4.3.0", "chown %u.%u: %s",
1172 user.mbdb_uid, gid, name);
1178 ** open() was successful, now close it so can
1179 ** be opened as the right owner again.
1180 ** Paranoia: reset mbdf since the file descriptor
1181 ** is no longer valid; better safe than sorry.
1184 sb.st_uid = user.mbdb_uid;
1189 else if (sb.st_nlink != 1)
1191 mailerr("550 5.2.0", "%s: too many links", path);
1194 else if (!S_ISREG(sb.st_mode))
1196 mailerr("550 5.2.0", "%s: irregular file", path);
1199 else if (sb.st_uid != user.mbdb_uid)
1201 ExitVal = EX_CANTCREAT;
1202 mailerr("550 5.2.0", "%s: wrong ownership (%d)",
1203 path, (int) sb.st_uid);
1207 /* change UID for quota checks */
1208 if (setreuid(0, user.mbdb_uid) < 0)
1210 mailerr("450 4.2.0", "setreuid(0, %d): %s (r=%d, e=%d)",
1211 (int) user.mbdb_uid, sm_errstring(errno),
1212 (int) getuid(), (int) geteuid());
1216 fprintf(stderr, "new euid = %d\n", (int) geteuid());
1218 mbfd = open(path, O_APPEND|O_WRONLY, 0);
1221 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1224 else if (fstat(mbfd, &fsb) < 0 ||
1225 fsb.st_nlink != 1 ||
1227 !S_ISREG(fsb.st_mode) ||
1228 sb.st_dev != fsb.st_dev ||
1229 sb.st_ino != fsb.st_ino ||
1230 # if HAS_ST_GEN && 0 /* AFS returns random values for st_gen */
1231 sb.st_gen != fsb.st_gen ||
1232 # endif /* HAS_ST_GEN && 0 */
1233 sb.st_uid != fsb.st_uid)
1235 ExitVal = EX_TEMPFAIL;
1236 mailerr("550 5.2.0", "%s: fstat: file changed after open",
1243 ** This code could be reused if we decide to add a
1244 ** per-user quota field to the sm_mbdb interface.
1248 ** Fail if the user has a quota specified, and delivery of this
1249 ** message would exceed that quota. We bounce such failures using
1250 ** EX_UNAVAILABLE, unless there were internal problems, since
1251 ** storing immense messages for later retries can cause queueing
1259 if (fstat(fd, &dsb) < 0)
1261 ExitVal = EX_TEMPFAIL;
1262 mailerr("451 4.3.0",
1263 "%s: fstat: can't stat temporary storage: %s",
1264 ui.mailspool, sm_errstring(errno));
1268 if (dsb.st_size + sb.st_size + 1 > ui.quota)
1270 ExitVal = EX_UNAVAILABLE;
1271 mailerr("551 5.2.2",
1272 "%s: Mailbox full or quota exceeded",
1279 /* Wait until we can get a lock on the file. */
1280 if (flock(mbfd, LOCK_EX) < 0)
1282 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1286 /* Get the starting offset of the new message */
1287 curoff = lseek(mbfd, (off_t) 0, SEEK_END);
1291 (void) sm_snprintf(biffmsg, sizeof(biffmsg), "%s@%lld\n",
1292 name, (LONGLONG_T) curoff);
1295 /* Copy the message into the file. */
1296 if (lseek(fd, (off_t) 0, SEEK_SET) == (off_t) -1)
1298 mailerr("450 4.2.0", "Temporary file: %s",
1299 sm_errstring(errno));
1303 fprintf(stderr, "before writing: euid = %d\n", (int) geteuid());
1305 #ifdef CONTENTLENGTH
1306 headerbytes = (BodyLength >= 0) ? HeaderLength : -1 ;
1309 if (headerbytes == 0)
1311 (void) sm_snprintf(buf, sizeof buf, "%s", ContentHdr);
1316 else if (headerbytes > sizeof(buf) || headerbytes < 0)
1317 readamount = sizeof(buf);
1319 readamount = headerbytes;
1320 if (readamount != 0)
1321 nr = read(fd, buf, readamount);
1324 if (headerbytes > 0)
1327 #else /* CONTENTLENGTH */
1328 while ((nr = read(fd, buf, sizeof(buf))) > 0)
1330 #endif /* CONTENTLENGTH */
1331 for (off = 0; off < nr; off += nw)
1333 if ((nw = write(mbfd, buf + off, nr - off)) < 0)
1335 errcode = "450 4.2.0";
1337 if (errno == EDQUOT && BounceQuota)
1338 errcode = "552 5.2.2";
1340 mailerr(errcode, "%s: %s",
1341 path, sm_errstring(errno));
1348 mailerr("450 4.2.0", "Temporary file: %s",
1349 sm_errstring(errno));
1353 /* Flush to disk, don't wait for update. */
1354 if (!nofsync && fsync(mbfd) < 0)
1356 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1359 fprintf(stderr, "reset euid = %d\n", (int) geteuid());
1362 (void) ftruncate(mbfd, curoff);
1363 err1: if (mbfd >= 0)
1365 err0: (void) setreuid(0, 0);
1371 ** Save the current size so if the close() fails below
1372 ** we can make sure no other process has changed the mailbox
1373 ** between the failed close and the re-open()/re-lock().
1374 ** If something else has changed the size, we shouldn't
1375 ** try to truncate it as we may do more harm then good
1376 ** (e.g., truncate a later message delivery).
1379 if (fstat(mbfd, &sb) < 0)
1382 cursize = sb.st_size;
1385 /* Close and check -- NFS doesn't write until the close. */
1388 errcode = "450 4.2.0";
1390 if (errno == EDQUOT && BounceQuota)
1391 errcode = "552 5.2.2";
1393 mailerr(errcode, "%s: %s", path, sm_errstring(errno));
1394 mbfd = open(path, O_WRONLY, 0);
1397 || flock(mbfd, LOCK_EX) < 0 ||
1398 fstat(mbfd, &sb) < 0 ||
1399 sb.st_size != cursize ||
1401 !S_ISREG(sb.st_mode) ||
1402 sb.st_dev != fsb.st_dev ||
1403 sb.st_ino != fsb.st_ino ||
1404 # if HAS_ST_GEN && 0 /* AFS returns random values for st_gen */
1405 sb.st_gen != fsb.st_gen ||
1406 # endif /* HAS_ST_GEN && 0 */
1407 sb.st_uid != fsb.st_uid
1410 /* Don't use a bogus file */
1418 /* Attempt to truncate back to pre-write size */
1422 notifybiff(biffmsg);
1424 if (setreuid(0, 0) < 0)
1426 mailerr("450 4.2.0", "setreuid(0, 0): %s",
1427 sm_errstring(errno));
1431 fprintf(stderr, "reset euid = %d\n", (int) geteuid());
1435 printf("250 2.1.5 %s Ok\r\n", name);
1439 ** user.lock files are necessary for compatibility with other
1440 ** systems, e.g., when the mail spool file is NFS exported.
1441 ** Alas, mailbox locking is more than just a local matter.
1445 bool Locked = false;
1456 if ((r = maillock(name, 15)) == L_SUCCESS)
1463 case L_TMPLOCK: /* Can't create tmp file */
1464 case L_TMPWRITE: /* Can't write pid into lockfile */
1465 case L_MAXTRYS: /* Failed after retrycnt attempts */
1469 case L_ERROR: /* Check errno for reason */
1472 default: /* other permanent errors */
1487 #else /* MAILLOCK */
1489 char LockName[MAXPATHLEN];
1500 if (strlen(path) + 6 > sizeof LockName)
1502 (void) sm_snprintf(LockName, sizeof LockName, "%s.lock", path);
1503 (void) time(&start);
1510 /* global timeout */
1512 if (now > start + LOCKTO_GLOB)
1517 fd = open(LockName, O_WRONLY|O_EXCL|O_CREAT, LOCKFILE_PMODE);
1520 /* defeat lock checking programs which test pid */
1521 (void) write(fd, "0", 2);
1526 if (stat(LockName, &st) < 0)
1528 if (statfailed++ > 5)
1537 if (now < st.st_ctime + LOCKTO_RM)
1540 /* try to remove stale lockfile */
1541 if (unlink(LockName) < 0)
1551 (void) unlink(LockName);
1554 #endif /* MAILLOCK */
1560 static bool initialized = false;
1565 static struct sockaddr_in addr;
1571 /* Be silent if biff service not available. */
1572 if ((sp = getservbyname("biff", "udp")) == NULL ||
1573 (hp = gethostbyname("localhost")) == NULL ||
1574 hp->h_length != INADDRSZ)
1577 addr.sin_family = hp->h_addrtype;
1578 memcpy(&addr.sin_addr, hp->h_addr, INADDRSZ);
1579 addr.sin_port = sp->s_port;
1582 /* No message, just return */
1586 /* Couldn't initialize addr struct */
1587 if (addr.sin_family == AF_UNSPEC)
1590 if (f < 0 && (f = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1592 len = strlen(msg) + 1;
1593 (void) sendto(f, msg, len, 0, (struct sockaddr *) &addr, sizeof(addr));
1600 # if _FFR_SPOOL_PATH
1601 mailerr(NULL, "usage: mail.local [-7] [-B] [-b] [-d] [-l] [-s] [-f from|-r from] [-h filename] [-p path] user ...");
1602 # else /* _FFR_SPOOL_PATH */
1603 mailerr(NULL, "usage: mail.local [-7] [-B] [-b] [-d] [-l] [-s] [-f from|-r from] [-h filename] user ...");
1604 # endif /* _FFR_SPOOL_PATH */
1611 mailerr(const char *hdr, const char *fmt, ...)
1612 #else /* __STDC__ */
1613 mailerr(hdr, fmt, va_alist)
1617 #endif /* __STDC__ */
1622 (void) e_to_sys(errno);
1624 SM_VA_START(ap, fmt);
1626 if (LMTPMode && hdr != NULL)
1628 sm_snprintf(ErrBuf, sizeof ErrBuf, "%s ", hdr);
1629 len = strlen(ErrBuf);
1631 (void) sm_vsnprintf(&ErrBuf[len], sizeof ErrBuf - len, fmt, ap);
1637 /* Log the message to syslog. */
1639 syslog(LOG_ERR, "%s", ErrBuf);
1646 printf("%s\r\n", ErrBuf);
1649 if (ExitVal != EX_USAGE)
1650 (void) fprintf(stderr, "mail.local: ");
1651 fprintf(stderr, "%s\n", ErrBuf);
1660 static char p[MAXPATHLEN];
1665 char Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_";
1667 unsigned char md5[18];
1668 # if MAXPATHLEN <= 24
1669 ERROR _MAXPATHLEN <= 24
1670 # endif /* MAXPATHLEN <= 24 */
1674 # endif /* HASHSPOOLMD5 */
1676 if (HashType == HASH_NONE || HashDepth * 2 >= MAXPATHLEN)
1691 MD5_Update(&ctx, name, strlen(name));
1692 MD5_Final(md5, &ctx);
1696 for (i = 0; i < 6; i++)
1698 bits = (unsigned) md5[(3 * i)] << 16;
1699 bits |= (unsigned) md5[(3 * i) + 1] << 8;
1700 bits |= (unsigned) md5[(3 * i) + 2];
1702 for (j = 3; j >= 0; j--)
1704 b64[(4 * i) + j] = Base64[(bits & 0x3f)];
1711 # endif /* HASHSPOOLMD5 */
1715 for (i = 0; i < HashDepth; i++)
1721 p[(i * 2) + 1] = '/';
1723 p[HashDepth * 2] = '\0';
1726 #endif /* HASHSPOOL */
1730 * Guess which errno's are temporary. Gag me.
1737 /* Temporary failures override hard errors. */
1738 if (ExitVal == EX_TEMPFAIL)
1741 switch (num) /* Hopefully temporary errors. */
1744 case EDQUOT: /* Disc quota exceeded */
1747 ExitVal = EX_UNAVAILABLE;
1753 case EAGAIN: /* Resource temporarily unavailable */
1756 case EBUSY: /* Device busy */
1759 case EPROCLIM: /* Too many processes */
1760 #endif /* EPROCLIM */
1762 case EUSERS: /* Too many users */
1765 case ECONNABORTED: /* Software caused connection abort */
1766 #endif /* ECONNABORTED */
1768 case ECONNREFUSED: /* Connection refused */
1769 #endif /* ECONNREFUSED */
1771 case ECONNRESET: /* Connection reset by peer */
1772 #endif /* ECONNRESET */
1774 case EDEADLK: /* Resource deadlock avoided */
1775 #endif /* EDEADLK */
1777 case EFBIG: /* File too large */
1780 case EHOSTDOWN: /* Host is down */
1781 #endif /* EHOSTDOWN */
1783 case EHOSTUNREACH: /* No route to host */
1784 #endif /* EHOSTUNREACH */
1786 case EMFILE: /* Too many open files */
1789 case ENETDOWN: /* Network is down */
1790 #endif /* ENETDOWN */
1792 case ENETRESET: /* Network dropped connection on reset */
1793 #endif /* ENETRESET */
1795 case ENETUNREACH: /* Network is unreachable */
1796 #endif /* ENETUNREACH */
1798 case ENFILE: /* Too many open files in system */
1801 case ENOBUFS: /* No buffer space available */
1802 #endif /* ENOBUFS */
1804 case ENOMEM: /* Cannot allocate memory */
1807 case ENOSPC: /* No space left on device */
1810 case EROFS: /* Read-only file system */
1813 case ESTALE: /* Stale NFS file handle */
1816 case ETIMEDOUT: /* Connection timed out */
1817 #endif /* ETIMEDOUT */
1818 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN && EWOULDBLOCK != EDEADLK
1819 case EWOULDBLOCK: /* Operation would block. */
1820 #endif /* defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN && EWOULDBLOCK != EDEADLK */
1821 ExitVal = EX_TEMPFAIL;
1825 ExitVal = EX_UNAVAILABLE;
1831 #if defined(ultrix) || defined(_CRAY)
1833 * Copyright (c) 1987, 1993
1834 * The Regents of the University of California. All rights reserved.
1836 * Redistribution and use in source and binary forms, with or without
1837 * modification, are permitted provided that the following conditions
1839 * 1. Redistributions of source code must retain the above copyright
1840 * notice, this list of conditions and the following disclaimer.
1841 * 2. Redistributions in binary form must reproduce the above copyright
1842 * notice, this list of conditions and the following disclaimer in the
1843 * documentation and/or other materials provided with the distribution.
1844 * 3. All advertising materials mentioning features or use of this software
1845 * must display the following acknowledgement:
1846 * This product includes software developed by the University of
1847 * California, Berkeley and its contributors.
1848 * 4. Neither the name of the University nor the names of its contributors
1849 * may be used to endorse or promote products derived from this software
1850 * without specific prior written permission.
1852 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1853 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1854 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1855 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
1856 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1857 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1858 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1859 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1860 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1861 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1865 # if defined(LIBC_SCCS) && !defined(lint)
1866 static char sccsid[] = "@(#)mktemp.c 8.1 (Berkeley) 6/4/93";
1867 # endif /* defined(LIBC_SCCS) && !defined(lint) */
1869 # include <sys/types.h>
1870 # include <sys/stat.h>
1876 static int _gettemp();
1883 return (_gettemp(path, &fd) ? fd : -1);
1887 _gettemp(path, doopen)
1889 register int *doopen;
1892 register char *start, *trv;
1897 for (trv = path; *trv; ++trv); /* extra X's get set to 0's */
1898 while (*--trv == 'X')
1900 *trv = (pid % 10) + '0';
1905 * check the target directory; if you have six X's and it
1906 * doesn't exist this runs for a *very* long time.
1908 for (start = trv + 1;; --trv)
1915 if (stat(path, &sbuf) < 0)
1917 if (!S_ISDIR(sbuf.st_mode))
1931 if ((*doopen = open(path, O_CREAT|O_EXCL|O_RDWR,
1934 if (errno != EEXIST)
1937 else if (stat(path, &sbuf) < 0)
1938 return(errno == ENOENT ? 1 : 0);
1940 /* tricky little algorithm for backward compatibility */
1949 if (isascii(*trv) && isdigit(*trv))
1959 #endif /* defined(ultrix) || defined(_CRAY) */