xref: /titanic_50/usr/src/cmd/sendmail/src/envelope.c (revision ba4e3c84e6b9390bbf7df80b5f1d11dec34cc525)
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.296 2006/03/31 18:53:50 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 		{
525 			if (e->e_dfp != NULL)
526 			{
527 				(void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
528 				e->e_dfp = NULL;
529 			}
530 			(void) xunlink(queuename(e, DATAFL_LETTER));
531 		}
532 		if (panic && QueueMode == QM_LOST)
533 		{
534 			/*
535 			**  leave the Qf file behind as
536 			**  the delivery attempt failed.
537 			*/
538 
539 			/* EMPTY */
540 		}
541 		else
542 		if (xunlink(queuename(e, ANYQFL_LETTER)) == 0)
543 		{
544 			/* add to available space in filesystem */
545 			updfs(e, -1, panic ? 0 : -1, "dropenvelope");
546 		}
547 
548 		if (e->e_ntries > 0 && LogLevel > 9)
549 			sm_syslog(LOG_INFO, id, "done; delay=%s, ntries=%d",
550 				  pintvl(curtime() - e->e_ctime, true),
551 				  e->e_ntries);
552 	}
553 	else if (queueit || !bitset(EF_INQUEUE, e->e_flags))
554 	{
555 		if (!split)
556 			queueup(e, false, true);
557 		else
558 		{
559 			ENVELOPE *oldsib;
560 			ENVELOPE *ee;
561 
562 			/*
563 			**  Save old sibling and set it to NULL to avoid
564 			**  queueing up the same envelopes again.
565 			**  This requires that envelopes in that list have
566 			**  been take care of before (or at some other place).
567 			*/
568 
569 			oldsib = e->e_sibling;
570 			e->e_sibling = NULL;
571 			if (!split_by_recipient(e) &&
572 			    bitset(EF_FATALERRS, e->e_flags))
573 			{
574 				syserr("!dropenvelope(%s): cannot commit data file %s, uid=%d",
575 					e->e_id, queuename(e, DATAFL_LETTER),
576 					(int) geteuid());
577 			}
578 			for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
579 				queueup(ee, false, true);
580 			queueup(e, false, true);
581 
582 			/* clean up */
583 			for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
584 			{
585 				/* now unlock the job */
586 				if (tTd(50, 8))
587 					sm_dprintf("dropenvelope(%s): unlocking job\n",
588 						   ee->e_id);
589 				closexscript(ee);
590 				unlockqueue(ee);
591 
592 				/* this envelope is marked unused */
593 				if (ee->e_dfp != NULL)
594 				{
595 					(void) sm_io_close(ee->e_dfp,
596 							   SM_TIME_DEFAULT);
597 					ee->e_dfp = NULL;
598 				}
599 				ee->e_id = NULL;
600 				ee->e_flags &= ~EF_HAS_DF;
601 			}
602 			e->e_sibling = oldsib;
603 		}
604 	}
605 
606 	/* now unlock the job */
607 	if (tTd(50, 8))
608 		sm_dprintf("dropenvelope(%s): unlocking job\n", id);
609 	closexscript(e);
610 	unlockqueue(e);
611 
612 	/* make sure that this envelope is marked unused */
613 	if (e->e_dfp != NULL)
614 	{
615 		(void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
616 		e->e_dfp = NULL;
617 	}
618 	e->e_id = NULL;
619 	e->e_flags &= ~EF_HAS_DF;
620 }
621 /*
622 **  CLEARENVELOPE -- clear an envelope without unlocking
623 **
624 **	This is normally used by a child process to get a clean
625 **	envelope without disturbing the parent.
626 **
627 **	Parameters:
628 **		e -- the envelope to clear.
629 **		fullclear - if set, the current envelope is total
630 **			garbage and should be ignored; otherwise,
631 **			release any resources it may indicate.
632 **		rpool -- either NULL, or a pointer to a resource pool
633 **			from which envelope memory is allocated, and
634 **			to which envelope resources are attached.
635 **
636 **	Returns:
637 **		none.
638 **
639 **	Side Effects:
640 **		Closes files associated with the envelope.
641 **		Marks the envelope as unallocated.
642 */
643 
644 void
645 clearenvelope(e, fullclear, rpool)
646 	register ENVELOPE *e;
647 	bool fullclear;
648 	SM_RPOOL_T *rpool;
649 {
650 	register HDR *bh;
651 	register HDR **nhp;
652 	extern ENVELOPE BlankEnvelope;
653 	char **p;
654 
655 	if (!fullclear)
656 	{
657 		/* clear out any file information */
658 		if (e->e_xfp != NULL)
659 			(void) sm_io_close(e->e_xfp, SM_TIME_DEFAULT);
660 		if (e->e_dfp != NULL)
661 			(void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
662 		e->e_xfp = e->e_dfp = NULL;
663 	}
664 
665 	/*
666 	**  Copy BlankEnvelope into *e.
667 	**  It is not safe to simply copy pointers to strings;
668 	**  the strings themselves must be copied (or set to NULL).
669 	**  The problem is that when we assign a new string value to
670 	**  a member of BlankEnvelope, we free the old string.
671 	**  We did not need to do this copying in sendmail 8.11 :-(
672 	**  and it is a potential performance hit.  Reference counted
673 	**  strings are one way out.
674 	*/
675 
676 	*e = BlankEnvelope;
677 	e->e_message = NULL;
678 	e->e_qfletter = '\0';
679 	e->e_quarmsg = NULL;
680 	macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), "");
681 
682 	/*
683 	**  Copy the macro table.
684 	**  We might be able to avoid this by zeroing the macro table
685 	**  and always searching BlankEnvelope.e_macro after e->e_macro
686 	**  in macvalue().
687 	*/
688 
689 	for (p = &e->e_macro.mac_table[0];
690 	     p <= &e->e_macro.mac_table[MAXMACROID];
691 	     ++p)
692 	{
693 		if (*p != NULL)
694 			*p = sm_rpool_strdup_x(rpool, *p);
695 	}
696 
697 	/*
698 	**  XXX There are many strings in the envelope structure
699 	**  XXX that we are not attempting to copy here.
700 	**  XXX Investigate this further.
701 	*/
702 
703 	e->e_rpool = rpool;
704 	e->e_macro.mac_rpool = rpool;
705 	if (Verbose)
706 		set_delivery_mode(SM_DELIVER, e);
707 	bh = BlankEnvelope.e_header;
708 	nhp = &e->e_header;
709 	while (bh != NULL)
710 	{
711 		*nhp = (HDR *) sm_rpool_malloc_x(rpool, sizeof *bh);
712 		memmove((char *) *nhp, (char *) bh, sizeof *bh);
713 		bh = bh->h_link;
714 		nhp = &(*nhp)->h_link;
715 	}
716 }
717 /*
718 **  INITSYS -- initialize instantiation of system
719 **
720 **	In Daemon mode, this is done in the child.
721 **
722 **	Parameters:
723 **		e -- the envelope to use.
724 **
725 **	Returns:
726 **		none.
727 **
728 **	Side Effects:
729 **		Initializes the system macros, some global variables,
730 **		etc.  In particular, the current time in various
731 **		forms is set.
732 */
733 
734 void
735 initsys(e)
736 	register ENVELOPE *e;
737 {
738 	char buf[10];
739 #ifdef TTYNAME
740 	static char ybuf[60];			/* holds tty id */
741 	register char *p;
742 	extern char *ttyname();
743 #endif /* TTYNAME */
744 
745 	/*
746 	**  Give this envelope a reality.
747 	**	I.e., an id, a transcript, and a creation time.
748 	**  We don't select the queue until all of the recipients are known.
749 	*/
750 
751 	openxscript(e);
752 	e->e_ctime = curtime();
753 	e->e_qfletter = '\0';
754 
755 	/*
756 	**  Set OutChannel to something useful if stdout isn't it.
757 	**	This arranges that any extra stuff the mailer produces
758 	**	gets sent back to the user on error (because it is
759 	**	tucked away in the transcript).
760 	*/
761 
762 	if (OpMode == MD_DAEMON && bitset(EF_QUEUERUN, e->e_flags) &&
763 	    e->e_xfp != NULL)
764 		OutChannel = e->e_xfp;
765 
766 	/*
767 	**  Set up some basic system macros.
768 	*/
769 
770 	/* process id */
771 	(void) sm_snprintf(buf, sizeof buf, "%d", (int) CurrentPid);
772 	macdefine(&e->e_macro, A_TEMP, 'p', buf);
773 
774 	/* hop count */
775 	(void) sm_snprintf(buf, sizeof buf, "%d", e->e_hopcount);
776 	macdefine(&e->e_macro, A_TEMP, 'c', buf);
777 
778 	/* time as integer, unix time, arpa time */
779 	settime(e);
780 
781 	/* Load average */
782 	sm_getla();
783 
784 #ifdef TTYNAME
785 	/* tty name */
786 	if (macvalue('y', e) == NULL)
787 	{
788 		p = ttyname(2);
789 		if (p != NULL)
790 		{
791 			if (strrchr(p, '/') != NULL)
792 				p = strrchr(p, '/') + 1;
793 			(void) sm_strlcpy(ybuf, sizeof ybuf, p);
794 			macdefine(&e->e_macro, A_PERM, 'y', ybuf);
795 		}
796 	}
797 #endif /* TTYNAME */
798 }
799 /*
800 **  SETTIME -- set the current time.
801 **
802 **	Parameters:
803 **		e -- the envelope in which the macros should be set.
804 **
805 **	Returns:
806 **		none.
807 **
808 **	Side Effects:
809 **		Sets the various time macros -- $a, $b, $d, $t.
810 */
811 
812 void
813 settime(e)
814 	register ENVELOPE *e;
815 {
816 	register char *p;
817 	auto time_t now;
818 	char buf[30];
819 	register struct tm *tm;
820 
821 	now = curtime();
822 	(void) sm_snprintf(buf, sizeof buf, "%ld", (long) now);
823 	macdefine(&e->e_macro, A_TEMP, macid("{time}"), buf);
824 	tm = gmtime(&now);
825 	(void) sm_snprintf(buf, sizeof buf, "%04d%02d%02d%02d%02d",
826 			   tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
827 			   tm->tm_hour, tm->tm_min);
828 	macdefine(&e->e_macro, A_TEMP, 't', buf);
829 	(void) sm_strlcpy(buf, ctime(&now), sizeof buf);
830 	p = strchr(buf, '\n');
831 	if (p != NULL)
832 		*p = '\0';
833 	macdefine(&e->e_macro, A_TEMP, 'd', buf);
834 	macdefine(&e->e_macro, A_TEMP, 'b', arpadate(buf));
835 	if (macvalue('a', e) == NULL)
836 		macdefine(&e->e_macro, A_PERM, 'a', macvalue('b', e));
837 }
838 /*
839 **  OPENXSCRIPT -- Open transcript file
840 **
841 **	Creates a transcript file for possible eventual mailing or
842 **	sending back.
843 **
844 **	Parameters:
845 **		e -- the envelope to create the transcript in/for.
846 **
847 **	Returns:
848 **		none
849 **
850 **	Side Effects:
851 **		Creates the transcript file.
852 */
853 
854 #ifndef O_APPEND
855 # define O_APPEND	0
856 #endif /* ! O_APPEND */
857 
858 void
859 openxscript(e)
860 	register ENVELOPE *e;
861 {
862 	register char *p;
863 
864 	if (e->e_xfp != NULL)
865 		return;
866 
867 #if 0
868 	if (e->e_lockfp == NULL && bitset(EF_INQUEUE, e->e_flags))
869 		syserr("openxscript: job not locked");
870 #endif /* 0 */
871 
872 	p = queuename(e, XSCRPT_LETTER);
873 	e->e_xfp = bfopen(p, FileMode, XscriptFileBufferSize,
874 			  SFF_NOTEXCL|SFF_OPENASROOT);
875 
876 	if (e->e_xfp == NULL)
877 	{
878 		syserr("Can't create transcript file %s", p);
879 		e->e_xfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT,
880 				      SM_PATH_DEVNULL, SM_IO_RDWR, NULL);
881 		if (e->e_xfp == NULL)
882 			syserr("!Can't open %s", SM_PATH_DEVNULL);
883 	}
884 	(void) sm_io_setvbuf(e->e_xfp, SM_TIME_DEFAULT, NULL, SM_IO_LBF, 0);
885 	if (tTd(46, 9))
886 	{
887 		sm_dprintf("openxscript(%s):\n  ", p);
888 		dumpfd(sm_io_getinfo(e->e_xfp, SM_IO_WHAT_FD, NULL), true,
889 		       false);
890 	}
891 }
892 /*
893 **  CLOSEXSCRIPT -- close the transcript file.
894 **
895 **	Parameters:
896 **		e -- the envelope containing the transcript to close.
897 **
898 **	Returns:
899 **		none.
900 **
901 **	Side Effects:
902 **		none.
903 */
904 
905 void
906 closexscript(e)
907 	register ENVELOPE *e;
908 {
909 	if (e->e_xfp == NULL)
910 		return;
911 #if 0
912 	if (e->e_lockfp == NULL)
913 		syserr("closexscript: job not locked");
914 #endif /* 0 */
915 	(void) sm_io_close(e->e_xfp, SM_TIME_DEFAULT);
916 	e->e_xfp = NULL;
917 }
918 /*
919 **  SETSENDER -- set the person who this message is from
920 **
921 **	Under certain circumstances allow the user to say who
922 **	s/he is (using -f or -r).  These are:
923 **	1.  The user's uid is zero (root).
924 **	2.  The user's login name is in an approved list (typically
925 **	    from a network server).
926 **	3.  The address the user is trying to claim has a
927 **	    "!" character in it (since #2 doesn't do it for
928 **	    us if we are dialing out for UUCP).
929 **	A better check to replace #3 would be if the
930 **	effective uid is "UUCP" -- this would require me
931 **	to rewrite getpwent to "grab" uucp as it went by,
932 **	make getname more nasty, do another passwd file
933 **	scan, or compile the UID of "UUCP" into the code,
934 **	all of which are reprehensible.
935 **
936 **	Assuming all of these fail, we figure out something
937 **	ourselves.
938 **
939 **	Parameters:
940 **		from -- the person we would like to believe this message
941 **			is from, as specified on the command line.
942 **		e -- the envelope in which we would like the sender set.
943 **		delimptr -- if non-NULL, set to the location of the
944 **			trailing delimiter.
945 **		delimchar -- the character that will delimit the sender
946 **			address.
947 **		internal -- set if this address is coming from an internal
948 **			source such as an owner alias.
949 **
950 **	Returns:
951 **		none.
952 **
953 **	Side Effects:
954 **		sets sendmail's notion of who the from person is.
955 */
956 
957 void
958 setsender(from, e, delimptr, delimchar, internal)
959 	char *from;
960 	register ENVELOPE *e;
961 	char **delimptr;
962 	int delimchar;
963 	bool internal;
964 {
965 	register char **pvp;
966 	char *realname = NULL;
967 	char *bp;
968 	char buf[MAXNAME + 2];
969 	char pvpbuf[PSBUFSIZE];
970 	extern char *FullName;
971 
972 	if (tTd(45, 1))
973 		sm_dprintf("setsender(%s)\n", from == NULL ? "" : from);
974 
975 	/* may be set from earlier calls */
976 	macdefine(&e->e_macro, A_PERM, 'x', "");
977 
978 	/*
979 	**  Figure out the real user executing us.
980 	**	Username can return errno != 0 on non-errors.
981 	*/
982 
983 	if (bitset(EF_QUEUERUN, e->e_flags) || OpMode == MD_SMTP ||
984 	    OpMode == MD_ARPAFTP || OpMode == MD_DAEMON)
985 		realname = from;
986 	if (realname == NULL || realname[0] == '\0')
987 		realname = username();
988 
989 	if (ConfigLevel < 2)
990 		SuprErrs = true;
991 
992 	macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e s");
993 
994 	/* preset state for then clause in case from == NULL */
995 	e->e_from.q_state = QS_BADADDR;
996 	e->e_from.q_flags = 0;
997 	if (from == NULL ||
998 	    parseaddr(from, &e->e_from, RF_COPYALL|RF_SENDERADDR,
999 		      delimchar, delimptr, e, false) == NULL ||
1000 	    QS_IS_BADADDR(e->e_from.q_state) ||
1001 	    e->e_from.q_mailer == ProgMailer ||
1002 	    e->e_from.q_mailer == FileMailer ||
1003 	    e->e_from.q_mailer == InclMailer)
1004 	{
1005 		/* log garbage addresses for traceback */
1006 		if (from != NULL && LogLevel > 2)
1007 		{
1008 			char *p;
1009 			char ebuf[MAXNAME * 2 + 2];
1010 
1011 			p = macvalue('_', e);
1012 			if (p == NULL)
1013 			{
1014 				char *host = RealHostName;
1015 
1016 				if (host == NULL)
1017 					host = MyHostName;
1018 				(void) sm_snprintf(ebuf, sizeof ebuf,
1019 						   "%.*s@%.*s", MAXNAME,
1020 						   realname, MAXNAME, host);
1021 				p = ebuf;
1022 			}
1023 			sm_syslog(LOG_NOTICE, e->e_id,
1024 				  "setsender: %s: invalid or unparsable, received from %s",
1025 				  shortenstring(from, 83), p);
1026 		}
1027 		if (from != NULL)
1028 		{
1029 			if (!QS_IS_BADADDR(e->e_from.q_state))
1030 			{
1031 				/* it was a bogus mailer in the from addr */
1032 				e->e_status = "5.1.7";
1033 				usrerrenh(e->e_status,
1034 					  "553 Invalid sender address");
1035 			}
1036 			SuprErrs = true;
1037 		}
1038 		if (from == realname ||
1039 		    parseaddr(from = realname,
1040 			      &e->e_from, RF_COPYALL|RF_SENDERADDR, ' ',
1041 			      NULL, e, false) == NULL)
1042 		{
1043 			char nbuf[100];
1044 
1045 			SuprErrs = true;
1046 			expand("\201n", nbuf, sizeof nbuf, e);
1047 			from = sm_rpool_strdup_x(e->e_rpool, nbuf);
1048 			if (parseaddr(from, &e->e_from, RF_COPYALL, ' ',
1049 				      NULL, e, false) == NULL &&
1050 			    parseaddr(from = "postmaster", &e->e_from,
1051 				      RF_COPYALL, ' ', NULL, e, false) == NULL)
1052 				syserr("553 5.3.0 setsender: can't even parse postmaster!");
1053 		}
1054 	}
1055 	else
1056 		FromFlag = true;
1057 	e->e_from.q_state = QS_SENDER;
1058 	if (tTd(45, 5))
1059 	{
1060 		sm_dprintf("setsender: QS_SENDER ");
1061 		printaddr(sm_debug_file(), &e->e_from, false);
1062 	}
1063 	SuprErrs = false;
1064 
1065 #if USERDB
1066 	if (bitnset(M_CHECKUDB, e->e_from.q_mailer->m_flags))
1067 	{
1068 		register char *p;
1069 
1070 		p = udbsender(e->e_from.q_user, e->e_rpool);
1071 		if (p != NULL)
1072 			from = p;
1073 	}
1074 #endif /* USERDB */
1075 
1076 	if (bitnset(M_HASPWENT, e->e_from.q_mailer->m_flags))
1077 	{
1078 		SM_MBDB_T user;
1079 
1080 		if (!internal)
1081 		{
1082 			/* if the user already given fullname don't redefine */
1083 			if (FullName == NULL)
1084 				FullName = macvalue('x', e);
1085 			if (FullName != NULL)
1086 			{
1087 				if (FullName[0] == '\0')
1088 					FullName = NULL;
1089 				else
1090 					FullName = newstr(FullName);
1091 			}
1092 		}
1093 
1094 		if (e->e_from.q_user[0] != '\0' &&
1095 		    sm_mbdb_lookup(e->e_from.q_user, &user) == EX_OK)
1096 		{
1097 			/*
1098 			**  Process passwd file entry.
1099 			*/
1100 
1101 			/* extract home directory */
1102 			if (*user.mbdb_homedir == '\0')
1103 				e->e_from.q_home = NULL;
1104 			else if (strcmp(user.mbdb_homedir, "/") == 0)
1105 				e->e_from.q_home = "";
1106 			else
1107 				e->e_from.q_home = sm_rpool_strdup_x(e->e_rpool,
1108 							user.mbdb_homedir);
1109 			macdefine(&e->e_macro, A_PERM, 'z', e->e_from.q_home);
1110 
1111 			/* extract user and group id */
1112 			if (user.mbdb_uid != SM_NO_UID)
1113 			{
1114 				e->e_from.q_uid = user.mbdb_uid;
1115 				e->e_from.q_gid = user.mbdb_gid;
1116 				e->e_from.q_flags |= QGOODUID;
1117 			}
1118 
1119 			/* extract full name from passwd file */
1120 			if (FullName == NULL && !internal &&
1121 			    user.mbdb_fullname[0] != '\0' &&
1122 			    strcmp(user.mbdb_name, e->e_from.q_user) == 0)
1123 			{
1124 				FullName = newstr(user.mbdb_fullname);
1125 			}
1126 		}
1127 		else
1128 		{
1129 			e->e_from.q_home = NULL;
1130 		}
1131 		if (FullName != NULL && !internal)
1132 			macdefine(&e->e_macro, A_TEMP, 'x', FullName);
1133 	}
1134 	else if (!internal && OpMode != MD_DAEMON && OpMode != MD_SMTP)
1135 	{
1136 		if (e->e_from.q_home == NULL)
1137 		{
1138 			e->e_from.q_home = getenv("HOME");
1139 			if (e->e_from.q_home != NULL)
1140 			{
1141 				if (*e->e_from.q_home == '\0')
1142 					e->e_from.q_home = NULL;
1143 				else if (strcmp(e->e_from.q_home, "/") == 0)
1144 					e->e_from.q_home++;
1145 			}
1146 		}
1147 		e->e_from.q_uid = RealUid;
1148 		e->e_from.q_gid = RealGid;
1149 		e->e_from.q_flags |= QGOODUID;
1150 	}
1151 
1152 	/*
1153 	**  Rewrite the from person to dispose of possible implicit
1154 	**	links in the net.
1155 	*/
1156 
1157 	pvp = prescan(from, delimchar, pvpbuf, sizeof pvpbuf, NULL, NULL, false);
1158 	if (pvp == NULL)
1159 	{
1160 		/* don't need to give error -- prescan did that already */
1161 		if (LogLevel > 2)
1162 			sm_syslog(LOG_NOTICE, e->e_id,
1163 				  "cannot prescan from (%s)",
1164 				  shortenstring(from, MAXSHORTSTR));
1165 		finis(true, true, ExitStat);
1166 	}
1167 	(void) REWRITE(pvp, 3, e);
1168 	(void) REWRITE(pvp, 1, e);
1169 	(void) REWRITE(pvp, 4, e);
1170 	macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
1171 	bp = buf + 1;
1172 	cataddr(pvp, NULL, bp, sizeof buf - 2, '\0');
1173 	if (*bp == '@' && !bitnset(M_NOBRACKET, e->e_from.q_mailer->m_flags))
1174 	{
1175 		/* heuristic: route-addr: add angle brackets */
1176 		(void) sm_strlcat(bp, ">", sizeof buf - 1);
1177 		*--bp = '<';
1178 	}
1179 	e->e_sender = sm_rpool_strdup_x(e->e_rpool, bp);
1180 	macdefine(&e->e_macro, A_PERM, 'f', e->e_sender);
1181 
1182 	/* save the domain spec if this mailer wants it */
1183 	if (e->e_from.q_mailer != NULL &&
1184 	    bitnset(M_CANONICAL, e->e_from.q_mailer->m_flags))
1185 	{
1186 		char **lastat;
1187 
1188 		/* get rid of any pesky angle brackets */
1189 		macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e s");
1190 		(void) REWRITE(pvp, 3, e);
1191 		(void) REWRITE(pvp, 1, e);
1192 		(void) REWRITE(pvp, 4, e);
1193 		macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
1194 
1195 		/* strip off to the last "@" sign */
1196 		for (lastat = NULL; *pvp != NULL; pvp++)
1197 		{
1198 			if (strcmp(*pvp, "@") == 0)
1199 				lastat = pvp;
1200 		}
1201 		if (lastat != NULL)
1202 		{
1203 			e->e_fromdomain = copyplist(lastat, true, e->e_rpool);
1204 			if (tTd(45, 3))
1205 			{
1206 				sm_dprintf("Saving from domain: ");
1207 				printav(sm_debug_file(), e->e_fromdomain);
1208 			}
1209 		}
1210 	}
1211 }
1212 /*
1213 **  PRINTENVFLAGS -- print envelope flags for debugging
1214 **
1215 **	Parameters:
1216 **		e -- the envelope with the flags to be printed.
1217 **
1218 **	Returns:
1219 **		none.
1220 */
1221 
1222 struct eflags
1223 {
1224 	char		*ef_name;
1225 	unsigned long	ef_bit;
1226 };
1227 
1228 static struct eflags	EnvelopeFlags[] =
1229 {
1230 	{ "OLDSTYLE",		EF_OLDSTYLE	},
1231 	{ "INQUEUE",		EF_INQUEUE	},
1232 	{ "NO_BODY_RETN",	EF_NO_BODY_RETN	},
1233 	{ "CLRQUEUE",		EF_CLRQUEUE	},
1234 	{ "SENDRECEIPT",	EF_SENDRECEIPT	},
1235 	{ "FATALERRS",		EF_FATALERRS	},
1236 	{ "DELETE_BCC",		EF_DELETE_BCC	},
1237 	{ "RESPONSE",		EF_RESPONSE	},
1238 	{ "RESENT",		EF_RESENT	},
1239 	{ "VRFYONLY",		EF_VRFYONLY	},
1240 	{ "WARNING",		EF_WARNING	},
1241 	{ "QUEUERUN",		EF_QUEUERUN	},
1242 	{ "GLOBALERRS",		EF_GLOBALERRS	},
1243 	{ "PM_NOTIFY",		EF_PM_NOTIFY	},
1244 	{ "METOO",		EF_METOO	},
1245 	{ "LOGSENDER",		EF_LOGSENDER	},
1246 	{ "NORECEIPT",		EF_NORECEIPT	},
1247 	{ "HAS8BIT",		EF_HAS8BIT	},
1248 	{ "NL_NOT_EOL",		EF_NL_NOT_EOL	},
1249 	{ "CRLF_NOT_EOL",	EF_CRLF_NOT_EOL	},
1250 	{ "RET_PARAM",		EF_RET_PARAM	},
1251 	{ "HAS_DF",		EF_HAS_DF	},
1252 	{ "IS_MIME",		EF_IS_MIME	},
1253 	{ "DONT_MIME",		EF_DONT_MIME	},
1254 	{ "DISCARD",		EF_DISCARD	},
1255 	{ "TOOBIG",		EF_TOOBIG	},
1256 	{ "SPLIT",		EF_SPLIT	},
1257 	{ "UNSAFE",		EF_UNSAFE	},
1258 	{ NULL,			0		}
1259 };
1260 
1261 void
1262 printenvflags(e)
1263 	register ENVELOPE *e;
1264 {
1265 	register struct eflags *ef;
1266 	bool first = true;
1267 
1268 	sm_dprintf("%lx", e->e_flags);
1269 	for (ef = EnvelopeFlags; ef->ef_name != NULL; ef++)
1270 	{
1271 		if (!bitset(ef->ef_bit, e->e_flags))
1272 			continue;
1273 		if (first)
1274 			sm_dprintf("<%s", ef->ef_name);
1275 		else
1276 			sm_dprintf(",%s", ef->ef_name);
1277 		first = false;
1278 	}
1279 	if (!first)
1280 		sm_dprintf(">\n");
1281 }
1282