2 * Copyright (c) 1998-2004, 2006, 2007 Sendmail, Inc. and its suppliers.
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.
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.
16 #include <sm/sendmail.h>
18 SM_RCSID("@(#)$Id: headers.c,v 8.310 2007/02/07 22:44:35 ca Exp $")
20 static HDR *allocheader __P((char *, char *, int, SM_RPOOL_T *, bool));
21 static size_t fix_mime_header __P((HDR *, ENVELOPE *));
22 static int priencode __P((char *));
23 static bool put_vanilla_header __P((HDR *, char *, MCI *));
26 ** SETUPHEADERS -- initialize headers in symbol table
41 for (hi = HdrInfo; hi->hi_field != NULL; hi++)
43 s = stab(hi->hi_field, ST_HEADER, ST_ENTER);
44 s->s_header.hi_flags = hi->hi_flags;
45 s->s_header.hi_ruleset = NULL;
50 ** DOCHOMPHEADER -- process and save a header line.
52 ** Called by chompheader.
55 ** line -- header as a text line.
56 ** pflag -- flags for chompheader() (from sendmail.h)
57 ** hdrp -- a pointer to the place to save the header.
58 ** e -- the envelope including this header.
61 ** flags for this header.
64 ** The header is saved on the header list.
65 ** Contents of 'line' are destroyed.
68 static struct hdrinfo NormalHeader = { NULL, 0, NULL };
69 static unsigned long dochompheader __P((char *, int, HDR **, ENVELOPE *));
72 dochompheader(line, pflag, hdrp, e)
78 unsigned char mid = '\0';
89 bool nullheader = false;
92 headeronly = hdrp != NULL;
96 /* strip off options */
99 if (!bitset(pflag, CHHDR_USER) && *p == '?')
104 q = strchr(++p, '?');
111 /* possibly macro conditional */
112 if (c == MACROEXPAND)
121 mid = (unsigned char) *p++;
139 mid = (unsigned char) macid(p);
140 if (bitset(0200, mid))
142 p += strlen(macname(mid)) + 2;
165 setbitn(bitidx(*p), mopts);
173 /* find canonical name */
175 while (isascii(*p) && isgraph(*p) && *p != ':')
178 while (isascii(*p) && isspace(*p))
180 if (*p++ != ':' || fname == fvalue)
183 syserr("553 5.3.0 header syntax error, line \"%s\"", line);
189 /* if the field is null, go ahead and use the default */
190 while (isascii(*p) && isspace(*p))
195 /* security scan: long field names are end-of-header */
196 if (strlen(fname) > 100)
199 /* check to see if it represents a ruleset call */
200 if (bitset(pflag, CHHDR_DEF))
204 (void) expand(fvalue, hbuf, sizeof(hbuf), e);
205 for (p = hbuf; isascii(*p) && isspace(*p); )
207 if ((*p++ & 0377) == CALLSUBR)
212 strc = *p == '+'; /* strip comments? */
215 if (strtorwset(p, &endp, ST_ENTER) > 0)
218 s = stab(fname, ST_HEADER, ST_ENTER);
220 s->s_header.hi_ruleset != NULL)
221 sm_syslog(LOG_WARNING, NOQID,
222 "Warning: redefined ruleset for header=%s, old=%s, new=%s",
224 s->s_header.hi_ruleset, p);
225 s->s_header.hi_ruleset = newstr(p);
227 s->s_header.hi_flags |= H_STRIPCOMM;
233 /* see if it is a known type */
234 s = stab(fname, ST_HEADER, ST_FIND);
243 sm_dprintf("no header flags match\n");
245 sm_dprintf("header match, flags=%lx, ruleset=%s\n",
247 hi->hi_ruleset == NULL ? "<NULL>"
251 /* see if this is a resent message */
252 if (!bitset(pflag, CHHDR_DEF) && !headeronly &&
253 bitset(H_RESENT, hi->hi_flags))
254 e->e_flags |= EF_RESENT;
256 /* if this is an Errors-To: header keep track of it now */
257 if (UseErrorsTo && !bitset(pflag, CHHDR_DEF) && !headeronly &&
258 bitset(H_ERRORSTO, hi->hi_flags))
259 (void) sendtolist(fvalue, NULLADDR, &e->e_errorqueue, 0, e);
261 /* if this means "end of header" quit now */
262 if (!headeronly && bitset(H_EOH, hi->hi_flags))
266 ** Horrible hack to work around problem with Lotus Notes SMTP
267 ** mail gateway, which generates From: headers with newlines in
268 ** them and the <address> on the second line. Although this is
269 ** legal RFC 822, many MUAs don't handle this properly and thus
270 ** never find the actual address.
273 if (bitset(H_FROM, hi->hi_flags) && SingleLineFromHeader)
275 while ((p = strchr(fvalue, '\n')) != NULL)
280 ** If there is a check ruleset, verify it against the header.
283 if (bitset(pflag, CHHDR_CHECK))
288 rscheckflags = RSF_COUNT;
289 if (!bitset(hi->hi_flags, H_FROM|H_RCPT))
290 rscheckflags |= RSF_UNSTRUCTURED;
292 /* no ruleset? look for default */
296 s = stab("*", ST_HEADER, ST_FIND);
299 rs = (&s->s_header)->hi_ruleset;
300 if (bitset((&s->s_header)->hi_flags,
302 rscheckflags |= RSF_RMCOMM;
305 else if (bitset(hi->hi_flags, H_STRIPCOMM))
306 rscheckflags |= RSF_RMCOMM;
315 /* - 3 to avoid problems with " at the end */
316 /* should be sizeof(qval), not MAXNAME */
317 for (k = 0; fvalue[k] != '\0' && l < MAXNAME - 3; k++)
321 /* XXX other control chars? */
322 case '\011': /* ht */
323 case '\012': /* nl */
324 case '\013': /* vt */
325 case '\014': /* np */
326 case '\015': /* cr */
333 qval[l++] = fvalue[k];
339 k += strlen(fvalue + k);
343 sm_syslog(LOG_WARNING, e->e_id,
344 "Warning: truncated header '%s' before check with '%s' len=%d max=%d",
345 fname, rs, k, MAXNAME - 1);
347 macdefine(&e->e_macro, A_TEMP,
348 macid("{currHeader}"), qval);
349 macdefine(&e->e_macro, A_TEMP,
350 macid("{hdr_name}"), fname);
352 (void) sm_snprintf(qval, sizeof(qval), "%d", k);
353 macdefine(&e->e_macro, A_TEMP, macid("{hdrlen}"), qval);
354 if (bitset(H_FROM, hi->hi_flags))
355 macdefine(&e->e_macro, A_PERM,
356 macid("{addr_type}"), "h s");
357 else if (bitset(H_RCPT, hi->hi_flags))
358 macdefine(&e->e_macro, A_PERM,
359 macid("{addr_type}"), "h r");
361 macdefine(&e->e_macro, A_PERM,
362 macid("{addr_type}"), "h");
363 (void) rscheck(rs, fvalue, NULL, e, rscheckflags, 3,
364 NULL, e->e_id, NULL);
369 ** Drop explicit From: if same as what we would generate.
370 ** This is to make MH (which doesn't always give a full name)
371 ** insert the full name information in all circumstances.
376 if (!bitset(EF_RESENT, e->e_flags))
378 if (!bitset(pflag, CHHDR_DEF) && !headeronly &&
379 !bitset(EF_QUEUERUN, e->e_flags) && sm_strcasecmp(fname, p) == 0)
383 sm_dprintf("comparing header from (%s) against default (%s or %s)\n",
384 fvalue, e->e_from.q_paddr, e->e_from.q_user);
386 if (e->e_from.q_paddr != NULL &&
387 e->e_from.q_mailer != NULL &&
388 bitnset(M_LOCALMAILER, e->e_from.q_mailer->m_flags) &&
389 (strcmp(fvalue, e->e_from.q_paddr) == 0 ||
390 strcmp(fvalue, e->e_from.q_user) == 0))
394 /* delete default value for this header */
395 for (hp = hdrp; (h = *hp) != NULL; hp = &h->h_link)
397 if (sm_strcasecmp(fname, h->h_field) == 0 &&
398 !bitset(H_USER, h->h_flags) &&
399 !bitset(H_FORCE, h->h_flags))
403 /* user-supplied value was null */
408 /* make this look like the user entered it */
409 h->h_flags |= H_USER;
415 /* copy conditions from default case */
416 memmove((char *) mopts, (char *) h->h_mflags,
423 /* create a new node */
424 h = (HDR *) sm_rpool_malloc_x(e->e_rpool, sizeof(*h));
425 h->h_field = sm_rpool_strdup_x(e->e_rpool, fname);
426 h->h_value = sm_rpool_strdup_x(e->e_rpool, fvalue);
428 memmove((char *) h->h_mflags, (char *) mopts, sizeof(mopts));
431 h->h_flags = hi->hi_flags;
432 if (bitset(pflag, CHHDR_USER) || bitset(pflag, CHHDR_QUEUE))
433 h->h_flags |= H_USER;
435 /* strip EOH flag if parsing MIME headers */
437 h->h_flags &= ~H_EOH;
438 if (bitset(pflag, CHHDR_DEF))
439 h->h_flags |= H_DEFAULT;
440 if (cond || mid != '\0')
441 h->h_flags |= H_CHECK;
443 /* hack to see if this is a new format message */
444 if (!bitset(pflag, CHHDR_DEF) && !headeronly &&
445 bitset(H_RCPT|H_FROM, h->h_flags) &&
446 (strchr(fvalue, ',') != NULL || strchr(fvalue, '(') != NULL ||
447 strchr(fvalue, '<') != NULL || strchr(fvalue, ';') != NULL))
449 e->e_flags &= ~EF_OLDSTYLE;
456 ** CHOMPHEADER -- process and save a header line.
458 ** Called by collect, readcf, and readqf to deal with header lines.
459 ** This is just a wrapper for dochompheader().
462 ** line -- header as a text line.
463 ** pflag -- flags for chompheader() (from sendmail.h)
464 ** hdrp -- a pointer to the place to save the header.
465 ** e -- the envelope including this header.
468 ** flags for this header.
471 ** The header is saved on the header list.
472 ** Contents of 'line' are destroyed.
477 chompheader(line, pflag, hdrp, e)
481 register ENVELOPE *e;
487 sm_dprintf("chompheader: ");
488 xputs(sm_debug_file(), line);
492 /* quote this if user (not config file) input */
493 if (bitset(pflag, CHHDR_USER))
499 xbufs = sizeof(xbuf);
500 xbp = quote_internal_chars(line, xbuf, &xbufs);
503 sm_dprintf("chompheader: quoted: ");
504 xputs(sm_debug_file(), xbp);
507 rval = dochompheader(xbp, pflag, hdrp, e);
512 rval = dochompheader(line, pflag, hdrp, e);
518 ** ALLOCHEADER -- allocate a header entry
521 ** field -- the name of the header field (will not be copied).
522 ** value -- the value of the field (will be copied).
523 ** flags -- flags to add to h_flags.
524 ** rp -- resource pool for allocations
525 ** space -- add leading space?
528 ** Pointer to a newly allocated and populated HDR.
531 ** o field and value must be in internal format, i.e.,
532 ** metacharacters must be "quoted", see quote_internal_chars().
533 ** o maybe add more flags to decide:
534 ** - what to copy (field/value)
535 ** - whether to convert value to an internal format
539 allocheader(field, value, flags, rp, space)
549 /* find info struct */
550 s = stab(field, ST_HEADER, ST_FIND);
552 /* allocate space for new header */
553 h = (HDR *) sm_rpool_malloc_x(rp, sizeof(*h));
561 SM_ASSERT(l + 2 > l);
562 n = sm_rpool_malloc_x(rp, l + 2);
565 sm_strlcpy(n + 1, value, l + 1);
569 h->h_value = sm_rpool_strdup_x(rp, value);
572 h->h_flags |= s->s_header.hi_flags;
573 clrbitmap(h->h_mflags);
580 ** ADDHEADER -- add a header entry to the end of the queue.
582 ** This bypasses the special checking of chompheader.
585 ** field -- the name of the header field (will not be copied).
586 ** value -- the value of the field (will be copied).
587 ** flags -- flags to add to h_flags.
589 ** space -- add leading space?
595 ** adds the field on the list of headers for this envelope.
597 ** Notes: field and value must be in internal format, i.e.,
598 ** metacharacters must be "quoted", see quote_internal_chars().
602 addheader(field, value, flags, e, space)
611 HDR **hdrlist = &e->e_header;
613 /* find current place in list -- keep back pointer? */
614 for (hp = hdrlist; (h = *hp) != NULL; hp = &h->h_link)
616 if (sm_strcasecmp(field, h->h_field) == 0)
620 /* allocate space for new header */
621 h = allocheader(field, value, flags, e->e_rpool, space);
627 ** INSHEADER -- insert a header entry at the specified index
628 ** This bypasses the special checking of chompheader.
631 ** idx -- index into the header list at which to insert
632 ** field -- the name of the header field (will be copied).
633 ** value -- the value of the field (will be copied).
634 ** flags -- flags to add to h_flags.
636 ** space -- add leading space?
642 ** inserts the field on the list of headers for this envelope.
645 ** - field and value must be in internal format, i.e.,
646 ** metacharacters must be "quoted", see quote_internal_chars().
647 ** - the header list contains headers that might not be
648 ** sent "out" (see putheader(): "skip"), hence there is no
649 ** reliable way to insert a header at an exact position
650 ** (except at the front or end).
654 insheader(idx, field, value, flags, e, space)
662 HDR *h, *srch, *last = NULL;
664 /* allocate space for new header */
665 h = allocheader(field, value, flags, e->e_rpool, space);
667 /* find insertion position */
668 for (srch = e->e_header; srch != NULL && idx > 0;
669 srch = srch->h_link, idx--)
672 if (e->e_header == NULL)
677 else if (srch == NULL)
679 SM_ASSERT(last != NULL);
685 h->h_link = srch->h_link;
691 ** HVALUE -- return value of a header.
693 ** Only "real" fields (i.e., ones that have not been supplied
694 ** as a default) are used.
697 ** field -- the field name.
698 ** header -- the header list.
701 ** pointer to the value part (internal format).
702 ** NULL if not found.
709 hvalue(field, header)
715 for (h = header; h != NULL; h = h->h_link)
717 if (!bitset(H_DEFAULT, h->h_flags) &&
718 sm_strcasecmp(h->h_field, field) == 0)
725 ** ISHEADER -- predicate telling if argument is a header.
727 ** A line is a header if it has a single word followed by
728 ** optional white space followed by a colon.
730 ** Header fields beginning with two dashes, although technically
731 ** permitted by RFC822, are automatically rejected in order
732 ** to make MIME work out. Without this we could have a technically
733 ** legal header such as ``--"foo:bar"'' that would also be a legal
737 ** h -- string to check for possible headerness.
740 ** true if h is a header.
754 if (s[0] == '-' && s[1] == '-')
757 while (*s > ' ' && *s != ':' && *s != '\0')
763 /* following technically violates RFC822 */
764 while (isascii(*s) && isspace(*s))
771 ** EATHEADER -- run through the stored header and extract info.
774 ** e -- the envelope to process.
775 ** full -- if set, do full processing (e.g., compute
776 ** message priority). This should not be set
777 ** when reading a queue file because some info
778 ** needed to compute the priority is wrong.
779 ** log -- call logsender()?
785 ** Sets a bunch of global variables from information
786 ** in the collected header.
790 eatheader(e, full, log)
791 register ENVELOPE *e;
801 ** Set up macros for possible expansion in headers.
804 macdefine(&e->e_macro, A_PERM, 'f', e->e_sender);
805 macdefine(&e->e_macro, A_PERM, 'g', e->e_sender);
806 if (e->e_origrcpt != NULL && *e->e_origrcpt != '\0')
807 macdefine(&e->e_macro, A_PERM, 'u', e->e_origrcpt);
809 macdefine(&e->e_macro, A_PERM, 'u', NULL);
811 /* full name of from person */
812 p = hvalue("full-name", e->e_header);
815 if (!rfc822_string(p))
818 ** Quote a full name with special characters
819 ** as a comment so crackaddr() doesn't destroy
820 ** the name portion of the address.
823 p = addquotes(p, e->e_rpool);
825 macdefine(&e->e_macro, A_PERM, 'x', p);
829 sm_dprintf("----- collected header -----\n");
831 for (h = e->e_header; h != NULL; h = h->h_link)
834 sm_dprintf("%s:", h->h_field);
835 if (h->h_value == NULL)
838 sm_dprintf("<NULL>\n");
842 /* do early binding */
843 if (bitset(H_DEFAULT, h->h_flags) &&
844 !bitset(H_BINDLATE, h->h_flags))
849 xputs(sm_debug_file(), h->h_value);
852 expand(h->h_value, buf, sizeof(buf), e);
853 if (buf[0] != '\0' &&
854 (buf[0] != ' ' || buf[1] != '\0'))
856 if (bitset(H_FROM, h->h_flags))
857 expand(crackaddr(buf, e),
858 buf, sizeof(buf), e);
859 h->h_value = sm_rpool_strdup_x(e->e_rpool, buf);
860 h->h_flags &= ~H_DEFAULT;
865 xputs(sm_debug_file(), h->h_value);
869 /* count the number of times it has been processed */
870 if (bitset(H_TRACE, h->h_flags))
873 /* send to this person if we so desire */
874 if (GrabTo && bitset(H_RCPT, h->h_flags) &&
875 !bitset(H_DEFAULT, h->h_flags) &&
876 (!bitset(EF_RESENT, e->e_flags) ||
877 bitset(H_RESENT, h->h_flags)))
880 int saveflags = e->e_flags;
883 (void) sendtolist(denlstring(h->h_value, true, false),
884 NULLADDR, &e->e_sendqueue, 0, e);
888 ** Change functionality so a fatal error on an
889 ** address doesn't affect the entire envelope.
892 /* delete fatal errors generated by this address */
893 if (!bitset(EF_FATALERRS, saveflags))
894 e->e_flags &= ~EF_FATALERRS;
898 /* save the message-id for logging */
899 p = "resent-message-id";
900 if (!bitset(EF_RESENT, e->e_flags))
902 if (sm_strcasecmp(h->h_field, p) == 0)
904 e->e_msgid = h->h_value;
905 while (isascii(*e->e_msgid) && isspace(*e->e_msgid))
907 macdefine(&e->e_macro, A_PERM, macid("{msg_id}"),
912 sm_dprintf("----------------------------\n");
914 /* if we are just verifying (that is, sendmail -t -bv), drop out now */
915 if (OpMode == MD_VERIFY)
918 /* store hop count */
919 if (hopcnt > e->e_hopcount)
921 e->e_hopcount = hopcnt;
922 (void) sm_snprintf(buf, sizeof(buf), "%d", e->e_hopcount);
923 macdefine(&e->e_macro, A_TEMP, 'c', buf);
926 /* message priority */
927 p = hvalue("precedence", e->e_header);
929 e->e_class = priencode(p);
931 e->e_timeoutclass = TOC_NONURGENT;
932 else if (e->e_class > 0)
933 e->e_timeoutclass = TOC_URGENT;
936 e->e_msgpriority = e->e_msgsize
937 - e->e_class * WkClassFact
938 + e->e_nrcpts * WkRecipFact;
941 /* check for DSN to properly set e_timeoutclass */
942 p = hvalue("content-type", e->e_header);
947 char pvpbuf[MAXLINE];
948 extern unsigned char MimeTokenTab[256];
950 /* tokenize header */
953 pvp = prescan(p, '\0', pvpbuf, sizeof(pvpbuf), NULL,
954 MimeTokenTab, false);
957 /* Check if multipart/report */
958 if (pvp != NULL && pvp[0] != NULL &&
959 pvp[1] != NULL && pvp[2] != NULL &&
960 sm_strcasecmp(*pvp++, "multipart") == 0 &&
961 strcmp(*pvp++, "/") == 0 &&
962 sm_strcasecmp(*pvp++, "report") == 0)
964 /* Look for report-type=delivery-status */
967 /* skip to semicolon separator */
968 while (*pvp != NULL && strcmp(*pvp, ";") != 0)
972 if (*pvp++ == NULL || *pvp == NULL)
975 /* look for report-type */
976 if (sm_strcasecmp(*pvp++, "report-type") != 0)
980 if (*pvp == NULL || strcmp(*pvp, "=") != 0)
984 if (*++pvp != NULL &&
986 "delivery-status") == 0)
987 e->e_timeoutclass = TOC_DSN;
989 /* found report-type, no need to continue */
995 /* message timeout priority */
996 p = hvalue("priority", e->e_header);
999 /* (this should be in the configuration file) */
1000 if (sm_strcasecmp(p, "urgent") == 0)
1001 e->e_timeoutclass = TOC_URGENT;
1002 else if (sm_strcasecmp(p, "normal") == 0)
1003 e->e_timeoutclass = TOC_NORMAL;
1004 else if (sm_strcasecmp(p, "non-urgent") == 0)
1005 e->e_timeoutclass = TOC_NONURGENT;
1006 else if (bitset(EF_RESPONSE, e->e_flags))
1007 e->e_timeoutclass = TOC_DSN;
1009 else if (bitset(EF_RESPONSE, e->e_flags))
1010 e->e_timeoutclass = TOC_DSN;
1012 /* date message originated */
1013 p = hvalue("posted-date", e->e_header);
1015 p = hvalue("date", e->e_header);
1017 macdefine(&e->e_macro, A_PERM, 'a', p);
1019 /* check to see if this is a MIME message */
1020 if ((e->e_bodytype != NULL &&
1021 sm_strcasecmp(e->e_bodytype, "8BITMIME") == 0) ||
1022 hvalue("MIME-Version", e->e_header) != NULL)
1024 e->e_flags |= EF_IS_MIME;
1026 e->e_bodytype = "8BITMIME";
1028 else if ((p = hvalue("Content-Type", e->e_header)) != NULL)
1030 /* this may be an RFC 1049 message */
1031 p = strpbrk(p, ";/");
1032 if (p == NULL || *p == ';')
1035 e->e_flags |= EF_DONT_MIME;
1040 ** From person in antiquated ARPANET mode
1041 ** required by UK Grey Book e-mail gateways (sigh)
1044 if (OpMode == MD_ARPAFTP)
1046 register struct hdrinfo *hi;
1048 for (hi = HdrInfo; hi->hi_field != NULL; hi++)
1050 if (bitset(H_FROM, hi->hi_flags) &&
1051 (!bitset(H_RESENT, hi->hi_flags) ||
1052 bitset(EF_RESENT, e->e_flags)) &&
1053 (p = hvalue(hi->hi_field, e->e_header)) != NULL)
1056 if (hi->hi_field != NULL)
1059 sm_dprintf("eatheader: setsender(*%s == %s)\n",
1061 setsender(p, e, NULL, '\0', true);
1066 ** Log collection information.
1069 if (log && bitset(EF_LOGSENDER, e->e_flags) && LogLevel > 4)
1071 logsender(e, e->e_msgid);
1072 e->e_flags &= ~EF_LOGSENDER;
1077 ** LOGSENDER -- log sender information
1080 ** e -- the envelope to log
1081 ** msgid -- the message id
1089 register ENVELOPE *e;
1095 char hbuf[MAXNAME + 1];
1096 char sbuf[MAXLINE + 1];
1097 char mbuf[MAXNAME + 1];
1099 /* don't allow newlines in the message-id */
1100 /* XXX do we still need this? sm_syslog() replaces control chars */
1106 if (l > sizeof(mbuf) - 1)
1107 l = sizeof(mbuf) - 1;
1108 memmove(mbuf, msgid, l);
1111 while ((p = strchr(p, '\n')) != NULL)
1115 if (bitset(EF_RESPONSE, e->e_flags))
1116 name = "[RESPONSE]";
1117 else if ((name = macvalue('_', e)) != NULL)
1120 else if (RealHostName == NULL)
1122 else if (RealHostName[0] == '[')
1123 name = RealHostName;
1127 (void) sm_snprintf(hbuf, sizeof(hbuf), "%.80s", RealHostName);
1128 if (RealHostAddr.sa.sa_family != 0)
1130 p = &hbuf[strlen(hbuf)];
1131 (void) sm_snprintf(p, SPACELEFT(hbuf, p),
1133 anynet_ntoa(&RealHostAddr));
1137 /* some versions of syslog only take 5 printf args */
1138 #if (SYSLOG_BUFSIZE) >= 256
1140 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1141 "from=%.200s, size=%ld, class=%d, nrcpts=%d",
1142 e->e_from.q_paddr == NULL ? "<NONE>" : e->e_from.q_paddr,
1143 e->e_msgsize, e->e_class, e->e_nrcpts);
1147 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1148 ", msgid=%.100s", mbuf);
1151 if (e->e_bodytype != NULL)
1153 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1154 ", bodytype=%.20s", e->e_bodytype);
1157 p = macvalue('r', e);
1160 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1161 ", proto=%.20s", p);
1164 p = macvalue(macid("{daemon_name}"), e);
1167 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1168 ", daemon=%.20s", p);
1171 sm_syslog(LOG_INFO, e->e_id, "%.850s, relay=%s", sbuf, name);
1173 #else /* (SYSLOG_BUFSIZE) >= 256 */
1175 sm_syslog(LOG_INFO, e->e_id,
1177 e->e_from.q_paddr == NULL ? "<NONE>"
1178 : shortenstring(e->e_from.q_paddr,
1180 sm_syslog(LOG_INFO, e->e_id,
1181 "size=%ld, class=%ld, nrcpts=%d",
1182 e->e_msgsize, e->e_class, e->e_nrcpts);
1184 sm_syslog(LOG_INFO, e->e_id,
1186 shortenstring(mbuf, 83));
1189 if (e->e_bodytype != NULL)
1191 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1192 "bodytype=%.20s, ", e->e_bodytype);
1195 p = macvalue('r', e);
1198 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1199 "proto=%.20s, ", p);
1202 sm_syslog(LOG_INFO, e->e_id,
1203 "%.400srelay=%s", sbuf, name);
1204 #endif /* (SYSLOG_BUFSIZE) >= 256 */
1208 ** PRIENCODE -- encode external priority names into internal values.
1211 ** p -- priority in ascii.
1214 ** priority as a numeric level.
1226 for (i = 0; i < NumPriorities; i++)
1228 if (sm_strcasecmp(p, Priorities[i].pri_name) == 0)
1229 return Priorities[i].pri_val;
1232 /* unknown priority */
1237 ** CRACKADDR -- parse an address and turn it into a macro
1239 ** This doesn't actually parse the address -- it just extracts
1240 ** it and replaces it with "$g". The parse is totally ad hoc
1241 ** and isn't even guaranteed to leave something syntactically
1242 ** identical to what it started with. However, it does leave
1243 ** something semantically identical if possible, else at least
1244 ** syntactically correct.
1246 ** For example, it changes "Real Name <real@example.com> (Comment)"
1247 ** to "Real Name <$g> (Comment)".
1249 ** This algorithm has been cleaned up to handle a wider range
1250 ** of cases -- notably quoted and backslash escaped strings.
1251 ** This modification makes it substantially better at preserving
1252 ** the original syntax.
1255 ** addr -- the address to be cracked.
1256 ** e -- the current envelope.
1259 ** a pointer to the new version.
1265 ** The return value is saved in local storage and should
1266 ** be copied if it is to be reused.
1269 #define SM_HAVE_ROOM ((bp < buflim) && (buflim <= bufend))
1272 ** Append a character to bp if we have room.
1273 ** If not, punt and return $g.
1276 #define SM_APPEND_CHAR(c) \
1286 ERROR MAXNAME must be at least 10
1287 #endif /* MAXNAME < 10 */
1291 register char *addr;
1296 int cmtlev; /* comment level in input string */
1297 int realcmtlev; /* comment level in output string */
1298 int anglelev; /* angle level in input string */
1299 int copylev; /* 0 == in address, >0 copying */
1300 int bracklev; /* bracket level for IPv6 addr check */
1301 bool addangle; /* put closing angle in output */
1302 bool qmode; /* quoting in original string? */
1303 bool realqmode; /* quoting in output string? */
1304 bool putgmac = false; /* already wrote $g */
1305 bool quoteit = false; /* need to quote next character */
1306 bool gotangle = false; /* found first '<' */
1307 bool gotcolon = false; /* found a ':' */
1313 static char buf[MAXNAME + 1];
1316 sm_dprintf("crackaddr(%s)\n", addr);
1318 buflim = bufend = &buf[sizeof(buf) - 1];
1321 /* skip over leading spaces but preserve them */
1322 while (*addr != '\0' && isascii(*addr) && isspace(*addr))
1324 SM_APPEND_CHAR(*addr);
1330 ** Start by assuming we have no angle brackets. This will be
1331 ** adjusted later if we find them.
1334 p = addrhead = addr;
1335 copylev = anglelev = cmtlev = realcmtlev = 0;
1337 qmode = realqmode = addangle = false;
1339 while ((c = *p++) != '\0')
1342 ** Try to keep legal syntax using spare buffer space
1343 ** (maintained by buflim).
1349 /* check for backslash escapes */
1352 /* arrange to quote the address */
1353 if (cmtlev <= 0 && !qmode)
1356 if ((c = *p++) == '\0')
1367 /* check for quoted strings */
1368 if (c == '"' && cmtlev <= 0)
1371 if (copylev > 0 && SM_HAVE_ROOM)
1377 realqmode = !realqmode;
1384 /* check for comments */
1389 /* allow space for closing paren */
1397 SM_APPEND_CHAR(' ');
1418 /* syntax error: unmatched ) */
1419 if (copylev > 0 && SM_HAVE_ROOM && bp > bufhead)
1423 /* count nesting on [ ... ] (for IPv6 domain literals) */
1429 /* check for group: list; syntax */
1430 if (c == ':' && anglelev <= 0 && bracklev <= 0 &&
1431 !gotcolon && !ColonOkInAddr)
1436 ** Check for DECnet phase IV ``::'' (host::user)
1437 ** or DECnet phase V ``:.'' syntaxes. The latter
1438 ** covers ``user@DEC:.tay.myhost'' and
1439 ** ``DEC:.tay.myhost::user'' syntaxes (bletch).
1442 if (*p == ':' || *p == '.')
1444 if (cmtlev <= 0 && !qmode)
1460 SM_APPEND_CHAR('"');
1462 /* back up over the ':' and any spaces */
1465 isascii(*--p) && isspace(*p))
1469 for (q = addrhead; q < p; )
1472 if (quoteit && c == '"')
1473 SM_APPEND_CHAR('\\');
1478 if (bp == &bufhead[1])
1481 SM_APPEND_CHAR('"');
1482 while ((c = *p++) != ':')
1487 /* any trailing white space is part of group: */
1488 while (isascii(*p) && isspace(*p))
1494 putgmac = quoteit = false;
1500 if (c == ';' && copylev <= 0 && !ColonOkInAddr)
1503 /* check for characters that may have to be quoted */
1504 if (strchr(MustQuoteChars, c) != NULL)
1507 ** If these occur as the phrase part of a <>
1508 ** construct, but are not inside of () or already
1509 ** quoted, they will have to be quoted. Note that
1510 ** now (but don't actually do the quoting).
1513 if (cmtlev <= 0 && !qmode)
1517 /* check for angle brackets */
1522 /* assume first of two angles is bogus */
1527 /* oops -- have to change our mind */
1539 SM_APPEND_CHAR('"');
1541 /* back up over the '<' and any spaces */
1544 isascii(*--p) && isspace(*p))
1548 for (q = addrhead; q < p; )
1551 if (quoteit && c == '"')
1553 SM_APPEND_CHAR('\\');
1564 SM_APPEND_CHAR('"');
1565 while ((c = *p++) != '<')
1570 putgmac = quoteit = false;
1586 else if (SM_HAVE_ROOM)
1588 /* syntax error: unmatched > */
1589 if (copylev > 0 && bp > bufhead)
1599 /* must be a real address character */
1601 if (copylev <= 0 && !putgmac)
1603 if (bp > buf && bp[-1] == ')')
1604 SM_APPEND_CHAR(' ');
1605 SM_APPEND_CHAR(MACROEXPAND);
1606 SM_APPEND_CHAR('g');
1611 /* repair any syntactic damage */
1612 if (realqmode && bp < bufend)
1614 while (realcmtlev-- > 0 && bp < bufend)
1616 if (addangle && bp < bufend)
1623 /* String too long, punt */
1625 buf[1] = MACROEXPAND;
1629 sm_syslog(LOG_ALERT, e->e_id,
1630 "Dropped invalid comments from header address");
1635 sm_dprintf("crackaddr=>`");
1636 xputs(sm_debug_file(), buf);
1643 ** PUTHEADER -- put the header part of a message from the in-core copy
1646 ** mci -- the connection information.
1647 ** hdr -- the header to put.
1648 ** e -- envelope to use.
1649 ** flags -- MIME conversion flags.
1652 ** true iff header part was written successfully
1659 putheader(mci, hdr, e, flags)
1662 register ENVELOPE *e;
1666 char buf[SM_MAX(MAXLINE,BUFSIZ)];
1670 sm_dprintf("--- putheader, mailer = %s ---\n",
1671 mci->mci_mailer->m_name);
1674 ** If we're in MIME mode, we're not really in the header of the
1675 ** message, just the header of one of the parts of the body of
1676 ** the message. Therefore MCIF_INHEADER should not be turned on.
1679 if (!bitset(MCIF_INMIME, mci->mci_flags))
1680 mci->mci_flags |= MCIF_INHEADER;
1682 for (h = hdr; h != NULL; h = h->h_link)
1684 register char *p = h->h_value;
1689 sm_dprintf(" %s:", h->h_field);
1690 xputs(sm_debug_file(), p);
1693 /* Skip empty headers */
1694 if (h->h_value == NULL)
1697 /* heuristic shortening of MIME fields to avoid MUA overflows */
1698 if (MaxMimeFieldLength > 0 &&
1699 wordinclass(h->h_field,
1700 macid("{checkMIMEFieldHeaders}")))
1704 len = fix_mime_header(h, e);
1707 sm_syslog(LOG_ALERT, e->e_id,
1708 "Truncated MIME %s header due to field size (length = %ld) (possible attack)",
1709 h->h_field, (unsigned long) len);
1711 sm_dprintf(" truncated MIME %s header due to field size (length = %ld) (possible attack)\n",
1713 (unsigned long) len);
1717 if (MaxMimeHeaderLength > 0 &&
1718 wordinclass(h->h_field,
1719 macid("{checkMIMETextHeaders}")))
1723 len = strlen(h->h_value);
1724 if (len > (size_t) MaxMimeHeaderLength)
1726 h->h_value[MaxMimeHeaderLength - 1] = '\0';
1727 sm_syslog(LOG_ALERT, e->e_id,
1728 "Truncated long MIME %s header (length = %ld) (possible attack)",
1729 h->h_field, (unsigned long) len);
1731 sm_dprintf(" truncated long MIME %s header (length = %ld) (possible attack)\n",
1733 (unsigned long) len);
1737 if (MaxMimeHeaderLength > 0 &&
1738 wordinclass(h->h_field,
1739 macid("{checkMIMEHeaders}")))
1743 len = strlen(h->h_value);
1744 if (shorten_rfc822_string(h->h_value,
1745 MaxMimeHeaderLength))
1747 if (len < MaxMimeHeaderLength)
1749 /* we only rebalanced a bogus header */
1750 sm_syslog(LOG_ALERT, e->e_id,
1751 "Fixed MIME %s header (possible attack)",
1754 sm_dprintf(" fixed MIME %s header (possible attack)\n",
1759 /* we actually shortened header */
1760 sm_syslog(LOG_ALERT, e->e_id,
1761 "Truncated long MIME %s header (length = %ld) (possible attack)",
1763 (unsigned long) len);
1765 sm_dprintf(" truncated long MIME %s header (length = %ld) (possible attack)\n",
1767 (unsigned long) len);
1773 ** Suppress Content-Transfer-Encoding: if we are MIMEing
1774 ** and we are potentially converting from 8 bit to 7 bit
1775 ** MIME. If converting, add a new CTE header in
1779 if (bitset(H_CTE, h->h_flags) &&
1780 bitset(MCIF_CVT8TO7|MCIF_CVT7TO8|MCIF_INMIME,
1782 !bitset(M87F_NO8TO7, flags))
1785 sm_dprintf(" (skipped (content-transfer-encoding))\n");
1789 if (bitset(MCIF_INMIME, mci->mci_flags))
1793 if (!put_vanilla_header(h, p, mci))
1798 if (bitset(H_CHECK|H_ACHECK, h->h_flags) &&
1799 !bitintersect(h->h_mflags, mci->mci_mailer->m_flags) &&
1800 (h->h_macro == '\0' ||
1801 (q = macvalue(bitidx(h->h_macro), e)) == NULL ||
1805 sm_dprintf(" (skipped)\n");
1809 /* handle Resent-... headers specially */
1810 if (bitset(H_RESENT, h->h_flags) && !bitset(EF_RESENT, e->e_flags))
1813 sm_dprintf(" (skipped (resent))\n");
1817 /* suppress return receipts if requested */
1818 if (bitset(H_RECEIPTTO, h->h_flags) &&
1819 (RrtImpliesDsn || bitset(EF_NORECEIPT, e->e_flags)))
1822 sm_dprintf(" (skipped (receipt))\n");
1826 /* macro expand value if generated internally */
1827 if (bitset(H_DEFAULT, h->h_flags) ||
1828 bitset(H_BINDLATE, h->h_flags))
1830 expand(p, buf, sizeof(buf), e);
1835 sm_dprintf(" (skipped -- null value)\n");
1840 if (bitset(H_BCC, h->h_flags))
1842 /* Bcc: field -- either truncate or delete */
1843 if (bitset(EF_DELETE_BCC, e->e_flags))
1846 sm_dprintf(" (skipped -- bcc)\n");
1850 /* no other recipient headers: truncate value */
1851 (void) sm_strlcpyn(obuf, sizeof(obuf), 2,
1853 if (!putline(obuf, mci))
1862 if (bitset(H_FROM|H_RCPT, h->h_flags))
1865 bool oldstyle = bitset(EF_OLDSTYLE, e->e_flags);
1867 if (bitset(H_FROM, h->h_flags))
1869 commaize(h, p, oldstyle, mci, e);
1873 if (!put_vanilla_header(h, p, mci))
1879 ** If we are converting this to a MIME message, add the
1880 ** MIME headers (but not in MIME mode!).
1884 if (bitset(MM_MIME8BIT, MimeMode) &&
1885 bitset(EF_HAS8BIT, e->e_flags) &&
1886 !bitset(EF_DONT_MIME, e->e_flags) &&
1887 !bitnset(M_8BITS, mci->mci_mailer->m_flags) &&
1888 !bitset(MCIF_CVT8TO7|MCIF_CVT7TO8|MCIF_INMIME, mci->mci_flags) &&
1889 hvalue("MIME-Version", e->e_header) == NULL)
1891 if (!putline("MIME-Version: 1.0", mci))
1893 if (hvalue("Content-Type", e->e_header) == NULL)
1895 (void) sm_snprintf(obuf, sizeof(obuf),
1896 "Content-Type: text/plain; charset=%s",
1898 if (!putline(obuf, mci))
1901 if (hvalue("Content-Transfer-Encoding", e->e_header) == NULL
1902 && !putline("Content-Transfer-Encoding: 8bit", mci))
1905 #endif /* MIME8TO7 */
1913 ** PUT_VANILLA_HEADER -- output a fairly ordinary header
1916 ** h -- the structure describing this header
1917 ** v -- the value of this header
1918 ** mci -- the connection info for output
1921 ** true iff header was written successfully
1925 put_vanilla_header(h, v, mci)
1933 char obuf[MAXLINE + 256]; /* additional length for h_field */
1935 putflags = PXLF_HEADER | PXLF_STRIPMQUOTE;
1936 if (bitnset(M_7BITHDRS, mci->mci_mailer->m_flags))
1937 putflags |= PXLF_STRIP8BIT;
1938 (void) sm_snprintf(obuf, sizeof(obuf), "%.200s:", h->h_field);
1939 obp = obuf + strlen(obuf);
1940 while ((nlp = strchr(v, '\n')) != NULL)
1947 ** XXX This is broken for SPACELEFT()==0
1948 ** However, SPACELEFT() is always > 0 unless MAXLINE==1.
1951 if (SPACELEFT(obuf, obp) - 1 < (size_t) l)
1952 l = SPACELEFT(obuf, obp) - 1;
1954 (void) sm_snprintf(obp, SPACELEFT(obuf, obp), "%.*s", l, v);
1955 if (!putxline(obuf, strlen(obuf), mci, putflags))
1959 if (*v != ' ' && *v != '\t')
1963 /* XXX This is broken for SPACELEFT()==0 */
1964 (void) sm_snprintf(obp, SPACELEFT(obuf, obp), "%.*s",
1965 (int) (SPACELEFT(obuf, obp) - 1), v);
1966 return putxline(obuf, strlen(obuf), mci, putflags);
1973 ** COMMAIZE -- output a header field, making a comma-translated list.
1976 ** h -- the header field to output.
1977 ** p -- the value to put in it.
1978 ** oldstyle -- true if this is an old style header.
1979 ** mci -- the connection information.
1980 ** e -- the envelope containing the message.
1983 ** true iff header field was written successfully
1986 ** outputs "p" to "mci".
1990 commaize(h, p, oldstyle, mci, e)
1995 register ENVELOPE *e;
1998 int opos, omax, spaces;
1999 bool firstone = true;
2000 int putflags = PXLF_HEADER | PXLF_STRIPMQUOTE;
2002 char obuf[MAXLINE + 3];
2005 ** Output the address list translated by the
2006 ** mailer and with commas.
2010 sm_dprintf("commaize(%s:%s)\n", h->h_field, p);
2012 if (bitnset(M_7BITHDRS, mci->mci_mailer->m_flags))
2013 putflags |= PXLF_STRIP8BIT;
2016 (void) sm_snprintf(obp, SPACELEFT(obuf, obp), "%.200s:", h->h_field);
2017 /* opos = strlen(obp); instead of the next 3 lines? */
2018 opos = strlen(h->h_field) + 1;
2024 while (*p != '\0' && isascii(*p) && isspace(*p))
2031 SM_ASSERT(sizeof(obuf) > opos * 2);
2034 ** Restrict number of spaces to half the length of buffer
2035 ** so the header field body can be put in here too.
2036 ** Note: this is a hack...
2039 if (spaces > sizeof(obuf) / 2)
2040 spaces = sizeof(obuf) / 2;
2041 (void) sm_snprintf(obp, SPACELEFT(obuf, obp), "%*s", spaces,
2045 SM_ASSERT(obp < &obuf[MAXLINE]);
2048 omax = mci->mci_mailer->m_linelimit - 2;
2049 if (omax < 0 || omax > 78)
2053 ** Run through the list of values.
2058 register char *name;
2065 ** Find the end of the name. New style names
2066 ** end with a comma, old style names end with
2067 ** a space character. However, spaces do not
2068 ** necessarily delimit an old-style name -- at
2069 ** signs mean keep going.
2072 /* find end of name */
2073 while ((isascii(*p) && isspace(*p)) || *p == ',')
2080 char pvpbuf[PSBUFSIZE];
2082 res = prescan(p, oldstyle ? ' ' : ',', pvpbuf,
2083 sizeof(pvpbuf), &oldp, ExtTokenTab, false);
2085 #if _FFR_IGNORE_BOGUS_ADDR
2086 /* ignore addresses that can't be parsed */
2092 #endif /* _FFR_IGNORE_BOGUS_ADDR */
2094 /* look to see if we have an at sign */
2095 while (*p != '\0' && isascii(*p) && isspace(*p))
2104 while (*p != '\0' && isascii(*p) && isspace(*p))
2107 /* at the end of one complete name */
2109 /* strip off trailing white space */
2111 ((isascii(*p) && isspace(*p)) || *p == ',' || *p == '\0'))
2117 ** if prescan() failed go a bit backwards; this is a hack,
2118 ** there should be some better error recovery.
2121 if (res == NULL && p > name &&
2122 !((isascii(*p) && isspace(*p)) || *p == ',' || *p == '\0'))
2127 /* translate the name to be relative */
2128 flags = RF_HEADERADDR|RF_ADDDOMAIN;
2129 if (bitset(H_FROM, h->h_flags))
2130 flags |= RF_SENDERADDR;
2132 else if (e->e_from.q_mailer != NULL &&
2133 bitnset(M_UDBRECIPIENT, e->e_from.q_mailer->m_flags))
2137 q = udbsender(name, e->e_rpool);
2143 name = remotename(name, mci->mci_mailer, flags, &status, e);
2149 name = denlstring(name, false, true);
2151 /* output the name with nice formatting */
2152 opos += strlen(name);
2155 if (opos > omax && !firstone)
2157 (void) sm_strlcpy(obp, ",\n", SPACELEFT(obuf, obp));
2158 if (!putxline(obuf, strlen(obuf), mci, putflags))
2161 (void) sm_strlcpy(obp, " ", sizeof(obuf));
2164 opos += strlen(name);
2168 (void) sm_strlcpy(obp, ", ", SPACELEFT(obuf, obp));
2172 while ((c = *name++) != '\0' && obp < &obuf[MAXLINE])
2177 if (obp < &obuf[sizeof(obuf)])
2180 obuf[sizeof(obuf) - 1] = '\0';
2181 return putxline(obuf, strlen(obuf), mci, putflags);
2188 ** COPYHEADER -- copy header list
2190 ** This routine is the equivalent of newstr for header lists
2193 ** header -- list of header structures to copy.
2194 ** rpool -- resource pool, or NULL
2197 ** a copy of 'header'.
2204 copyheader(header, rpool)
2205 register HDR *header;
2208 register HDR *newhdr;
2210 register HDR **tail = &ret;
2212 while (header != NULL)
2214 newhdr = (HDR *) sm_rpool_malloc_x(rpool, sizeof(*newhdr));
2215 STRUCTCOPY(*header, *newhdr);
2217 tail = &newhdr->h_link;
2218 header = header->h_link;
2226 ** FIX_MIME_HEADER -- possibly truncate/rebalance parameters in a MIME header
2228 ** Run through all of the parameters of a MIME header and
2229 ** possibly truncate and rebalance the parameter according
2230 ** to MaxMimeFieldLength.
2233 ** h -- the header to truncate/rebalance
2234 ** e -- the current envelope
2237 ** length of last offending field, 0 if all ok.
2240 ** string modified in place
2244 fix_mime_header(h, e)
2248 char *begin = h->h_value;
2253 if (begin == NULL || *begin == '\0')
2256 /* Split on each ';' */
2257 /* find_character() never returns NULL */
2258 while ((end = find_character(begin, ';')) != NULL)
2265 len = strlen(begin);
2267 /* Shorten individual parameter */
2268 if (shorten_rfc822_string(begin, MaxMimeFieldLength))
2270 if (len < MaxMimeFieldLength)
2272 /* we only rebalanced a bogus field */
2273 sm_syslog(LOG_ALERT, e->e_id,
2274 "Fixed MIME %s header field (possible attack)",
2277 sm_dprintf(" fixed MIME %s header field (possible attack)\n",
2282 /* we actually shortened the header */
2287 /* Collapse the possibly shortened string with rest */
2288 bp = begin + strlen(begin);
2296 /* copy character by character due to overlap */