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.
16 "@(#) Copyright (c) 1998-2004 Sendmail, Inc. and its suppliers.\n\
17 All rights reserved.\n\
18 Copyright (c) 1990, 1993, 1994\n\
19 The Regents of the University of California. All rights reserved.\n")
21 SM_IDSTR(id
, "@(#)$Id: mail.local.c,v 8.253 2004/11/01 20:42:42 ca Exp $")
24 #include <sm/errstring.h>
26 #include <sm/limits.h>
29 # undef EX_OK /* unistd.h may have another use for this */
31 # define LOCKFILE_PMODE 0
33 #include <sm/sysexits.h>
37 #endif /* ! HASHSPOOL */
39 # define HASHSPOOLMD5 0
40 #endif /* ! HASHSPOOLMD5 */
43 ** This is not intended to work on System V derived systems
44 ** such as Solaris or HP-UX, since they use a totally different
45 ** approach to mailboxes (essentially, they have a set-group-ID program
46 ** rather than set-user-ID, and they rely on the ability to "give away"
47 ** files to do their work). IT IS NOT A BUG that this doesn't
48 ** work on such architectures.
55 #include <sys/types.h>
59 # include <sys/socket.h>
60 # include <sys/file.h>
61 # include <netinet/in.h>
62 # include <arpa/nameser.h>
66 #include <sm/string.h>
71 #include <sendmail/pathnames.h>
78 # include <openssl/md5.h>
79 # endif /* HASHSPOOLMD5 */
80 #endif /* HASHSPOOL */
84 # define LOCKTO_RM 300 /* timeout for stale lockfile removal */
85 #endif /* ! LOCKTO_RM */
87 # define LOCKTO_GLOB 400 /* global timeout for lockfile creation */
88 #endif /* ! LOCKTO_GLOB */
90 /* define a realloc() which works for NULL pointers */
91 #define REALLOC(ptr, size) (((ptr) == NULL) ? malloc(size) : realloc(ptr, size))
94 ** If you don't have flock, you could try using lockf instead.
98 # define flock(a, b) lockf(a, b, 0)
101 # endif /* LOCK_EX */
102 # define LOCK_EX F_LOCK
103 #endif /* LDA_USE_LOCKF */
106 # include <sys/file.h>
107 #endif /* ! LOCK_EX */
110 ** If you don't have setreuid, and you have saved uids, and you have
111 ** a seteuid() call that doesn't try to emulate using setuid(), then
112 ** you can try defining LDA_USE_SETEUID.
115 #ifdef LDA_USE_SETEUID
116 # define setreuid(r, e) seteuid(e)
117 #endif /* LDA_USE_SETEUID */
119 #ifdef LDA_CONTENTLENGTH
120 # define CONTENTLENGTH 1
121 #endif /* LDA_CONTENTLENGTH */
124 # define INADDRSZ 4 /* size of an IPv4 address in bytes */
125 #endif /* ! INADDRSZ */
128 # include <maillock.h>
129 #endif /* MAILLOCK */
131 #ifndef MAILER_DAEMON
132 # define MAILER_DAEMON "MAILER-DAEMON"
133 #endif /* ! MAILER_DAEMON */
136 char ContentHdr
[40] = "Content-Length: ";
139 #endif /* CONTENTLENGTH */
141 bool EightBitMime
= true; /* advertise 8BITMIME in LMTP */
142 char ErrBuf
[10240]; /* error buffer */
143 int ExitVal
= EX_OK
; /* sysexits.h error value. */
144 bool HoldErrs
= false; /* Hold errors in ErrBuf */
145 bool LMTPMode
= false;
146 bool BounceQuota
= false; /* permanent error when over quota */
147 bool CloseMBDB
= false;
148 char *HomeMailFile
= NULL
; /* store mail in homedir */
151 int HashType
= HASH_NONE
;
153 bool StripRcptDomain
= true;
154 #else /* HASHSPOOL */
155 # define StripRcptDomain true
156 #endif /* HASHSPOOL */
157 char SpoolPath
[MAXPATHLEN
];
159 char *parseaddr
__P((char *, bool));
160 char *process_recipient
__P((char *));
161 void dolmtp
__P((void));
162 void deliver
__P((int, char *));
163 int e_to_sys
__P((int));
164 void notifybiff
__P((char *));
165 int store
__P((char *, bool *));
166 void usage
__P((void));
167 int lockmbox
__P((char *));
168 void unlockmbox
__P((void));
169 void mailerr
__P((const char *, const char *, ...));
170 void flush_error
__P((void));
172 const char *hashname
__P((char *));
173 #endif /* HASHSPOOL */
183 CloseMBDB
= false; /* not really necessary, but ... */
197 char *mbdbname
= "pw";
203 /* make sure we have some open file descriptors */
204 for (fd
= 10; fd
< 30; fd
++)
207 /* use a reasonable umask */
211 openlog("mail.local", 0, LOG_MAIL
);
212 # else /* LOG_MAIL */
213 openlog("mail.local", 0);
214 # endif /* LOG_MAIL */
218 /* XXX can this be converted to a compile time check? */
219 if (sm_strlcpy(SpoolPath
, _PATH_MAILDIR
, sizeof(SpoolPath
)) >=
222 mailerr("421", "Configuration error: _PATH_MAILDIR too large");
226 while ((ch
= getopt(argc
, argv
, "7bdD:f:h:r:lH:p:n")) != -1)
227 #else /* HASHSPOOL */
228 while ((ch
= getopt(argc
, argv
, "7bdD:f:h:r:l")) != -1)
229 #endif /* HASHSPOOL */
233 case '7': /* Do not advertise 8BITMIME */
234 EightBitMime
= false;
237 case 'b': /* bounce mail when over quota. */
241 case 'd': /* Backward compatible. */
244 case 'D': /* mailbox database type */
249 case 'r': /* Backward compatible. */
252 mailerr(NULL
, "Multiple -f options");
259 if (optarg
!= NULL
|| *optarg
!= '\0')
260 HomeMailFile
= optarg
;
263 mailerr(NULL
, "-h: missing filename");
275 if (optarg
== NULL
|| *optarg
== '\0')
277 mailerr(NULL
, "-H: missing hashinfo");
283 HashType
= HASH_USER
;
290 # endif /* HASHSPOOLMD5 */
293 mailerr(NULL
, "-H: unknown hash type");
296 if (optarg
[1] == '\0')
298 mailerr(NULL
, "-H: invalid hash depth");
301 HashDepth
= atoi(&optarg
[1]);
302 if ((HashDepth
<= 0) || ((HashDepth
* 2) >= MAXPATHLEN
))
304 mailerr(NULL
, "-H: invalid hash depth");
310 if (optarg
== NULL
|| *optarg
== '\0')
312 mailerr(NULL
, "-p: missing spool path");
315 if (sm_strlcpy(SpoolPath
, optarg
, sizeof(SpoolPath
)) >=
318 mailerr(NULL
, "-p: invalid spool path");
324 StripRcptDomain
= false;
326 #endif /* HASHSPOOL */
336 /* initialize biff structures */
339 err
= sm_mbdb_initialize(mbdbname
);
342 char *errcode
= "521";
344 if (err
== EX_TEMPFAIL
)
347 mailerr(errcode
, "Can not open mailbox database %s: %s",
348 mbdbname
, sm_strexit(err
));
357 mailerr("421", "Users should not be specified in command line if LMTP required");
358 sm_exit(EX_TEMPFAIL
);
366 /* Non-LMTP from here on out */
371 ** If from not specified, use the name from getlogin() if the
372 ** uid matches, otherwise, use the name from the password file
373 ** corresponding to the uid.
377 if (from
== NULL
&& ((from
= getlogin()) == NULL
||
378 (pw
= getpwnam(from
)) == NULL
||
380 from
= (pw
= getpwuid(uid
)) != NULL
? pw
->pw_name
: "???";
383 ** There is no way to distinguish the error status of one delivery
384 ** from the rest of the deliveries. So, if we failed hard on one
385 ** or more deliveries, but had no failures on any of the others, we
386 ** return a hard failure. If we failed temporarily on one or more
387 ** deliveries, we return a temporary failure regardless of the other
388 ** failures. This results in the delivery being reattempted later
389 ** at the expense of repeated failures and multiple deliveries.
393 fd
= store(from
, NULL
);
400 for (; *argv
!= NULL
; ++argv
)
424 while (*p
!= ',' && *p
!= ':' && *p
!= '\0')
429 /* Skip over , or : */
436 while (*p
!= '\0' && *p
!= '@' && *p
!= '>')
446 while (*p
!= '\0' && *p
!= '\"')
455 if (*p
== '\0' || *(p
+ 1) == '\0')
459 if (*p
== '+' && rcpt
)
469 while (*p
!= '\0' && *p
!= '>')
479 if (*p
!= '\0' && *p
!= ' ')
491 mailerr("421 4.3.0", "Memory exhausted");
492 sm_exit(EX_TEMPFAIL
);
495 (void) sm_strlcpy(p
, s
, l
);
500 process_recipient(addr
)
505 switch (sm_mbdb_lookup(addr
, &user
))
511 return "550 5.1.1 User unknown";
514 return "451 4.3.0 User database failure; retry later";
517 return "550 5.3.0 User database failure";
526 char *return_path
= NULL
;
527 char **rcpt_addr
= NULL
;
530 bool gotlhlo
= false;
535 char myhostname
[1024];
538 memset(myhostname
, '\0', sizeof myhostname
);
539 (void) gethostname(myhostname
, sizeof myhostname
- 1);
540 if (myhostname
[0] == '\0')
541 sm_strlcpy(myhostname
, "localhost", sizeof myhostname
);
543 printf("220 %s LMTP ready\r\n", myhostname
);
546 (void) fflush(stdout
);
547 if (fgets(buf
, sizeof(buf
) - 1, stdin
) == NULL
)
549 p
= buf
+ strlen(buf
) - 1;
550 if (p
>= buf
&& *p
== '\n')
552 if (p
>= buf
&& *p
== '\r')
559 if (sm_strcasecmp(buf
, "data") == 0)
565 mailerr("503 5.5.1", "No recipients");
569 msgfd
= store(return_path
, &inbody
);
571 if (msgfd
< 0 && !inbody
)
577 for (i
= 0; i
< rcpt_num
; i
++)
581 /* print error for rcpt */
585 p
= strchr(rcpt_addr
[i
], '+');
588 deliver(msgfd
, rcpt_addr
[i
]);
600 if (sm_strncasecmp(buf
, "lhlo ", 5) == 0)
602 /* check for duplicate per RFC 1651 4.2 */
605 mailerr("503", "%s Duplicate LHLO",
610 printf("250-%s\r\n", myhostname
);
612 printf("250-8BITMIME\r\n");
613 printf("250-ENHANCEDSTATUSCODES\r\n");
614 printf("250 PIPELINING\r\n");
623 if (sm_strncasecmp(buf
, "mail ", 5) == 0)
625 if (return_path
!= NULL
)
628 "Nested MAIL command");
631 if (sm_strncasecmp(buf
+ 5, "from:", 5) != 0 ||
632 ((return_path
= parseaddr(buf
+ 10,
636 "Syntax error in parameters");
639 printf("250 2.5.0 Ok\r\n");
648 if (sm_strcasecmp(buf
, "noop") == 0)
650 printf("250 2.0.0 Ok\r\n");
659 if (sm_strcasecmp(buf
, "quit") == 0)
661 printf("221 2.0.0 Bye\r\n");
670 if (sm_strncasecmp(buf
, "rcpt ", 5) == 0)
672 if (return_path
== NULL
)
675 "Need MAIL command");
678 if (rcpt_num
>= rcpt_alloc
)
680 rcpt_alloc
+= RCPT_GROW
;
681 rcpt_addr
= (char **)
682 REALLOC((char *) rcpt_addr
,
685 if (rcpt_addr
== NULL
)
689 sm_exit(EX_TEMPFAIL
);
692 if (sm_strncasecmp(buf
+ 5, "to:", 3) != 0 ||
693 ((rcpt_addr
[rcpt_num
] = parseaddr(buf
+ 8,
694 StripRcptDomain
)) == NULL
))
697 "Syntax error in parameters");
700 err
= process_recipient(rcpt_addr
[rcpt_num
]);
703 mailerr(NULL
, "%s", err
);
707 printf("250 2.1.5 Ok\r\n");
710 else if (sm_strcasecmp(buf
, "rset") == 0)
712 printf("250 2.0.0 Ok\r\n");
716 free(rcpt_addr
[--rcpt_num
]);
717 if (return_path
!= NULL
)
728 if (sm_strncasecmp(buf
, "vrfy ", 5) == 0)
730 printf("252 2.3.3 Try RCPT to attempt delivery\r\n");
739 mailerr("500 5.5.2", "Syntax error");
754 bool eline
; /* previous line was empty */
755 bool fullline
= true; /* current line is terminated */
756 bool prevfl
; /* previous line was terminated */
759 char tmpbuf
[sizeof _PATH_LOCTMP
+ 1];
765 (void) sm_strlcpy(tmpbuf
, _PATH_LOCTMP
, sizeof tmpbuf
);
766 if ((fd
= mkstemp(tmpbuf
)) < 0 || (fp
= fdopen(fd
, "w+")) == NULL
)
770 mailerr("451 4.3.0", "Unable to open temporary file");
773 (void) unlink(tmpbuf
);
777 printf("354 Go ahead\r\n");
778 (void) fflush(stdout
);
784 (void) fprintf(fp
, "From %s %s", from
, ctime(&tval
));
789 #endif /* CONTENTLENGTH */
793 while (fgets(line
, sizeof(line
), stdin
) != (char *) NULL
)
798 prevfl
= fullline
; /* preserve state of previous line */
799 while (line
[line_len
] != '\n' && line_len
< sizeof(line
) - 2)
803 /* Check for dot-stuffing */
804 if (prevfl
&& LMTPMode
&& line
[0] == '.')
806 if (line
[1] == '\n' ||
807 (line
[1] == '\r' && line
[2] == '\n'))
809 memcpy(line
, line
+ 1, line_len
);
813 /* Check to see if we have the full line from fgets() */
817 if (line
[line_len
- 1] == '\n')
820 line
[line_len
- 2] == '\r')
822 line
[line_len
- 2] = '\n';
823 line
[line_len
- 1] = '\0';
828 else if (line
[line_len
- 1] == '\r')
830 /* Did we just miss the CRLF? */
834 line
[line_len
- 1] = '\n';
838 (void) ungetc(peek
, stdin
);
845 if (prevfl
&& line
[0] == '\n' && HeaderLength
== 0)
849 HeaderLength
= ftell(fp
);
850 if (HeaderLength
<= 0)
853 ** shouldn't happen, unless ftell() is
860 #else /* CONTENTLENGTH */
861 if (prevfl
&& line
[0] == '\n')
863 #endif /* CONTENTLENGTH */
866 if (eline
&& line
[0] == 'F' &&
868 !memcmp(line
, "From ", 5))
869 (void) putc('>', fp
);
872 /* discard existing "Content-Length:" headers */
873 if (prevfl
&& HeaderLength
== 0 &&
874 (line
[0] == 'C' || line
[0] == 'c') &&
875 sm_strncasecmp(line
, ContentHdr
, 15) == 0)
878 ** be paranoid: clear the line
879 ** so no "wrong matches" may occur later
884 #endif /* CONTENTLENGTH */
889 (void) fwrite(line
, sizeof(char), line_len
, fp
);
893 "Temporary file write error");
901 /* check if an error occurred */
907 /* Got a premature EOF -- toss message and exit */
911 /* If message not newline terminated, need an extra. */
912 if (fp
!= NULL
&& strchr(line
, '\n') == NULL
)
913 (void) putc('\n', fp
);
919 BodyLength
= ftell(fp
);
920 if (HeaderLength
== 0 && BodyLength
> 0) /* empty body */
922 HeaderLength
= BodyLength
;
926 BodyLength
= BodyLength
- HeaderLength
- 1 ;
928 if (HeaderLength
> 0 && BodyLength
>= 0)
930 (void) sm_snprintf(line
, sizeof line
, "%lld\n",
931 (LONGLONG_T
) BodyLength
);
932 (void) sm_strlcpy(&ContentHdr
[16], line
,
933 sizeof(ContentHdr
) - 16);
936 BodyLength
= -1; /* Something is wrong here */
937 #endif /* CONTENTLENGTH */
939 /* Output a newline; note, empty messages are allowed. */
941 (void) putc('\n', fp
);
943 if (fp
== NULL
|| fflush(fp
) == EOF
|| ferror(fp
) != 0)
945 mailerr("451 4.3.0", "Temporary file write error");
960 char path
[MAXPATHLEN
];
961 int mbfd
= -1, nr
= 0, nw
, off
;
965 off_t curoff
, cursize
;
969 #endif /* CONTENTLENGTH */
970 char biffmsg
[100], buf
[8 * 1024];
974 ** Disallow delivery to unknown names -- special mailboxes can be
975 ** handled in the sendmail aliases file.
978 exitval
= sm_mbdb_lookup(name
, &user
);
985 exitval
= EX_UNAVAILABLE
;
986 mailerr("550 5.1.1", "%s: User unknown", name
);
990 mailerr("451 4.3.0", "%s: User database failure; retry later",
995 exitval
= EX_UNAVAILABLE
;
996 mailerr("550 5.3.0", "%s: User database failure", name
);
1000 if (exitval
!= EX_OK
)
1002 if (ExitVal
!= EX_TEMPFAIL
)
1010 ** Keep name reasonably short to avoid buffer overruns.
1011 ** This isn't necessary on BSD because of the proper
1012 ** definition of snprintf(), but it can cause problems
1013 ** on other systems.
1014 ** Also, clear out any bogus characters.
1018 if (strlen(name
) > 40)
1020 for (p
= name
; *p
!= '\0'; p
++)
1024 else if (!isprint(*p
))
1027 #endif /* !HASHSPOOL */
1030 if (HomeMailFile
== NULL
)
1032 if (sm_strlcpyn(path
, sizeof(path
),
1035 #else /* HASHSPOOL */
1037 #endif /* HASHSPOOL */
1041 #endif /* HASHSPOOL */
1042 name
) >= sizeof(path
))
1044 exitval
= EX_UNAVAILABLE
;
1045 mailerr("550 5.1.1", "%s: Invalid mailbox path", name
);
1049 else if (*user
.mbdb_homedir
== '\0')
1051 exitval
= EX_UNAVAILABLE
;
1052 mailerr("550 5.1.1", "%s: User missing home directory", name
);
1055 else if (sm_snprintf(path
, sizeof(path
), "%s/%s",
1056 user
.mbdb_homedir
, HomeMailFile
) >= sizeof(path
))
1058 exitval
= EX_UNAVAILABLE
;
1059 mailerr("550 5.1.1", "%s: Invalid mailbox path", name
);
1065 ** If the mailbox is linked or a symlink, fail. There's an obvious
1066 ** race here, that the file was replaced with a symbolic link after
1067 ** the lstat returned, but before the open. We attempt to detect
1068 ** this by comparing the original stat information and information
1069 ** returned by an fstat of the file descriptor returned by the open.
1071 ** NB: this is a symptom of a larger problem, that the mail spooling
1072 ** directory is writeable by the wrong users. If that directory is
1073 ** writeable, system security is compromised for other reasons, and
1074 ** it cannot be fixed here.
1076 ** If we created the mailbox, set the owner/group. If that fails,
1077 ** just return. Another process may have already opened it, so we
1078 ** can't unlink it. Historically, binmail set the owner/group at
1079 ** each mail delivery. We no longer do this, assuming that if the
1080 ** ownership or permissions were changed there was a reason.
1083 ** open(2) should support flock'ing the file.
1089 #else /* MAILLOCK */
1091 #endif /* MAILLOCK */
1092 if ((off
= lockmbox(p
)) != 0)
1094 if (off
== EX_TEMPFAIL
|| e_to_sys(off
) == EX_TEMPFAIL
)
1096 ExitVal
= EX_TEMPFAIL
;
1097 errcode
= "451 4.3.0";
1100 errcode
= "551 5.3.0";
1102 mailerr(errcode
, "lockmailbox %s failed; error code %d %s",
1103 p
, off
, errno
> 0 ? sm_errstring(errno
) : "");
1107 if (lstat(path
, &sb
) < 0)
1110 int mode
= S_IRUSR
|S_IWUSR
;
1111 gid_t gid
= user
.mbdb_gid
;
1116 mode
|= S_IRGRP
|S_IWGRP
;
1117 #endif /* MAILGID */
1119 mbfd
= open(path
, O_APPEND
|O_CREAT
|O_EXCL
|O_WRONLY
,
1123 if (lstat(path
, &sb
) < 0)
1125 ExitVal
= EX_CANTCREAT
;
1126 mailerr("550 5.2.0",
1127 "%s: lstat: file changed after open", path
);
1132 if (save_errno
== EEXIST
)
1135 /* open failed, don't try again */
1136 mailerr("450 4.2.0", "%s: %s", path
,
1137 sm_errstring(save_errno
));
1140 else if (fchown(mbfd
, user
.mbdb_uid
, gid
) < 0)
1142 mailerr("451 4.3.0", "chown %u.%u: %s",
1143 user
.mbdb_uid
, gid
, name
);
1149 ** open() was successful, now close it so can
1150 ** be opened as the right owner again.
1151 ** Paranoia: reset mbdf since the file descriptor
1152 ** is no longer valid; better safe than sorry.
1155 sb
.st_uid
= user
.mbdb_uid
;
1160 else if (sb
.st_nlink
!= 1)
1162 mailerr("550 5.2.0", "%s: too many links", path
);
1165 else if (!S_ISREG(sb
.st_mode
))
1167 mailerr("550 5.2.0", "%s: irregular file", path
);
1170 else if (sb
.st_uid
!= user
.mbdb_uid
)
1172 ExitVal
= EX_CANTCREAT
;
1173 mailerr("550 5.2.0", "%s: wrong ownership (%d)",
1174 path
, (int) sb
.st_uid
);
1178 /* change UID for quota checks */
1179 if (setreuid(0, user
.mbdb_uid
) < 0)
1181 mailerr("450 4.2.0", "setreuid(0, %d): %s (r=%d, e=%d)",
1182 (int) user
.mbdb_uid
, sm_errstring(errno
),
1183 (int) getuid(), (int) geteuid());
1187 fprintf(stderr
, "new euid = %d\n", (int) geteuid());
1189 mbfd
= open(path
, O_APPEND
|O_WRONLY
, 0);
1192 mailerr("450 4.2.0", "%s: %s", path
, sm_errstring(errno
));
1195 else if (fstat(mbfd
, &fsb
) < 0 ||
1196 fsb
.st_nlink
!= 1 ||
1198 !S_ISREG(fsb
.st_mode
) ||
1199 sb
.st_dev
!= fsb
.st_dev
||
1200 sb
.st_ino
!= fsb
.st_ino
||
1201 # if HAS_ST_GEN && 0 /* AFS returns random values for st_gen */
1202 sb
.st_gen
!= fsb
.st_gen
||
1203 # endif /* HAS_ST_GEN && 0 */
1204 sb
.st_uid
!= fsb
.st_uid
)
1206 ExitVal
= EX_TEMPFAIL
;
1207 mailerr("550 5.2.0", "%s: fstat: file changed after open",
1214 ** This code could be reused if we decide to add a
1215 ** per-user quota field to the sm_mbdb interface.
1219 ** Fail if the user has a quota specified, and delivery of this
1220 ** message would exceed that quota. We bounce such failures using
1221 ** EX_UNAVAILABLE, unless there were internal problems, since
1222 ** storing immense messages for later retries can cause queueing
1230 if (fstat(fd
, &dsb
) < 0)
1232 ExitVal
= EX_TEMPFAIL
;
1233 mailerr("451 4.3.0",
1234 "%s: fstat: can't stat temporary storage: %s",
1235 ui
.mailspool
, sm_errstring(errno
));
1239 if (dsb
.st_size
+ sb
.st_size
+ 1 > ui
.quota
)
1241 ExitVal
= EX_UNAVAILABLE
;
1242 mailerr("551 5.2.2",
1243 "%s: Mailbox full or quota exceeded",
1250 /* Wait until we can get a lock on the file. */
1251 if (flock(mbfd
, LOCK_EX
) < 0)
1253 mailerr("450 4.2.0", "%s: %s", path
, sm_errstring(errno
));
1257 /* Get the starting offset of the new message */
1258 curoff
= lseek(mbfd
, (off_t
) 0, SEEK_END
);
1259 (void) sm_snprintf(biffmsg
, sizeof(biffmsg
), "%s@%lld\n",
1260 name
, (LONGLONG_T
) curoff
);
1262 /* Copy the message into the file. */
1263 if (lseek(fd
, (off_t
) 0, SEEK_SET
) == (off_t
) -1)
1265 mailerr("450 4.2.0", "Temporary file: %s",
1266 sm_errstring(errno
));
1270 fprintf(stderr
, "before writing: euid = %d\n", (int) geteuid());
1272 #ifdef CONTENTLENGTH
1273 headerbytes
= (BodyLength
>= 0) ? HeaderLength
: -1 ;
1276 if (headerbytes
== 0)
1278 (void) sm_snprintf(buf
, sizeof buf
, "%s", ContentHdr
);
1283 else if (headerbytes
> sizeof(buf
) || headerbytes
< 0)
1284 readamount
= sizeof(buf
);
1286 readamount
= headerbytes
;
1287 if (readamount
!= 0)
1288 nr
= read(fd
, buf
, readamount
);
1291 if (headerbytes
> 0)
1294 #else /* CONTENTLENGTH */
1295 while ((nr
= read(fd
, buf
, sizeof(buf
))) > 0)
1297 #endif /* CONTENTLENGTH */
1298 for (off
= 0; off
< nr
; off
+= nw
)
1300 if ((nw
= write(mbfd
, buf
+ off
, nr
- off
)) < 0)
1302 errcode
= "450 4.2.0";
1304 if (errno
== EDQUOT
&& BounceQuota
)
1305 errcode
= "552 5.2.2";
1307 mailerr(errcode
, "%s: %s",
1308 path
, sm_errstring(errno
));
1315 mailerr("450 4.2.0", "Temporary file: %s",
1316 sm_errstring(errno
));
1320 /* Flush to disk, don't wait for update. */
1321 if (fsync(mbfd
) < 0)
1323 mailerr("450 4.2.0", "%s: %s", path
, sm_errstring(errno
));
1326 fprintf(stderr
, "reset euid = %d\n", (int) geteuid());
1329 (void) ftruncate(mbfd
, curoff
);
1330 err1
: if (mbfd
>= 0)
1332 err0
: (void) setreuid(0, 0);
1338 ** Save the current size so if the close() fails below
1339 ** we can make sure no other process has changed the mailbox
1340 ** between the failed close and the re-open()/re-lock().
1341 ** If something else has changed the size, we shouldn't
1342 ** try to truncate it as we may do more harm then good
1343 ** (e.g., truncate a later message delivery).
1346 if (fstat(mbfd
, &sb
) < 0)
1349 cursize
= sb
.st_size
;
1352 /* Close and check -- NFS doesn't write until the close. */
1355 errcode
= "450 4.2.0";
1357 if (errno
== EDQUOT
&& BounceQuota
)
1358 errcode
= "552 5.2.2";
1360 mailerr(errcode
, "%s: %s", path
, sm_errstring(errno
));
1361 mbfd
= open(path
, O_WRONLY
, 0);
1364 || flock(mbfd
, LOCK_EX
) < 0 ||
1365 fstat(mbfd
, &sb
) < 0 ||
1366 sb
.st_size
!= cursize
||
1368 !S_ISREG(sb
.st_mode
) ||
1369 sb
.st_dev
!= fsb
.st_dev
||
1370 sb
.st_ino
!= fsb
.st_ino
||
1371 # if HAS_ST_GEN && 0 /* AFS returns random values for st_gen */
1372 sb
.st_gen
!= fsb
.st_gen
||
1373 # endif /* HAS_ST_GEN && 0 */
1374 sb
.st_uid
!= fsb
.st_uid
1377 /* Don't use a bogus file */
1385 /* Attempt to truncate back to pre-write size */
1389 notifybiff(biffmsg
);
1391 if (setreuid(0, 0) < 0)
1393 mailerr("450 4.2.0", "setreuid(0, 0): %s",
1394 sm_errstring(errno
));
1398 fprintf(stderr
, "reset euid = %d\n", (int) geteuid());
1402 printf("250 2.1.5 %s Ok\r\n", name
);
1406 ** user.lock files are necessary for compatibility with other
1407 ** systems, e.g., when the mail spool file is NFS exported.
1408 ** Alas, mailbox locking is more than just a local matter.
1412 bool Locked
= false;
1423 if ((r
= maillock(name
, 15)) == L_SUCCESS
)
1430 case L_TMPLOCK
: /* Can't create tmp file */
1431 case L_TMPWRITE
: /* Can't write pid into lockfile */
1432 case L_MAXTRYS
: /* Failed after retrycnt attempts */
1436 case L_ERROR
: /* Check errno for reason */
1439 default: /* other permanent errors */
1454 #else /* MAILLOCK */
1456 char LockName
[MAXPATHLEN
];
1467 if (strlen(path
) + 6 > sizeof LockName
)
1469 (void) sm_snprintf(LockName
, sizeof LockName
, "%s.lock", path
);
1470 (void) time(&start
);
1477 /* global timeout */
1479 if (now
> start
+ LOCKTO_GLOB
)
1484 fd
= open(LockName
, O_WRONLY
|O_EXCL
|O_CREAT
, LOCKFILE_PMODE
);
1487 /* defeat lock checking programs which test pid */
1488 (void) write(fd
, "0", 2);
1493 if (stat(LockName
, &st
) < 0)
1495 if (statfailed
++ > 5)
1504 if (now
< st
.st_ctime
+ LOCKTO_RM
)
1507 /* try to remove stale lockfile */
1508 if (unlink(LockName
) < 0)
1518 (void) unlink(LockName
);
1521 #endif /* MAILLOCK */
1527 static bool initialized
= false;
1532 static struct sockaddr_in addr
;
1538 /* Be silent if biff service not available. */
1539 if ((sp
= getservbyname("biff", "udp")) == NULL
||
1540 (hp
= gethostbyname("localhost")) == NULL
||
1541 hp
->h_length
!= INADDRSZ
)
1544 addr
.sin_family
= hp
->h_addrtype
;
1545 memcpy(&addr
.sin_addr
, hp
->h_addr
, INADDRSZ
);
1546 addr
.sin_port
= sp
->s_port
;
1549 /* No message, just return */
1553 /* Couldn't initialize addr struct */
1554 if (addr
.sin_family
== AF_UNSPEC
)
1557 if (f
< 0 && (f
= socket(AF_INET
, SOCK_DGRAM
, 0)) < 0)
1559 len
= strlen(msg
) + 1;
1560 (void) sendto(f
, msg
, len
, 0, (struct sockaddr
*) &addr
, sizeof(addr
));
1567 mailerr(NULL
, "usage: mail.local [-7] [-b] [-d] [-l] [-f from|-r from] [-h filename] user ...");
1574 mailerr(const char *hdr
, const char *fmt
, ...)
1575 #else /* __STDC__ */
1576 mailerr(hdr
, fmt
, va_alist
)
1580 #endif /* __STDC__ */
1585 (void) e_to_sys(errno
);
1587 SM_VA_START(ap
, fmt
);
1589 if (LMTPMode
&& hdr
!= NULL
)
1591 sm_snprintf(ErrBuf
, sizeof ErrBuf
, "%s ", hdr
);
1592 len
= strlen(ErrBuf
);
1594 (void) sm_vsnprintf(&ErrBuf
[len
], sizeof ErrBuf
- len
, fmt
, ap
);
1600 /* Log the message to syslog. */
1602 syslog(LOG_ERR
, "%s", ErrBuf
);
1609 printf("%s\r\n", ErrBuf
);
1612 if (ExitVal
!= EX_USAGE
)
1613 (void) fprintf(stderr
, "mail.local: ");
1614 fprintf(stderr
, "%s\n", ErrBuf
);
1623 static char p
[MAXPATHLEN
];
1628 char Base64
[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_";
1630 unsigned char md5
[18];
1631 # if MAXPATHLEN <= 24
1632 ERROR _MAXPATHLEN
<= 24
1633 # endif /* MAXPATHLEN <= 24 */
1637 # endif /* HASHSPOOLMD5 */
1639 if (HashType
== HASH_NONE
|| HashDepth
* 2 >= MAXPATHLEN
)
1654 MD5_Update(&ctx
, name
, strlen(name
));
1655 MD5_Final(md5
, &ctx
);
1659 for (i
= 0; i
< 6; i
++)
1661 bits
= (unsigned) md5
[(3 * i
)] << 16;
1662 bits
|= (unsigned) md5
[(3 * i
) + 1] << 8;
1663 bits
|= (unsigned) md5
[(3 * i
) + 2];
1665 for (j
= 3; j
>= 0; j
--)
1667 b64
[(4 * i
) + j
] = Base64
[(bits
& 0x3f)];
1674 # endif /* HASHSPOOLMD5 */
1678 for (i
= 0; i
< HashDepth
; i
++)
1684 p
[(i
* 2) + 1] = '/';
1686 p
[HashDepth
* 2] = '\0';
1689 #endif /* HASHSPOOL */
1693 * Guess which errno's are temporary. Gag me.
1700 /* Temporary failures override hard errors. */
1701 if (ExitVal
== EX_TEMPFAIL
)
1704 switch (num
) /* Hopefully temporary errors. */
1707 case EDQUOT
: /* Disc quota exceeded */
1710 ExitVal
= EX_UNAVAILABLE
;
1716 case EAGAIN
: /* Resource temporarily unavailable */
1719 case EBUSY
: /* Device busy */
1722 case EPROCLIM
: /* Too many processes */
1723 #endif /* EPROCLIM */
1725 case EUSERS
: /* Too many users */
1728 case ECONNABORTED
: /* Software caused connection abort */
1729 #endif /* ECONNABORTED */
1731 case ECONNREFUSED
: /* Connection refused */
1732 #endif /* ECONNREFUSED */
1734 case ECONNRESET
: /* Connection reset by peer */
1735 #endif /* ECONNRESET */
1737 case EDEADLK
: /* Resource deadlock avoided */
1738 #endif /* EDEADLK */
1740 case EFBIG
: /* File too large */
1743 case EHOSTDOWN
: /* Host is down */
1744 #endif /* EHOSTDOWN */
1746 case EHOSTUNREACH
: /* No route to host */
1747 #endif /* EHOSTUNREACH */
1749 case EMFILE
: /* Too many open files */
1752 case ENETDOWN
: /* Network is down */
1753 #endif /* ENETDOWN */
1755 case ENETRESET
: /* Network dropped connection on reset */
1756 #endif /* ENETRESET */
1758 case ENETUNREACH
: /* Network is unreachable */
1759 #endif /* ENETUNREACH */
1761 case ENFILE
: /* Too many open files in system */
1764 case ENOBUFS
: /* No buffer space available */
1765 #endif /* ENOBUFS */
1767 case ENOMEM
: /* Cannot allocate memory */
1770 case ENOSPC
: /* No space left on device */
1773 case EROFS
: /* Read-only file system */
1776 case ESTALE
: /* Stale NFS file handle */
1779 case ETIMEDOUT
: /* Connection timed out */
1780 #endif /* ETIMEDOUT */
1781 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN && EWOULDBLOCK != EDEADLK
1782 case EWOULDBLOCK
: /* Operation would block. */
1783 #endif /* defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN && EWOULDBLOCK != EDEADLK */
1784 ExitVal
= EX_TEMPFAIL
;
1788 ExitVal
= EX_UNAVAILABLE
;
1794 #if defined(ultrix) || defined(_CRAY)
1796 * Copyright (c) 1987, 1993
1797 * The Regents of the University of California. All rights reserved.
1799 * Redistribution and use in source and binary forms, with or without
1800 * modification, are permitted provided that the following conditions
1802 * 1. Redistributions of source code must retain the above copyright
1803 * notice, this list of conditions and the following disclaimer.
1804 * 2. Redistributions in binary form must reproduce the above copyright
1805 * notice, this list of conditions and the following disclaimer in the
1806 * documentation and/or other materials provided with the distribution.
1807 * 3. All advertising materials mentioning features or use of this software
1808 * must display the following acknowledgement:
1809 * This product includes software developed by the University of
1810 * California, Berkeley and its contributors.
1811 * 4. Neither the name of the University nor the names of its contributors
1812 * may be used to endorse or promote products derived from this software
1813 * without specific prior written permission.
1815 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1816 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1817 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1818 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
1819 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1820 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1821 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1822 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1823 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1824 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1828 # if defined(LIBC_SCCS) && !defined(lint)
1829 static char sccsid
[] = "@(#)mktemp.c 8.1 (Berkeley) 6/4/93";
1830 # endif /* defined(LIBC_SCCS) && !defined(lint) */
1832 # include <sys/types.h>
1833 # include <sys/stat.h>
1839 static int _gettemp();
1846 return (_gettemp(path
, &fd
) ? fd
: -1);
1850 _gettemp(path
, doopen
)
1852 register int *doopen
;
1855 register char *start
, *trv
;
1860 for (trv
= path
; *trv
; ++trv
); /* extra X's get set to 0's */
1861 while (*--trv
== 'X')
1863 *trv
= (pid
% 10) + '0';
1868 * check the target directory; if you have six X's and it
1869 * doesn't exist this runs for a *very* long time.
1871 for (start
= trv
+ 1;; --trv
)
1878 if (stat(path
, &sbuf
) < 0)
1880 if (!S_ISDIR(sbuf
.st_mode
))
1894 if ((*doopen
= open(path
, O_CREAT
|O_EXCL
|O_RDWR
,
1897 if (errno
!= EEXIST
)
1900 else if (stat(path
, &sbuf
) < 0)
1901 return(errno
== ENOENT
? 1 : 0);
1903 /* tricky little algorithm for backward compatibility */
1912 if (isascii(*trv
) && isdigit(*trv
))
1922 #endif /* defined(ultrix) || defined(_CRAY) */