envelope.c revision 168515
1/*
2 * Copyright (c) 1998-2003, 2006 Sendmail, Inc. and its suppliers.
3 *	All rights reserved.
4 * Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.
5 * Copyright (c) 1988, 1993
6 *	The Regents of the University of California.  All rights reserved.
7 *
8 * By using this file, you agree to the terms and conditions set
9 * forth in the LICENSE file which can be found at the top level of
10 * the sendmail distribution.
11 *
12 */
13
14#include <sendmail.h>
15
16SM_RCSID("@(#)$Id: envelope.c,v 8.302 2006/11/10 23:12:52 ca Exp $")
17
18/*
19**  CLRSESSENVELOPE -- clear session oriented data in an envelope
20**
21**	Parameters:
22**		e -- the envelope to clear.
23**
24**	Returns:
25**		none.
26*/
27
28void
29clrsessenvelope(e)
30	ENVELOPE *e;
31{
32#if SASL
33	macdefine(&e->e_macro, A_PERM, macid("{auth_type}"), "");
34	macdefine(&e->e_macro, A_PERM, macid("{auth_authen}"), "");
35	macdefine(&e->e_macro, A_PERM, macid("{auth_author}"), "");
36	macdefine(&e->e_macro, A_PERM, macid("{auth_ssf}"), "");
37#endif /* SASL */
38#if STARTTLS
39	macdefine(&e->e_macro, A_PERM, macid("{cert_issuer}"), "");
40	macdefine(&e->e_macro, A_PERM, macid("{cert_subject}"), "");
41	macdefine(&e->e_macro, A_PERM, macid("{cipher_bits}"), "");
42	macdefine(&e->e_macro, A_PERM, macid("{cipher}"), "");
43	macdefine(&e->e_macro, A_PERM, macid("{tls_version}"), "");
44	macdefine(&e->e_macro, A_PERM, macid("{verify}"), "");
45# if _FFR_TLS_1
46	macdefine(&e->e_macro, A_PERM, macid("{alg_bits}"), "");
47	macdefine(&e->e_macro, A_PERM, macid("{cn_issuer}"), "");
48	macdefine(&e->e_macro, A_PERM, macid("{cn_subject}"), "");
49# endif /* _FFR_TLS_1 */
50#endif /* STARTTLS */
51}
52
53/*
54**  NEWENVELOPE -- fill in a new envelope
55**
56**	Supports inheritance.
57**
58**	Parameters:
59**		e -- the new envelope to fill in.
60**		parent -- the envelope to be the parent of e.
61**		rpool -- either NULL, or a pointer to a resource pool
62**			from which envelope memory is allocated, and
63**			to which envelope resources are attached.
64**
65**	Returns:
66**		e.
67**
68**	Side Effects:
69**		none.
70*/
71
72ENVELOPE *
73newenvelope(e, parent, rpool)
74	register ENVELOPE *e;
75	register ENVELOPE *parent;
76	SM_RPOOL_T *rpool;
77{
78	int sendmode;
79
80	/*
81	**  This code used to read:
82	**	if (e == parent && e->e_parent != NULL)
83	**		parent = e->e_parent;
84	**  So if e == parent && e->e_parent == NULL then we would
85	**  set e->e_parent = e, which creates a loop in the e_parent chain.
86	**  This meant macvalue() could go into an infinite loop.
87	*/
88
89	if (parent != NULL)
90		sendmode = parent->e_sendmode;
91	else
92		sendmode = DM_NOTSET;
93
94	if (e == parent)
95		parent = e->e_parent;
96	clearenvelope(e, true, rpool);
97	if (e == CurEnv)
98		memmove((char *) &e->e_from,
99			(char *) &NullAddress,
100			sizeof(e->e_from));
101	else
102		memmove((char *) &e->e_from,
103			(char *) &CurEnv->e_from,
104			sizeof(e->e_from));
105	e->e_parent = parent;
106	assign_queueid(e);
107	e->e_ctime = curtime();
108	if (parent != NULL)
109	{
110		e->e_msgpriority = parent->e_msgsize;
111		if (parent->e_quarmsg == NULL)
112		{
113			e->e_quarmsg = NULL;
114			macdefine(&e->e_macro, A_PERM,
115				  macid("{quarantine}"), "");
116		}
117		else
118		{
119			e->e_quarmsg = sm_rpool_strdup_x(rpool,
120							 parent->e_quarmsg);
121			macdefine(&e->e_macro, A_PERM,
122				  macid("{quarantine}"), e->e_quarmsg);
123		}
124	}
125	e->e_puthdr = putheader;
126	e->e_putbody = putbody;
127	if (CurEnv->e_xfp != NULL)
128		(void) sm_io_flush(CurEnv->e_xfp, SM_TIME_DEFAULT);
129	if (sendmode != DM_NOTSET)
130		e->e_sendmode = sendmode;
131
132	return e;
133}
134
135/* values for msg_timeout, see also IS_* below for usage (bit layout) */
136#define MSG_T_O		0x01	/* normal timeout */
137#define MSG_T_O_NOW	0x02	/* NOW timeout */
138#define MSG_NOT_BY	0x04	/* Deliver-By time exceeded, mode R */
139#define MSG_WARN	0x10	/* normal queue warning */
140#define MSG_WARN_BY	0x20	/* Deliver-By time exceeded, mode N */
141
142#define IS_MSG_ERR(x)	(((x) & 0x0f) != 0)	/* return an error */
143
144/* immediate return */
145#define IS_IMM_RET(x)	(((x) & (MSG_T_O_NOW|MSG_NOT_BY)) != 0)
146#define IS_MSG_WARN(x)	(((x) & 0xf0) != 0)	/* return a warning */
147
148/*
149**  DROPENVELOPE -- deallocate an envelope.
150**
151**	Parameters:
152**		e -- the envelope to deallocate.
153**		fulldrop -- if set, do return receipts.
154**		split -- if true, split by recipient if message is queued up
155**
156**	Returns:
157**		none.
158**
159**	Side Effects:
160**		housekeeping necessary to dispose of an envelope.
161**		Unlocks this queue file.
162*/
163
164void
165dropenvelope(e, fulldrop, split)
166	register ENVELOPE *e;
167	bool fulldrop;
168	bool split;
169{
170	bool panic = false;
171	bool queueit = false;
172	int msg_timeout = 0;
173	bool failure_return = false;
174	bool delay_return = false;
175	bool success_return = false;
176	bool pmnotify = bitset(EF_PM_NOTIFY, e->e_flags);
177	bool done = false;
178	register ADDRESS *q;
179	char *id = e->e_id;
180	time_t now;
181	char buf[MAXLINE];
182
183	if (tTd(50, 1))
184	{
185		sm_dprintf("dropenvelope %p: id=", e);
186		xputs(sm_debug_file(), e->e_id);
187		sm_dprintf(", flags=");
188		printenvflags(e);
189		if (tTd(50, 10))
190		{
191			sm_dprintf("sendq=");
192			printaddr(sm_debug_file(), e->e_sendqueue, true);
193		}
194	}
195
196	if (LogLevel > 84)
197		sm_syslog(LOG_DEBUG, id,
198			  "dropenvelope, e_flags=0x%lx, OpMode=%c, pid=%d",
199			  e->e_flags, OpMode, (int) CurrentPid);
200
201	/* we must have an id to remove disk files */
202	if (id == NULL)
203		return;
204
205	/* if verify-only mode, we can skip most of this */
206	if (OpMode == MD_VERIFY)
207		goto simpledrop;
208
209	if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags))
210		logsender(e, NULL);
211	e->e_flags &= ~EF_LOGSENDER;
212
213	/* post statistics */
214	poststats(StatFile);
215
216	/*
217	**  Extract state information from dregs of send list.
218	*/
219
220	now = curtime();
221	if (now >= e->e_ctime + TimeOuts.to_q_return[e->e_timeoutclass])
222		msg_timeout = MSG_T_O;
223	if (IS_DLVR_RETURN(e) && e->e_deliver_by > 0 &&
224	    now >= e->e_ctime + e->e_deliver_by &&
225	    !bitset(EF_RESPONSE, e->e_flags))
226	{
227		msg_timeout = MSG_NOT_BY;
228		e->e_flags |= EF_FATALERRS|EF_CLRQUEUE;
229	}
230	else if (TimeOuts.to_q_return[e->e_timeoutclass] == NOW &&
231		 !bitset(EF_RESPONSE, e->e_flags))
232	{
233		msg_timeout = MSG_T_O_NOW;
234		e->e_flags |= EF_FATALERRS|EF_CLRQUEUE;
235	}
236
237	e->e_flags &= ~EF_QUEUERUN;
238	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
239	{
240		if (QS_IS_UNDELIVERED(q->q_state))
241			queueit = true;
242
243		/* see if a notification is needed */
244		if (bitset(QPINGONFAILURE, q->q_flags) &&
245		    ((IS_MSG_ERR(msg_timeout) &&
246		      QS_IS_UNDELIVERED(q->q_state)) ||
247		     QS_IS_BADADDR(q->q_state) ||
248		     IS_IMM_RET(msg_timeout)))
249		{
250			failure_return = true;
251			if (!done && q->q_owner == NULL &&
252			    !emptyaddr(&e->e_from))
253			{
254				(void) sendtolist(e->e_from.q_paddr, NULLADDR,
255						  &e->e_errorqueue, 0, e);
256				done = true;
257			}
258		}
259		else if ((bitset(QPINGONSUCCESS, q->q_flags) &&
260			  ((QS_IS_SENT(q->q_state) &&
261			    bitnset(M_LOCALMAILER, q->q_mailer->m_flags)) ||
262			   bitset(QRELAYED|QEXPANDED|QDELIVERED, q->q_flags))) ||
263			  bitset(QBYTRACE, q->q_flags) ||
264			  bitset(QBYNRELAY, q->q_flags))
265		{
266			success_return = true;
267		}
268	}
269
270	if (e->e_class < 0)
271		e->e_flags |= EF_NO_BODY_RETN;
272
273	/*
274	**  See if the message timed out.
275	*/
276
277	if (!queueit)
278		/* EMPTY */
279		/* nothing to do */ ;
280	else if (IS_MSG_ERR(msg_timeout))
281	{
282		if (failure_return)
283		{
284			if (msg_timeout == MSG_NOT_BY)
285			{
286				(void) sm_snprintf(buf, sizeof(buf),
287					"delivery time expired %lds",
288					e->e_deliver_by);
289			}
290			else
291			{
292				(void) sm_snprintf(buf, sizeof(buf),
293					"Cannot send message for %s",
294					pintvl(TimeOuts.to_q_return[e->e_timeoutclass],
295						false));
296			}
297
298			/* don't free, allocated from e_rpool */
299			e->e_message = sm_rpool_strdup_x(e->e_rpool, buf);
300			message(buf);
301			e->e_flags |= EF_CLRQUEUE;
302		}
303		if (msg_timeout == MSG_NOT_BY)
304		{
305			(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
306				"Delivery time (%lds) expired\n",
307				e->e_deliver_by);
308		}
309		else
310			(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
311				"Message could not be delivered for %s\n",
312				pintvl(TimeOuts.to_q_return[e->e_timeoutclass],
313					false));
314		(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
315			"Message will be deleted from queue\n");
316		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
317		{
318			if (QS_IS_UNDELIVERED(q->q_state))
319			{
320				q->q_state = QS_BADADDR;
321				if (msg_timeout == MSG_NOT_BY)
322					q->q_status = "5.4.7";
323				else
324					q->q_status = "4.4.7";
325			}
326		}
327	}
328	else
329	{
330		if (TimeOuts.to_q_warning[e->e_timeoutclass] > 0 &&
331		    now >= e->e_ctime +
332				TimeOuts.to_q_warning[e->e_timeoutclass])
333			msg_timeout = MSG_WARN;
334		else if (IS_DLVR_NOTIFY(e) &&
335			 e->e_deliver_by > 0 &&
336			 now >= e->e_ctime + e->e_deliver_by)
337			msg_timeout = MSG_WARN_BY;
338
339		if (IS_MSG_WARN(msg_timeout))
340		{
341			if (!bitset(EF_WARNING|EF_RESPONSE, e->e_flags) &&
342			    e->e_class >= 0 &&
343			    e->e_from.q_paddr != NULL &&
344			    strcmp(e->e_from.q_paddr, "<>") != 0 &&
345			    sm_strncasecmp(e->e_from.q_paddr, "owner-", 6) != 0 &&
346			    (strlen(e->e_from.q_paddr) <= 8 ||
347			     sm_strcasecmp(&e->e_from.q_paddr[strlen(e->e_from.q_paddr) - 8],
348					   "-request") != 0))
349			{
350				for (q = e->e_sendqueue; q != NULL;
351				     q = q->q_next)
352				{
353					if (QS_IS_UNDELIVERED(q->q_state)
354#if _FFR_NODELAYDSN_ON_HOLD
355					    && !bitnset(M_HOLD,
356							q->q_mailer->m_flags)
357#endif /* _FFR_NODELAYDSN_ON_HOLD */
358					   )
359					{
360						if (msg_timeout ==
361						    MSG_WARN_BY &&
362						    (bitset(QPINGONDELAY,
363							    q->q_flags) ||
364						    !bitset(QHASNOTIFY,
365							    q->q_flags))
366						   )
367						{
368							q->q_flags |= QBYNDELAY;
369							delay_return = true;
370						}
371						if (bitset(QPINGONDELAY,
372							   q->q_flags))
373						{
374							q->q_flags |= QDELAYED;
375							delay_return = true;
376						}
377					}
378				}
379			}
380			if (delay_return)
381			{
382				if (msg_timeout == MSG_WARN_BY)
383				{
384					(void) sm_snprintf(buf, sizeof(buf),
385						"Warning: Delivery time (%lds) exceeded",
386						e->e_deliver_by);
387				}
388				else
389					(void) sm_snprintf(buf, sizeof(buf),
390						"Warning: could not send message for past %s",
391						pintvl(TimeOuts.to_q_warning[e->e_timeoutclass],
392							false));
393
394				/* don't free, allocated from e_rpool */
395				e->e_message = sm_rpool_strdup_x(e->e_rpool,
396								 buf);
397				message(buf);
398				e->e_flags |= EF_WARNING;
399			}
400			if (msg_timeout == MSG_WARN_BY)
401			{
402				(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
403					"Warning: Delivery time (%lds) exceeded\n",
404					e->e_deliver_by);
405			}
406			else
407				(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
408					"Warning: message still undelivered after %s\n",
409					pintvl(TimeOuts.to_q_warning[e->e_timeoutclass],
410					     false));
411			(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
412				      "Will keep trying until message is %s old\n",
413				      pintvl(TimeOuts.to_q_return[e->e_timeoutclass],
414					     false));
415		}
416	}
417
418	if (tTd(50, 2))
419		sm_dprintf("failure_return=%d delay_return=%d success_return=%d queueit=%d\n",
420			failure_return, delay_return, success_return, queueit);
421
422	/*
423	**  If we had some fatal error, but no addresses are marked as
424	**  bad, mark them _all_ as bad.
425	*/
426
427	if (bitset(EF_FATALERRS, e->e_flags) && !failure_return)
428	{
429		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
430		{
431			if ((QS_IS_OK(q->q_state) ||
432			     QS_IS_VERIFIED(q->q_state)) &&
433			    bitset(QPINGONFAILURE, q->q_flags))
434			{
435				failure_return = true;
436				q->q_state = QS_BADADDR;
437			}
438		}
439	}
440
441	/*
442	**  Send back return receipts as requested.
443	*/
444
445	if (success_return && !failure_return && !delay_return && fulldrop &&
446	    !bitset(PRIV_NORECEIPTS, PrivacyFlags) &&
447	    strcmp(e->e_from.q_paddr, "<>") != 0)
448	{
449		auto ADDRESS *rlist = NULL;
450
451		if (tTd(50, 8))
452			sm_dprintf("dropenvelope(%s): sending return receipt\n",
453				id);
454		e->e_flags |= EF_SENDRECEIPT;
455		(void) sendtolist(e->e_from.q_paddr, NULLADDR, &rlist, 0, e);
456		(void) returntosender("Return receipt", rlist, RTSF_NO_BODY, e);
457	}
458	e->e_flags &= ~EF_SENDRECEIPT;
459
460	/*
461	**  Arrange to send error messages if there are fatal errors.
462	*/
463
464	if ((failure_return || delay_return) && e->e_errormode != EM_QUIET)
465	{
466		if (tTd(50, 8))
467			sm_dprintf("dropenvelope(%s): saving mail\n", id);
468		panic = savemail(e, !bitset(EF_NO_BODY_RETN, e->e_flags));
469	}
470
471	/*
472	**  Arrange to send warning messages to postmaster as requested.
473	*/
474
475	if ((failure_return || pmnotify) &&
476	    PostMasterCopy != NULL &&
477	    !bitset(EF_RESPONSE, e->e_flags) &&
478	    e->e_class >= 0)
479	{
480		auto ADDRESS *rlist = NULL;
481		char pcopy[MAXNAME];
482
483		if (failure_return)
484		{
485			expand(PostMasterCopy, pcopy, sizeof(pcopy), e);
486
487			if (tTd(50, 8))
488				sm_dprintf("dropenvelope(%s): sending postmaster copy to %s\n",
489					id, pcopy);
490			(void) sendtolist(pcopy, NULLADDR, &rlist, 0, e);
491		}
492		if (pmnotify)
493			(void) sendtolist("postmaster", NULLADDR,
494					  &rlist, 0, e);
495		(void) returntosender(e->e_message, rlist,
496				      RTSF_PM_BOUNCE|RTSF_NO_BODY, e);
497	}
498
499	/*
500	**  Instantiate or deinstantiate the queue.
501	*/
502
503simpledrop:
504	if (tTd(50, 8))
505		sm_dprintf("dropenvelope(%s): at simpledrop, queueit=%d\n",
506			id, queueit);
507	if (!queueit || bitset(EF_CLRQUEUE, e->e_flags))
508	{
509		if (tTd(50, 1))
510		{
511			sm_dprintf("\n===== Dropping queue files for %s... queueit=%d, e_flags=",
512				e->e_id, queueit);
513			printenvflags(e);
514		}
515		if (!panic)
516		{
517			if (e->e_dfp != NULL)
518			{
519				(void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
520				e->e_dfp = NULL;
521			}
522			(void) xunlink(queuename(e, DATAFL_LETTER));
523		}
524		if (panic && QueueMode == QM_LOST)
525		{
526			/*
527			**  leave the Qf file behind as
528			**  the delivery attempt failed.
529			*/
530
531			/* EMPTY */
532		}
533		else
534		if (xunlink(queuename(e, ANYQFL_LETTER)) == 0)
535		{
536			/* add to available space in filesystem */
537			updfs(e, -1, panic ? 0 : -1, "dropenvelope");
538		}
539
540		if (e->e_ntries > 0 && LogLevel > 9)
541			sm_syslog(LOG_INFO, id, "done; delay=%s, ntries=%d",
542				  pintvl(curtime() - e->e_ctime, true),
543				  e->e_ntries);
544	}
545	else if (queueit || !bitset(EF_INQUEUE, e->e_flags))
546	{
547		if (!split)
548			queueup(e, false, true);
549		else
550		{
551			ENVELOPE *oldsib;
552			ENVELOPE *ee;
553
554			/*
555			**  Save old sibling and set it to NULL to avoid
556			**  queueing up the same envelopes again.
557			**  This requires that envelopes in that list have
558			**  been take care of before (or at some other place).
559			*/
560
561			oldsib = e->e_sibling;
562			e->e_sibling = NULL;
563			if (!split_by_recipient(e) &&
564			    bitset(EF_FATALERRS, e->e_flags))
565			{
566				syserr("!dropenvelope(%s): cannot commit data file %s, uid=%d",
567					e->e_id, queuename(e, DATAFL_LETTER),
568					(int) geteuid());
569			}
570			for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
571				queueup(ee, false, true);
572			queueup(e, false, true);
573
574			/* clean up */
575			for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
576			{
577				/* now unlock the job */
578				if (tTd(50, 8))
579					sm_dprintf("dropenvelope(%s): unlocking job\n",
580						   ee->e_id);
581				closexscript(ee);
582				unlockqueue(ee);
583
584				/* this envelope is marked unused */
585				if (ee->e_dfp != NULL)
586				{
587					(void) sm_io_close(ee->e_dfp,
588							   SM_TIME_DEFAULT);
589					ee->e_dfp = NULL;
590				}
591				ee->e_id = NULL;
592				ee->e_flags &= ~EF_HAS_DF;
593			}
594			e->e_sibling = oldsib;
595		}
596	}
597
598	/* now unlock the job */
599	if (tTd(50, 8))
600		sm_dprintf("dropenvelope(%s): unlocking job\n", id);
601	closexscript(e);
602	unlockqueue(e);
603
604	/* make sure that this envelope is marked unused */
605	if (e->e_dfp != NULL)
606	{
607		(void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
608		e->e_dfp = NULL;
609	}
610	e->e_id = NULL;
611	e->e_flags &= ~EF_HAS_DF;
612}
613/*
614**  CLEARENVELOPE -- clear an envelope without unlocking
615**
616**	This is normally used by a child process to get a clean
617**	envelope without disturbing the parent.
618**
619**	Parameters:
620**		e -- the envelope to clear.
621**		fullclear - if set, the current envelope is total
622**			garbage and should be ignored; otherwise,
623**			release any resources it may indicate.
624**		rpool -- either NULL, or a pointer to a resource pool
625**			from which envelope memory is allocated, and
626**			to which envelope resources are attached.
627**
628**	Returns:
629**		none.
630**
631**	Side Effects:
632**		Closes files associated with the envelope.
633**		Marks the envelope as unallocated.
634*/
635
636void
637clearenvelope(e, fullclear, rpool)
638	register ENVELOPE *e;
639	bool fullclear;
640	SM_RPOOL_T *rpool;
641{
642	register HDR *bh;
643	register HDR **nhp;
644	extern ENVELOPE BlankEnvelope;
645	char **p;
646
647	if (!fullclear)
648	{
649		/* clear out any file information */
650		if (e->e_xfp != NULL)
651			(void) sm_io_close(e->e_xfp, SM_TIME_DEFAULT);
652		if (e->e_dfp != NULL)
653			(void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
654		e->e_xfp = e->e_dfp = NULL;
655	}
656
657	/*
658	**  Copy BlankEnvelope into *e.
659	**  It is not safe to simply copy pointers to strings;
660	**  the strings themselves must be copied (or set to NULL).
661	**  The problem is that when we assign a new string value to
662	**  a member of BlankEnvelope, we free the old string.
663	**  We did not need to do this copying in sendmail 8.11 :-(
664	**  and it is a potential performance hit.  Reference counted
665	**  strings are one way out.
666	*/
667
668	*e = BlankEnvelope;
669	e->e_message = NULL;
670	e->e_qfletter = '\0';
671	e->e_quarmsg = NULL;
672	macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), "");
673
674	/*
675	**  Copy the macro table.
676	**  We might be able to avoid this by zeroing the macro table
677	**  and always searching BlankEnvelope.e_macro after e->e_macro
678	**  in macvalue().
679	*/
680
681	for (p = &e->e_macro.mac_table[0];
682	     p <= &e->e_macro.mac_table[MAXMACROID];
683	     ++p)
684	{
685		if (*p != NULL)
686			*p = sm_rpool_strdup_x(rpool, *p);
687	}
688
689	/*
690	**  XXX There are many strings in the envelope structure
691	**  XXX that we are not attempting to copy here.
692	**  XXX Investigate this further.
693	*/
694
695	e->e_rpool = rpool;
696	e->e_macro.mac_rpool = rpool;
697	if (Verbose)
698		set_delivery_mode(SM_DELIVER, e);
699	bh = BlankEnvelope.e_header;
700	nhp = &e->e_header;
701	while (bh != NULL)
702	{
703		*nhp = (HDR *) sm_rpool_malloc_x(rpool, sizeof(*bh));
704		memmove((char *) *nhp, (char *) bh, sizeof(*bh));
705		bh = bh->h_link;
706		nhp = &(*nhp)->h_link;
707	}
708}
709/*
710**  INITSYS -- initialize instantiation of system
711**
712**	In Daemon mode, this is done in the child.
713**
714**	Parameters:
715**		e -- the envelope to use.
716**
717**	Returns:
718**		none.
719**
720**	Side Effects:
721**		Initializes the system macros, some global variables,
722**		etc.  In particular, the current time in various
723**		forms is set.
724*/
725
726void
727initsys(e)
728	register ENVELOPE *e;
729{
730	char buf[10];
731#ifdef TTYNAME
732	static char ybuf[60];			/* holds tty id */
733	register char *p;
734	extern char *ttyname();
735#endif /* TTYNAME */
736
737	/*
738	**  Give this envelope a reality.
739	**	I.e., an id, a transcript, and a creation time.
740	**  We don't select the queue until all of the recipients are known.
741	*/
742
743	openxscript(e);
744	e->e_ctime = curtime();
745	e->e_qfletter = '\0';
746
747	/*
748	**  Set OutChannel to something useful if stdout isn't it.
749	**	This arranges that any extra stuff the mailer produces
750	**	gets sent back to the user on error (because it is
751	**	tucked away in the transcript).
752	*/
753
754	if (OpMode == MD_DAEMON && bitset(EF_QUEUERUN, e->e_flags) &&
755	    e->e_xfp != NULL)
756		OutChannel = e->e_xfp;
757
758	/*
759	**  Set up some basic system macros.
760	*/
761
762	/* process id */
763	(void) sm_snprintf(buf, sizeof(buf), "%d", (int) CurrentPid);
764	macdefine(&e->e_macro, A_TEMP, 'p', buf);
765
766	/* hop count */
767	(void) sm_snprintf(buf, sizeof(buf), "%d", e->e_hopcount);
768	macdefine(&e->e_macro, A_TEMP, 'c', buf);
769
770	/* time as integer, unix time, arpa time */
771	settime(e);
772
773	/* Load average */
774	sm_getla();
775
776#ifdef TTYNAME
777	/* tty name */
778	if (macvalue('y', e) == NULL)
779	{
780		p = ttyname(2);
781		if (p != NULL)
782		{
783			if (strrchr(p, '/') != NULL)
784				p = strrchr(p, '/') + 1;
785			(void) sm_strlcpy(ybuf, sizeof(ybuf), p);
786			macdefine(&e->e_macro, A_PERM, 'y', ybuf);
787		}
788	}
789#endif /* TTYNAME */
790}
791/*
792**  SETTIME -- set the current time.
793**
794**	Parameters:
795**		e -- the envelope in which the macros should be set.
796**
797**	Returns:
798**		none.
799**
800**	Side Effects:
801**		Sets the various time macros -- $a, $b, $d, $t.
802*/
803
804void
805settime(e)
806	register ENVELOPE *e;
807{
808	register char *p;
809	auto time_t now;
810	char buf[30];
811	register struct tm *tm;
812
813	now = curtime();
814	(void) sm_snprintf(buf, sizeof(buf), "%ld", (long) now);
815	macdefine(&e->e_macro, A_TEMP, macid("{time}"), buf);
816	tm = gmtime(&now);
817	(void) sm_snprintf(buf, sizeof(buf), "%04d%02d%02d%02d%02d",
818			   tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
819			   tm->tm_hour, tm->tm_min);
820	macdefine(&e->e_macro, A_TEMP, 't', buf);
821	(void) sm_strlcpy(buf, ctime(&now), sizeof(buf));
822	p = strchr(buf, '\n');
823	if (p != NULL)
824		*p = '\0';
825	macdefine(&e->e_macro, A_TEMP, 'd', buf);
826	macdefine(&e->e_macro, A_TEMP, 'b', arpadate(buf));
827	if (macvalue('a', e) == NULL)
828		macdefine(&e->e_macro, A_PERM, 'a', macvalue('b', e));
829}
830/*
831**  OPENXSCRIPT -- Open transcript file
832**
833**	Creates a transcript file for possible eventual mailing or
834**	sending back.
835**
836**	Parameters:
837**		e -- the envelope to create the transcript in/for.
838**
839**	Returns:
840**		none
841**
842**	Side Effects:
843**		Creates the transcript file.
844*/
845
846#ifndef O_APPEND
847# define O_APPEND	0
848#endif /* ! O_APPEND */
849
850void
851openxscript(e)
852	register ENVELOPE *e;
853{
854	register char *p;
855
856	if (e->e_xfp != NULL)
857		return;
858
859#if 0
860	if (e->e_lockfp == NULL && bitset(EF_INQUEUE, e->e_flags))
861		syserr("openxscript: job not locked");
862#endif /* 0 */
863
864	p = queuename(e, XSCRPT_LETTER);
865	e->e_xfp = bfopen(p, FileMode, XscriptFileBufferSize,
866			  SFF_NOTEXCL|SFF_OPENASROOT);
867
868	if (e->e_xfp == NULL)
869	{
870		syserr("Can't create transcript file %s", p);
871		e->e_xfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT,
872				      SM_PATH_DEVNULL, SM_IO_RDWR, NULL);
873		if (e->e_xfp == NULL)
874			syserr("!Can't open %s", SM_PATH_DEVNULL);
875	}
876	(void) sm_io_setvbuf(e->e_xfp, SM_TIME_DEFAULT, NULL, SM_IO_LBF, 0);
877	if (tTd(46, 9))
878	{
879		sm_dprintf("openxscript(%s):\n  ", p);
880		dumpfd(sm_io_getinfo(e->e_xfp, SM_IO_WHAT_FD, NULL), true,
881		       false);
882	}
883}
884/*
885**  CLOSEXSCRIPT -- close the transcript file.
886**
887**	Parameters:
888**		e -- the envelope containing the transcript to close.
889**
890**	Returns:
891**		none.
892**
893**	Side Effects:
894**		none.
895*/
896
897void
898closexscript(e)
899	register ENVELOPE *e;
900{
901	if (e->e_xfp == NULL)
902		return;
903#if 0
904	if (e->e_lockfp == NULL)
905		syserr("closexscript: job not locked");
906#endif /* 0 */
907	(void) sm_io_close(e->e_xfp, SM_TIME_DEFAULT);
908	e->e_xfp = NULL;
909}
910/*
911**  SETSENDER -- set the person who this message is from
912**
913**	Under certain circumstances allow the user to say who
914**	s/he is (using -f or -r).  These are:
915**	1.  The user's uid is zero (root).
916**	2.  The user's login name is in an approved list (typically
917**	    from a network server).
918**	3.  The address the user is trying to claim has a
919**	    "!" character in it (since #2 doesn't do it for
920**	    us if we are dialing out for UUCP).
921**	A better check to replace #3 would be if the
922**	effective uid is "UUCP" -- this would require me
923**	to rewrite getpwent to "grab" uucp as it went by,
924**	make getname more nasty, do another passwd file
925**	scan, or compile the UID of "UUCP" into the code,
926**	all of which are reprehensible.
927**
928**	Assuming all of these fail, we figure out something
929**	ourselves.
930**
931**	Parameters:
932**		from -- the person we would like to believe this message
933**			is from, as specified on the command line.
934**		e -- the envelope in which we would like the sender set.
935**		delimptr -- if non-NULL, set to the location of the
936**			trailing delimiter.
937**		delimchar -- the character that will delimit the sender
938**			address.
939**		internal -- set if this address is coming from an internal
940**			source such as an owner alias.
941**
942**	Returns:
943**		none.
944**
945**	Side Effects:
946**		sets sendmail's notion of who the from person is.
947*/
948
949void
950setsender(from, e, delimptr, delimchar, internal)
951	char *from;
952	register ENVELOPE *e;
953	char **delimptr;
954	int delimchar;
955	bool internal;
956{
957	register char **pvp;
958	char *realname = NULL;
959	char *bp;
960	char buf[MAXNAME + 2];
961	char pvpbuf[PSBUFSIZE];
962	extern char *FullName;
963
964	if (tTd(45, 1))
965		sm_dprintf("setsender(%s)\n", from == NULL ? "" : from);
966
967	/* may be set from earlier calls */
968	macdefine(&e->e_macro, A_PERM, 'x', "");
969
970	/*
971	**  Figure out the real user executing us.
972	**	Username can return errno != 0 on non-errors.
973	*/
974
975	if (bitset(EF_QUEUERUN, e->e_flags) || OpMode == MD_SMTP ||
976	    OpMode == MD_ARPAFTP || OpMode == MD_DAEMON)
977		realname = from;
978	if (realname == NULL || realname[0] == '\0')
979		realname = username();
980
981	if (ConfigLevel < 2)
982		SuprErrs = true;
983
984	macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e s");
985
986	/* preset state for then clause in case from == NULL */
987	e->e_from.q_state = QS_BADADDR;
988	e->e_from.q_flags = 0;
989	if (from == NULL ||
990	    parseaddr(from, &e->e_from, RF_COPYALL|RF_SENDERADDR,
991		      delimchar, delimptr, e, false) == NULL ||
992	    QS_IS_BADADDR(e->e_from.q_state) ||
993	    e->e_from.q_mailer == ProgMailer ||
994	    e->e_from.q_mailer == FileMailer ||
995	    e->e_from.q_mailer == InclMailer)
996	{
997		/* log garbage addresses for traceback */
998		if (from != NULL && LogLevel > 2)
999		{
1000			char *p;
1001			char ebuf[MAXNAME * 2 + 2];
1002
1003			p = macvalue('_', e);
1004			if (p == NULL)
1005			{
1006				char *host = RealHostName;
1007
1008				if (host == NULL)
1009					host = MyHostName;
1010				(void) sm_snprintf(ebuf, sizeof(ebuf),
1011						   "%.*s@%.*s", MAXNAME,
1012						   realname, MAXNAME, host);
1013				p = ebuf;
1014			}
1015			sm_syslog(LOG_NOTICE, e->e_id,
1016				  "setsender: %s: invalid or unparsable, received from %s",
1017				  shortenstring(from, 83), p);
1018		}
1019		if (from != NULL)
1020		{
1021			if (!QS_IS_BADADDR(e->e_from.q_state))
1022			{
1023				/* it was a bogus mailer in the from addr */
1024				e->e_status = "5.1.7";
1025				usrerrenh(e->e_status,
1026					  "553 Invalid sender address");
1027			}
1028			SuprErrs = true;
1029		}
1030		if (from == realname ||
1031		    parseaddr(from = realname,
1032			      &e->e_from, RF_COPYALL|RF_SENDERADDR, ' ',
1033			      NULL, e, false) == NULL)
1034		{
1035			char nbuf[100];
1036
1037			SuprErrs = true;
1038			expand("\201n", nbuf, sizeof(nbuf), e);
1039			from = sm_rpool_strdup_x(e->e_rpool, nbuf);
1040			if (parseaddr(from, &e->e_from, RF_COPYALL, ' ',
1041				      NULL, e, false) == NULL &&
1042			    parseaddr(from = "postmaster", &e->e_from,
1043				      RF_COPYALL, ' ', NULL, e, false) == NULL)
1044				syserr("553 5.3.0 setsender: can't even parse postmaster!");
1045		}
1046	}
1047	else
1048		FromFlag = true;
1049	e->e_from.q_state = QS_SENDER;
1050	if (tTd(45, 5))
1051	{
1052		sm_dprintf("setsender: QS_SENDER ");
1053		printaddr(sm_debug_file(), &e->e_from, false);
1054	}
1055	SuprErrs = false;
1056
1057#if USERDB
1058	if (bitnset(M_CHECKUDB, e->e_from.q_mailer->m_flags))
1059	{
1060		register char *p;
1061
1062		p = udbsender(e->e_from.q_user, e->e_rpool);
1063		if (p != NULL)
1064			from = p;
1065	}
1066#endif /* USERDB */
1067
1068	if (bitnset(M_HASPWENT, e->e_from.q_mailer->m_flags))
1069	{
1070		SM_MBDB_T user;
1071
1072		if (!internal)
1073		{
1074			/* if the user already given fullname don't redefine */
1075			if (FullName == NULL)
1076				FullName = macvalue('x', e);
1077			if (FullName != NULL)
1078			{
1079				if (FullName[0] == '\0')
1080					FullName = NULL;
1081				else
1082					FullName = newstr(FullName);
1083			}
1084		}
1085
1086		if (e->e_from.q_user[0] != '\0' &&
1087		    sm_mbdb_lookup(e->e_from.q_user, &user) == EX_OK)
1088		{
1089			/*
1090			**  Process passwd file entry.
1091			*/
1092
1093			/* extract home directory */
1094			if (*user.mbdb_homedir == '\0')
1095				e->e_from.q_home = NULL;
1096			else if (strcmp(user.mbdb_homedir, "/") == 0)
1097				e->e_from.q_home = "";
1098			else
1099				e->e_from.q_home = sm_rpool_strdup_x(e->e_rpool,
1100							user.mbdb_homedir);
1101			macdefine(&e->e_macro, A_PERM, 'z', e->e_from.q_home);
1102
1103			/* extract user and group id */
1104			if (user.mbdb_uid != SM_NO_UID)
1105			{
1106				e->e_from.q_uid = user.mbdb_uid;
1107				e->e_from.q_gid = user.mbdb_gid;
1108				e->e_from.q_flags |= QGOODUID;
1109			}
1110
1111			/* extract full name from passwd file */
1112			if (FullName == NULL && !internal &&
1113			    user.mbdb_fullname[0] != '\0' &&
1114			    strcmp(user.mbdb_name, e->e_from.q_user) == 0)
1115			{
1116				FullName = newstr(user.mbdb_fullname);
1117			}
1118		}
1119		else
1120		{
1121			e->e_from.q_home = NULL;
1122		}
1123		if (FullName != NULL && !internal)
1124			macdefine(&e->e_macro, A_TEMP, 'x', FullName);
1125	}
1126	else if (!internal && OpMode != MD_DAEMON && OpMode != MD_SMTP)
1127	{
1128		if (e->e_from.q_home == NULL)
1129		{
1130			e->e_from.q_home = getenv("HOME");
1131			if (e->e_from.q_home != NULL)
1132			{
1133				if (*e->e_from.q_home == '\0')
1134					e->e_from.q_home = NULL;
1135				else if (strcmp(e->e_from.q_home, "/") == 0)
1136					e->e_from.q_home++;
1137			}
1138		}
1139		e->e_from.q_uid = RealUid;
1140		e->e_from.q_gid = RealGid;
1141		e->e_from.q_flags |= QGOODUID;
1142	}
1143
1144	/*
1145	**  Rewrite the from person to dispose of possible implicit
1146	**	links in the net.
1147	*/
1148
1149	pvp = prescan(from, delimchar, pvpbuf, sizeof(pvpbuf), NULL,
1150			IntTokenTab, false);
1151	if (pvp == NULL)
1152	{
1153		/* don't need to give error -- prescan did that already */
1154		if (LogLevel > 2)
1155			sm_syslog(LOG_NOTICE, e->e_id,
1156				  "cannot prescan from (%s)",
1157				  shortenstring(from, MAXSHORTSTR));
1158		finis(true, true, ExitStat);
1159	}
1160	(void) REWRITE(pvp, 3, e);
1161	(void) REWRITE(pvp, 1, e);
1162	(void) REWRITE(pvp, 4, e);
1163	macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
1164	bp = buf + 1;
1165	cataddr(pvp, NULL, bp, sizeof(buf) - 2, '\0', false);
1166	if (*bp == '@' && !bitnset(M_NOBRACKET, e->e_from.q_mailer->m_flags))
1167	{
1168		/* heuristic: route-addr: add angle brackets */
1169		(void) sm_strlcat(bp, ">", sizeof(buf) - 1);
1170		*--bp = '<';
1171	}
1172	e->e_sender = sm_rpool_strdup_x(e->e_rpool, bp);
1173	macdefine(&e->e_macro, A_PERM, 'f', e->e_sender);
1174
1175	/* save the domain spec if this mailer wants it */
1176	if (e->e_from.q_mailer != NULL &&
1177	    bitnset(M_CANONICAL, e->e_from.q_mailer->m_flags))
1178	{
1179		char **lastat;
1180
1181		/* get rid of any pesky angle brackets */
1182		macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e s");
1183		(void) REWRITE(pvp, 3, e);
1184		(void) REWRITE(pvp, 1, e);
1185		(void) REWRITE(pvp, 4, e);
1186		macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
1187
1188		/* strip off to the last "@" sign */
1189		for (lastat = NULL; *pvp != NULL; pvp++)
1190		{
1191			if (strcmp(*pvp, "@") == 0)
1192				lastat = pvp;
1193		}
1194		if (lastat != NULL)
1195		{
1196			e->e_fromdomain = copyplist(lastat, true, e->e_rpool);
1197			if (tTd(45, 3))
1198			{
1199				sm_dprintf("Saving from domain: ");
1200				printav(sm_debug_file(), e->e_fromdomain);
1201			}
1202		}
1203	}
1204}
1205/*
1206**  PRINTENVFLAGS -- print envelope flags for debugging
1207**
1208**	Parameters:
1209**		e -- the envelope with the flags to be printed.
1210**
1211**	Returns:
1212**		none.
1213*/
1214
1215struct eflags
1216{
1217	char		*ef_name;
1218	unsigned long	ef_bit;
1219};
1220
1221static struct eflags	EnvelopeFlags[] =
1222{
1223	{ "OLDSTYLE",		EF_OLDSTYLE	},
1224	{ "INQUEUE",		EF_INQUEUE	},
1225	{ "NO_BODY_RETN",	EF_NO_BODY_RETN	},
1226	{ "CLRQUEUE",		EF_CLRQUEUE	},
1227	{ "SENDRECEIPT",	EF_SENDRECEIPT	},
1228	{ "FATALERRS",		EF_FATALERRS	},
1229	{ "DELETE_BCC",		EF_DELETE_BCC	},
1230	{ "RESPONSE",		EF_RESPONSE	},
1231	{ "RESENT",		EF_RESENT	},
1232	{ "VRFYONLY",		EF_VRFYONLY	},
1233	{ "WARNING",		EF_WARNING	},
1234	{ "QUEUERUN",		EF_QUEUERUN	},
1235	{ "GLOBALERRS",		EF_GLOBALERRS	},
1236	{ "PM_NOTIFY",		EF_PM_NOTIFY	},
1237	{ "METOO",		EF_METOO	},
1238	{ "LOGSENDER",		EF_LOGSENDER	},
1239	{ "NORECEIPT",		EF_NORECEIPT	},
1240	{ "HAS8BIT",		EF_HAS8BIT	},
1241	{ "NL_NOT_EOL",		EF_NL_NOT_EOL	},
1242	{ "CRLF_NOT_EOL",	EF_CRLF_NOT_EOL	},
1243	{ "RET_PARAM",		EF_RET_PARAM	},
1244	{ "HAS_DF",		EF_HAS_DF	},
1245	{ "IS_MIME",		EF_IS_MIME	},
1246	{ "DONT_MIME",		EF_DONT_MIME	},
1247	{ "DISCARD",		EF_DISCARD	},
1248	{ "TOOBIG",		EF_TOOBIG	},
1249	{ "SPLIT",		EF_SPLIT	},
1250	{ "UNSAFE",		EF_UNSAFE	},
1251	{ NULL,			0		}
1252};
1253
1254void
1255printenvflags(e)
1256	register ENVELOPE *e;
1257{
1258	register struct eflags *ef;
1259	bool first = true;
1260
1261	sm_dprintf("%lx", e->e_flags);
1262	for (ef = EnvelopeFlags; ef->ef_name != NULL; ef++)
1263	{
1264		if (!bitset(ef->ef_bit, e->e_flags))
1265			continue;
1266		if (first)
1267			sm_dprintf("<%s", ef->ef_name);
1268		else
1269			sm_dprintf(",%s", ef->ef_name);
1270		first = false;
1271	}
1272	if (!first)
1273		sm_dprintf(">\n");
1274}
1275