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