2 * Copyright (c) 1998-2003 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.
11 * $FreeBSD: src/contrib/sendmail/mail.local/mail.local.c,v 1.6.6.14 2003/03/29 19:33:16 gshapiro Exp $
18 "@(#) Copyright (c) 1998-2001 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.239.2.5 2003/03/15 23:43:20 gshapiro Exp $")
26 #include <sm/errstring.h>
28 #include <sm/limits.h>
31 # undef EX_OK /* unistd.h may have another use for this */
34 #include <sm/sysexits.h>
37 ** This is not intended to work on System V derived systems
38 ** such as Solaris or HP-UX, since they use a totally different
39 ** approach to mailboxes (essentially, they have a set-group-ID program
40 ** rather than set-user-ID, and they rely on the ability to "give away"
41 ** files to do their work). IT IS NOT A BUG that this doesn't
42 ** work on such architectures.
49 #include <sys/types.h>
53 # include <sys/socket.h>
54 # include <sys/file.h>
55 # include <netinet/in.h>
56 # include <arpa/nameser.h>
60 #include <sm/string.h>
65 #include <sendmail/pathnames.h>
68 /* additional mode for open() */
73 # define LOCKTO_RM 300 /* timeout for stale lockfile removal */
74 #endif /* ! LOCKTO_RM */
76 # define LOCKTO_GLOB 400 /* global timeout for lockfile creation */
77 #endif /* ! LOCKTO_GLOB */
79 /* define a realloc() which works for NULL pointers */
80 #define REALLOC(ptr, size) (((ptr) == NULL) ? malloc(size) : realloc(ptr, size))
83 ** If you don't have flock, you could try using lockf instead.
87 # define flock(a, b) lockf(a, b, 0)
91 # define LOCK_EX F_LOCK
92 #endif /* LDA_USE_LOCKF */
95 # include <sys/file.h>
96 #endif /* ! LOCK_EX */
99 ** If you don't have setreuid, and you have saved uids, and you have
100 ** a seteuid() call that doesn't try to emulate using setuid(), then
101 ** you can try defining LDA_USE_SETEUID.
104 #ifdef LDA_USE_SETEUID
105 # define setreuid(r, e) seteuid(e)
106 #endif /* LDA_USE_SETEUID */
108 #ifdef LDA_CONTENTLENGTH
109 # define CONTENTLENGTH 1
110 #endif /* LDA_CONTENTLENGTH */
113 # define INADDRSZ 4 /* size of an IPv4 address in bytes */
114 #endif /* ! INADDRSZ */
117 # include <maillock.h>
118 #endif /* MAILLOCK */
120 #ifndef MAILER_DAEMON
121 # define MAILER_DAEMON "MAILER-DAEMON"
122 #endif /* ! MAILER_DAEMON */
125 char ContentHdr[40] = "Content-Length: ";
128 #endif /* CONTENTLENGTH */
130 bool EightBitMime = true; /* advertise 8BITMIME in LMTP */
131 char ErrBuf[10240]; /* error buffer */
132 int ExitVal = EX_OK; /* sysexits.h error value. */
134 bool nofsync = false;
135 bool HoldErrs = false; /* Hold errors in ErrBuf */
136 bool LMTPMode = false;
137 bool BounceQuota = false; /* permanent error when over quota */
138 char *HomeMailFile = NULL; /* store mail in homedir */
140 void deliver __P((int, char *));
141 int e_to_sys __P((int));
142 void notifybiff __P((char *));
143 int store __P((char *, bool *));
144 void usage __P((void));
145 int lockmbox __P((char *));
146 void unlockmbox __P((void));
147 void mailerr __P((const char *, const char *, ...));
148 void flush_error __P((void));
160 char *mbdbname = "pw";
166 /* make sure we have some open file descriptors */
167 for (fd = 10; fd < 30; fd++)
170 /* use a reasonable umask */
174 openlog("mail.local", 0, LOG_MAIL);
175 # else /* LOG_MAIL */
176 openlog("mail.local", 0);
177 # endif /* LOG_MAIL */
180 while ((ch = getopt(argc, argv, "7BbdD:f:h:r:ls")) != -1)
184 case '7': /* Do not advertise 8BITMIME */
185 EightBitMime = false;
192 case 'b': /* bounce mail when over quota. */
196 case 'd': /* Backward compatible. */
199 case 'D': /* mailbox database type */
204 case 'r': /* Backward compatible. */
207 mailerr(NULL, "Multiple -f options");
214 if (optarg != NULL || *optarg != '\0')
215 HomeMailFile = optarg;
218 mailerr(NULL, "-h: missing filename");
239 /* initialize biff structures */
243 err = sm_mbdb_initialize(mbdbname);
246 char *errcode = "521";
248 if (err == EX_TEMPFAIL)
251 mailerr(errcode, "Can not open mailbox database %s: %s",
252 mbdbname, sm_strexit(err));
258 extern void dolmtp __P((void));
262 mailerr("421", "Users should not be specified in command line if LMTP required");
271 /* Non-LMTP from here on out */
276 ** If from not specified, use the name from getlogin() if the
277 ** uid matches, otherwise, use the name from the password file
278 ** corresponding to the uid.
282 if (from == NULL && ((from = getlogin()) == NULL ||
283 (pw = getpwnam(from)) == NULL ||
285 from = (pw = getpwuid(uid)) != NULL ? pw->pw_name : "???";
288 ** There is no way to distinguish the error status of one delivery
289 ** from the rest of the deliveries. So, if we failed hard on one
290 ** or more deliveries, but had no failures on any of the others, we
291 ** return a hard failure. If we failed temporarily on one or more
292 ** deliveries, we return a temporary failure regardless of the other
293 ** failures. This results in the delivery being reattempted later
294 ** at the expense of repeated failures and multiple deliveries.
298 fd = store(from, NULL);
305 for (; *argv != NULL; ++argv)
329 while (*p != ',' && *p != ':' && *p != '\0')
334 /* Skip over , or : */
341 while (*p != '\0' && *p != '@' && *p != '>')
351 while (*p != '\0' && *p != '\"')
360 if (*p == '\0' || *(p + 1) == '\0')
364 if (*p == '+' && rcpt)
374 while (*p != '\0' && *p != '>')
384 if (*p != '\0' && *p != ' ')
396 mailerr("421 4.3.0", "Memory exhausted");
400 (void) sm_strlcpy(p, s, l);
405 process_recipient(addr)
410 switch (sm_mbdb_lookup(addr, &user))
416 return "550 5.1.1 User unknown";
419 return "451 4.3.0 User database failure; retry later";
422 return "550 5.3.0 User database failure";
431 char *return_path = NULL;
432 char **rcpt_addr = NULL;
435 bool gotlhlo = false;
440 char myhostname[1024];
443 memset(myhostname, '\0', sizeof myhostname);
444 (void) gethostname(myhostname, sizeof myhostname - 1);
445 if (myhostname[0] == '\0')
446 sm_strlcpy(myhostname, "localhost", sizeof myhostname);
448 printf("220 %s LMTP ready\r\n", myhostname);
451 (void) fflush(stdout);
452 if (fgets(buf, sizeof(buf) - 1, stdin) == NULL)
454 p = buf + strlen(buf) - 1;
455 if (p >= buf && *p == '\n')
457 if (p >= buf && *p == '\r')
464 if (sm_strcasecmp(buf, "data") == 0)
470 mailerr("503 5.5.1", "No recipients");
474 msgfd = store(return_path, &inbody);
476 if (msgfd < 0 && !inbody)
482 for (i = 0; i < rcpt_num; i++)
486 /* print error for rcpt */
490 p = strchr(rcpt_addr[i], '+');
493 deliver(msgfd, rcpt_addr[i]);
505 if (sm_strncasecmp(buf, "lhlo ", 5) == 0)
507 /* check for duplicate per RFC 1651 4.2 */
510 mailerr("503", "%s Duplicate LHLO",
515 printf("250-%s\r\n", myhostname);
517 printf("250-8BITMIME\r\n");
518 printf("250-ENHANCEDSTATUSCODES\r\n");
519 printf("250 PIPELINING\r\n");
528 if (sm_strncasecmp(buf, "mail ", 5) == 0)
530 if (return_path != NULL)
533 "Nested MAIL command");
536 if (sm_strncasecmp(buf + 5, "from:", 5) != 0 ||
537 ((return_path = parseaddr(buf + 10,
541 "Syntax error in parameters");
544 printf("250 2.5.0 Ok\r\n");
553 if (sm_strcasecmp(buf, "noop") == 0)
555 printf("250 2.0.0 Ok\r\n");
564 if (sm_strcasecmp(buf, "quit") == 0)
566 printf("221 2.0.0 Bye\r\n");
575 if (sm_strncasecmp(buf, "rcpt ", 5) == 0)
577 if (return_path == NULL)
580 "Need MAIL command");
583 if (rcpt_num >= rcpt_alloc)
585 rcpt_alloc += RCPT_GROW;
586 rcpt_addr = (char **)
587 REALLOC((char *) rcpt_addr,
590 if (rcpt_addr == NULL)
597 if (sm_strncasecmp(buf + 5, "to:", 3) != 0 ||
598 ((rcpt_addr[rcpt_num] = parseaddr(buf + 8,
602 "Syntax error in parameters");
605 err = process_recipient(rcpt_addr[rcpt_num]);
608 mailerr(NULL, "%s", err);
612 printf("250 2.1.5 Ok\r\n");
615 else if (sm_strcasecmp(buf, "rset") == 0)
617 printf("250 2.0.0 Ok\r\n");
621 free(rcpt_addr[--rcpt_num]);
622 if (return_path != NULL)
633 if (sm_strncasecmp(buf, "vrfy ", 5) == 0)
635 printf("252 2.3.3 Try RCPT to attempt delivery\r\n");
644 mailerr("500 5.5.2", "Syntax error");
659 bool eline; /* previous line was empty */
660 bool fullline = true; /* current line is terminated */
661 bool prevfl; /* previous line was terminated */
664 char tmpbuf[sizeof _PATH_LOCTMP + 1];
670 (void) sm_strlcpy(tmpbuf, _PATH_LOCTMP, sizeof tmpbuf);
671 if ((fd = mkstemp(tmpbuf)) < 0 || (fp = fdopen(fd, "w+")) == NULL)
675 mailerr("451 4.3.0", "Unable to open temporary file");
678 (void) unlink(tmpbuf);
682 printf("354 Go ahead\r\n");
683 (void) fflush(stdout);
689 (void) fprintf(fp, "From %s %s", from, ctime(&tval));
694 #endif /* CONTENTLENGTH */
698 while (fgets(line, sizeof(line), stdin) != (char *) NULL)
703 prevfl = fullline; /* preserve state of previous line */
704 while (line[line_len] != '\n' && line_len < sizeof(line) - 2)
708 /* Check for dot-stuffing */
709 if (prevfl && LMTPMode && line[0] == '.')
711 if (line[1] == '\n' ||
712 (line[1] == '\r' && line[2] == '\n'))
714 memcpy(line, line + 1, line_len);
718 /* Check to see if we have the full line from fgets() */
722 if (line[line_len - 1] == '\n')
725 line[line_len - 2] == '\r')
727 line[line_len - 2] = '\n';
728 line[line_len - 1] = '\0';
733 else if (line[line_len - 1] == '\r')
735 /* Did we just miss the CRLF? */
739 line[line_len - 1] = '\n';
743 (void) ungetc(peek, stdin);
750 if (prevfl && line[0] == '\n' && HeaderLength == 0)
754 HeaderLength = ftell(fp);
755 if (HeaderLength <= 0)
758 ** shouldn't happen, unless ftell() is
765 #else /* CONTENTLENGTH */
766 if (prevfl && line[0] == '\n')
768 #endif /* CONTENTLENGTH */
771 if (eline && line[0] == 'F' &&
773 !memcmp(line, "From ", 5))
774 (void) putc('>', fp);
777 /* discard existing "Content-Length:" headers */
778 if (prevfl && HeaderLength == 0 &&
779 (line[0] == 'C' || line[0] == 'c') &&
780 sm_strncasecmp(line, ContentHdr, 15) == 0)
783 ** be paranoid: clear the line
784 ** so no "wrong matches" may occur later
789 #endif /* CONTENTLENGTH */
794 (void) fwrite(line, sizeof(char), line_len, fp);
798 "Temporary file write error");
806 /* check if an error occurred */
812 /* Got a premature EOF -- toss message and exit */
816 /* If message not newline terminated, need an extra. */
817 if (fp != NULL && strchr(line, '\n') == NULL)
818 (void) putc('\n', fp);
824 BodyLength = ftell(fp);
825 if (HeaderLength == 0 && BodyLength > 0) /* empty body */
827 HeaderLength = BodyLength;
831 BodyLength = BodyLength - HeaderLength - 1 ;
833 if (HeaderLength > 0 && BodyLength >= 0)
835 (void) sm_snprintf(line, sizeof line, "%lld\n",
836 (LONGLONG_T) BodyLength);
837 (void) sm_strlcpy(&ContentHdr[16], line,
838 sizeof(ContentHdr) - 16);
841 BodyLength = -1; /* Something is wrong here */
842 #endif /* CONTENTLENGTH */
844 /* Output a newline; note, empty messages are allowed. */
846 (void) putc('\n', fp);
848 if (fp == NULL || fflush(fp) == EOF || ferror(fp) != 0)
850 mailerr("451 4.3.0", "Temporary file write error");
865 char path[MAXPATHLEN];
866 int mbfd = -1, nr = 0, nw, off;
874 #endif /* CONTENTLENGTH */
875 char biffmsg[100], buf[8 * 1024];
879 ** Disallow delivery to unknown names -- special mailboxes can be
880 ** handled in the sendmail aliases file.
883 exitval = sm_mbdb_lookup(name, &user);
890 exitval = EX_UNAVAILABLE;
891 mailerr("550 5.1.1", "%s: User unknown", name);
895 mailerr("451 4.3.0", "%s: User database failure; retry later",
900 exitval = EX_UNAVAILABLE;
901 mailerr("550 5.3.0", "%s: User database failure", name);
905 if (exitval != EX_OK)
907 if (ExitVal != EX_TEMPFAIL)
915 ** Keep name reasonably short to avoid buffer overruns.
916 ** This isn't necessary on BSD because of the proper
917 ** definition of snprintf(), but it can cause problems
919 ** Also, clear out any bogus characters.
922 if (strlen(name) > 40)
924 for (p = name; *p != '\0'; p++)
928 else if (!isprint(*p))
933 if (HomeMailFile == NULL)
935 if (sm_snprintf(path, sizeof(path), "%s/%s",
936 _PATH_MAILDIR, name) >= sizeof(path))
938 exitval = EX_UNAVAILABLE;
939 mailerr("550 5.1.1", "%s: Invalid mailbox path", name);
943 else if (*user.mbdb_homedir == '\0')
945 exitval = EX_UNAVAILABLE;
946 mailerr("550 5.1.1", "%s: User missing home directory", name);
949 else if (sm_snprintf(path, sizeof(path), "%s/%s",
950 user.mbdb_homedir, HomeMailFile) >= sizeof(path))
952 exitval = EX_UNAVAILABLE;
953 mailerr("550 5.1.1", "%s: Invalid mailbox path", name);
959 ** If the mailbox is linked or a symlink, fail. There's an obvious
960 ** race here, that the file was replaced with a symbolic link after
961 ** the lstat returned, but before the open. We attempt to detect
962 ** this by comparing the original stat information and information
963 ** returned by an fstat of the file descriptor returned by the open.
965 ** NB: this is a symptom of a larger problem, that the mail spooling
966 ** directory is writeable by the wrong users. If that directory is
967 ** writeable, system security is compromised for other reasons, and
968 ** it cannot be fixed here.
970 ** If we created the mailbox, set the owner/group. If that fails,
971 ** just return. Another process may have already opened it, so we
972 ** can't unlink it. Historically, binmail set the owner/group at
973 ** each mail delivery. We no longer do this, assuming that if the
974 ** ownership or permissions were changed there was a reason.
977 ** open(2) should support flock'ing the file.
985 #endif /* MAILLOCK */
986 if ((off = lockmbox(p)) != 0)
988 if (off == EX_TEMPFAIL || e_to_sys(off) == EX_TEMPFAIL)
990 ExitVal = EX_TEMPFAIL;
991 errcode = "451 4.3.0";
994 errcode = "551 5.3.0";
996 mailerr(errcode, "lockmailbox %s failed; error code %d %s",
997 p, off, errno > 0 ? sm_errstring(errno) : "");
1001 if (lstat(path, &sb) < 0)
1004 int mode = S_IRUSR|S_IWUSR;
1005 gid_t gid = user.mbdb_gid;
1010 mode |= S_IRGRP|S_IWGRP;
1011 #endif /* MAILGID */
1013 mbfd = open(path, O_APPEND|O_CREAT|O_EXCL|O_WRONLY|EXTRA_MODE,
1017 if (lstat(path, &sb) < 0)
1019 ExitVal = EX_CANTCREAT;
1020 mailerr("550 5.2.0",
1021 "%s: lstat: file changed after open", path);
1026 if (save_errno == EEXIST)
1029 /* open failed, don't try again */
1030 mailerr("450 4.2.0", "%s: %s", path,
1031 sm_errstring(save_errno));
1034 else if (fchown(mbfd, user.mbdb_uid, gid) < 0)
1036 mailerr("451 4.3.0", "chown %u.%u: %s",
1037 user.mbdb_uid, gid, name);
1043 ** open() was successful, now close it so can
1044 ** be opened as the right owner again.
1045 ** Paranoia: reset mbdf since the file descriptor
1046 ** is no longer valid; better safe than sorry.
1049 sb.st_uid = user.mbdb_uid;
1054 else if (sb.st_nlink != 1)
1056 mailerr("550 5.2.0", "%s: too many links", path);
1059 else if (!S_ISREG(sb.st_mode))
1061 mailerr("550 5.2.0", "%s: irregular file", path);
1064 else if (sb.st_uid != user.mbdb_uid)
1066 ExitVal = EX_CANTCREAT;
1067 mailerr("550 5.2.0", "%s: wrong ownership (%d)",
1068 path, (int) sb.st_uid);
1072 /* change UID for quota checks */
1073 if (setreuid(0, user.mbdb_uid) < 0)
1075 mailerr("450 4.2.0", "setreuid(0, %d): %s (r=%d, e=%d)",
1076 (int) user.mbdb_uid, sm_errstring(errno),
1077 (int) getuid(), (int) geteuid());
1081 fprintf(stderr, "new euid = %d\n", (int) geteuid());
1083 mbfd = open(path, O_APPEND|O_WRONLY|EXTRA_MODE, 0);
1086 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1089 else if (fstat(mbfd, &fsb) < 0 ||
1090 fsb.st_nlink != 1 ||
1092 !S_ISREG(fsb.st_mode) ||
1093 sb.st_dev != fsb.st_dev ||
1094 sb.st_ino != fsb.st_ino ||
1095 # if HAS_ST_GEN && 0 /* AFS returns random values for st_gen */
1096 sb.st_gen != fsb.st_gen ||
1097 # endif /* HAS_ST_GEN && 0 */
1098 sb.st_uid != fsb.st_uid)
1100 ExitVal = EX_TEMPFAIL;
1101 mailerr("550 5.2.0", "%s: fstat: file changed after open",
1108 ** This code could be reused if we decide to add a
1109 ** per-user quota field to the sm_mbdb interface.
1113 ** Fail if the user has a quota specified, and delivery of this
1114 ** message would exceed that quota. We bounce such failures using
1115 ** EX_UNAVAILABLE, unless there were internal problems, since
1116 ** storing immense messages for later retries can cause queueing
1124 if (fstat(fd, &dsb) < 0)
1126 ExitVal = EX_TEMPFAIL;
1127 mailerr("451 4.3.0",
1128 "%s: fstat: can't stat temporary storage: %s",
1129 ui.mailspool, sm_errstring(errno));
1133 if (dsb.st_size + sb.st_size + 1 > ui.quota)
1135 ExitVal = EX_UNAVAILABLE;
1136 mailerr("551 5.2.2",
1137 "%s: Mailbox full or quota exceeded",
1144 /* Wait until we can get a lock on the file. */
1145 if (flock(mbfd, LOCK_EX) < 0)
1147 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1151 /* Get the starting offset of the new message */
1152 curoff = lseek(mbfd, (off_t) 0, SEEK_END);
1156 (void) sm_snprintf(biffmsg, sizeof(biffmsg), "%s@%lld\n",
1157 name, (LONGLONG_T) curoff);
1160 /* Copy the message into the file. */
1161 if (lseek(fd, (off_t) 0, SEEK_SET) == (off_t) -1)
1163 mailerr("450 4.2.0", "Temporary file: %s",
1164 sm_errstring(errno));
1168 fprintf(stderr, "before writing: euid = %d\n", (int) geteuid());
1170 #ifdef CONTENTLENGTH
1171 headerbytes = (BodyLength >= 0) ? HeaderLength : -1 ;
1174 if (headerbytes == 0)
1176 (void) sm_snprintf(buf, sizeof buf, "%s", ContentHdr);
1181 else if (headerbytes > sizeof(buf) || headerbytes < 0)
1182 readamount = sizeof(buf);
1184 readamount = headerbytes;
1185 if (readamount != 0)
1186 nr = read(fd, buf, readamount);
1189 if (headerbytes > 0)
1192 #else /* CONTENTLENGTH */
1193 while ((nr = read(fd, buf, sizeof(buf))) > 0)
1195 #endif /* CONTENTLENGTH */
1196 for (off = 0; off < nr; off += nw)
1198 if ((nw = write(mbfd, buf + off, nr - off)) < 0)
1200 errcode = "450 4.2.0";
1202 if (errno == EDQUOT && BounceQuota)
1203 errcode = "552 5.2.2";
1205 mailerr(errcode, "%s: %s",
1206 path, sm_errstring(errno));
1213 mailerr("450 4.2.0", "Temporary file: %s",
1214 sm_errstring(errno));
1218 /* Flush to disk, don't wait for update. */
1219 if (!nofsync && fsync(mbfd) < 0)
1221 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1223 (void) setreuid(0, 0);
1225 fprintf(stderr, "reset euid = %d\n", (int) geteuid());
1228 (void) ftruncate(mbfd, curoff);
1229 err1: if (mbfd >= 0)
1235 /* Close and check -- NFS doesn't write until the close. */
1238 errcode = "450 4.2.0";
1240 if (errno == EDQUOT && BounceQuota)
1241 errcode = "552 5.2.2";
1243 mailerr(errcode, "%s: %s", path, sm_errstring(errno));
1244 mbfd = open(path, O_WRONLY|EXTRA_MODE, 0);
1246 || fstat(mbfd, &sb) < 0 ||
1248 !S_ISREG(sb.st_mode) ||
1249 sb.st_dev != fsb.st_dev ||
1250 sb.st_ino != fsb.st_ino ||
1251 # if HAS_ST_GEN && 0 /* AFS returns random values for st_gen */
1252 sb.st_gen != fsb.st_gen ||
1253 # endif /* HAS_ST_GEN && 0 */
1254 sb.st_uid != fsb.st_uid
1257 /* Don't use a bogus file */
1265 /* Attempt to truncate back to pre-write size */
1269 notifybiff(biffmsg);
1271 if (setreuid(0, 0) < 0)
1273 mailerr("450 4.2.0", "setreuid(0, 0): %s",
1274 sm_errstring(errno));
1278 fprintf(stderr, "reset euid = %d\n", (int) geteuid());
1282 printf("250 2.1.5 %s Ok\r\n", name);
1286 ** user.lock files are necessary for compatibility with other
1287 ** systems, e.g., when the mail spool file is NFS exported.
1288 ** Alas, mailbox locking is more than just a local matter.
1292 bool Locked = false;
1303 if ((r = maillock(name, 15)) == L_SUCCESS)
1310 case L_TMPLOCK: /* Can't create tmp file */
1311 case L_TMPWRITE: /* Can't write pid into lockfile */
1312 case L_MAXTRYS: /* Failed after retrycnt attempts */
1316 case L_ERROR: /* Check errno for reason */
1319 default: /* other permanent errors */
1334 #else /* MAILLOCK */
1336 char LockName[MAXPATHLEN];
1347 if (strlen(path) + 6 > sizeof LockName)
1349 (void) sm_snprintf(LockName, sizeof LockName, "%s.lock", path);
1350 (void) time(&start);
1357 /* global timeout */
1359 if (now > start + LOCKTO_GLOB)
1364 fd = open(LockName, O_WRONLY|O_EXCL|O_CREAT, 0);
1367 /* defeat lock checking programs which test pid */
1368 (void) write(fd, "0", 2);
1373 if (stat(LockName, &st) < 0)
1375 if (statfailed++ > 5)
1384 if (now < st.st_ctime + LOCKTO_RM)
1387 /* try to remove stale lockfile */
1388 if (unlink(LockName) < 0)
1398 (void) unlink(LockName);
1401 #endif /* MAILLOCK */
1407 static bool initialized = false;
1412 static struct sockaddr_in addr;
1418 /* Be silent if biff service not available. */
1419 if ((sp = getservbyname("biff", "udp")) == NULL ||
1420 (hp = gethostbyname("localhost")) == NULL ||
1421 hp->h_length != INADDRSZ)
1424 addr.sin_family = hp->h_addrtype;
1425 memcpy(&addr.sin_addr, hp->h_addr, INADDRSZ);
1426 addr.sin_port = sp->s_port;
1429 /* No message, just return */
1433 /* Couldn't initialize addr struct */
1434 if (addr.sin_family == AF_UNSPEC)
1437 if (f < 0 && (f = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1439 len = strlen(msg) + 1;
1440 (void) sendto(f, msg, len, 0, (struct sockaddr *) &addr, sizeof(addr));
1447 mailerr(NULL, "usage: mail.local [-7] [-B] [-b] [-d] [-l] [-s] [-f from|-r from] [-h filename] user ...");
1454 mailerr(const char *hdr, const char *fmt, ...)
1455 #else /* __STDC__ */
1456 mailerr(hdr, fmt, va_alist)
1460 #endif /* __STDC__ */
1465 (void) e_to_sys(errno);
1467 SM_VA_START(ap, fmt);
1469 if (LMTPMode && hdr != NULL)
1471 sm_snprintf(ErrBuf, sizeof ErrBuf, "%s ", hdr);
1472 len = strlen(ErrBuf);
1474 (void) sm_vsnprintf(&ErrBuf[len], sizeof ErrBuf - len, fmt, ap);
1480 /* Log the message to syslog. */
1482 syslog(LOG_ERR, "%s", ErrBuf);
1489 printf("%s\r\n", ErrBuf);
1492 if (ExitVal != EX_USAGE)
1493 (void) fprintf(stderr, "mail.local: ");
1494 fprintf(stderr, "%s\n", ErrBuf);
1500 * Guess which errno's are temporary. Gag me.
1507 /* Temporary failures override hard errors. */
1508 if (ExitVal == EX_TEMPFAIL)
1511 switch (num) /* Hopefully temporary errors. */
1514 case EDQUOT: /* Disc quota exceeded */
1517 ExitVal = EX_UNAVAILABLE;
1523 case EAGAIN: /* Resource temporarily unavailable */
1526 case EBUSY: /* Device busy */
1529 case EPROCLIM: /* Too many processes */
1530 #endif /* EPROCLIM */
1532 case EUSERS: /* Too many users */
1535 case ECONNABORTED: /* Software caused connection abort */
1536 #endif /* ECONNABORTED */
1538 case ECONNREFUSED: /* Connection refused */
1539 #endif /* ECONNREFUSED */
1541 case ECONNRESET: /* Connection reset by peer */
1542 #endif /* ECONNRESET */
1544 case EDEADLK: /* Resource deadlock avoided */
1545 #endif /* EDEADLK */
1547 case EFBIG: /* File too large */
1550 case EHOSTDOWN: /* Host is down */
1551 #endif /* EHOSTDOWN */
1553 case EHOSTUNREACH: /* No route to host */
1554 #endif /* EHOSTUNREACH */
1556 case EMFILE: /* Too many open files */
1559 case ENETDOWN: /* Network is down */
1560 #endif /* ENETDOWN */
1562 case ENETRESET: /* Network dropped connection on reset */
1563 #endif /* ENETRESET */
1565 case ENETUNREACH: /* Network is unreachable */
1566 #endif /* ENETUNREACH */
1568 case ENFILE: /* Too many open files in system */
1571 case ENOBUFS: /* No buffer space available */
1572 #endif /* ENOBUFS */
1574 case ENOMEM: /* Cannot allocate memory */
1577 case ENOSPC: /* No space left on device */
1580 case EROFS: /* Read-only file system */
1583 case ESTALE: /* Stale NFS file handle */
1586 case ETIMEDOUT: /* Connection timed out */
1587 #endif /* ETIMEDOUT */
1588 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN && EWOULDBLOCK != EDEADLK
1589 case EWOULDBLOCK: /* Operation would block. */
1590 #endif /* defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN && EWOULDBLOCK != EDEADLK */
1591 ExitVal = EX_TEMPFAIL;
1595 ExitVal = EX_UNAVAILABLE;
1601 #if defined(ultrix) || defined(_CRAY)
1603 * Copyright (c) 1987, 1993
1604 * The Regents of the University of California. All rights reserved.
1606 * Redistribution and use in source and binary forms, with or without
1607 * modification, are permitted provided that the following conditions
1609 * 1. Redistributions of source code must retain the above copyright
1610 * notice, this list of conditions and the following disclaimer.
1611 * 2. Redistributions in binary form must reproduce the above copyright
1612 * notice, this list of conditions and the following disclaimer in the
1613 * documentation and/or other materials provided with the distribution.
1614 * 3. All advertising materials mentioning features or use of this software
1615 * must display the following acknowledgement:
1616 * This product includes software developed by the University of
1617 * California, Berkeley and its contributors.
1618 * 4. Neither the name of the University nor the names of its contributors
1619 * may be used to endorse or promote products derived from this software
1620 * without specific prior written permission.
1622 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1623 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1624 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1625 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
1626 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1627 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1628 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1629 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1630 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1631 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1635 # if defined(LIBC_SCCS) && !defined(lint)
1636 static char sccsid[] = "@(#)mktemp.c 8.1 (Berkeley) 6/4/93";
1637 # endif /* defined(LIBC_SCCS) && !defined(lint) */
1639 # include <sys/types.h>
1640 # include <sys/stat.h>
1646 static int _gettemp();
1653 return (_gettemp(path, &fd) ? fd : -1);
1657 _gettemp(path, doopen)
1659 register int *doopen;
1662 register char *start, *trv;
1667 for (trv = path; *trv; ++trv); /* extra X's get set to 0's */
1668 while (*--trv == 'X')
1670 *trv = (pid % 10) + '0';
1675 * check the target directory; if you have six X's and it
1676 * doesn't exist this runs for a *very* long time.
1678 for (start = trv + 1;; --trv)
1685 if (stat(path, &sbuf) < 0)
1687 if (!S_ISDIR(sbuf.st_mode))
1701 if ((*doopen = open(path, O_CREAT|O_EXCL|O_RDWR,
1704 if (errno != EEXIST)
1707 else if (stat(path, &sbuf) < 0)
1708 return(errno == ENOENT ? 1 : 0);
1710 /* tricky little algorithm for backward compatibility */
1719 if (isascii(*trv) && isdigit(*trv))
1729 #endif /* defined(ultrix) || defined(_CRAY) */