1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #ifndef lint
10 static char sccsid[] = "@(#)envelope.c	8.18 (Berkeley) 11/19/93";
11 #endif /* not lint */
12 
13 #include "sendmail.h"
14 #include <sys/time.h>
15 #include <pwd.h>
16 
17 /*
18 **  NEWENVELOPE -- allocate a new envelope
19 **
20 **	Supports inheritance.
21 **
22 **	Parameters:
23 **		e -- the new envelope to fill in.
24 **		parent -- the envelope to be the parent of e.
25 **
26 **	Returns:
27 **		e.
28 **
29 **	Side Effects:
30 **		none.
31 */
32 
33 ENVELOPE *
34 newenvelope(e, parent)
35 	register ENVELOPE *e;
36 	register ENVELOPE *parent;
37 {
38 	extern putheader(), putbody();
39 	extern ENVELOPE BlankEnvelope;
40 
41 	if (e == parent && e->e_parent != NULL)
42 		parent = e->e_parent;
43 	clearenvelope(e, TRUE);
44 	if (e == CurEnv)
45 		bcopy((char *) &NullAddress, (char *) &e->e_from, sizeof e->e_from);
46 	else
47 		bcopy((char *) &CurEnv->e_from, (char *) &e->e_from, sizeof e->e_from);
48 	e->e_parent = parent;
49 	e->e_ctime = curtime();
50 	if (parent != NULL)
51 		e->e_msgpriority = parent->e_msgsize;
52 	e->e_puthdr = putheader;
53 	e->e_putbody = putbody;
54 	if (CurEnv->e_xfp != NULL)
55 		(void) fflush(CurEnv->e_xfp);
56 
57 	return (e);
58 }
59 /*
60 **  DROPENVELOPE -- deallocate an envelope.
61 **
62 **	Parameters:
63 **		e -- the envelope to deallocate.
64 **
65 **	Returns:
66 **		none.
67 **
68 **	Side Effects:
69 **		housekeeping necessary to dispose of an envelope.
70 **		Unlocks this queue file.
71 */
72 
73 void
74 dropenvelope(e)
75 	register ENVELOPE *e;
76 {
77 	bool queueit = FALSE;
78 	bool saveit = bitset(EF_FATALERRS, e->e_flags);
79 	register ADDRESS *q;
80 	char *id = e->e_id;
81 	char buf[MAXLINE];
82 
83 	if (tTd(50, 1))
84 	{
85 		printf("dropenvelope %x: id=", e);
86 		xputs(e->e_id);
87 		printf(", flags=%o\n", e->e_flags);
88 		if (tTd(50, 10))
89 		{
90 			printf("sendq=");
91 			printaddr(e->e_sendqueue, TRUE);
92 		}
93 	}
94 
95 	/* we must have an id to remove disk files */
96 	if (id == NULL)
97 		return;
98 
99 #ifdef LOG
100 	if (LogLevel > 84)
101 		syslog(LOG_DEBUG, "dropenvelope, id=%s, flags=%o, pid=%d",
102 				  id, e->e_flags, getpid());
103 #endif /* LOG */
104 
105 	/* post statistics */
106 	poststats(StatFile);
107 
108 	/*
109 	**  Extract state information from dregs of send list.
110 	*/
111 
112 	e->e_flags &= ~EF_QUEUERUN;
113 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
114 	{
115 		if (bitset(QQUEUEUP, q->q_flags))
116 			queueit = TRUE;
117 		if (!bitset(QDONTSEND, q->q_flags) &&
118 		    bitset(QBADADDR, q->q_flags))
119 		{
120 			if (q->q_owner == NULL &&
121 			    strcmp(e->e_from.q_paddr, "<>") != 0)
122 				(void) sendtolist(e->e_from.q_paddr, NULL,
123 						  &e->e_errorqueue, e);
124 		}
125 	}
126 
127 	/*
128 	**  See if the message timed out.
129 	*/
130 
131 	if (!queueit)
132 		/* nothing to do */ ;
133 	else if (curtime() > e->e_ctime + TimeOuts.to_q_return)
134 	{
135 		(void) sprintf(buf, "Cannot send message for %s",
136 			pintvl(TimeOuts.to_q_return, FALSE));
137 		if (e->e_message != NULL)
138 			free(e->e_message);
139 		e->e_message = newstr(buf);
140 		message(buf);
141 		e->e_flags |= EF_CLRQUEUE;
142 		saveit = TRUE;
143 		fprintf(e->e_xfp, "Message could not be delivered for %s\n",
144 			pintvl(TimeOuts.to_q_return, FALSE));
145 		fprintf(e->e_xfp, "Message will be deleted from queue\n");
146 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
147 		{
148 			if (bitset(QQUEUEUP, q->q_flags))
149 				q->q_flags |= QBADADDR;
150 		}
151 	}
152 	else if (TimeOuts.to_q_warning > 0 &&
153 	    curtime() > e->e_ctime + TimeOuts.to_q_warning)
154 	{
155 		if (!bitset(EF_WARNING|EF_RESPONSE, e->e_flags) &&
156 		    e->e_class >= 0 &&
157 		    strcmp(e->e_from.q_paddr, "<>") != 0)
158 		{
159 			(void) sprintf(buf,
160 				"warning: cannot send message for %s",
161 				pintvl(TimeOuts.to_q_warning, FALSE));
162 			if (e->e_message != NULL)
163 				free(e->e_message);
164 			e->e_message = newstr(buf);
165 			message(buf);
166 			e->e_flags |= EF_WARNING;
167 			saveit = TRUE;
168 		}
169 		fprintf(e->e_xfp,
170 			"Warning: message still undelivered after %s\n",
171 			pintvl(TimeOuts.to_q_warning, FALSE));
172 		fprintf(e->e_xfp, "Will keep trying until message is %s old\n",
173 			pintvl(TimeOuts.to_q_return, FALSE));
174 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
175 		{
176 			if (bitset(QQUEUEUP, q->q_flags))
177 				q->q_flags |= QREPORT;
178 		}
179 	}
180 
181 	/*
182 	**  Send back return receipts as requested.
183 	*/
184 
185 	if (e->e_receiptto != NULL && bitset(EF_SENDRECEIPT, e->e_flags))
186 	{
187 		auto ADDRESS *rlist = NULL;
188 
189 		(void) sendtolist(e->e_receiptto, NULLADDR, &rlist, e);
190 		(void) returntosender("Return receipt", rlist, FALSE, e);
191 	}
192 
193 	/*
194 	**  Arrange to send error messages if there are fatal errors.
195 	*/
196 
197 	if (saveit && e->e_errormode != EM_QUIET)
198 		savemail(e);
199 
200 	/*
201 	**  Arrange to send warning messages to postmaster as requested.
202 	*/
203 
204 	if (bitset(EF_PM_NOTIFY, e->e_flags) && PostMasterCopy != NULL &&
205 	    !bitset(EF_RESPONSE, e->e_flags) && e->e_class >= 0)
206 	{
207 		auto ADDRESS *rlist = NULL;
208 
209 		(void) sendtolist(PostMasterCopy, NULLADDR, &rlist, e);
210 		(void) returntosender(e->e_message, rlist, FALSE, e);
211 	}
212 
213 	/*
214 	**  Instantiate or deinstantiate the queue.
215 	*/
216 
217 	if ((!queueit && !bitset(EF_KEEPQUEUE, e->e_flags)) ||
218 	    bitset(EF_CLRQUEUE, e->e_flags))
219 	{
220 		if (tTd(50, 1))
221 			printf("\n===== Dropping [dq]f%s =====\n\n", e->e_id);
222 		if (e->e_df != NULL)
223 			xunlink(e->e_df);
224 		xunlink(queuename(e, 'q'));
225 
226 #ifdef LOG
227 		if (LogLevel > 10)
228 			syslog(LOG_INFO, "%s: done", id);
229 #endif
230 	}
231 	else if (queueit || !bitset(EF_INQUEUE, e->e_flags))
232 	{
233 #ifdef QUEUE
234 		queueup(e, bitset(EF_KEEPQUEUE, e->e_flags), FALSE);
235 #else /* QUEUE */
236 		syserr("554 dropenvelope: queueup");
237 #endif /* QUEUE */
238 	}
239 
240 	/* now unlock the job */
241 	closexscript(e);
242 	unlockqueue(e);
243 
244 	/* make sure that this envelope is marked unused */
245 	if (e->e_dfp != NULL)
246 		(void) xfclose(e->e_dfp, "dropenvelope", e->e_df);
247 	e->e_dfp = NULL;
248 	e->e_id = e->e_df = NULL;
249 #ifdef XDEBUG
250 	checkfd012("dropenvelope");
251 #endif
252 }
253 /*
254 **  CLEARENVELOPE -- clear an envelope without unlocking
255 **
256 **	This is normally used by a child process to get a clean
257 **	envelope without disturbing the parent.
258 **
259 **	Parameters:
260 **		e -- the envelope to clear.
261 **		fullclear - if set, the current envelope is total
262 **			garbage and should be ignored; otherwise,
263 **			release any resources it may indicate.
264 **
265 **	Returns:
266 **		none.
267 **
268 **	Side Effects:
269 **		Closes files associated with the envelope.
270 **		Marks the envelope as unallocated.
271 */
272 
273 void
274 clearenvelope(e, fullclear)
275 	register ENVELOPE *e;
276 	bool fullclear;
277 {
278 	register HDR *bh;
279 	register HDR **nhp;
280 	extern ENVELOPE BlankEnvelope;
281 
282 	if (!fullclear)
283 	{
284 		/* clear out any file information */
285 		if (e->e_xfp != NULL)
286 			(void) xfclose(e->e_xfp, "clearenvelope xfp", e->e_id);
287 		if (e->e_dfp != NULL)
288 			(void) xfclose(e->e_dfp, "clearenvelope dfp", e->e_df);
289 		e->e_xfp = e->e_dfp = NULL;
290 	}
291 
292 	/* now clear out the data */
293 	STRUCTCOPY(BlankEnvelope, *e);
294 	if (Verbose)
295 		e->e_sendmode = SM_DELIVER;
296 	bh = BlankEnvelope.e_header;
297 	nhp = &e->e_header;
298 	while (bh != NULL)
299 	{
300 		*nhp = (HDR *) xalloc(sizeof *bh);
301 		bcopy((char *) bh, (char *) *nhp, sizeof *bh);
302 		bh = bh->h_link;
303 		nhp = &(*nhp)->h_link;
304 	}
305 }
306 /*
307 **  INITSYS -- initialize instantiation of system
308 **
309 **	In Daemon mode, this is done in the child.
310 **
311 **	Parameters:
312 **		none.
313 **
314 **	Returns:
315 **		none.
316 **
317 **	Side Effects:
318 **		Initializes the system macros, some global variables,
319 **		etc.  In particular, the current time in various
320 **		forms is set.
321 */
322 
323 void
324 initsys(e)
325 	register ENVELOPE *e;
326 {
327 	char cbuf[5];				/* holds hop count */
328 	char pbuf[10];				/* holds pid */
329 #ifdef TTYNAME
330 	static char ybuf[60];			/* holds tty id */
331 	register char *p;
332 #endif /* TTYNAME */
333 	extern char *ttyname();
334 	extern void settime();
335 	extern char Version[];
336 
337 	/*
338 	**  Give this envelope a reality.
339 	**	I.e., an id, a transcript, and a creation time.
340 	*/
341 
342 	openxscript(e);
343 	e->e_ctime = curtime();
344 
345 	/*
346 	**  Set OutChannel to something useful if stdout isn't it.
347 	**	This arranges that any extra stuff the mailer produces
348 	**	gets sent back to the user on error (because it is
349 	**	tucked away in the transcript).
350 	*/
351 
352 	if (OpMode == MD_DAEMON && bitset(EF_QUEUERUN, e->e_flags) &&
353 	    e->e_xfp != NULL)
354 		OutChannel = e->e_xfp;
355 
356 	/*
357 	**  Set up some basic system macros.
358 	*/
359 
360 	/* process id */
361 	(void) sprintf(pbuf, "%d", getpid());
362 	define('p', newstr(pbuf), e);
363 
364 	/* hop count */
365 	(void) sprintf(cbuf, "%d", e->e_hopcount);
366 	define('c', newstr(cbuf), e);
367 
368 	/* time as integer, unix time, arpa time */
369 	settime(e);
370 
371 #ifdef TTYNAME
372 	/* tty name */
373 	if (macvalue('y', e) == NULL)
374 	{
375 		p = ttyname(2);
376 		if (p != NULL)
377 		{
378 			if (strrchr(p, '/') != NULL)
379 				p = strrchr(p, '/') + 1;
380 			(void) strcpy(ybuf, p);
381 			define('y', ybuf, e);
382 		}
383 	}
384 #endif /* TTYNAME */
385 }
386 /*
387 **  SETTIME -- set the current time.
388 **
389 **	Parameters:
390 **		none.
391 **
392 **	Returns:
393 **		none.
394 **
395 **	Side Effects:
396 **		Sets the various time macros -- $a, $b, $d, $t.
397 */
398 
399 void
400 settime(e)
401 	register ENVELOPE *e;
402 {
403 	register char *p;
404 	auto time_t now;
405 	char tbuf[20];				/* holds "current" time */
406 	char dbuf[30];				/* holds ctime(tbuf) */
407 	register struct tm *tm;
408 	extern char *arpadate();
409 	extern struct tm *gmtime();
410 
411 	now = curtime();
412 	tm = gmtime(&now);
413 	(void) sprintf(tbuf, "%04d%02d%02d%02d%02d", tm->tm_year + 1900,
414 			tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min);
415 	define('t', newstr(tbuf), e);
416 	(void) strcpy(dbuf, ctime(&now));
417 	p = strchr(dbuf, '\n');
418 	if (p != NULL)
419 		*p = '\0';
420 	define('d', newstr(dbuf), e);
421 	p = arpadate(dbuf);
422 	p = newstr(p);
423 	if (macvalue('a', e) == NULL)
424 		define('a', p, e);
425 	define('b', p, e);
426 }
427 /*
428 **  OPENXSCRIPT -- Open transcript file
429 **
430 **	Creates a transcript file for possible eventual mailing or
431 **	sending back.
432 **
433 **	Parameters:
434 **		e -- the envelope to create the transcript in/for.
435 **
436 **	Returns:
437 **		none
438 **
439 **	Side Effects:
440 **		Creates the transcript file.
441 */
442 
443 #ifndef O_APPEND
444 #define O_APPEND	0
445 #endif
446 
447 void
448 openxscript(e)
449 	register ENVELOPE *e;
450 {
451 	register char *p;
452 	int fd;
453 
454 	if (e->e_xfp != NULL)
455 		return;
456 	p = queuename(e, 'x');
457 	fd = open(p, O_WRONLY|O_CREAT|O_APPEND, 0644);
458 	if (fd < 0)
459 	{
460 		syserr("Can't create transcript file %s", p);
461 		fd = open("/dev/null", O_WRONLY, 0644);
462 		if (fd < 0)
463 			syserr("!Can't open /dev/null");
464 	}
465 	e->e_xfp = fdopen(fd, "w");
466 	if (e->e_xfp == NULL)
467 	{
468 		syserr("!Can't create transcript stream %s", p);
469 	}
470 	if (tTd(46, 9))
471 	{
472 		printf("openxscript(%s):\n  ", p);
473 		dumpfd(fileno(e->e_xfp), TRUE, FALSE);
474 	}
475 }
476 /*
477 **  CLOSEXSCRIPT -- close the transcript file.
478 **
479 **	Parameters:
480 **		e -- the envelope containing the transcript to close.
481 **
482 **	Returns:
483 **		none.
484 **
485 **	Side Effects:
486 **		none.
487 */
488 
489 void
490 closexscript(e)
491 	register ENVELOPE *e;
492 {
493 	if (e->e_xfp == NULL)
494 		return;
495 	(void) xfclose(e->e_xfp, "closexscript", e->e_id);
496 	e->e_xfp = NULL;
497 }
498 /*
499 **  SETSENDER -- set the person who this message is from
500 **
501 **	Under certain circumstances allow the user to say who
502 **	s/he is (using -f or -r).  These are:
503 **	1.  The user's uid is zero (root).
504 **	2.  The user's login name is in an approved list (typically
505 **	    from a network server).
506 **	3.  The address the user is trying to claim has a
507 **	    "!" character in it (since #2 doesn't do it for
508 **	    us if we are dialing out for UUCP).
509 **	A better check to replace #3 would be if the
510 **	effective uid is "UUCP" -- this would require me
511 **	to rewrite getpwent to "grab" uucp as it went by,
512 **	make getname more nasty, do another passwd file
513 **	scan, or compile the UID of "UUCP" into the code,
514 **	all of which are reprehensible.
515 **
516 **	Assuming all of these fail, we figure out something
517 **	ourselves.
518 **
519 **	Parameters:
520 **		from -- the person we would like to believe this message
521 **			is from, as specified on the command line.
522 **		e -- the envelope in which we would like the sender set.
523 **		delimptr -- if non-NULL, set to the location of the
524 **			trailing delimiter.
525 **		internal -- set if this address is coming from an internal
526 **			source such as an owner alias.
527 **
528 **	Returns:
529 **		none.
530 **
531 **	Side Effects:
532 **		sets sendmail's notion of who the from person is.
533 */
534 
535 void
536 setsender(from, e, delimptr, internal)
537 	char *from;
538 	register ENVELOPE *e;
539 	char **delimptr;
540 	bool internal;
541 {
542 	register char **pvp;
543 	char *realname = NULL;
544 	register struct passwd *pw;
545 	char delimchar;
546 	char *bp;
547 	char buf[MAXNAME + 2];
548 	char pvpbuf[PSBUFSIZE];
549 	extern struct passwd *getpwnam();
550 	extern char *FullName;
551 
552 	if (tTd(45, 1))
553 		printf("setsender(%s)\n", from == NULL ? "" : from);
554 
555 	/*
556 	**  Figure out the real user executing us.
557 	**	Username can return errno != 0 on non-errors.
558 	*/
559 
560 	if (bitset(EF_QUEUERUN, e->e_flags) || OpMode == MD_SMTP)
561 		realname = from;
562 	if (realname == NULL || realname[0] == '\0')
563 		realname = username();
564 
565 	if (ConfigLevel < 2)
566 		SuprErrs = TRUE;
567 
568 	delimchar = internal ? '\0' : ' ';
569 	e->e_from.q_flags = QBADADDR;
570 	if (from == NULL ||
571 	    parseaddr(from, &e->e_from, RF_COPYALL|RF_SENDERADDR,
572 		      delimchar, delimptr, e) == NULL ||
573 	    bitset(QBADADDR, e->e_from.q_flags) ||
574 	    e->e_from.q_mailer == ProgMailer ||
575 	    e->e_from.q_mailer == FileMailer ||
576 	    e->e_from.q_mailer == InclMailer)
577 	{
578 		/* log garbage addresses for traceback */
579 # ifdef LOG
580 		if (from != NULL && LogLevel > 2)
581 		{
582 			char *p;
583 			char ebuf[MAXNAME * 2 + 2];
584 
585 			p = macvalue('_', e);
586 			if (p == NULL)
587 			{
588 				char *host = RealHostName;
589 				if (host == NULL)
590 					host = MyHostName;
591 				(void) sprintf(ebuf, "%s@%s", realname, host);
592 				p = ebuf;
593 			}
594 			syslog(LOG_NOTICE,
595 				"setsender: %s: invalid or unparseable, received from %s",
596 				from, p);
597 		}
598 # endif /* LOG */
599 		if (from != NULL)
600 		{
601 			if (!bitset(QBADADDR, e->e_from.q_flags))
602 			{
603 				/* it was a bogus mailer in the from addr */
604 				usrerr("553 Invalid sender address");
605 			}
606 			SuprErrs = TRUE;
607 		}
608 		if (from == realname ||
609 		    parseaddr(from = newstr(realname), &e->e_from,
610 			      RF_COPYALL|RF_SENDERADDR, ' ', NULL, e) == NULL)
611 		{
612 			char nbuf[100];
613 
614 			SuprErrs = TRUE;
615 			expand("\201n", nbuf, &nbuf[sizeof nbuf], e);
616 			if (parseaddr(from = newstr(nbuf), &e->e_from,
617 				      RF_COPYALL, ' ', NULL, e) == NULL &&
618 			    parseaddr(from = "postmaster", &e->e_from,
619 			    	      RF_COPYALL, ' ', NULL, e) == NULL)
620 				syserr("553 setsender: can't even parse postmaster!");
621 		}
622 	}
623 	else
624 		FromFlag = TRUE;
625 	e->e_from.q_flags |= QDONTSEND;
626 	if (tTd(45, 5))
627 	{
628 		printf("setsender: QDONTSEND ");
629 		printaddr(&e->e_from, FALSE);
630 	}
631 	SuprErrs = FALSE;
632 
633 	pvp = NULL;
634 	if (e->e_from.q_mailer == LocalMailer)
635 	{
636 # ifdef USERDB
637 		register char *p;
638 		extern char *udbsender();
639 # endif
640 
641 		if (!internal)
642 		{
643 			/* if the user has given fullname already, don't redefine */
644 			if (FullName == NULL)
645 				FullName = macvalue('x', e);
646 			if (FullName != NULL && FullName[0] == '\0')
647 				FullName = NULL;
648 
649 # ifdef USERDB
650 			p = udbsender(e->e_from.q_user);
651 
652 			if (p != NULL)
653 			{
654 				/*
655 				**  We have an alternate address for the sender
656 				*/
657 
658 				pvp = prescan(p, '\0', pvpbuf, NULL);
659 			}
660 # endif /* USERDB */
661 		}
662 
663 		if ((pw = getpwnam(e->e_from.q_user)) != NULL)
664 		{
665 			/*
666 			**  Process passwd file entry.
667 			*/
668 
669 
670 			/* extract home directory */
671 			e->e_from.q_home = newstr(pw->pw_dir);
672 			define('z', e->e_from.q_home, e);
673 
674 			/* extract user and group id */
675 			e->e_from.q_uid = pw->pw_uid;
676 			e->e_from.q_gid = pw->pw_gid;
677 
678 			/* extract full name from passwd file */
679 			if (FullName == NULL && pw->pw_gecos != NULL &&
680 			    strcmp(pw->pw_name, e->e_from.q_user) == 0 &&
681 			    !internal)
682 			{
683 				buildfname(pw->pw_gecos, e->e_from.q_user, buf);
684 				if (buf[0] != '\0')
685 					FullName = newstr(buf);
686 			}
687 		}
688 		if (FullName != NULL && !internal)
689 			define('x', FullName, e);
690 	}
691 	else if (!internal)
692 	{
693 		if (e->e_from.q_home == NULL)
694 			e->e_from.q_home = getenv("HOME");
695 		e->e_from.q_uid = RealUid;
696 		e->e_from.q_gid = RealGid;
697 	}
698 
699 	/*
700 	**  Rewrite the from person to dispose of possible implicit
701 	**	links in the net.
702 	*/
703 
704 	if (pvp == NULL)
705 		pvp = prescan(from, delimchar, pvpbuf, NULL);
706 	if (pvp == NULL)
707 	{
708 		/* don't need to give error -- prescan did that already */
709 # ifdef LOG
710 		if (LogLevel > 2)
711 			syslog(LOG_NOTICE, "cannot prescan from (%s)", from);
712 # endif
713 		finis();
714 	}
715 	(void) rewrite(pvp, 3, e);
716 	(void) rewrite(pvp, 1, e);
717 	(void) rewrite(pvp, 4, e);
718 	bp = buf + 1;
719 	cataddr(pvp, NULL, bp, sizeof buf - 2, '\0');
720 	if (*bp == '@')
721 	{
722 		/* heuristic: route-addr: add angle brackets */
723 		strcat(bp, ">");
724 		*--bp = '<';
725 	}
726 	e->e_sender = newstr(bp);
727 	define('f', e->e_sender, e);
728 
729 	/* save the domain spec if this mailer wants it */
730 	if (!internal && e->e_from.q_mailer != NULL &&
731 	    bitnset(M_CANONICAL, e->e_from.q_mailer->m_flags))
732 	{
733 		extern char **copyplist();
734 
735 		while (*pvp != NULL && strcmp(*pvp, "@") != 0)
736 			pvp++;
737 		if (*pvp != NULL)
738 			e->e_fromdomain = copyplist(pvp, TRUE);
739 	}
740 }
741