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 $
12 * $DragonFly: src/contrib/sendmail/mail.local/Attic/mail.local.c,v 1.2 2003/06/17 04:24:06 dillon Exp $
19 "@(#) Copyright (c) 1998-2001 Sendmail, Inc. and its suppliers.\n\
20 All rights reserved.\n\
21 Copyright (c) 1990, 1993, 1994\n\
22 The Regents of the University of California. All rights reserved.\n")
24 SM_IDSTR(id, "@(#)$Id: mail.local.c,v 8.239.2.5 2003/03/15 23:43:20 gshapiro Exp $")
27 #include <sm/errstring.h>
29 #include <sm/limits.h>
32 # undef EX_OK /* unistd.h may have another use for this */
35 #include <sm/sysexits.h>
38 ** This is not intended to work on System V derived systems
39 ** such as Solaris or HP-UX, since they use a totally different
40 ** approach to mailboxes (essentially, they have a set-group-ID program
41 ** rather than set-user-ID, and they rely on the ability to "give away"
42 ** files to do their work). IT IS NOT A BUG that this doesn't
43 ** work on such architectures.
50 #include <sys/types.h>
54 # include <sys/socket.h>
55 # include <sys/file.h>
56 # include <netinet/in.h>
57 # include <arpa/nameser.h>
61 #include <sm/string.h>
66 #include <sendmail/pathnames.h>
69 /* additional mode for open() */
74 # define LOCKTO_RM 300 /* timeout for stale lockfile removal */
75 #endif /* ! LOCKTO_RM */
77 # define LOCKTO_GLOB 400 /* global timeout for lockfile creation */
78 #endif /* ! LOCKTO_GLOB */
80 /* define a realloc() which works for NULL pointers */
81 #define REALLOC(ptr, size) (((ptr) == NULL) ? malloc(size) : realloc(ptr, size))
84 ** If you don't have flock, you could try using lockf instead.
88 # define flock(a, b) lockf(a, b, 0)
92 # define LOCK_EX F_LOCK
93 #endif /* LDA_USE_LOCKF */
96 # include <sys/file.h>
97 #endif /* ! LOCK_EX */
100 ** If you don't have setreuid, and you have saved uids, and you have
101 ** a seteuid() call that doesn't try to emulate using setuid(), then
102 ** you can try defining LDA_USE_SETEUID.
105 #ifdef LDA_USE_SETEUID
106 # define setreuid(r, e) seteuid(e)
107 #endif /* LDA_USE_SETEUID */
109 #ifdef LDA_CONTENTLENGTH
110 # define CONTENTLENGTH 1
111 #endif /* LDA_CONTENTLENGTH */
114 # define INADDRSZ 4 /* size of an IPv4 address in bytes */
115 #endif /* ! INADDRSZ */
118 # include <maillock.h>
119 #endif /* MAILLOCK */
121 #ifndef MAILER_DAEMON
122 # define MAILER_DAEMON "MAILER-DAEMON"
123 #endif /* ! MAILER_DAEMON */
126 char ContentHdr[40] = "Content-Length: ";
129 #endif /* CONTENTLENGTH */
131 bool EightBitMime = true; /* advertise 8BITMIME in LMTP */
132 char ErrBuf[10240]; /* error buffer */
133 int ExitVal = EX_OK; /* sysexits.h error value. */
135 bool nofsync = false;
136 bool HoldErrs = false; /* Hold errors in ErrBuf */
137 bool LMTPMode = false;
138 bool BounceQuota = false; /* permanent error when over quota */
139 char *HomeMailFile = NULL; /* store mail in homedir */
141 void deliver __P((int, char *));
142 int e_to_sys __P((int));
143 void notifybiff __P((char *));
144 int store __P((char *, bool *));
145 void usage __P((void));
146 int lockmbox __P((char *));
147 void unlockmbox __P((void));
148 void mailerr __P((const char *, const char *, ...));
149 void flush_error __P((void));
161 char *mbdbname = "pw";
167 /* make sure we have some open file descriptors */
168 for (fd = 10; fd < 30; fd++)
171 /* use a reasonable umask */
175 openlog("mail.local", 0, LOG_MAIL);
176 # else /* LOG_MAIL */
177 openlog("mail.local", 0);
178 # endif /* LOG_MAIL */
181 while ((ch = getopt(argc, argv, "7BbdD:f:h:r:ls")) != -1)
185 case '7': /* Do not advertise 8BITMIME */
186 EightBitMime = false;
193 case 'b': /* bounce mail when over quota. */
197 case 'd': /* Backward compatible. */
200 case 'D': /* mailbox database type */
205 case 'r': /* Backward compatible. */
208 mailerr(NULL, "Multiple -f options");
215 if (optarg != NULL || *optarg != '\0')
216 HomeMailFile = optarg;
219 mailerr(NULL, "-h: missing filename");
240 /* initialize biff structures */
244 err = sm_mbdb_initialize(mbdbname);
247 char *errcode = "521";
249 if (err == EX_TEMPFAIL)
252 mailerr(errcode, "Can not open mailbox database %s: %s",
253 mbdbname, sm_strexit(err));
259 extern void dolmtp __P((void));
263 mailerr("421", "Users should not be specified in command line if LMTP required");
272 /* Non-LMTP from here on out */
277 ** If from not specified, use the name from getlogin() if the
278 ** uid matches, otherwise, use the name from the password file
279 ** corresponding to the uid.
283 if (from == NULL && ((from = getlogin()) == NULL ||
284 (pw = getpwnam(from)) == NULL ||
286 from = (pw = getpwuid(uid)) != NULL ? pw->pw_name : "???";
289 ** There is no way to distinguish the error status of one delivery
290 ** from the rest of the deliveries. So, if we failed hard on one
291 ** or more deliveries, but had no failures on any of the others, we
292 ** return a hard failure. If we failed temporarily on one or more
293 ** deliveries, we return a temporary failure regardless of the other
294 ** failures. This results in the delivery being reattempted later
295 ** at the expense of repeated failures and multiple deliveries.
299 fd = store(from, NULL);
306 for (; *argv != NULL; ++argv)
330 while (*p != ',' && *p != ':' && *p != '\0')
335 /* Skip over , or : */
342 while (*p != '\0' && *p != '@' && *p != '>')
352 while (*p != '\0' && *p != '\"')
361 if (*p == '\0' || *(p + 1) == '\0')
365 if (*p == '+' && rcpt)
375 while (*p != '\0' && *p != '>')
385 if (*p != '\0' && *p != ' ')
397 mailerr("421 4.3.0", "Memory exhausted");
401 (void) sm_strlcpy(p, s, l);
406 process_recipient(addr)
411 switch (sm_mbdb_lookup(addr, &user))
417 return "550 5.1.1 User unknown";
420 return "451 4.3.0 User database failure; retry later";
423 return "550 5.3.0 User database failure";
432 char *return_path = NULL;
433 char **rcpt_addr = NULL;
436 bool gotlhlo = false;
441 char myhostname[1024];
444 memset(myhostname, '\0', sizeof myhostname);
445 (void) gethostname(myhostname, sizeof myhostname - 1);
446 if (myhostname[0] == '\0')
447 sm_strlcpy(myhostname, "localhost", sizeof myhostname);
449 printf("220 %s LMTP ready\r\n", myhostname);
452 (void) fflush(stdout);
453 if (fgets(buf, sizeof(buf) - 1, stdin) == NULL)
455 p = buf + strlen(buf) - 1;
456 if (p >= buf && *p == '\n')
458 if (p >= buf && *p == '\r')
465 if (sm_strcasecmp(buf, "data") == 0)
471 mailerr("503 5.5.1", "No recipients");
475 msgfd = store(return_path, &inbody);
477 if (msgfd < 0 && !inbody)
483 for (i = 0; i < rcpt_num; i++)
487 /* print error for rcpt */
491 p = strchr(rcpt_addr[i], '+');
494 deliver(msgfd, rcpt_addr[i]);
506 if (sm_strncasecmp(buf, "lhlo ", 5) == 0)
508 /* check for duplicate per RFC 1651 4.2 */
511 mailerr("503", "%s Duplicate LHLO",
516 printf("250-%s\r\n", myhostname);
518 printf("250-8BITMIME\r\n");
519 printf("250-ENHANCEDSTATUSCODES\r\n");
520 printf("250 PIPELINING\r\n");
529 if (sm_strncasecmp(buf, "mail ", 5) == 0)
531 if (return_path != NULL)
534 "Nested MAIL command");
537 if (sm_strncasecmp(buf + 5, "from:", 5) != 0 ||
538 ((return_path = parseaddr(buf + 10,
542 "Syntax error in parameters");
545 printf("250 2.5.0 Ok\r\n");
554 if (sm_strcasecmp(buf, "noop") == 0)
556 printf("250 2.0.0 Ok\r\n");
565 if (sm_strcasecmp(buf, "quit") == 0)
567 printf("221 2.0.0 Bye\r\n");
576 if (sm_strncasecmp(buf, "rcpt ", 5) == 0)
578 if (return_path == NULL)
581 "Need MAIL command");
584 if (rcpt_num >= rcpt_alloc)
586 rcpt_alloc += RCPT_GROW;
587 rcpt_addr = (char **)
588 REALLOC((char *) rcpt_addr,
591 if (rcpt_addr == NULL)
598 if (sm_strncasecmp(buf + 5, "to:", 3) != 0 ||
599 ((rcpt_addr[rcpt_num] = parseaddr(buf + 8,
603 "Syntax error in parameters");
606 err = process_recipient(rcpt_addr[rcpt_num]);
609 mailerr(NULL, "%s", err);
613 printf("250 2.1.5 Ok\r\n");
616 else if (sm_strcasecmp(buf, "rset") == 0)
618 printf("250 2.0.0 Ok\r\n");
622 free(rcpt_addr[--rcpt_num]);
623 if (return_path != NULL)
634 if (sm_strncasecmp(buf, "vrfy ", 5) == 0)
636 printf("252 2.3.3 Try RCPT to attempt delivery\r\n");
645 mailerr("500 5.5.2", "Syntax error");
660 bool eline; /* previous line was empty */
661 bool fullline = true; /* current line is terminated */
662 bool prevfl; /* previous line was terminated */
665 char tmpbuf[sizeof _PATH_LOCTMP + 1];
671 (void) sm_strlcpy(tmpbuf, _PATH_LOCTMP, sizeof tmpbuf);
672 if ((fd = mkstemp(tmpbuf)) < 0 || (fp = fdopen(fd, "w+")) == NULL)
676 mailerr("451 4.3.0", "Unable to open temporary file");
679 (void) unlink(tmpbuf);
683 printf("354 Go ahead\r\n");
684 (void) fflush(stdout);
690 (void) fprintf(fp, "From %s %s", from, ctime(&tval));
695 #endif /* CONTENTLENGTH */
699 while (fgets(line, sizeof(line), stdin) != (char *) NULL)
704 prevfl = fullline; /* preserve state of previous line */
705 while (line[line_len] != '\n' && line_len < sizeof(line) - 2)
709 /* Check for dot-stuffing */
710 if (prevfl && LMTPMode && line[0] == '.')
712 if (line[1] == '\n' ||
713 (line[1] == '\r' && line[2] == '\n'))
715 memcpy(line, line + 1, line_len);
719 /* Check to see if we have the full line from fgets() */
723 if (line[line_len - 1] == '\n')
726 line[line_len - 2] == '\r')
728 line[line_len - 2] = '\n';
729 line[line_len - 1] = '\0';
734 else if (line[line_len - 1] == '\r')
736 /* Did we just miss the CRLF? */
740 line[line_len - 1] = '\n';
744 (void) ungetc(peek, stdin);
751 if (prevfl && line[0] == '\n' && HeaderLength == 0)
755 HeaderLength = ftell(fp);
756 if (HeaderLength <= 0)
759 ** shouldn't happen, unless ftell() is
766 #else /* CONTENTLENGTH */
767 if (prevfl && line[0] == '\n')
769 #endif /* CONTENTLENGTH */
772 if (eline && line[0] == 'F' &&
774 !memcmp(line, "From ", 5))
775 (void) putc('>', fp);
778 /* discard existing "Content-Length:" headers */
779 if (prevfl && HeaderLength == 0 &&
780 (line[0] == 'C' || line[0] == 'c') &&
781 sm_strncasecmp(line, ContentHdr, 15) == 0)
784 ** be paranoid: clear the line
785 ** so no "wrong matches" may occur later
790 #endif /* CONTENTLENGTH */
795 (void) fwrite(line, sizeof(char), line_len, fp);
799 "Temporary file write error");
807 /* check if an error occurred */
813 /* Got a premature EOF -- toss message and exit */
817 /* If message not newline terminated, need an extra. */
818 if (fp != NULL && strchr(line, '\n') == NULL)
819 (void) putc('\n', fp);
825 BodyLength = ftell(fp);
826 if (HeaderLength == 0 && BodyLength > 0) /* empty body */
828 HeaderLength = BodyLength;
832 BodyLength = BodyLength - HeaderLength - 1 ;
834 if (HeaderLength > 0 && BodyLength >= 0)
836 (void) sm_snprintf(line, sizeof line, "%lld\n",
837 (LONGLONG_T) BodyLength);
838 (void) sm_strlcpy(&ContentHdr[16], line,
839 sizeof(ContentHdr) - 16);
842 BodyLength = -1; /* Something is wrong here */
843 #endif /* CONTENTLENGTH */
845 /* Output a newline; note, empty messages are allowed. */
847 (void) putc('\n', fp);
849 if (fp == NULL || fflush(fp) == EOF || ferror(fp) != 0)
851 mailerr("451 4.3.0", "Temporary file write error");
866 char path[MAXPATHLEN];
867 int mbfd = -1, nr = 0, nw, off;
875 #endif /* CONTENTLENGTH */
876 char biffmsg[100], buf[8 * 1024];
880 ** Disallow delivery to unknown names -- special mailboxes can be
881 ** handled in the sendmail aliases file.
884 exitval = sm_mbdb_lookup(name, &user);
891 exitval = EX_UNAVAILABLE;
892 mailerr("550 5.1.1", "%s: User unknown", name);
896 mailerr("451 4.3.0", "%s: User database failure; retry later",
901 exitval = EX_UNAVAILABLE;
902 mailerr("550 5.3.0", "%s: User database failure", name);
906 if (exitval != EX_OK)
908 if (ExitVal != EX_TEMPFAIL)
916 ** Keep name reasonably short to avoid buffer overruns.
917 ** This isn't necessary on BSD because of the proper
918 ** definition of snprintf(), but it can cause problems
920 ** Also, clear out any bogus characters.
923 if (strlen(name) > 40)
925 for (p = name; *p != '\0'; p++)
929 else if (!isprint(*p))
934 if (HomeMailFile == NULL)
936 if (sm_snprintf(path, sizeof(path), "%s/%s",
937 _PATH_MAILDIR, name) >= sizeof(path))
939 exitval = EX_UNAVAILABLE;
940 mailerr("550 5.1.1", "%s: Invalid mailbox path", name);
944 else if (*user.mbdb_homedir == '\0')
946 exitval = EX_UNAVAILABLE;
947 mailerr("550 5.1.1", "%s: User missing home directory", name);
950 else if (sm_snprintf(path, sizeof(path), "%s/%s",
951 user.mbdb_homedir, HomeMailFile) >= sizeof(path))
953 exitval = EX_UNAVAILABLE;
954 mailerr("550 5.1.1", "%s: Invalid mailbox path", name);
960 ** If the mailbox is linked or a symlink, fail. There's an obvious
961 ** race here, that the file was replaced with a symbolic link after
962 ** the lstat returned, but before the open. We attempt to detect
963 ** this by comparing the original stat information and information
964 ** returned by an fstat of the file descriptor returned by the open.
966 ** NB: this is a symptom of a larger problem, that the mail spooling
967 ** directory is writeable by the wrong users. If that directory is
968 ** writeable, system security is compromised for other reasons, and
969 ** it cannot be fixed here.
971 ** If we created the mailbox, set the owner/group. If that fails,
972 ** just return. Another process may have already opened it, so we
973 ** can't unlink it. Historically, binmail set the owner/group at
974 ** each mail delivery. We no longer do this, assuming that if the
975 ** ownership or permissions were changed there was a reason.
978 ** open(2) should support flock'ing the file.
986 #endif /* MAILLOCK */
987 if ((off = lockmbox(p)) != 0)
989 if (off == EX_TEMPFAIL || e_to_sys(off) == EX_TEMPFAIL)
991 ExitVal = EX_TEMPFAIL;
992 errcode = "451 4.3.0";
995 errcode = "551 5.3.0";
997 mailerr(errcode, "lockmailbox %s failed; error code %d %s",
998 p, off, errno > 0 ? sm_errstring(errno) : "");
1002 if (lstat(path, &sb) < 0)
1005 int mode = S_IRUSR|S_IWUSR;
1006 gid_t gid = user.mbdb_gid;
1011 mode |= S_IRGRP|S_IWGRP;
1012 #endif /* MAILGID */
1014 mbfd = open(path, O_APPEND|O_CREAT|O_EXCL|O_WRONLY|EXTRA_MODE,
1018 if (lstat(path, &sb) < 0)
1020 ExitVal = EX_CANTCREAT;
1021 mailerr("550 5.2.0",
1022 "%s: lstat: file changed after open", path);
1027 if (save_errno == EEXIST)
1030 /* open failed, don't try again */
1031 mailerr("450 4.2.0", "%s: %s", path,
1032 sm_errstring(save_errno));
1035 else if (fchown(mbfd, user.mbdb_uid, gid) < 0)
1037 mailerr("451 4.3.0", "chown %u.%u: %s",
1038 user.mbdb_uid, gid, name);
1044 ** open() was successful, now close it so can
1045 ** be opened as the right owner again.
1046 ** Paranoia: reset mbdf since the file descriptor
1047 ** is no longer valid; better safe than sorry.
1050 sb.st_uid = user.mbdb_uid;
1055 else if (sb.st_nlink != 1)
1057 mailerr("550 5.2.0", "%s: too many links", path);
1060 else if (!S_ISREG(sb.st_mode))
1062 mailerr("550 5.2.0", "%s: irregular file", path);
1065 else if (sb.st_uid != user.mbdb_uid)
1067 ExitVal = EX_CANTCREAT;
1068 mailerr("550 5.2.0", "%s: wrong ownership (%d)",
1069 path, (int) sb.st_uid);
1073 /* change UID for quota checks */
1074 if (setreuid(0, user.mbdb_uid) < 0)
1076 mailerr("450 4.2.0", "setreuid(0, %d): %s (r=%d, e=%d)",
1077 (int) user.mbdb_uid, sm_errstring(errno),
1078 (int) getuid(), (int) geteuid());
1082 fprintf(stderr, "new euid = %d\n", (int) geteuid());
1084 mbfd = open(path, O_APPEND|O_WRONLY|EXTRA_MODE, 0);
1087 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1090 else if (fstat(mbfd, &fsb) < 0 ||
1091 fsb.st_nlink != 1 ||
1093 !S_ISREG(fsb.st_mode) ||
1094 sb.st_dev != fsb.st_dev ||
1095 sb.st_ino != fsb.st_ino ||
1096 # if HAS_ST_GEN && 0 /* AFS returns random values for st_gen */
1097 sb.st_gen != fsb.st_gen ||
1098 # endif /* HAS_ST_GEN && 0 */
1099 sb.st_uid != fsb.st_uid)
1101 ExitVal = EX_TEMPFAIL;
1102 mailerr("550 5.2.0", "%s: fstat: file changed after open",
1109 ** This code could be reused if we decide to add a
1110 ** per-user quota field to the sm_mbdb interface.
1114 ** Fail if the user has a quota specified, and delivery of this
1115 ** message would exceed that quota. We bounce such failures using
1116 ** EX_UNAVAILABLE, unless there were internal problems, since
1117 ** storing immense messages for later retries can cause queueing
1125 if (fstat(fd, &dsb) < 0)
1127 ExitVal = EX_TEMPFAIL;
1128 mailerr("451 4.3.0",
1129 "%s: fstat: can't stat temporary storage: %s",
1130 ui.mailspool, sm_errstring(errno));
1134 if (dsb.st_size + sb.st_size + 1 > ui.quota)
1136 ExitVal = EX_UNAVAILABLE;
1137 mailerr("551 5.2.2",
1138 "%s: Mailbox full or quota exceeded",
1145 /* Wait until we can get a lock on the file. */
1146 if (flock(mbfd, LOCK_EX) < 0)
1148 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1152 /* Get the starting offset of the new message */
1153 curoff = lseek(mbfd, (off_t) 0, SEEK_END);
1157 (void) sm_snprintf(biffmsg, sizeof(biffmsg), "%s@%lld\n",
1158 name, (LONGLONG_T) curoff);
1161 /* Copy the message into the file. */
1162 if (lseek(fd, (off_t) 0, SEEK_SET) == (off_t) -1)
1164 mailerr("450 4.2.0", "Temporary file: %s",
1165 sm_errstring(errno));
1169 fprintf(stderr, "before writing: euid = %d\n", (int) geteuid());
1171 #ifdef CONTENTLENGTH
1172 headerbytes = (BodyLength >= 0) ? HeaderLength : -1 ;
1175 if (headerbytes == 0)
1177 (void) sm_snprintf(buf, sizeof buf, "%s", ContentHdr);
1182 else if (headerbytes > sizeof(buf) || headerbytes < 0)
1183 readamount = sizeof(buf);
1185 readamount = headerbytes;
1186 if (readamount != 0)
1187 nr = read(fd, buf, readamount);
1190 if (headerbytes > 0)
1193 #else /* CONTENTLENGTH */
1194 while ((nr = read(fd, buf, sizeof(buf))) > 0)
1196 #endif /* CONTENTLENGTH */
1197 for (off = 0; off < nr; off += nw)
1199 if ((nw = write(mbfd, buf + off, nr - off)) < 0)
1201 errcode = "450 4.2.0";
1203 if (errno == EDQUOT && BounceQuota)
1204 errcode = "552 5.2.2";
1206 mailerr(errcode, "%s: %s",
1207 path, sm_errstring(errno));
1214 mailerr("450 4.2.0", "Temporary file: %s",
1215 sm_errstring(errno));
1219 /* Flush to disk, don't wait for update. */
1220 if (!nofsync && fsync(mbfd) < 0)
1222 mailerr("450 4.2.0", "%s: %s", path, sm_errstring(errno));
1224 (void) setreuid(0, 0);
1226 fprintf(stderr, "reset euid = %d\n", (int) geteuid());
1229 (void) ftruncate(mbfd, curoff);
1230 err1: if (mbfd >= 0)
1236 /* Close and check -- NFS doesn't write until the close. */
1239 errcode = "450 4.2.0";
1241 if (errno == EDQUOT && BounceQuota)
1242 errcode = "552 5.2.2";
1244 mailerr(errcode, "%s: %s", path, sm_errstring(errno));
1245 mbfd = open(path, O_WRONLY|EXTRA_MODE, 0);
1247 || fstat(mbfd, &sb) < 0 ||
1249 !S_ISREG(sb.st_mode) ||
1250 sb.st_dev != fsb.st_dev ||
1251 sb.st_ino != fsb.st_ino ||
1252 # if HAS_ST_GEN && 0 /* AFS returns random values for st_gen */
1253 sb.st_gen != fsb.st_gen ||
1254 # endif /* HAS_ST_GEN && 0 */
1255 sb.st_uid != fsb.st_uid
1258 /* Don't use a bogus file */
1266 /* Attempt to truncate back to pre-write size */
1270 notifybiff(biffmsg);
1272 if (setreuid(0, 0) < 0)
1274 mailerr("450 4.2.0", "setreuid(0, 0): %s",
1275 sm_errstring(errno));
1279 fprintf(stderr, "reset euid = %d\n", (int) geteuid());
1283 printf("250 2.1.5 %s Ok\r\n", name);
1287 ** user.lock files are necessary for compatibility with other
1288 ** systems, e.g., when the mail spool file is NFS exported.
1289 ** Alas, mailbox locking is more than just a local matter.
1293 bool Locked = false;
1304 if ((r = maillock(name, 15)) == L_SUCCESS)
1311 case L_TMPLOCK: /* Can't create tmp file */
1312 case L_TMPWRITE: /* Can't write pid into lockfile */
1313 case L_MAXTRYS: /* Failed after retrycnt attempts */
1317 case L_ERROR: /* Check errno for reason */
1320 default: /* other permanent errors */
1335 #else /* MAILLOCK */
1337 char LockName[MAXPATHLEN];
1348 if (strlen(path) + 6 > sizeof LockName)
1350 (void) sm_snprintf(LockName, sizeof LockName, "%s.lock", path);
1351 (void) time(&start);
1358 /* global timeout */
1360 if (now > start + LOCKTO_GLOB)
1365 fd = open(LockName, O_WRONLY|O_EXCL|O_CREAT, 0);
1368 /* defeat lock checking programs which test pid */
1369 (void) write(fd, "0", 2);
1374 if (stat(LockName, &st) < 0)
1376 if (statfailed++ > 5)
1385 if (now < st.st_ctime + LOCKTO_RM)
1388 /* try to remove stale lockfile */
1389 if (unlink(LockName) < 0)
1399 (void) unlink(LockName);
1402 #endif /* MAILLOCK */
1408 static bool initialized = false;
1413 static struct sockaddr_in addr;
1419 /* Be silent if biff service not available. */
1420 if ((sp = getservbyname("biff", "udp")) == NULL ||
1421 (hp = gethostbyname("localhost")) == NULL ||
1422 hp->h_length != INADDRSZ)
1425 addr.sin_family = hp->h_addrtype;
1426 memcpy(&addr.sin_addr, hp->h_addr, INADDRSZ);
1427 addr.sin_port = sp->s_port;
1430 /* No message, just return */
1434 /* Couldn't initialize addr struct */
1435 if (addr.sin_family == AF_UNSPEC)
1438 if (f < 0 && (f = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1440 len = strlen(msg) + 1;
1441 (void) sendto(f, msg, len, 0, (struct sockaddr *) &addr, sizeof(addr));
1448 mailerr(NULL, "usage: mail.local [-7] [-B] [-b] [-d] [-l] [-s] [-f from|-r from] [-h filename] user ...");
1455 mailerr(const char *hdr, const char *fmt, ...)
1456 #else /* __STDC__ */
1457 mailerr(hdr, fmt, va_alist)
1461 #endif /* __STDC__ */
1466 (void) e_to_sys(errno);
1468 SM_VA_START(ap, fmt);
1470 if (LMTPMode && hdr != NULL)
1472 sm_snprintf(ErrBuf, sizeof ErrBuf, "%s ", hdr);
1473 len = strlen(ErrBuf);
1475 (void) sm_vsnprintf(&ErrBuf[len], sizeof ErrBuf - len, fmt, ap);
1481 /* Log the message to syslog. */
1483 syslog(LOG_ERR, "%s", ErrBuf);
1490 printf("%s\r\n", ErrBuf);
1493 if (ExitVal != EX_USAGE)
1494 (void) fprintf(stderr, "mail.local: ");
1495 fprintf(stderr, "%s\n", ErrBuf);
1501 * Guess which errno's are temporary. Gag me.
1508 /* Temporary failures override hard errors. */
1509 if (ExitVal == EX_TEMPFAIL)
1512 switch (num) /* Hopefully temporary errors. */
1515 case EDQUOT: /* Disc quota exceeded */
1518 ExitVal = EX_UNAVAILABLE;
1524 case EAGAIN: /* Resource temporarily unavailable */
1527 case EBUSY: /* Device busy */
1530 case EPROCLIM: /* Too many processes */
1531 #endif /* EPROCLIM */
1533 case EUSERS: /* Too many users */
1536 case ECONNABORTED: /* Software caused connection abort */
1537 #endif /* ECONNABORTED */
1539 case ECONNREFUSED: /* Connection refused */
1540 #endif /* ECONNREFUSED */
1542 case ECONNRESET: /* Connection reset by peer */
1543 #endif /* ECONNRESET */
1545 case EDEADLK: /* Resource deadlock avoided */
1546 #endif /* EDEADLK */
1548 case EFBIG: /* File too large */
1551 case EHOSTDOWN: /* Host is down */
1552 #endif /* EHOSTDOWN */
1554 case EHOSTUNREACH: /* No route to host */
1555 #endif /* EHOSTUNREACH */
1557 case EMFILE: /* Too many open files */
1560 case ENETDOWN: /* Network is down */
1561 #endif /* ENETDOWN */
1563 case ENETRESET: /* Network dropped connection on reset */
1564 #endif /* ENETRESET */
1566 case ENETUNREACH: /* Network is unreachable */
1567 #endif /* ENETUNREACH */
1569 case ENFILE: /* Too many open files in system */
1572 case ENOBUFS: /* No buffer space available */
1573 #endif /* ENOBUFS */
1575 case ENOMEM: /* Cannot allocate memory */
1578 case ENOSPC: /* No space left on device */
1581 case EROFS: /* Read-only file system */
1584 case ESTALE: /* Stale NFS file handle */
1587 case ETIMEDOUT: /* Connection timed out */
1588 #endif /* ETIMEDOUT */
1589 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN && EWOULDBLOCK != EDEADLK
1590 case EWOULDBLOCK: /* Operation would block. */
1591 #endif /* defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN && EWOULDBLOCK != EDEADLK */
1592 ExitVal = EX_TEMPFAIL;
1596 ExitVal = EX_UNAVAILABLE;
1602 #if defined(ultrix) || defined(_CRAY)
1604 * Copyright (c) 1987, 1993
1605 * The Regents of the University of California. All rights reserved.
1607 * Redistribution and use in source and binary forms, with or without
1608 * modification, are permitted provided that the following conditions
1610 * 1. Redistributions of source code must retain the above copyright
1611 * notice, this list of conditions and the following disclaimer.
1612 * 2. Redistributions in binary form must reproduce the above copyright
1613 * notice, this list of conditions and the following disclaimer in the
1614 * documentation and/or other materials provided with the distribution.
1615 * 3. All advertising materials mentioning features or use of this software
1616 * must display the following acknowledgement:
1617 * This product includes software developed by the University of
1618 * California, Berkeley and its contributors.
1619 * 4. Neither the name of the University nor the names of its contributors
1620 * may be used to endorse or promote products derived from this software
1621 * without specific prior written permission.
1623 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1624 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1625 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1626 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
1627 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1628 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1629 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1630 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1631 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1632 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1636 # if defined(LIBC_SCCS) && !defined(lint)
1637 static char sccsid[] = "@(#)mktemp.c 8.1 (Berkeley) 6/4/93";
1638 # endif /* defined(LIBC_SCCS) && !defined(lint) */
1640 # include <sys/types.h>
1641 # include <sys/stat.h>
1647 static int _gettemp();
1654 return (_gettemp(path, &fd) ? fd : -1);
1658 _gettemp(path, doopen)
1660 register int *doopen;
1663 register char *start, *trv;
1668 for (trv = path; *trv; ++trv); /* extra X's get set to 0's */
1669 while (*--trv == 'X')
1671 *trv = (pid % 10) + '0';
1676 * check the target directory; if you have six X's and it
1677 * doesn't exist this runs for a *very* long time.
1679 for (start = trv + 1;; --trv)
1686 if (stat(path, &sbuf) < 0)
1688 if (!S_ISDIR(sbuf.st_mode))
1702 if ((*doopen = open(path, O_CREAT|O_EXCL|O_RDWR,
1705 if (errno != EEXIST)
1708 else if (stat(path, &sbuf) < 0)
1709 return(errno == ENOENT ? 1 : 0);
1711 /* tricky little algorithm for backward compatibility */
1720 if (isascii(*trv) && isdigit(*trv))
1730 #endif /* defined(ultrix) || defined(_CRAY) */