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.253 2004/11/01 20:42:42 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 */
187 CloseMBDB = false; /* not really necessary, but ... */
201 char *mbdbname = "pw";
207 /* make sure we have some open file descriptors */
208 for (fd = 10; fd < 30; fd++)
211 /* use a reasonable umask */
215 openlog("mail.local", 0, LOG_MAIL);
216 # else /* LOG_MAIL */
217 openlog("mail.local", 0);
218 # endif /* LOG_MAIL */
222 /* XXX can this be converted to a compile time check? */
223 if (sm_strlcpy(SpoolPath, _PATH_MAILDIR, sizeof(SpoolPath)) >=
226 mailerr("421", "Configuration error: _PATH_MAILDIR too large");
230 while ((ch = getopt(argc, argv, "7BbdD:f:h:r:lH:p:ns")) != -1)
231 #else /* HASHSPOOL */
232 while ((ch = getopt(argc, argv, "7BbdD:f:h:r:ls")) != -1)
233 #endif /* HASHSPOOL */
237 case '7': /* Do not advertise 8BITMIME */
238 EightBitMime = false;
245 case 'b': /* bounce mail when over quota. */
249 case 'd': /* Backward compatible. */
252 case 'D': /* mailbox database type */
257 case 'r': /* Backward compatible. */
260 mailerr(NULL, "Multiple -f options");
267 if (optarg != NULL || *optarg != '\0')
268 HomeMailFile = optarg;
271 mailerr(NULL, "-h: missing filename");
286 if (optarg == NULL || *optarg == '\0')
288 mailerr(NULL, "-H: missing hashinfo");
294 HashType = HASH_USER;
301 # endif /* HASHSPOOLMD5 */
304 mailerr(NULL, "-H: unknown hash type");
307 if (optarg[1] == '\0')
309 mailerr(NULL, "-H: invalid hash depth");
312 HashDepth = atoi(&optarg[1]);
313 if ((HashDepth <= 0) || ((HashDepth * 2) >= MAXPATHLEN))
315 mailerr(NULL, "-H: invalid hash depth");
321 if (optarg == NULL || *optarg == '\0')
323 mailerr(NULL, "-p: missing spool path");
326 if (sm_strlcpy(SpoolPath, optarg, sizeof(SpoolPath)) >=
329 mailerr(NULL, "-p: invalid spool path");
335 StripRcptDomain = false;
337 #endif /* HASHSPOOL */
347 /* initialize biff structures */
351 err = sm_mbdb_initialize(mbdbname);
354 char *errcode = "521";
356 if (err == EX_TEMPFAIL)
359 mailerr(errcode, "Can not open mailbox database %s: %s",
360 mbdbname, sm_strexit(err));
369 mailerr("421", "Users should not be specified in command line if LMTP required");
370 sm_exit(EX_TEMPFAIL);
378 /* Non-LMTP from here on out */
383 ** If from not specified, use the name from getlogin() if the
384 ** uid matches, otherwise, use the name from the password file
385 ** corresponding to the uid.
389 if (from == NULL && ((from = getlogin()) == NULL ||
390 (pw = getpwnam(from)) == NULL ||
392 from = (pw = getpwuid(uid)) != NULL ? pw->pw_name : "???";
395 ** There is no way to distinguish the error status of one delivery
396 ** from the rest of the deliveries. So, if we failed hard on one
397 ** or more deliveries, but had no failures on any of the others, we
398 ** return a hard failure. If we failed temporarily on one or more
399 ** deliveries, we return a temporary failure regardless of the other
400 ** failures. This results in the delivery being reattempted later
401 ** at the expense of repeated failures and multiple deliveries.
405 fd = store(from, NULL);
412 for (; *argv != NULL; ++argv)
436 while (*p != ',' && *p != ':' && *p != '\0')
441 /* Skip over , or : */
448 while (*p != '\0' && *p != '@' && *p != '>')
458 while (*p != '\0' && *p != '\"')
467 if (*p == '\0' || *(p + 1) == '\0')
471 if (*p == '+' && rcpt)
481 while (*p != '\0' && *p != '>')
491 if (*p != '\0' && *p != ' ')
503 mailerr("421 4.3.0", "Memory exhausted");
504 sm_exit(EX_TEMPFAIL);
507 (void) sm_strlcpy(p, s, l);
512 process_recipient(addr)
517 switch (sm_mbdb_lookup(addr, &user))
523 return "550 5.1.1 User unknown";
526 return "451 4.3.0 User database failure; retry later";
529 return "550 5.3.0 User database failure";
538 char *return_path = NULL;
539 char **rcpt_addr = NULL;
542 bool gotlhlo = false;
547 char myhostname[1024];
550 memset(myhostname, '\0', sizeof myhostname);
551 (void) gethostname(myhostname, sizeof myhostname - 1);
552 if (myhostname[0] == '\0')
553 sm_strlcpy(myhostname, "localhost", sizeof myhostname);
555 printf("220 %s LMTP ready\r\n", myhostname);
558 (void) fflush(stdout);
559 if (fgets(buf, sizeof(buf) - 1, stdin) == NULL)
561 p = buf + strlen(buf) - 1;
562 if (p >= buf && *p == '\n')
564 if (p >= buf && *p == '\r')
571 if (sm_strcasecmp(buf, "data") == 0)
577 mailerr("503 5.5.1", "No recipients");
581 msgfd = store(return_path, &inbody);
583 if (msgfd < 0 && !inbody)
589 for (i = 0; i < rcpt_num; i++)
593 /* print error for rcpt */
597 p = strchr(rcpt_addr[i], '+');
600 deliver(msgfd, rcpt_addr[i]);
612 if (sm_strncasecmp(buf, "lhlo ", 5) == 0)
614 /* check for duplicate per RFC 1651 4.2 */
617 mailerr("503", "%s Duplicate LHLO",
622 printf("250-%s\r\n", myhostname);
624 printf("250-8BITMIME\r\n");
625 printf("250-ENHANCEDSTATUSCODES\r\n");
626 printf("250 PIPELINING\r\n");
635 if (sm_strncasecmp(buf, "mail ", 5) == 0)
637 if (return_path != NULL)
640 "Nested MAIL command");
643 if (sm_strncasecmp(buf + 5, "from:", 5) != 0 ||
644 ((return_path = parseaddr(buf + 10,
648 "Syntax error in parameters");
651 printf("250 2.5.0 Ok\r\n");
660 if (sm_strcasecmp(buf, "noop") == 0)
662 printf("250 2.0.0 Ok\r\n");
671 if (sm_strcasecmp(buf, "quit") == 0)
673 printf("221 2.0.0 Bye\r\n");
682 if (sm_strncasecmp(buf, "rcpt ", 5) == 0)
684 if (return_path == NULL)
687 "Need MAIL command");
690 if (rcpt_num >= rcpt_alloc)
692 rcpt_alloc += RCPT_GROW;
693 rcpt_addr = (char **)
694 REALLOC((char *) rcpt_addr,
697 if (rcpt_addr == NULL)
701 sm_exit(EX_TEMPFAIL);
704 if (sm_strncasecmp(buf + 5, "to:", 3) != 0 ||
705 ((rcpt_addr[rcpt_num] = parseaddr(buf + 8,
706 StripRcptDomain)) == NULL))
709 "Syntax error in parameters");
712 err = process_recipient(rcpt_addr[rcpt_num]);
715 mailerr(NULL, "%s", err);
719 printf("250 2.1.5 Ok\r\n");
722 else if (sm_strcasecmp(buf, "rset") == 0)
724 printf("250 2.0.0 Ok\r\n");
728 free(rcpt_addr[--rcpt_num]);
729 if (return_path != NULL)
740 if (sm_strncasecmp(buf, "vrfy ", 5) == 0)
742 printf("252 2.3.3 Try RCPT to attempt delivery\r\n");
751 mailerr("500 5.5.2", "Syntax error");
766 bool eline; /* previous line was empty */
767 bool fullline = true; /* current line is terminated */
768 bool prevfl; /* previous line was terminated */
771 char tmpbuf[sizeof _PATH_LOCTMP + 1];
777 (void) sm_strlcpy(tmpbuf, _PATH_LOCTMP, sizeof tmpbuf);
778 if ((fd = mkstemp(tmpbuf)) < 0 || (fp = fdopen(fd, "w+")) == NULL)
782 mailerr("451 4.3.0", "Unable to open temporary file");
785 (void) unlink(tmpbuf);
789 printf("354 Go ahead\r\n");
790 (void) fflush(stdout);
796 (void) fprintf(fp, "From %s %s", from, ctime(&tval));
801 #endif /* CONTENTLENGTH */
805 while (fgets(line, sizeof(line), stdin) != (char *) NULL)
810 prevfl = fullline; /* preserve state of previous line */
811 while (line[line_len] != '\n' && line_len < sizeof(line) - 2)
815 /* Check for dot-stuffing */
816 if (prevfl && LMTPMode && line[0] == '.')
818 if (line[1] == '\n' ||
819 (line[1] == '\r' && line[2] == '\n'))
821 memcpy(line, line + 1, line_len);
825 /* Check to see if we have the full line from fgets() */
829 if (line[line_len - 1] == '\n')
832 line[line_len - 2] == '\r')
834 line[line_len - 2] = '\n';
835 line[line_len - 1] = '\0';
840 else if (line[line_len - 1] == '\r')
842 /* Did we just miss the CRLF? */
846 line[line_len - 1] = '\n';
850 (void) ungetc(peek, stdin);
857 if (prevfl && line[0] == '\n' && HeaderLength == 0)
861 HeaderLength = ftell(fp);
862 if (HeaderLength <= 0)
865 ** shouldn't happen, unless ftell() is
872 #else /* CONTENTLENGTH */
873 if (prevfl && line[0] == '\n')
875 #endif /* CONTENTLENGTH */
878 if (eline && line[0] == 'F' &&
880 !memcmp(line, "From ", 5))
881 (void) putc('>', fp);
884 /* discard existing "Content-Length:" headers */
885 if (prevfl && HeaderLength == 0 &&
886 (line[0] == 'C' || line[0] == 'c') &&
887 sm_strncasecmp(line, ContentHdr, 15) == 0)
890 ** be paranoid: clear the line
891 ** so no "wrong matches" may occur later
896 #endif /* CONTENTLENGTH */
901 (void) fwrite(line, sizeof(char), line_len, fp);
905 "Temporary file write error");
913 /* check if an error occurred */
919 /* Got a premature EOF -- toss message and exit */
923 /* If message not newline terminated, need an extra. */
924 if (fp != NULL && strchr(line, '\n') == NULL)
925 (void) putc('\n', fp);
931 BodyLength = ftell(fp);
932 if (HeaderLength == 0 && BodyLength > 0) /* empty body */
934 HeaderLength = BodyLength;
938 BodyLength = BodyLength - HeaderLength - 1 ;
940 if (HeaderLength > 0 && BodyLength >= 0)
942 (void) sm_snprintf(line, sizeof line, "%lld\n",
943 (LONGLONG_T) BodyLength);
944 (void) sm_strlcpy(&ContentHdr[16], line,
945 sizeof(ContentHdr) - 16);
948 BodyLength = -1; /* Something is wrong here */
949 #endif /* CONTENTLENGTH */
951 /* Output a newline; note, empty messages are allowed. */
953 (void) putc('\n', fp);
955 if (fp == NULL || fflush(fp) == EOF || ferror(fp) != 0)
957 mailerr("451 4.3.0", "Temporary file write error");
972 char path[MAXPATHLEN];
973 int mbfd = -1, nr = 0, nw, off;
977 off_t curoff, cursize;
981 #endif /* CONTENTLENGTH */
982 char biffmsg[100], buf[8 * 1024];
986 ** Disallow delivery to unknown names -- special mailboxes can be
987 ** handled in the sendmail aliases file.
990 exitval = sm_mbdb_lookup(name, &user);
997 exitval = EX_UNAVAILABLE;
998 mailerr("550 5.1.1", "%s: User unknown", name);
1002 mailerr("451 4.3.0", "%s: User database failure; retry later",
1007 exitval = EX_UNAVAILABLE;
1008 mailerr("550 5.3.0", "%s: User database failure", name);
1012 if (exitval != EX_OK)
1014 if (ExitVal != EX_TEMPFAIL)
1022 ** Keep name reasonably short to avoid buffer overruns.
1023 ** This isn't necessary on BSD because of the proper
1024 ** definition of snprintf(), but it can cause problems
1025 ** on other systems.
1026 ** Also, clear out any bogus characters.
1030 if (strlen(name) > 40)
1032 for (p = name; *p != '\0'; p++)
1036 else if (!isprint(*p))
1039 #endif /* !HASHSPOOL */
1042 if (HomeMailFile == NULL)
1044 if (sm_strlcpyn(path, sizeof(path),
1047 #else /* HASHSPOOL */
1049 #endif /* HASHSPOOL */
1053 #endif /* HASHSPOOL */
1054 name) >= sizeof(path))
1056 exitval = EX_UNAVAILABLE;
1057 mailerr("550 5.1.1", "%s: Invalid mailbox path", name);
1061 else if (*user.mbdb_homedir == '\0')
1063 exitval = EX_UNAVAILABLE;
1064 mailerr("550 5.1.1", "%s: User missing home directory", name);
1067 else if (sm_snprintf(path, sizeof(path), "%s/%s",
1068 user.mbdb_homedir, HomeMailFile) >= sizeof(path))
1070 exitval = EX_UNAVAILABLE;
1071 mailerr("550 5.1.1", "%s: Invalid mailbox path", name);
1077 ** If the mailbox is linked or a symlink, fail. There's an obvious
1078 ** race here, that the file was replaced with a symbolic link after
1079 ** the lstat returned, but before the open. We attempt to detect
1080 ** this by comparing the original stat information and information
1081 ** returned by an fstat of the file descriptor returned by the open.
1083 ** NB: this is a symptom of a larger problem, that the mail spooling
1084 ** directory is writeable by the wrong users. If that directory is
1085 ** writeable, system security is compromised for other reasons, and
1086 ** it cannot be fixed here.
1088 ** If we created the mailbox, set the owner/group. If that fails,
1089 ** just return. Another process may have already opened it, so we
1090 ** can't unlink it. Historically, binmail set the owner/group at
1091 ** each mail delivery. We no longer do this, assuming that if the
1092 ** ownership or permissions were changed there was a reason.
1095 ** open(2) should support flock'ing the file.
1101 #else /* MAILLOCK */
1103 #endif /* MAILLOCK */
1104 if ((off = lockmbox(p)) != 0)
1106 if (off == EX_TEMPFAIL || e_to_sys(off) == EX_TEMPFAIL)
1108 ExitVal = EX_TEMPFAIL;
1109 errcode = "451 4.3.0";
1112 errcode = "551 5.3.0";
1114 mailerr(errcode, "lockmailbox %s failed; error code %d %s",
1115 p, off, errno > 0 ? sm_errstring(errno) : "");
1119 if (lstat(path, &sb) < 0)
1122 int mode = S_IRUSR|S_IWUSR;
1123 gid_t gid = user.mbdb_gid;
1128 mode |= S_IRGRP|S_IWGRP;
1129 #endif /* MAILGID */
1131 mbfd = open(path, O_APPEND|O_CREAT|O_EXCL|O_WRONLY,
1135 if (lstat(path, &sb) < 0)
1137 ExitVal = EX_CANTCREAT;
1138 mailerr("550 5.2.0",
1139 "%s: lstat: file changed after open", path);
1144 if (save_errno == EEXIST)
1147 /* open failed, don't try again */
1148 mailerr("450 4.2.0", "%s: %s", path,
1149 sm_errstring(save_errno));
1152 else if (fchown(mbfd, user.mbdb_uid, gid) < 0)
1154 mailerr("451 4.3.0", "chown %u.%u: %s",
1155 user.mbdb_uid, gid, name);
1161 ** open() was successful, now close it so can
1162 ** be opened as the right owner again.
1163 ** Paranoia: reset mbdf since the file descriptor
1164 ** is no longer valid; better safe than sorry.
1167 sb.st_uid = user.mbdb_uid;
1172 else if (sb.st_nlink != 1)
1174 mailerr("550 5.2.0", "%s: too many links", path);
1177 else if (!S_ISREG(sb.st_mode))
1179 mailerr("550 5.2.0", "%s: irregular file", path);
1182 else if (sb.st_uid != user.mbdb_uid)
1184 ExitVal = EX_CANTCREAT;
1185 mailerr("550 5.2.0", "%s: wrong ownership (%d)",
1186 path, (int) sb.st_uid);
1190 /* change UID for quota checks */
1191 if (setreuid(0, user.mbdb_uid) < 0)
1193 mailerr("450 4.2.0", "setreuid(0, %d): %s (r=%d, e=%d)",
1194 (int) user.mbdb_uid, sm_errstring(errno),
1195 (int) getuid(), (int) geteuid());
1199 fprintf(stderr, "new euid = %d\n", (int) geteuid());
1201 mbfd = open(path, O_APPEND|O_WRONLY, 0);
1204 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1207 else if (fstat(mbfd, &fsb) < 0 ||
1208 fsb.st_nlink != 1 ||
1210 !S_ISREG(fsb.st_mode) ||
1211 sb.st_dev != fsb.st_dev ||
1212 sb.st_ino != fsb.st_ino ||
1213 # if HAS_ST_GEN && 0 /* AFS returns random values for st_gen */
1214 sb.st_gen != fsb.st_gen ||
1215 # endif /* HAS_ST_GEN && 0 */
1216 sb.st_uid != fsb.st_uid)
1218 ExitVal = EX_TEMPFAIL;
1219 mailerr("550 5.2.0", "%s: fstat: file changed after open",
1226 ** This code could be reused if we decide to add a
1227 ** per-user quota field to the sm_mbdb interface.
1231 ** Fail if the user has a quota specified, and delivery of this
1232 ** message would exceed that quota. We bounce such failures using
1233 ** EX_UNAVAILABLE, unless there were internal problems, since
1234 ** storing immense messages for later retries can cause queueing
1242 if (fstat(fd, &dsb) < 0)
1244 ExitVal = EX_TEMPFAIL;
1245 mailerr("451 4.3.0",
1246 "%s: fstat: can't stat temporary storage: %s",
1247 ui.mailspool, sm_errstring(errno));
1251 if (dsb.st_size + sb.st_size + 1 > ui.quota)
1253 ExitVal = EX_UNAVAILABLE;
1254 mailerr("551 5.2.2",
1255 "%s: Mailbox full or quota exceeded",
1262 /* Wait until we can get a lock on the file. */
1263 if (flock(mbfd, LOCK_EX) < 0)
1265 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1269 /* Get the starting offset of the new message */
1270 curoff = lseek(mbfd, (off_t) 0, SEEK_END);
1274 (void) sm_snprintf(biffmsg, sizeof(biffmsg), "%s@%lld\n",
1275 name, (LONGLONG_T) curoff);
1278 /* Copy the message into the file. */
1279 if (lseek(fd, (off_t) 0, SEEK_SET) == (off_t) -1)
1281 mailerr("450 4.2.0", "Temporary file: %s",
1282 sm_errstring(errno));
1286 fprintf(stderr, "before writing: euid = %d\n", (int) geteuid());
1288 #ifdef CONTENTLENGTH
1289 headerbytes = (BodyLength >= 0) ? HeaderLength : -1 ;
1292 if (headerbytes == 0)
1294 (void) sm_snprintf(buf, sizeof buf, "%s", ContentHdr);
1299 else if (headerbytes > sizeof(buf) || headerbytes < 0)
1300 readamount = sizeof(buf);
1302 readamount = headerbytes;
1303 if (readamount != 0)
1304 nr = read(fd, buf, readamount);
1307 if (headerbytes > 0)
1310 #else /* CONTENTLENGTH */
1311 while ((nr = read(fd, buf, sizeof(buf))) > 0)
1313 #endif /* CONTENTLENGTH */
1314 for (off = 0; off < nr; off += nw)
1316 if ((nw = write(mbfd, buf + off, nr - off)) < 0)
1318 errcode = "450 4.2.0";
1320 if (errno == EDQUOT && BounceQuota)
1321 errcode = "552 5.2.2";
1323 mailerr(errcode, "%s: %s",
1324 path, sm_errstring(errno));
1331 mailerr("450 4.2.0", "Temporary file: %s",
1332 sm_errstring(errno));
1336 /* Flush to disk, don't wait for update. */
1337 if (!nofsync && fsync(mbfd) < 0)
1339 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1342 fprintf(stderr, "reset euid = %d\n", (int) geteuid());
1345 (void) ftruncate(mbfd, curoff);
1346 err1: if (mbfd >= 0)
1348 err0: (void) setreuid(0, 0);
1354 ** Save the current size so if the close() fails below
1355 ** we can make sure no other process has changed the mailbox
1356 ** between the failed close and the re-open()/re-lock().
1357 ** If something else has changed the size, we shouldn't
1358 ** try to truncate it as we may do more harm then good
1359 ** (e.g., truncate a later message delivery).
1362 if (fstat(mbfd, &sb) < 0)
1365 cursize = sb.st_size;
1368 /* Close and check -- NFS doesn't write until the close. */
1371 errcode = "450 4.2.0";
1373 if (errno == EDQUOT && BounceQuota)
1374 errcode = "552 5.2.2";
1376 mailerr(errcode, "%s: %s", path, sm_errstring(errno));
1377 mbfd = open(path, O_WRONLY, 0);
1380 || flock(mbfd, LOCK_EX) < 0 ||
1381 fstat(mbfd, &sb) < 0 ||
1382 sb.st_size != cursize ||
1384 !S_ISREG(sb.st_mode) ||
1385 sb.st_dev != fsb.st_dev ||
1386 sb.st_ino != fsb.st_ino ||
1387 # if HAS_ST_GEN && 0 /* AFS returns random values for st_gen */
1388 sb.st_gen != fsb.st_gen ||
1389 # endif /* HAS_ST_GEN && 0 */
1390 sb.st_uid != fsb.st_uid
1393 /* Don't use a bogus file */
1401 /* Attempt to truncate back to pre-write size */
1405 notifybiff(biffmsg);
1407 if (setreuid(0, 0) < 0)
1409 mailerr("450 4.2.0", "setreuid(0, 0): %s",
1410 sm_errstring(errno));
1414 fprintf(stderr, "reset euid = %d\n", (int) geteuid());
1418 printf("250 2.1.5 %s Ok\r\n", name);
1422 ** user.lock files are necessary for compatibility with other
1423 ** systems, e.g., when the mail spool file is NFS exported.
1424 ** Alas, mailbox locking is more than just a local matter.
1428 bool Locked = false;
1439 if ((r = maillock(name, 15)) == L_SUCCESS)
1446 case L_TMPLOCK: /* Can't create tmp file */
1447 case L_TMPWRITE: /* Can't write pid into lockfile */
1448 case L_MAXTRYS: /* Failed after retrycnt attempts */
1452 case L_ERROR: /* Check errno for reason */
1455 default: /* other permanent errors */
1470 #else /* MAILLOCK */
1472 char LockName[MAXPATHLEN];
1483 if (strlen(path) + 6 > sizeof LockName)
1485 (void) sm_snprintf(LockName, sizeof LockName, "%s.lock", path);
1486 (void) time(&start);
1493 /* global timeout */
1495 if (now > start + LOCKTO_GLOB)
1500 fd = open(LockName, O_WRONLY|O_EXCL|O_CREAT, LOCKFILE_PMODE);
1503 /* defeat lock checking programs which test pid */
1504 (void) write(fd, "0", 2);
1509 if (stat(LockName, &st) < 0)
1511 if (statfailed++ > 5)
1520 if (now < st.st_ctime + LOCKTO_RM)
1523 /* try to remove stale lockfile */
1524 if (unlink(LockName) < 0)
1534 (void) unlink(LockName);
1537 #endif /* MAILLOCK */
1543 static bool initialized = false;
1548 static struct sockaddr_in addr;
1554 /* Be silent if biff service not available. */
1555 if ((sp = getservbyname("biff", "udp")) == NULL ||
1556 (hp = gethostbyname("localhost")) == NULL ||
1557 hp->h_length != INADDRSZ)
1560 addr.sin_family = hp->h_addrtype;
1561 memcpy(&addr.sin_addr, hp->h_addr, INADDRSZ);
1562 addr.sin_port = sp->s_port;
1565 /* No message, just return */
1569 /* Couldn't initialize addr struct */
1570 if (addr.sin_family == AF_UNSPEC)
1573 if (f < 0 && (f = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1575 len = strlen(msg) + 1;
1576 (void) sendto(f, msg, len, 0, (struct sockaddr *) &addr, sizeof(addr));
1583 mailerr(NULL, "usage: mail.local [-7] [-B] [-b] [-d] [-l] [-s] [-f from|-r from] [-h filename] user ...");
1590 mailerr(const char *hdr, const char *fmt, ...)
1591 #else /* __STDC__ */
1592 mailerr(hdr, fmt, va_alist)
1596 #endif /* __STDC__ */
1601 (void) e_to_sys(errno);
1603 SM_VA_START(ap, fmt);
1605 if (LMTPMode && hdr != NULL)
1607 sm_snprintf(ErrBuf, sizeof ErrBuf, "%s ", hdr);
1608 len = strlen(ErrBuf);
1610 (void) sm_vsnprintf(&ErrBuf[len], sizeof ErrBuf - len, fmt, ap);
1616 /* Log the message to syslog. */
1618 syslog(LOG_ERR, "%s", ErrBuf);
1625 printf("%s\r\n", ErrBuf);
1628 if (ExitVal != EX_USAGE)
1629 (void) fprintf(stderr, "mail.local: ");
1630 fprintf(stderr, "%s\n", ErrBuf);
1639 static char p[MAXPATHLEN];
1644 char Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_";
1646 unsigned char md5[18];
1647 # if MAXPATHLEN <= 24
1648 ERROR _MAXPATHLEN <= 24
1649 # endif /* MAXPATHLEN <= 24 */
1653 # endif /* HASHSPOOLMD5 */
1655 if (HashType == HASH_NONE || HashDepth * 2 >= MAXPATHLEN)
1670 MD5_Update(&ctx, name, strlen(name));
1671 MD5_Final(md5, &ctx);
1675 for (i = 0; i < 6; i++)
1677 bits = (unsigned) md5[(3 * i)] << 16;
1678 bits |= (unsigned) md5[(3 * i) + 1] << 8;
1679 bits |= (unsigned) md5[(3 * i) + 2];
1681 for (j = 3; j >= 0; j--)
1683 b64[(4 * i) + j] = Base64[(bits & 0x3f)];
1690 # endif /* HASHSPOOLMD5 */
1694 for (i = 0; i < HashDepth; i++)
1700 p[(i * 2) + 1] = '/';
1702 p[HashDepth * 2] = '\0';
1705 #endif /* HASHSPOOL */
1709 * Guess which errno's are temporary. Gag me.
1716 /* Temporary failures override hard errors. */
1717 if (ExitVal == EX_TEMPFAIL)
1720 switch (num) /* Hopefully temporary errors. */
1723 case EDQUOT: /* Disc quota exceeded */
1726 ExitVal = EX_UNAVAILABLE;
1732 case EAGAIN: /* Resource temporarily unavailable */
1735 case EBUSY: /* Device busy */
1738 case EPROCLIM: /* Too many processes */
1739 #endif /* EPROCLIM */
1741 case EUSERS: /* Too many users */
1744 case ECONNABORTED: /* Software caused connection abort */
1745 #endif /* ECONNABORTED */
1747 case ECONNREFUSED: /* Connection refused */
1748 #endif /* ECONNREFUSED */
1750 case ECONNRESET: /* Connection reset by peer */
1751 #endif /* ECONNRESET */
1753 case EDEADLK: /* Resource deadlock avoided */
1754 #endif /* EDEADLK */
1756 case EFBIG: /* File too large */
1759 case EHOSTDOWN: /* Host is down */
1760 #endif /* EHOSTDOWN */
1762 case EHOSTUNREACH: /* No route to host */
1763 #endif /* EHOSTUNREACH */
1765 case EMFILE: /* Too many open files */
1768 case ENETDOWN: /* Network is down */
1769 #endif /* ENETDOWN */
1771 case ENETRESET: /* Network dropped connection on reset */
1772 #endif /* ENETRESET */
1774 case ENETUNREACH: /* Network is unreachable */
1775 #endif /* ENETUNREACH */
1777 case ENFILE: /* Too many open files in system */
1780 case ENOBUFS: /* No buffer space available */
1781 #endif /* ENOBUFS */
1783 case ENOMEM: /* Cannot allocate memory */
1786 case ENOSPC: /* No space left on device */
1789 case EROFS: /* Read-only file system */
1792 case ESTALE: /* Stale NFS file handle */
1795 case ETIMEDOUT: /* Connection timed out */
1796 #endif /* ETIMEDOUT */
1797 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN && EWOULDBLOCK != EDEADLK
1798 case EWOULDBLOCK: /* Operation would block. */
1799 #endif /* defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN && EWOULDBLOCK != EDEADLK */
1800 ExitVal = EX_TEMPFAIL;
1804 ExitVal = EX_UNAVAILABLE;
1810 #if defined(ultrix) || defined(_CRAY)
1812 * Copyright (c) 1987, 1993
1813 * The Regents of the University of California. All rights reserved.
1815 * Redistribution and use in source and binary forms, with or without
1816 * modification, are permitted provided that the following conditions
1818 * 1. Redistributions of source code must retain the above copyright
1819 * notice, this list of conditions and the following disclaimer.
1820 * 2. Redistributions in binary form must reproduce the above copyright
1821 * notice, this list of conditions and the following disclaimer in the
1822 * documentation and/or other materials provided with the distribution.
1823 * 3. All advertising materials mentioning features or use of this software
1824 * must display the following acknowledgement:
1825 * This product includes software developed by the University of
1826 * California, Berkeley and its contributors.
1827 * 4. Neither the name of the University nor the names of its contributors
1828 * may be used to endorse or promote products derived from this software
1829 * without specific prior written permission.
1831 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1832 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1833 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1834 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
1835 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1836 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1837 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1838 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1839 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1840 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1844 # if defined(LIBC_SCCS) && !defined(lint)
1845 static char sccsid[] = "@(#)mktemp.c 8.1 (Berkeley) 6/4/93";
1846 # endif /* defined(LIBC_SCCS) && !defined(lint) */
1848 # include <sys/types.h>
1849 # include <sys/stat.h>
1855 static int _gettemp();
1862 return (_gettemp(path, &fd) ? fd : -1);
1866 _gettemp(path, doopen)
1868 register int *doopen;
1871 register char *start, *trv;
1876 for (trv = path; *trv; ++trv); /* extra X's get set to 0's */
1877 while (*--trv == 'X')
1879 *trv = (pid % 10) + '0';
1884 * check the target directory; if you have six X's and it
1885 * doesn't exist this runs for a *very* long time.
1887 for (start = trv + 1;; --trv)
1894 if (stat(path, &sbuf) < 0)
1896 if (!S_ISDIR(sbuf.st_mode))
1910 if ((*doopen = open(path, O_CREAT|O_EXCL|O_RDWR,
1913 if (errno != EEXIST)
1916 else if (stat(path, &sbuf) < 0)
1917 return(errno == ENOENT ? 1 : 0);
1919 /* tricky little algorithm for backward compatibility */
1928 if (isascii(*trv) && isdigit(*trv))
1938 #endif /* defined(ultrix) || defined(_CRAY) */