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.254 2006/10/12 22:23:45 ca 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 # define LOCKTO_RM 300 /* timeout for stale lockfile removal */
87 #endif /* ! LOCKTO_RM */
89 # define LOCKTO_GLOB 400 /* global timeout for lockfile creation */
90 #endif /* ! LOCKTO_GLOB */
92 /* define a realloc() which works for NULL pointers */
93 #define REALLOC(ptr, size) (((ptr) == NULL) ? malloc(size) : realloc(ptr, size))
96 ** If you don't have flock, you could try using lockf instead.
100 # define flock(a, b) lockf(a, b, 0)
103 # endif /* LOCK_EX */
104 # define LOCK_EX F_LOCK
105 #endif /* LDA_USE_LOCKF */
108 # include <sys/file.h>
109 #endif /* ! LOCK_EX */
112 ** If you don't have setreuid, and you have saved uids, and you have
113 ** a seteuid() call that doesn't try to emulate using setuid(), then
114 ** you can try defining LDA_USE_SETEUID.
117 #ifdef LDA_USE_SETEUID
118 # define setreuid(r, e) seteuid(e)
119 #endif /* LDA_USE_SETEUID */
121 #ifdef LDA_CONTENTLENGTH
122 # define CONTENTLENGTH 1
123 #endif /* LDA_CONTENTLENGTH */
126 # define INADDRSZ 4 /* size of an IPv4 address in bytes */
127 #endif /* ! INADDRSZ */
130 # include <maillock.h>
131 #endif /* MAILLOCK */
133 #ifndef MAILER_DAEMON
134 # define MAILER_DAEMON "MAILER-DAEMON"
135 #endif /* ! MAILER_DAEMON */
138 char ContentHdr[40] = "Content-Length: ";
141 #endif /* CONTENTLENGTH */
143 bool EightBitMime = true; /* advertise 8BITMIME in LMTP */
144 char ErrBuf[10240]; /* error buffer */
145 int ExitVal = EX_OK; /* sysexits.h error value. */
147 bool nofsync = false;
148 bool HoldErrs = false; /* Hold errors in ErrBuf */
149 bool LMTPMode = false;
150 bool BounceQuota = false; /* permanent error when over quota */
151 bool CloseMBDB = false;
152 char *HomeMailFile = NULL; /* store mail in homedir */
155 int HashType = HASH_NONE;
157 bool StripRcptDomain = true;
158 #else /* HASHSPOOL */
159 # define StripRcptDomain true
160 #endif /* HASHSPOOL */
161 char SpoolPath[MAXPATHLEN];
163 char *parseaddr __P((char *, bool));
164 char *process_recipient __P((char *));
165 void dolmtp __P((void));
166 void deliver __P((int, char *));
167 int e_to_sys __P((int));
168 void notifybiff __P((char *));
169 int store __P((char *, bool *));
170 void usage __P((void));
171 int lockmbox __P((char *));
172 void unlockmbox __P((void));
173 void mailerr __P((const char *, const char *, ...));
174 void flush_error __P((void));
176 const char *hashname __P((char *));
177 #endif /* HASHSPOOL */
180 static void sm_exit __P((int));
189 CloseMBDB = false; /* not really necessary, but ... */
203 char *mbdbname = "pw";
209 /* make sure we have some open file descriptors */
210 for (fd = 10; fd < 30; fd++)
213 /* use a reasonable umask */
217 openlog("mail.local", 0, LOG_MAIL);
218 # else /* LOG_MAIL */
219 openlog("mail.local", 0);
220 # endif /* LOG_MAIL */
224 /* XXX can this be converted to a compile time check? */
225 if (sm_strlcpy(SpoolPath, _PATH_MAILDIR, sizeof(SpoolPath)) >=
228 mailerr("421", "Configuration error: _PATH_MAILDIR too large");
232 while ((ch = getopt(argc, argv, "7BbdD:f:h:r:lH:p:ns")) != -1)
233 #else /* HASHSPOOL */
234 while ((ch = getopt(argc, argv, "7BbdD:f:h:r:ls")) != -1)
235 #endif /* HASHSPOOL */
239 case '7': /* Do not advertise 8BITMIME */
240 EightBitMime = false;
247 case 'b': /* bounce mail when over quota. */
251 case 'd': /* Backward compatible. */
254 case 'D': /* mailbox database type */
259 case 'r': /* Backward compatible. */
262 mailerr(NULL, "Multiple -f options");
269 if (optarg != NULL || *optarg != '\0')
270 HomeMailFile = optarg;
273 mailerr(NULL, "-h: missing filename");
288 if (optarg == NULL || *optarg == '\0')
290 mailerr(NULL, "-H: missing hashinfo");
296 HashType = HASH_USER;
303 # endif /* HASHSPOOLMD5 */
306 mailerr(NULL, "-H: unknown hash type");
309 if (optarg[1] == '\0')
311 mailerr(NULL, "-H: invalid hash depth");
314 HashDepth = atoi(&optarg[1]);
315 if ((HashDepth <= 0) || ((HashDepth * 2) >= MAXPATHLEN))
317 mailerr(NULL, "-H: invalid hash depth");
323 if (optarg == NULL || *optarg == '\0')
325 mailerr(NULL, "-p: missing spool path");
328 if (sm_strlcpy(SpoolPath, optarg, sizeof(SpoolPath)) >=
331 mailerr(NULL, "-p: invalid spool path");
337 StripRcptDomain = false;
339 #endif /* HASHSPOOL */
349 /* initialize biff structures */
353 err = sm_mbdb_initialize(mbdbname);
356 char *errcode = "521";
358 if (err == EX_TEMPFAIL)
361 mailerr(errcode, "Can not open mailbox database %s: %s",
362 mbdbname, sm_strexit(err));
371 mailerr("421", "Users should not be specified in command line if LMTP required");
372 sm_exit(EX_TEMPFAIL);
380 /* Non-LMTP from here on out */
385 ** If from not specified, use the name from getlogin() if the
386 ** uid matches, otherwise, use the name from the password file
387 ** corresponding to the uid.
391 if (from == NULL && ((from = getlogin()) == NULL ||
392 (pw = getpwnam(from)) == NULL ||
394 from = (pw = getpwuid(uid)) != NULL ? pw->pw_name : "???";
397 ** There is no way to distinguish the error status of one delivery
398 ** from the rest of the deliveries. So, if we failed hard on one
399 ** or more deliveries, but had no failures on any of the others, we
400 ** return a hard failure. If we failed temporarily on one or more
401 ** deliveries, we return a temporary failure regardless of the other
402 ** failures. This results in the delivery being reattempted later
403 ** at the expense of repeated failures and multiple deliveries.
407 fd = store(from, NULL);
414 for (; *argv != NULL; ++argv)
438 while (*p != ',' && *p != ':' && *p != '\0')
443 /* Skip over , or : */
450 while (*p != '\0' && *p != '@' && *p != '>')
460 while (*p != '\0' && *p != '\"')
469 if (*p == '\0' || *(p + 1) == '\0')
473 if (*p == '+' && rcpt)
483 while (*p != '\0' && *p != '>')
493 if (*p != '\0' && *p != ' ')
505 mailerr("421 4.3.0", "Memory exhausted");
506 sm_exit(EX_TEMPFAIL);
509 (void) sm_strlcpy(p, s, l);
514 process_recipient(addr)
519 switch (sm_mbdb_lookup(addr, &user))
525 return "550 5.1.1 User unknown";
528 return "451 4.3.0 User database failure; retry later";
531 return "550 5.3.0 User database failure";
540 char *return_path = NULL;
541 char **rcpt_addr = NULL;
544 bool gotlhlo = false;
549 char myhostname[1024];
552 memset(myhostname, '\0', sizeof myhostname);
553 (void) gethostname(myhostname, sizeof myhostname - 1);
554 if (myhostname[0] == '\0')
555 sm_strlcpy(myhostname, "localhost", sizeof myhostname);
557 printf("220 %s LMTP ready\r\n", myhostname);
560 (void) fflush(stdout);
561 if (fgets(buf, sizeof(buf) - 1, stdin) == NULL)
563 p = buf + strlen(buf) - 1;
564 if (p >= buf && *p == '\n')
566 if (p >= buf && *p == '\r')
573 if (sm_strcasecmp(buf, "data") == 0)
579 mailerr("503 5.5.1", "No recipients");
583 msgfd = store(return_path, &inbody);
585 if (msgfd < 0 && !inbody)
591 for (i = 0; i < rcpt_num; i++)
595 /* print error for rcpt */
599 p = strchr(rcpt_addr[i], '+');
602 deliver(msgfd, rcpt_addr[i]);
614 if (sm_strncasecmp(buf, "lhlo ", 5) == 0)
616 /* check for duplicate per RFC 1651 4.2 */
619 mailerr("503", "%s Duplicate LHLO",
624 printf("250-%s\r\n", myhostname);
626 printf("250-8BITMIME\r\n");
627 printf("250-ENHANCEDSTATUSCODES\r\n");
628 printf("250 PIPELINING\r\n");
637 if (sm_strncasecmp(buf, "mail ", 5) == 0)
639 if (return_path != NULL)
642 "Nested MAIL command");
645 if (sm_strncasecmp(buf + 5, "from:", 5) != 0 ||
646 ((return_path = parseaddr(buf + 10,
650 "Syntax error in parameters");
653 printf("250 2.5.0 Ok\r\n");
662 if (sm_strcasecmp(buf, "noop") == 0)
664 printf("250 2.0.0 Ok\r\n");
673 if (sm_strcasecmp(buf, "quit") == 0)
675 printf("221 2.0.0 Bye\r\n");
684 if (sm_strncasecmp(buf, "rcpt ", 5) == 0)
686 if (return_path == NULL)
689 "Need MAIL command");
692 if (rcpt_num >= rcpt_alloc)
694 rcpt_alloc += RCPT_GROW;
695 rcpt_addr = (char **)
696 REALLOC((char *) rcpt_addr,
699 if (rcpt_addr == NULL)
703 sm_exit(EX_TEMPFAIL);
706 if (sm_strncasecmp(buf + 5, "to:", 3) != 0 ||
707 ((rcpt_addr[rcpt_num] = parseaddr(buf + 8,
708 StripRcptDomain)) == NULL))
711 "Syntax error in parameters");
714 err = process_recipient(rcpt_addr[rcpt_num]);
717 mailerr(NULL, "%s", err);
721 printf("250 2.1.5 Ok\r\n");
724 else if (sm_strcasecmp(buf, "rset") == 0)
726 printf("250 2.0.0 Ok\r\n");
730 free(rcpt_addr[--rcpt_num]);
731 if (return_path != NULL)
742 if (sm_strncasecmp(buf, "vrfy ", 5) == 0)
744 printf("252 2.3.3 Try RCPT to attempt delivery\r\n");
753 mailerr("500 5.5.2", "Syntax error");
768 bool eline; /* previous line was empty */
769 bool fullline = true; /* current line is terminated */
770 bool prevfl; /* previous line was terminated */
773 char tmpbuf[sizeof _PATH_LOCTMP + 1];
779 (void) sm_strlcpy(tmpbuf, _PATH_LOCTMP, sizeof tmpbuf);
780 if ((fd = mkstemp(tmpbuf)) < 0 || (fp = fdopen(fd, "w+")) == NULL)
784 mailerr("451 4.3.0", "Unable to open temporary file");
787 (void) unlink(tmpbuf);
791 printf("354 Go ahead\r\n");
792 (void) fflush(stdout);
798 (void) fprintf(fp, "From %s %s", from, ctime(&tval));
803 #endif /* CONTENTLENGTH */
807 while (fgets(line, sizeof(line), stdin) != (char *) NULL)
812 prevfl = fullline; /* preserve state of previous line */
813 while (line[line_len] != '\n' && line_len < sizeof(line) - 2)
817 /* Check for dot-stuffing */
818 if (prevfl && LMTPMode && line[0] == '.')
820 if (line[1] == '\n' ||
821 (line[1] == '\r' && line[2] == '\n'))
823 memcpy(line, line + 1, line_len);
827 /* Check to see if we have the full line from fgets() */
831 if (line[line_len - 1] == '\n')
834 line[line_len - 2] == '\r')
836 line[line_len - 2] = '\n';
837 line[line_len - 1] = '\0';
842 else if (line[line_len - 1] == '\r')
844 /* Did we just miss the CRLF? */
848 line[line_len - 1] = '\n';
852 (void) ungetc(peek, stdin);
859 if (prevfl && line[0] == '\n' && HeaderLength == 0)
863 HeaderLength = ftell(fp);
864 if (HeaderLength <= 0)
867 ** shouldn't happen, unless ftell() is
874 #else /* CONTENTLENGTH */
875 if (prevfl && line[0] == '\n')
877 #endif /* CONTENTLENGTH */
880 if (eline && line[0] == 'F' &&
882 !memcmp(line, "From ", 5))
883 (void) putc('>', fp);
886 /* discard existing "Content-Length:" headers */
887 if (prevfl && HeaderLength == 0 &&
888 (line[0] == 'C' || line[0] == 'c') &&
889 sm_strncasecmp(line, ContentHdr, 15) == 0)
892 ** be paranoid: clear the line
893 ** so no "wrong matches" may occur later
898 #endif /* CONTENTLENGTH */
903 (void) fwrite(line, sizeof(char), line_len, fp);
907 "Temporary file write error");
915 /* check if an error occurred */
921 /* Got a premature EOF -- toss message and exit */
925 /* If message not newline terminated, need an extra. */
926 if (fp != NULL && strchr(line, '\n') == NULL)
927 (void) putc('\n', fp);
933 BodyLength = ftell(fp);
934 if (HeaderLength == 0 && BodyLength > 0) /* empty body */
936 HeaderLength = BodyLength;
940 BodyLength = BodyLength - HeaderLength - 1 ;
942 if (HeaderLength > 0 && BodyLength >= 0)
944 (void) sm_snprintf(line, sizeof line, "%lld\n",
945 (LONGLONG_T) BodyLength);
946 (void) sm_strlcpy(&ContentHdr[16], line,
947 sizeof(ContentHdr) - 16);
950 BodyLength = -1; /* Something is wrong here */
951 #endif /* CONTENTLENGTH */
953 /* Output a newline; note, empty messages are allowed. */
955 (void) putc('\n', fp);
957 if (fp == NULL || fflush(fp) == EOF || ferror(fp) != 0)
959 mailerr("451 4.3.0", "Temporary file write error");
974 char path[MAXPATHLEN];
975 int mbfd = -1, nr = 0, nw, off;
979 off_t curoff, cursize;
983 #endif /* CONTENTLENGTH */
984 char biffmsg[100], buf[8 * 1024];
988 ** Disallow delivery to unknown names -- special mailboxes can be
989 ** handled in the sendmail aliases file.
992 exitval = sm_mbdb_lookup(name, &user);
999 exitval = EX_UNAVAILABLE;
1000 mailerr("550 5.1.1", "%s: User unknown", name);
1004 mailerr("451 4.3.0", "%s: User database failure; retry later",
1009 exitval = EX_UNAVAILABLE;
1010 mailerr("550 5.3.0", "%s: User database failure", name);
1014 if (exitval != EX_OK)
1016 if (ExitVal != EX_TEMPFAIL)
1024 ** Keep name reasonably short to avoid buffer overruns.
1025 ** This isn't necessary on BSD because of the proper
1026 ** definition of snprintf(), but it can cause problems
1027 ** on other systems.
1028 ** Also, clear out any bogus characters.
1032 if (strlen(name) > 40)
1034 for (p = name; *p != '\0'; p++)
1038 else if (!isprint(*p))
1041 #endif /* !HASHSPOOL */
1044 if (HomeMailFile == NULL)
1046 if (sm_strlcpyn(path, sizeof(path),
1049 #else /* HASHSPOOL */
1051 #endif /* HASHSPOOL */
1055 #endif /* HASHSPOOL */
1056 name) >= sizeof(path))
1058 exitval = EX_UNAVAILABLE;
1059 mailerr("550 5.1.1", "%s: Invalid mailbox path", name);
1063 else if (*user.mbdb_homedir == '\0')
1065 exitval = EX_UNAVAILABLE;
1066 mailerr("550 5.1.1", "%s: User missing home directory", name);
1069 else if (sm_snprintf(path, sizeof(path), "%s/%s",
1070 user.mbdb_homedir, HomeMailFile) >= sizeof(path))
1072 exitval = EX_UNAVAILABLE;
1073 mailerr("550 5.1.1", "%s: Invalid mailbox path", name);
1079 ** If the mailbox is linked or a symlink, fail. There's an obvious
1080 ** race here, that the file was replaced with a symbolic link after
1081 ** the lstat returned, but before the open. We attempt to detect
1082 ** this by comparing the original stat information and information
1083 ** returned by an fstat of the file descriptor returned by the open.
1085 ** NB: this is a symptom of a larger problem, that the mail spooling
1086 ** directory is writeable by the wrong users. If that directory is
1087 ** writeable, system security is compromised for other reasons, and
1088 ** it cannot be fixed here.
1090 ** If we created the mailbox, set the owner/group. If that fails,
1091 ** just return. Another process may have already opened it, so we
1092 ** can't unlink it. Historically, binmail set the owner/group at
1093 ** each mail delivery. We no longer do this, assuming that if the
1094 ** ownership or permissions were changed there was a reason.
1097 ** open(2) should support flock'ing the file.
1103 #else /* MAILLOCK */
1105 #endif /* MAILLOCK */
1106 if ((off = lockmbox(p)) != 0)
1108 if (off == EX_TEMPFAIL || e_to_sys(off) == EX_TEMPFAIL)
1110 ExitVal = EX_TEMPFAIL;
1111 errcode = "451 4.3.0";
1114 errcode = "551 5.3.0";
1116 mailerr(errcode, "lockmailbox %s failed; error code %d %s",
1117 p, off, errno > 0 ? sm_errstring(errno) : "");
1121 if (lstat(path, &sb) < 0)
1124 int mode = S_IRUSR|S_IWUSR;
1125 gid_t gid = user.mbdb_gid;
1130 mode |= S_IRGRP|S_IWGRP;
1131 #endif /* MAILGID */
1133 mbfd = open(path, O_APPEND|O_CREAT|O_EXCL|O_WRONLY,
1137 if (lstat(path, &sb) < 0)
1139 ExitVal = EX_CANTCREAT;
1140 mailerr("550 5.2.0",
1141 "%s: lstat: file changed after open", path);
1146 if (save_errno == EEXIST)
1149 /* open failed, don't try again */
1150 mailerr("450 4.2.0", "%s: %s", path,
1151 sm_errstring(save_errno));
1154 else if (fchown(mbfd, user.mbdb_uid, gid) < 0)
1156 mailerr("451 4.3.0", "chown %u.%u: %s",
1157 user.mbdb_uid, gid, name);
1163 ** open() was successful, now close it so can
1164 ** be opened as the right owner again.
1165 ** Paranoia: reset mbdf since the file descriptor
1166 ** is no longer valid; better safe than sorry.
1169 sb.st_uid = user.mbdb_uid;
1174 else if (sb.st_nlink != 1)
1176 mailerr("550 5.2.0", "%s: too many links", path);
1179 else if (!S_ISREG(sb.st_mode))
1181 mailerr("550 5.2.0", "%s: irregular file", path);
1184 else if (sb.st_uid != user.mbdb_uid)
1186 ExitVal = EX_CANTCREAT;
1187 mailerr("550 5.2.0", "%s: wrong ownership (%d)",
1188 path, (int) sb.st_uid);
1192 /* change UID for quota checks */
1193 if (setreuid(0, user.mbdb_uid) < 0)
1195 mailerr("450 4.2.0", "setreuid(0, %d): %s (r=%d, e=%d)",
1196 (int) user.mbdb_uid, sm_errstring(errno),
1197 (int) getuid(), (int) geteuid());
1201 fprintf(stderr, "new euid = %d\n", (int) geteuid());
1203 mbfd = open(path, O_APPEND|O_WRONLY, 0);
1206 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1209 else if (fstat(mbfd, &fsb) < 0 ||
1210 fsb.st_nlink != 1 ||
1212 !S_ISREG(fsb.st_mode) ||
1213 sb.st_dev != fsb.st_dev ||
1214 sb.st_ino != fsb.st_ino ||
1215 # if HAS_ST_GEN && 0 /* AFS returns random values for st_gen */
1216 sb.st_gen != fsb.st_gen ||
1217 # endif /* HAS_ST_GEN && 0 */
1218 sb.st_uid != fsb.st_uid)
1220 ExitVal = EX_TEMPFAIL;
1221 mailerr("550 5.2.0", "%s: fstat: file changed after open",
1228 ** This code could be reused if we decide to add a
1229 ** per-user quota field to the sm_mbdb interface.
1233 ** Fail if the user has a quota specified, and delivery of this
1234 ** message would exceed that quota. We bounce such failures using
1235 ** EX_UNAVAILABLE, unless there were internal problems, since
1236 ** storing immense messages for later retries can cause queueing
1244 if (fstat(fd, &dsb) < 0)
1246 ExitVal = EX_TEMPFAIL;
1247 mailerr("451 4.3.0",
1248 "%s: fstat: can't stat temporary storage: %s",
1249 ui.mailspool, sm_errstring(errno));
1253 if (dsb.st_size + sb.st_size + 1 > ui.quota)
1255 ExitVal = EX_UNAVAILABLE;
1256 mailerr("551 5.2.2",
1257 "%s: Mailbox full or quota exceeded",
1264 /* Wait until we can get a lock on the file. */
1265 if (flock(mbfd, LOCK_EX) < 0)
1267 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1271 /* Get the starting offset of the new message */
1272 curoff = lseek(mbfd, (off_t) 0, SEEK_END);
1276 (void) sm_snprintf(biffmsg, sizeof(biffmsg), "%s@%lld\n",
1277 name, (LONGLONG_T) curoff);
1280 /* Copy the message into the file. */
1281 if (lseek(fd, (off_t) 0, SEEK_SET) == (off_t) -1)
1283 mailerr("450 4.2.0", "Temporary file: %s",
1284 sm_errstring(errno));
1288 fprintf(stderr, "before writing: euid = %d\n", (int) geteuid());
1290 #ifdef CONTENTLENGTH
1291 headerbytes = (BodyLength >= 0) ? HeaderLength : -1 ;
1294 if (headerbytes == 0)
1296 (void) sm_snprintf(buf, sizeof buf, "%s", ContentHdr);
1301 else if (headerbytes > sizeof(buf) || headerbytes < 0)
1302 readamount = sizeof(buf);
1304 readamount = headerbytes;
1305 if (readamount != 0)
1306 nr = read(fd, buf, readamount);
1309 if (headerbytes > 0)
1312 #else /* CONTENTLENGTH */
1313 while ((nr = read(fd, buf, sizeof(buf))) > 0)
1315 #endif /* CONTENTLENGTH */
1316 for (off = 0; off < nr; off += nw)
1318 if ((nw = write(mbfd, buf + off, nr - off)) < 0)
1320 errcode = "450 4.2.0";
1322 if (errno == EDQUOT && BounceQuota)
1323 errcode = "552 5.2.2";
1325 mailerr(errcode, "%s: %s",
1326 path, sm_errstring(errno));
1333 mailerr("450 4.2.0", "Temporary file: %s",
1334 sm_errstring(errno));
1338 /* Flush to disk, don't wait for update. */
1339 if (!nofsync && fsync(mbfd) < 0)
1341 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1344 fprintf(stderr, "reset euid = %d\n", (int) geteuid());
1347 (void) ftruncate(mbfd, curoff);
1348 err1: if (mbfd >= 0)
1350 err0: (void) setreuid(0, 0);
1356 ** Save the current size so if the close() fails below
1357 ** we can make sure no other process has changed the mailbox
1358 ** between the failed close and the re-open()/re-lock().
1359 ** If something else has changed the size, we shouldn't
1360 ** try to truncate it as we may do more harm then good
1361 ** (e.g., truncate a later message delivery).
1364 if (fstat(mbfd, &sb) < 0)
1367 cursize = sb.st_size;
1370 /* Close and check -- NFS doesn't write until the close. */
1373 errcode = "450 4.2.0";
1375 if (errno == EDQUOT && BounceQuota)
1376 errcode = "552 5.2.2";
1378 mailerr(errcode, "%s: %s", path, sm_errstring(errno));
1379 mbfd = open(path, O_WRONLY, 0);
1382 || flock(mbfd, LOCK_EX) < 0 ||
1383 fstat(mbfd, &sb) < 0 ||
1384 sb.st_size != cursize ||
1386 !S_ISREG(sb.st_mode) ||
1387 sb.st_dev != fsb.st_dev ||
1388 sb.st_ino != fsb.st_ino ||
1389 # if HAS_ST_GEN && 0 /* AFS returns random values for st_gen */
1390 sb.st_gen != fsb.st_gen ||
1391 # endif /* HAS_ST_GEN && 0 */
1392 sb.st_uid != fsb.st_uid
1395 /* Don't use a bogus file */
1403 /* Attempt to truncate back to pre-write size */
1407 notifybiff(biffmsg);
1409 if (setreuid(0, 0) < 0)
1411 mailerr("450 4.2.0", "setreuid(0, 0): %s",
1412 sm_errstring(errno));
1416 fprintf(stderr, "reset euid = %d\n", (int) geteuid());
1420 printf("250 2.1.5 %s Ok\r\n", name);
1424 ** user.lock files are necessary for compatibility with other
1425 ** systems, e.g., when the mail spool file is NFS exported.
1426 ** Alas, mailbox locking is more than just a local matter.
1430 bool Locked = false;
1441 if ((r = maillock(name, 15)) == L_SUCCESS)
1448 case L_TMPLOCK: /* Can't create tmp file */
1449 case L_TMPWRITE: /* Can't write pid into lockfile */
1450 case L_MAXTRYS: /* Failed after retrycnt attempts */
1454 case L_ERROR: /* Check errno for reason */
1457 default: /* other permanent errors */
1472 #else /* MAILLOCK */
1474 char LockName[MAXPATHLEN];
1485 if (strlen(path) + 6 > sizeof LockName)
1487 (void) sm_snprintf(LockName, sizeof LockName, "%s.lock", path);
1488 (void) time(&start);
1495 /* global timeout */
1497 if (now > start + LOCKTO_GLOB)
1502 fd = open(LockName, O_WRONLY|O_EXCL|O_CREAT, LOCKFILE_PMODE);
1505 /* defeat lock checking programs which test pid */
1506 (void) write(fd, "0", 2);
1511 if (stat(LockName, &st) < 0)
1513 if (statfailed++ > 5)
1522 if (now < st.st_ctime + LOCKTO_RM)
1525 /* try to remove stale lockfile */
1526 if (unlink(LockName) < 0)
1536 (void) unlink(LockName);
1539 #endif /* MAILLOCK */
1545 static bool initialized = false;
1550 static struct sockaddr_in addr;
1556 /* Be silent if biff service not available. */
1557 if ((sp = getservbyname("biff", "udp")) == NULL ||
1558 (hp = gethostbyname("localhost")) == NULL ||
1559 hp->h_length != INADDRSZ)
1562 addr.sin_family = hp->h_addrtype;
1563 memcpy(&addr.sin_addr, hp->h_addr, INADDRSZ);
1564 addr.sin_port = sp->s_port;
1567 /* No message, just return */
1571 /* Couldn't initialize addr struct */
1572 if (addr.sin_family == AF_UNSPEC)
1575 if (f < 0 && (f = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1577 len = strlen(msg) + 1;
1578 (void) sendto(f, msg, len, 0, (struct sockaddr *) &addr, sizeof(addr));
1585 mailerr(NULL, "usage: mail.local [-7] [-B] [-b] [-d] [-l] [-s] [-f from|-r from] [-h filename] user ...");
1592 mailerr(const char *hdr, const char *fmt, ...)
1593 #else /* __STDC__ */
1594 mailerr(hdr, fmt, va_alist)
1598 #endif /* __STDC__ */
1603 (void) e_to_sys(errno);
1605 SM_VA_START(ap, fmt);
1607 if (LMTPMode && hdr != NULL)
1609 sm_snprintf(ErrBuf, sizeof ErrBuf, "%s ", hdr);
1610 len = strlen(ErrBuf);
1612 (void) sm_vsnprintf(&ErrBuf[len], sizeof ErrBuf - len, fmt, ap);
1618 /* Log the message to syslog. */
1620 syslog(LOG_ERR, "%s", ErrBuf);
1627 printf("%s\r\n", ErrBuf);
1630 if (ExitVal != EX_USAGE)
1631 (void) fprintf(stderr, "mail.local: ");
1632 fprintf(stderr, "%s\n", ErrBuf);
1641 static char p[MAXPATHLEN];
1646 char Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_";
1648 unsigned char md5[18];
1649 # if MAXPATHLEN <= 24
1650 ERROR _MAXPATHLEN <= 24
1651 # endif /* MAXPATHLEN <= 24 */
1655 # endif /* HASHSPOOLMD5 */
1657 if (HashType == HASH_NONE || HashDepth * 2 >= MAXPATHLEN)
1672 MD5_Update(&ctx, name, strlen(name));
1673 MD5_Final(md5, &ctx);
1677 for (i = 0; i < 6; i++)
1679 bits = (unsigned) md5[(3 * i)] << 16;
1680 bits |= (unsigned) md5[(3 * i) + 1] << 8;
1681 bits |= (unsigned) md5[(3 * i) + 2];
1683 for (j = 3; j >= 0; j--)
1685 b64[(4 * i) + j] = Base64[(bits & 0x3f)];
1692 # endif /* HASHSPOOLMD5 */
1696 for (i = 0; i < HashDepth; i++)
1702 p[(i * 2) + 1] = '/';
1704 p[HashDepth * 2] = '\0';
1707 #endif /* HASHSPOOL */
1711 * Guess which errno's are temporary. Gag me.
1718 /* Temporary failures override hard errors. */
1719 if (ExitVal == EX_TEMPFAIL)
1722 switch (num) /* Hopefully temporary errors. */
1725 case EDQUOT: /* Disc quota exceeded */
1728 ExitVal = EX_UNAVAILABLE;
1734 case EAGAIN: /* Resource temporarily unavailable */
1737 case EBUSY: /* Device busy */
1740 case EPROCLIM: /* Too many processes */
1741 #endif /* EPROCLIM */
1743 case EUSERS: /* Too many users */
1746 case ECONNABORTED: /* Software caused connection abort */
1747 #endif /* ECONNABORTED */
1749 case ECONNREFUSED: /* Connection refused */
1750 #endif /* ECONNREFUSED */
1752 case ECONNRESET: /* Connection reset by peer */
1753 #endif /* ECONNRESET */
1755 case EDEADLK: /* Resource deadlock avoided */
1756 #endif /* EDEADLK */
1758 case EFBIG: /* File too large */
1761 case EHOSTDOWN: /* Host is down */
1762 #endif /* EHOSTDOWN */
1764 case EHOSTUNREACH: /* No route to host */
1765 #endif /* EHOSTUNREACH */
1767 case EMFILE: /* Too many open files */
1770 case ENETDOWN: /* Network is down */
1771 #endif /* ENETDOWN */
1773 case ENETRESET: /* Network dropped connection on reset */
1774 #endif /* ENETRESET */
1776 case ENETUNREACH: /* Network is unreachable */
1777 #endif /* ENETUNREACH */
1779 case ENFILE: /* Too many open files in system */
1782 case ENOBUFS: /* No buffer space available */
1783 #endif /* ENOBUFS */
1785 case ENOMEM: /* Cannot allocate memory */
1788 case ENOSPC: /* No space left on device */
1791 case EROFS: /* Read-only file system */
1794 case ESTALE: /* Stale NFS file handle */
1797 case ETIMEDOUT: /* Connection timed out */
1798 #endif /* ETIMEDOUT */
1799 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN && EWOULDBLOCK != EDEADLK
1800 case EWOULDBLOCK: /* Operation would block. */
1801 #endif /* defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN && EWOULDBLOCK != EDEADLK */
1802 ExitVal = EX_TEMPFAIL;
1806 ExitVal = EX_UNAVAILABLE;
1812 #if defined(ultrix) || defined(_CRAY)
1814 * Copyright (c) 1987, 1993
1815 * The Regents of the University of California. All rights reserved.
1817 * Redistribution and use in source and binary forms, with or without
1818 * modification, are permitted provided that the following conditions
1820 * 1. Redistributions of source code must retain the above copyright
1821 * notice, this list of conditions and the following disclaimer.
1822 * 2. Redistributions in binary form must reproduce the above copyright
1823 * notice, this list of conditions and the following disclaimer in the
1824 * documentation and/or other materials provided with the distribution.
1825 * 3. All advertising materials mentioning features or use of this software
1826 * must display the following acknowledgement:
1827 * This product includes software developed by the University of
1828 * California, Berkeley and its contributors.
1829 * 4. Neither the name of the University nor the names of its contributors
1830 * may be used to endorse or promote products derived from this software
1831 * without specific prior written permission.
1833 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1834 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1835 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1836 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
1837 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1838 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1839 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1840 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1841 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1842 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1846 # if defined(LIBC_SCCS) && !defined(lint)
1847 static char sccsid[] = "@(#)mktemp.c 8.1 (Berkeley) 6/4/93";
1848 # endif /* defined(LIBC_SCCS) && !defined(lint) */
1850 # include <sys/types.h>
1851 # include <sys/stat.h>
1857 static int _gettemp();
1864 return (_gettemp(path, &fd) ? fd : -1);
1868 _gettemp(path, doopen)
1870 register int *doopen;
1873 register char *start, *trv;
1878 for (trv = path; *trv; ++trv); /* extra X's get set to 0's */
1879 while (*--trv == 'X')
1881 *trv = (pid % 10) + '0';
1886 * check the target directory; if you have six X's and it
1887 * doesn't exist this runs for a *very* long time.
1889 for (start = trv + 1;; --trv)
1896 if (stat(path, &sbuf) < 0)
1898 if (!S_ISDIR(sbuf.st_mode))
1912 if ((*doopen = open(path, O_CREAT|O_EXCL|O_RDWR,
1915 if (errno != EEXIST)
1918 else if (stat(path, &sbuf) < 0)
1919 return(errno == ENOENT ? 1 : 0);
1921 /* tricky little algorithm for backward compatibility */
1930 if (isascii(*trv) && isdigit(*trv))
1940 #endif /* defined(ultrix) || defined(_CRAY) */