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