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