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