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