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.
15 #include <sm/sendmail.h>
17 SM_RCSID("@(#)$Id: headers.c,v 8.318 2012/06/14 23:54:02 ca Exp $")
19 static HDR *allocheader __P((char *, char *, int, SM_RPOOL_T *, bool));
20 static size_t fix_mime_header __P((HDR *, ENVELOPE *));
21 static int priencode __P((char *));
22 static bool put_vanilla_header __P((HDR *, char *, MCI *));
25 ** SETUPHEADERS -- initialize headers in symbol table
40 for (hi = HdrInfo; hi->hi_field != NULL; hi++)
42 s = stab(hi->hi_field, ST_HEADER, ST_ENTER);
43 s->s_header.hi_flags = hi->hi_flags;
44 s->s_header.hi_ruleset = NULL;
49 ** DOCHOMPHEADER -- process and save a header line.
51 ** Called by chompheader.
54 ** line -- header as a text line.
55 ** pflag -- flags for chompheader() (from sendmail.h)
56 ** hdrp -- a pointer to the place to save the header.
57 ** e -- the envelope including this header.
60 ** flags for this header.
63 ** The header is saved on the header list.
64 ** Contents of 'line' are destroyed.
67 static struct hdrinfo NormalHeader = { NULL, 0, NULL };
68 static unsigned long dochompheader __P((char *, int, HDR **, ENVELOPE *));
71 dochompheader(line, pflag, hdrp, e)
77 unsigned char mid = '\0';
88 bool nullheader = false;
91 headeronly = hdrp != NULL;
95 /* strip off options */
98 if (!bitset(pflag, CHHDR_USER) && *p == '?')
103 q = strchr(++p, '?');
110 /* possibly macro conditional */
111 if (c == MACROEXPAND)
120 mid = (unsigned char) *p++;
138 mid = (unsigned char) macid(p);
139 if (bitset(0200, mid))
141 p += strlen(macname(mid)) + 2;
164 setbitn(bitidx(*p), mopts);
172 /* find canonical name */
174 while (isascii(*p) && isgraph(*p) && *p != ':')
177 while (isascii(*p) && isspace(*p))
179 if (*p++ != ':' || fname == fvalue)
182 syserr("553 5.3.0 header syntax error, line \"%s\"", line);
188 /* if the field is null, go ahead and use the default */
189 while (isascii(*p) && isspace(*p))
194 /* security scan: long field names are end-of-header */
195 if (strlen(fname) > 100)
198 /* check to see if it represents a ruleset call */
199 if (bitset(pflag, CHHDR_DEF))
203 (void) expand(fvalue, hbuf, sizeof(hbuf), e);
204 for (p = hbuf; isascii(*p) && isspace(*p); )
206 if ((*p++ & 0377) == CALLSUBR)
211 strc = *p == '+'; /* strip comments? */
214 if (strtorwset(p, &endp, ST_ENTER) > 0)
217 s = stab(fname, ST_HEADER, ST_ENTER);
219 s->s_header.hi_ruleset != NULL)
220 sm_syslog(LOG_WARNING, NOQID,
221 "Warning: redefined ruleset for header=%s, old=%s, new=%s",
223 s->s_header.hi_ruleset, p);
224 s->s_header.hi_ruleset = newstr(p);
226 s->s_header.hi_flags |= H_STRIPCOMM;
232 /* see if it is a known type */
233 s = stab(fname, ST_HEADER, ST_FIND);
242 sm_dprintf("no header flags match\n");
244 sm_dprintf("header match, flags=%lx, ruleset=%s\n",
246 hi->hi_ruleset == NULL ? "<NULL>"
250 /* see if this is a resent message */
251 if (!bitset(pflag, CHHDR_DEF) && !headeronly &&
252 bitset(H_RESENT, hi->hi_flags))
253 e->e_flags |= EF_RESENT;
255 /* if this is an Errors-To: header keep track of it now */
256 if (UseErrorsTo && !bitset(pflag, CHHDR_DEF) && !headeronly &&
257 bitset(H_ERRORSTO, hi->hi_flags))
258 (void) sendtolist(fvalue, NULLADDR, &e->e_errorqueue, 0, e);
260 /* if this means "end of header" quit now */
261 if (!headeronly && bitset(H_EOH, hi->hi_flags))
265 ** Horrible hack to work around problem with Lotus Notes SMTP
266 ** mail gateway, which generates From: headers with newlines in
267 ** them and the <address> on the second line. Although this is
268 ** legal RFC 822, many MUAs don't handle this properly and thus
269 ** never find the actual address.
272 if (bitset(H_FROM, hi->hi_flags) && SingleLineFromHeader)
274 while ((p = strchr(fvalue, '\n')) != NULL)
279 ** If there is a check ruleset, verify it against the header.
282 if (bitset(pflag, CHHDR_CHECK))
287 rscheckflags = RSF_COUNT;
288 if (!bitset(hi->hi_flags, H_FROM|H_RCPT))
289 rscheckflags |= RSF_UNSTRUCTURED;
291 /* no ruleset? look for default */
295 s = stab("*", ST_HEADER, ST_FIND);
298 rs = (&s->s_header)->hi_ruleset;
299 if (bitset((&s->s_header)->hi_flags,
301 rscheckflags |= RSF_RMCOMM;
304 else if (bitset(hi->hi_flags, H_STRIPCOMM))
305 rscheckflags |= RSF_RMCOMM;
314 /* - 3 to avoid problems with " at the end */
315 /* should be sizeof(qval), not MAXNAME */
316 for (k = 0; fvalue[k] != '\0' && l < MAXNAME - 3; k++)
320 /* XXX other control chars? */
321 case '\011': /* ht */
322 case '\012': /* nl */
323 case '\013': /* vt */
324 case '\014': /* np */
325 case '\015': /* cr */
332 qval[l++] = fvalue[k];
338 k += strlen(fvalue + k);
342 sm_syslog(LOG_WARNING, e->e_id,
343 "Warning: truncated header '%s' before check with '%s' len=%d max=%d",
344 fname, rs, k, MAXNAME - 1);
346 macdefine(&e->e_macro, A_TEMP,
347 macid("{currHeader}"), qval);
348 macdefine(&e->e_macro, A_TEMP,
349 macid("{hdr_name}"), fname);
351 (void) sm_snprintf(qval, sizeof(qval), "%d", k);
352 macdefine(&e->e_macro, A_TEMP, macid("{hdrlen}"), qval);
353 if (bitset(H_FROM, hi->hi_flags))
354 macdefine(&e->e_macro, A_PERM,
355 macid("{addr_type}"), "h s");
356 else if (bitset(H_RCPT, hi->hi_flags))
357 macdefine(&e->e_macro, A_PERM,
358 macid("{addr_type}"), "h r");
360 macdefine(&e->e_macro, A_PERM,
361 macid("{addr_type}"), "h");
362 (void) rscheck(rs, fvalue, NULL, e, rscheckflags, 3,
363 NULL, e->e_id, NULL);
368 ** Drop explicit From: if same as what we would generate.
369 ** This is to make MH (which doesn't always give a full name)
370 ** insert the full name information in all circumstances.
375 if (!bitset(EF_RESENT, e->e_flags))
377 if (!bitset(pflag, CHHDR_DEF) && !headeronly &&
378 !bitset(EF_QUEUERUN, e->e_flags) && sm_strcasecmp(fname, p) == 0)
382 sm_dprintf("comparing header from (%s) against default (%s or %s)\n",
383 fvalue, e->e_from.q_paddr, e->e_from.q_user);
385 if (e->e_from.q_paddr != NULL &&
386 e->e_from.q_mailer != NULL &&
387 bitnset(M_LOCALMAILER, e->e_from.q_mailer->m_flags) &&
388 (strcmp(fvalue, e->e_from.q_paddr) == 0 ||
389 strcmp(fvalue, e->e_from.q_user) == 0))
393 /* delete default value for this header */
394 for (hp = hdrp; (h = *hp) != NULL; hp = &h->h_link)
396 if (sm_strcasecmp(fname, h->h_field) == 0 &&
397 !bitset(H_USER, h->h_flags) &&
398 !bitset(H_FORCE, h->h_flags))
402 /* user-supplied value was null */
407 /* make this look like the user entered it */
408 h->h_flags |= H_USER;
414 /* copy conditions from default case */
415 memmove((char *) mopts, (char *) h->h_mflags,
422 /* create a new node */
423 h = (HDR *) sm_rpool_malloc_x(e->e_rpool, sizeof(*h));
424 h->h_field = sm_rpool_strdup_x(e->e_rpool, fname);
425 h->h_value = sm_rpool_strdup_x(e->e_rpool, fvalue);
427 memmove((char *) h->h_mflags, (char *) mopts, sizeof(mopts));
430 h->h_flags = hi->hi_flags;
431 if (bitset(pflag, CHHDR_USER) || bitset(pflag, CHHDR_QUEUE))
432 h->h_flags |= H_USER;
434 /* strip EOH flag if parsing MIME headers */
436 h->h_flags &= ~H_EOH;
437 if (bitset(pflag, CHHDR_DEF))
438 h->h_flags |= H_DEFAULT;
439 if (cond || mid != '\0')
440 h->h_flags |= H_CHECK;
442 /* hack to see if this is a new format message */
443 if (!bitset(pflag, CHHDR_DEF) && !headeronly &&
444 bitset(H_RCPT|H_FROM, h->h_flags) &&
445 (strchr(fvalue, ',') != NULL || strchr(fvalue, '(') != NULL ||
446 strchr(fvalue, '<') != NULL || strchr(fvalue, ';') != NULL))
448 e->e_flags &= ~EF_OLDSTYLE;
455 ** CHOMPHEADER -- process and save a header line.
457 ** Called by collect, readcf, and readqf to deal with header lines.
458 ** This is just a wrapper for dochompheader().
461 ** line -- header as a text line.
462 ** pflag -- flags for chompheader() (from sendmail.h)
463 ** hdrp -- a pointer to the place to save the header.
464 ** e -- the envelope including this header.
467 ** flags for this header.
470 ** The header is saved on the header list.
471 ** Contents of 'line' are destroyed.
476 chompheader(line, pflag, hdrp, e)
480 register ENVELOPE *e;
486 sm_dprintf("chompheader: ");
487 xputs(sm_debug_file(), line);
491 /* quote this if user (not config file) input */
492 if (bitset(pflag, CHHDR_USER))
498 xbufs = sizeof(xbuf);
499 xbp = quote_internal_chars(line, xbuf, &xbufs);
502 sm_dprintf("chompheader: quoted: ");
503 xputs(sm_debug_file(), xbp);
506 rval = dochompheader(xbp, pflag, hdrp, e);
511 rval = dochompheader(line, pflag, hdrp, e);
517 ** ALLOCHEADER -- allocate a header entry
520 ** field -- the name of the header field (will not be copied).
521 ** value -- the value of the field (will be copied).
522 ** flags -- flags to add to h_flags.
523 ** rp -- resource pool for allocations
524 ** space -- add leading space?
527 ** Pointer to a newly allocated and populated HDR.
530 ** o field and value must be in internal format, i.e.,
531 ** metacharacters must be "quoted", see quote_internal_chars().
532 ** o maybe add more flags to decide:
533 ** - what to copy (field/value)
534 ** - whether to convert value to an internal format
538 allocheader(field, value, flags, rp, space)
548 /* find info struct */
549 s = stab(field, ST_HEADER, ST_FIND);
551 /* allocate space for new header */
552 h = (HDR *) sm_rpool_malloc_x(rp, sizeof(*h));
560 SM_ASSERT(l + 2 > l);
561 n = sm_rpool_malloc_x(rp, l + 2);
564 sm_strlcpy(n + 1, value, l + 1);
568 h->h_value = sm_rpool_strdup_x(rp, value);
571 h->h_flags |= s->s_header.hi_flags;
572 clrbitmap(h->h_mflags);
579 ** ADDHEADER -- add a header entry to the end of the queue.
581 ** This bypasses the special checking of chompheader.
584 ** field -- the name of the header field (will not be copied).
585 ** value -- the value of the field (will be copied).
586 ** flags -- flags to add to h_flags.
588 ** space -- add leading space?
594 ** adds the field on the list of headers for this envelope.
596 ** Notes: field and value must be in internal format, i.e.,
597 ** metacharacters must be "quoted", see quote_internal_chars().
601 addheader(field, value, flags, e, space)
610 HDR **hdrlist = &e->e_header;
612 /* find current place in list -- keep back pointer? */
613 for (hp = hdrlist; (h = *hp) != NULL; hp = &h->h_link)
615 if (sm_strcasecmp(field, h->h_field) == 0)
619 /* allocate space for new header */
620 h = allocheader(field, value, flags, e->e_rpool, space);
626 ** INSHEADER -- insert a header entry at the specified index
627 ** This bypasses the special checking of chompheader.
630 ** idx -- index into the header list at which to insert
631 ** field -- the name of the header field (will be copied).
632 ** value -- the value of the field (will be copied).
633 ** flags -- flags to add to h_flags.
635 ** space -- add leading space?
641 ** inserts the field on the list of headers for this envelope.
644 ** - field and value must be in internal format, i.e.,
645 ** metacharacters must be "quoted", see quote_internal_chars().
646 ** - the header list contains headers that might not be
647 ** sent "out" (see putheader(): "skip"), hence there is no
648 ** reliable way to insert a header at an exact position
649 ** (except at the front or end).
653 insheader(idx, field, value, flags, e, space)
661 HDR *h, *srch, *last = NULL;
663 /* allocate space for new header */
664 h = allocheader(field, value, flags, e->e_rpool, space);
666 /* find insertion position */
667 for (srch = e->e_header; srch != NULL && idx > 0;
668 srch = srch->h_link, idx--)
671 if (e->e_header == NULL)
676 else if (srch == NULL)
678 SM_ASSERT(last != NULL);
684 h->h_link = srch->h_link;
690 ** HVALUE -- return value of a header.
692 ** Only "real" fields (i.e., ones that have not been supplied
693 ** as a default) are used.
696 ** field -- the field name.
697 ** header -- the header list.
700 ** pointer to the value part (internal format).
701 ** NULL if not found.
708 hvalue(field, header)
714 for (h = header; h != NULL; h = h->h_link)
716 if (!bitset(H_DEFAULT, h->h_flags) &&
717 sm_strcasecmp(h->h_field, field) == 0)
724 while (isascii(*s) && isspace(*s))
733 ** ISHEADER -- predicate telling if argument is a header.
735 ** A line is a header if it has a single word followed by
736 ** optional white space followed by a colon.
738 ** Header fields beginning with two dashes, although technically
739 ** permitted by RFC822, are automatically rejected in order
740 ** to make MIME work out. Without this we could have a technically
741 ** legal header such as ``--"foo:bar"'' that would also be a legal
745 ** h -- string to check for possible headerness.
748 ** true if h is a header.
762 if (s[0] == '-' && s[1] == '-')
765 while (*s > ' ' && *s != ':' && *s != '\0')
771 /* following technically violates RFC822 */
772 while (isascii(*s) && isspace(*s))
779 ** EATHEADER -- run through the stored header and extract info.
782 ** e -- the envelope to process.
783 ** full -- if set, do full processing (e.g., compute
784 ** message priority). This should not be set
785 ** when reading a queue file because some info
786 ** needed to compute the priority is wrong.
787 ** log -- call logsender()?
793 ** Sets a bunch of global variables from information
794 ** in the collected header.
798 eatheader(e, full, log)
799 register ENVELOPE *e;
809 ** Set up macros for possible expansion in headers.
812 macdefine(&e->e_macro, A_PERM, 'f', e->e_sender);
813 macdefine(&e->e_macro, A_PERM, 'g', e->e_sender);
814 if (e->e_origrcpt != NULL && *e->e_origrcpt != '\0')
815 macdefine(&e->e_macro, A_PERM, 'u', e->e_origrcpt);
817 macdefine(&e->e_macro, A_PERM, 'u', NULL);
819 /* full name of from person */
820 p = hvalue("full-name", e->e_header);
823 if (!rfc822_string(p))
826 ** Quote a full name with special characters
827 ** as a comment so crackaddr() doesn't destroy
828 ** the name portion of the address.
831 p = addquotes(p, e->e_rpool);
833 macdefine(&e->e_macro, A_PERM, 'x', p);
837 sm_dprintf("----- collected header -----\n");
839 for (h = e->e_header; h != NULL; h = h->h_link)
842 sm_dprintf("%s:", h->h_field);
843 if (h->h_value == NULL)
846 sm_dprintf("<NULL>\n");
850 /* do early binding */
851 if (bitset(H_DEFAULT, h->h_flags) &&
852 !bitset(H_BINDLATE, h->h_flags))
857 xputs(sm_debug_file(), h->h_value);
860 expand(h->h_value, buf, sizeof(buf), e);
861 if (buf[0] != '\0' &&
862 (buf[0] != ' ' || buf[1] != '\0'))
864 if (bitset(H_FROM, h->h_flags))
865 expand(crackaddr(buf, e),
866 buf, sizeof(buf), e);
867 h->h_value = sm_rpool_strdup_x(e->e_rpool, buf);
868 h->h_flags &= ~H_DEFAULT;
873 xputs(sm_debug_file(), h->h_value);
877 /* count the number of times it has been processed */
878 if (bitset(H_TRACE, h->h_flags))
881 /* send to this person if we so desire */
882 if (GrabTo && bitset(H_RCPT, h->h_flags) &&
883 !bitset(H_DEFAULT, h->h_flags) &&
884 (!bitset(EF_RESENT, e->e_flags) ||
885 bitset(H_RESENT, h->h_flags)))
888 int saveflags = e->e_flags;
891 (void) sendtolist(denlstring(h->h_value, true, false),
892 NULLADDR, &e->e_sendqueue, 0, e);
896 ** Change functionality so a fatal error on an
897 ** address doesn't affect the entire envelope.
900 /* delete fatal errors generated by this address */
901 if (!bitset(EF_FATALERRS, saveflags))
902 e->e_flags &= ~EF_FATALERRS;
906 /* save the message-id for logging */
907 p = "resent-message-id";
908 if (!bitset(EF_RESENT, e->e_flags))
910 if (sm_strcasecmp(h->h_field, p) == 0)
912 e->e_msgid = h->h_value;
913 while (isascii(*e->e_msgid) && isspace(*e->e_msgid))
915 macdefine(&e->e_macro, A_PERM, macid("{msg_id}"),
920 sm_dprintf("----------------------------\n");
922 /* if we are just verifying (that is, sendmail -t -bv), drop out now */
923 if (OpMode == MD_VERIFY)
926 /* store hop count */
927 if (hopcnt > e->e_hopcount)
929 e->e_hopcount = hopcnt;
930 (void) sm_snprintf(buf, sizeof(buf), "%d", e->e_hopcount);
931 macdefine(&e->e_macro, A_TEMP, 'c', buf);
934 /* message priority */
935 p = hvalue("precedence", e->e_header);
937 e->e_class = priencode(p);
939 e->e_timeoutclass = TOC_NONURGENT;
940 else if (e->e_class > 0)
941 e->e_timeoutclass = TOC_URGENT;
944 e->e_msgpriority = e->e_msgsize
945 - e->e_class * WkClassFact
946 + e->e_nrcpts * WkRecipFact;
949 /* check for DSN to properly set e_timeoutclass */
950 p = hvalue("content-type", e->e_header);
955 char pvpbuf[MAXLINE];
956 extern unsigned char MimeTokenTab[256];
958 /* tokenize header */
961 pvp = prescan(p, '\0', pvpbuf, sizeof(pvpbuf), NULL,
962 MimeTokenTab, false);
965 /* Check if multipart/report */
966 if (pvp != NULL && pvp[0] != NULL &&
967 pvp[1] != NULL && pvp[2] != NULL &&
968 sm_strcasecmp(*pvp++, "multipart") == 0 &&
969 strcmp(*pvp++, "/") == 0 &&
970 sm_strcasecmp(*pvp++, "report") == 0)
972 /* Look for report-type=delivery-status */
975 /* skip to semicolon separator */
976 while (*pvp != NULL && strcmp(*pvp, ";") != 0)
980 if (*pvp++ == NULL || *pvp == NULL)
983 /* look for report-type */
984 if (sm_strcasecmp(*pvp++, "report-type") != 0)
988 if (*pvp == NULL || strcmp(*pvp, "=") != 0)
992 if (*++pvp != NULL &&
994 "delivery-status") == 0)
995 e->e_timeoutclass = TOC_DSN;
997 /* found report-type, no need to continue */
1003 /* message timeout priority */
1004 p = hvalue("priority", e->e_header);
1007 /* (this should be in the configuration file) */
1008 if (sm_strcasecmp(p, "urgent") == 0)
1009 e->e_timeoutclass = TOC_URGENT;
1010 else if (sm_strcasecmp(p, "normal") == 0)
1011 e->e_timeoutclass = TOC_NORMAL;
1012 else if (sm_strcasecmp(p, "non-urgent") == 0)
1013 e->e_timeoutclass = TOC_NONURGENT;
1014 else if (bitset(EF_RESPONSE, e->e_flags))
1015 e->e_timeoutclass = TOC_DSN;
1017 else if (bitset(EF_RESPONSE, e->e_flags))
1018 e->e_timeoutclass = TOC_DSN;
1020 /* date message originated */
1021 p = hvalue("posted-date", e->e_header);
1023 p = hvalue("date", e->e_header);
1025 macdefine(&e->e_macro, A_PERM, 'a', p);
1027 /* check to see if this is a MIME message */
1028 if ((e->e_bodytype != NULL &&
1029 sm_strcasecmp(e->e_bodytype, "8BITMIME") == 0) ||
1030 hvalue("MIME-Version", e->e_header) != NULL)
1032 e->e_flags |= EF_IS_MIME;
1034 e->e_bodytype = "8BITMIME";
1036 else if ((p = hvalue("Content-Type", e->e_header)) != NULL)
1038 /* this may be an RFC 1049 message */
1039 p = strpbrk(p, ";/");
1040 if (p == NULL || *p == ';')
1043 e->e_flags |= EF_DONT_MIME;
1048 ** From person in antiquated ARPANET mode
1049 ** required by UK Grey Book e-mail gateways (sigh)
1052 if (OpMode == MD_ARPAFTP)
1054 register struct hdrinfo *hi;
1056 for (hi = HdrInfo; hi->hi_field != NULL; hi++)
1058 if (bitset(H_FROM, hi->hi_flags) &&
1059 (!bitset(H_RESENT, hi->hi_flags) ||
1060 bitset(EF_RESENT, e->e_flags)) &&
1061 (p = hvalue(hi->hi_field, e->e_header)) != NULL)
1064 if (hi->hi_field != NULL)
1067 sm_dprintf("eatheader: setsender(*%s == %s)\n",
1069 setsender(p, e, NULL, '\0', true);
1074 ** Log collection information.
1078 sm_dprintf("eatheader: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d, log=%d\n",
1079 e->e_id, bitset(EF_LOGSENDER, e->e_flags), LogLevel,
1081 if (log && bitset(EF_LOGSENDER, e->e_flags) && LogLevel > 4)
1083 logsender(e, e->e_msgid);
1084 e->e_flags &= ~EF_LOGSENDER;
1089 ** LOGSENDER -- log sender information
1092 ** e -- the envelope to log
1093 ** msgid -- the message id
1101 register ENVELOPE *e;
1107 char hbuf[MAXNAME + 1];
1108 char sbuf[MAXLINE + 1];
1109 char mbuf[MAXNAME + 1];
1111 /* don't allow newlines in the message-id */
1112 /* XXX do we still need this? sm_syslog() replaces control chars */
1118 if (l > sizeof(mbuf) - 1)
1119 l = sizeof(mbuf) - 1;
1120 memmove(mbuf, msgid, l);
1123 while ((p = strchr(p, '\n')) != NULL)
1127 if (bitset(EF_RESPONSE, e->e_flags))
1128 name = "[RESPONSE]";
1129 else if ((name = macvalue('_', e)) != NULL)
1132 else if (RealHostName == NULL)
1134 else if (RealHostName[0] == '[')
1135 name = RealHostName;
1139 (void) sm_snprintf(hbuf, sizeof(hbuf), "%.80s", RealHostName);
1140 if (RealHostAddr.sa.sa_family != 0)
1142 p = &hbuf[strlen(hbuf)];
1143 (void) sm_snprintf(p, SPACELEFT(hbuf, p),
1145 anynet_ntoa(&RealHostAddr));
1149 /* some versions of syslog only take 5 printf args */
1150 #if (SYSLOG_BUFSIZE) >= 256
1152 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1153 "from=%.200s, size=%ld, class=%d, nrcpts=%d",
1154 e->e_from.q_paddr == NULL ? "<NONE>" : e->e_from.q_paddr,
1155 PRT_NONNEGL(e->e_msgsize), e->e_class, e->e_nrcpts);
1159 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1160 ", msgid=%.100s", mbuf);
1163 if (e->e_bodytype != NULL)
1165 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1166 ", bodytype=%.20s", e->e_bodytype);
1169 p = macvalue('r', e);
1172 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1173 ", proto=%.20s", p);
1176 p = macvalue(macid("{daemon_name}"), e);
1179 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1180 ", daemon=%.20s", p);
1183 sm_syslog(LOG_INFO, e->e_id, "%.850s, relay=%s", sbuf, name);
1185 #else /* (SYSLOG_BUFSIZE) >= 256 */
1187 sm_syslog(LOG_INFO, e->e_id,
1189 e->e_from.q_paddr == NULL ? "<NONE>"
1190 : shortenstring(e->e_from.q_paddr,
1192 sm_syslog(LOG_INFO, e->e_id,
1193 "size=%ld, class=%ld, nrcpts=%d",
1194 PRT_NONNEGL(e->e_msgsize), e->e_class, e->e_nrcpts);
1196 sm_syslog(LOG_INFO, e->e_id,
1198 shortenstring(mbuf, 83));
1201 if (e->e_bodytype != NULL)
1203 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1204 "bodytype=%.20s, ", e->e_bodytype);
1207 p = macvalue('r', e);
1210 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1211 "proto=%.20s, ", p);
1214 sm_syslog(LOG_INFO, e->e_id,
1215 "%.400srelay=%s", sbuf, name);
1216 #endif /* (SYSLOG_BUFSIZE) >= 256 */
1220 ** PRIENCODE -- encode external priority names into internal values.
1223 ** p -- priority in ascii.
1226 ** priority as a numeric level.
1238 for (i = 0; i < NumPriorities; i++)
1240 if (sm_strcasecmp(p, Priorities[i].pri_name) == 0)
1241 return Priorities[i].pri_val;
1244 /* unknown priority */
1249 ** CRACKADDR -- parse an address and turn it into a macro
1251 ** This doesn't actually parse the address -- it just extracts
1252 ** it and replaces it with "$g". The parse is totally ad hoc
1253 ** and isn't even guaranteed to leave something syntactically
1254 ** identical to what it started with. However, it does leave
1255 ** something semantically identical if possible, else at least
1256 ** syntactically correct.
1258 ** For example, it changes "Real Name <real@example.com> (Comment)"
1259 ** to "Real Name <$g> (Comment)".
1261 ** This algorithm has been cleaned up to handle a wider range
1262 ** of cases -- notably quoted and backslash escaped strings.
1263 ** This modification makes it substantially better at preserving
1264 ** the original syntax.
1267 ** addr -- the address to be cracked.
1268 ** e -- the current envelope.
1271 ** a pointer to the new version.
1277 ** The return value is saved in local storage and should
1278 ** be copied if it is to be reused.
1281 #define SM_HAVE_ROOM ((bp < buflim) && (buflim <= bufend))
1284 ** Append a character to bp if we have room.
1285 ** If not, punt and return $g.
1288 #define SM_APPEND_CHAR(c) \
1298 ERROR MAXNAME must be at least 10
1299 #endif /* MAXNAME < 10 */
1303 register char *addr;
1308 int cmtlev; /* comment level in input string */
1309 int realcmtlev; /* comment level in output string */
1310 int anglelev; /* angle level in input string */
1311 int copylev; /* 0 == in address, >0 copying */
1312 int bracklev; /* bracket level for IPv6 addr check */
1313 bool addangle; /* put closing angle in output */
1314 bool qmode; /* quoting in original string? */
1315 bool realqmode; /* quoting in output string? */
1316 bool putgmac = false; /* already wrote $g */
1317 bool quoteit = false; /* need to quote next character */
1318 bool gotangle = false; /* found first '<' */
1319 bool gotcolon = false; /* found a ':' */
1325 static char buf[MAXNAME + 1];
1328 sm_dprintf("crackaddr(%s)\n", addr);
1330 buflim = bufend = &buf[sizeof(buf) - 1];
1333 /* skip over leading spaces but preserve them */
1334 while (*addr != '\0' && isascii(*addr) && isspace(*addr))
1336 SM_APPEND_CHAR(*addr);
1342 ** Start by assuming we have no angle brackets. This will be
1343 ** adjusted later if we find them.
1346 p = addrhead = addr;
1347 copylev = anglelev = cmtlev = realcmtlev = 0;
1349 qmode = realqmode = addangle = false;
1351 while ((c = *p++) != '\0')
1354 ** Try to keep legal syntax using spare buffer space
1355 ** (maintained by buflim).
1361 /* check for backslash escapes */
1364 /* arrange to quote the address */
1365 if (cmtlev <= 0 && !qmode)
1368 if ((c = *p++) == '\0')
1379 /* check for quoted strings */
1380 if (c == '"' && cmtlev <= 0)
1383 if (copylev > 0 && SM_HAVE_ROOM)
1389 realqmode = !realqmode;
1396 /* check for comments */
1401 /* allow space for closing paren */
1409 SM_APPEND_CHAR(' ');
1430 /* syntax error: unmatched ) */
1431 if (copylev > 0 && SM_HAVE_ROOM && bp > bufhead)
1435 /* count nesting on [ ... ] (for IPv6 domain literals) */
1441 /* check for group: list; syntax */
1442 if (c == ':' && anglelev <= 0 && bracklev <= 0 &&
1443 !gotcolon && !ColonOkInAddr)
1448 ** Check for DECnet phase IV ``::'' (host::user)
1449 ** or DECnet phase V ``:.'' syntaxes. The latter
1450 ** covers ``user@DEC:.tay.myhost'' and
1451 ** ``DEC:.tay.myhost::user'' syntaxes (bletch).
1454 if (*p == ':' || *p == '.')
1456 if (cmtlev <= 0 && !qmode)
1472 SM_APPEND_CHAR('"');
1474 /* back up over the ':' and any spaces */
1477 isascii(*--p) && isspace(*p))
1481 for (q = addrhead; q < p; )
1484 if (quoteit && c == '"')
1485 SM_APPEND_CHAR('\\');
1490 if (bp == &bufhead[1])
1493 SM_APPEND_CHAR('"');
1494 while ((c = *p++) != ':')
1499 /* any trailing white space is part of group: */
1500 while (isascii(*p) && isspace(*p))
1506 putgmac = quoteit = false;
1512 if (c == ';' && copylev <= 0 && !ColonOkInAddr)
1515 /* check for characters that may have to be quoted */
1516 if (strchr(MustQuoteChars, c) != NULL)
1519 ** If these occur as the phrase part of a <>
1520 ** construct, but are not inside of () or already
1521 ** quoted, they will have to be quoted. Note that
1522 ** now (but don't actually do the quoting).
1525 if (cmtlev <= 0 && !qmode)
1529 /* check for angle brackets */
1534 /* assume first of two angles is bogus */
1539 /* oops -- have to change our mind */
1551 SM_APPEND_CHAR('"');
1553 /* back up over the '<' and any spaces */
1556 isascii(*--p) && isspace(*p))
1560 for (q = addrhead; q < p; )
1563 if (quoteit && c == '"')
1565 SM_APPEND_CHAR('\\');
1576 SM_APPEND_CHAR('"');
1577 while ((c = *p++) != '<')
1582 putgmac = quoteit = false;
1598 else if (SM_HAVE_ROOM)
1600 /* syntax error: unmatched > */
1601 if (copylev > 0 && bp > bufhead)
1611 /* must be a real address character */
1613 if (copylev <= 0 && !putgmac)
1615 if (bp > buf && bp[-1] == ')')
1616 SM_APPEND_CHAR(' ');
1617 SM_APPEND_CHAR(MACROEXPAND);
1618 SM_APPEND_CHAR('g');
1623 /* repair any syntactic damage */
1624 if (realqmode && bp < bufend)
1626 while (realcmtlev-- > 0 && bp < bufend)
1628 if (addangle && bp < bufend)
1635 /* String too long, punt */
1637 buf[1] = MACROEXPAND;
1641 sm_syslog(LOG_ALERT, e->e_id,
1642 "Dropped invalid comments from header address");
1647 sm_dprintf("crackaddr=>`");
1648 xputs(sm_debug_file(), buf);
1655 ** PUTHEADER -- put the header part of a message from the in-core copy
1658 ** mci -- the connection information.
1659 ** hdr -- the header to put.
1660 ** e -- envelope to use.
1661 ** flags -- MIME conversion flags.
1664 ** true iff header part was written successfully
1671 putheader(mci, hdr, e, flags)
1674 register ENVELOPE *e;
1678 char buf[SM_MAX(MAXLINE,BUFSIZ)];
1682 sm_dprintf("--- putheader, mailer = %s ---\n",
1683 mci->mci_mailer->m_name);
1686 ** If we're in MIME mode, we're not really in the header of the
1687 ** message, just the header of one of the parts of the body of
1688 ** the message. Therefore MCIF_INHEADER should not be turned on.
1691 if (!bitset(MCIF_INMIME, mci->mci_flags))
1692 mci->mci_flags |= MCIF_INHEADER;
1694 for (h = hdr; h != NULL; h = h->h_link)
1696 register char *p = h->h_value;
1701 sm_dprintf(" %s:", h->h_field);
1702 xputs(sm_debug_file(), p);
1705 /* Skip empty headers */
1706 if (h->h_value == NULL)
1709 /* heuristic shortening of MIME fields to avoid MUA overflows */
1710 if (MaxMimeFieldLength > 0 &&
1711 wordinclass(h->h_field,
1712 macid("{checkMIMEFieldHeaders}")))
1716 len = fix_mime_header(h, e);
1719 sm_syslog(LOG_ALERT, e->e_id,
1720 "Truncated MIME %s header due to field size (length = %ld) (possible attack)",
1721 h->h_field, (unsigned long) len);
1723 sm_dprintf(" truncated MIME %s header due to field size (length = %ld) (possible attack)\n",
1725 (unsigned long) len);
1729 if (MaxMimeHeaderLength > 0 &&
1730 wordinclass(h->h_field,
1731 macid("{checkMIMETextHeaders}")))
1735 len = strlen(h->h_value);
1736 if (len > (size_t) MaxMimeHeaderLength)
1738 h->h_value[MaxMimeHeaderLength - 1] = '\0';
1739 sm_syslog(LOG_ALERT, e->e_id,
1740 "Truncated long MIME %s header (length = %ld) (possible attack)",
1741 h->h_field, (unsigned long) len);
1743 sm_dprintf(" truncated long MIME %s header (length = %ld) (possible attack)\n",
1745 (unsigned long) len);
1749 if (MaxMimeHeaderLength > 0 &&
1750 wordinclass(h->h_field,
1751 macid("{checkMIMEHeaders}")))
1755 len = strlen(h->h_value);
1756 if (shorten_rfc822_string(h->h_value,
1757 MaxMimeHeaderLength))
1759 if (len < MaxMimeHeaderLength)
1761 /* we only rebalanced a bogus header */
1762 sm_syslog(LOG_ALERT, e->e_id,
1763 "Fixed MIME %s header (possible attack)",
1766 sm_dprintf(" fixed MIME %s header (possible attack)\n",
1771 /* we actually shortened header */
1772 sm_syslog(LOG_ALERT, e->e_id,
1773 "Truncated long MIME %s header (length = %ld) (possible attack)",
1775 (unsigned long) len);
1777 sm_dprintf(" truncated long MIME %s header (length = %ld) (possible attack)\n",
1779 (unsigned long) len);
1785 ** Suppress Content-Transfer-Encoding: if we are MIMEing
1786 ** and we are potentially converting from 8 bit to 7 bit
1787 ** MIME. If converting, add a new CTE header in
1791 if (bitset(H_CTE, h->h_flags) &&
1792 bitset(MCIF_CVT8TO7|MCIF_CVT7TO8|MCIF_INMIME,
1794 !bitset(M87F_NO8TO7, flags))
1797 sm_dprintf(" (skipped (content-transfer-encoding))\n");
1801 if (bitset(MCIF_INMIME, mci->mci_flags))
1805 if (!put_vanilla_header(h, p, mci))
1810 if (bitset(H_CHECK|H_ACHECK, h->h_flags) &&
1811 !bitintersect(h->h_mflags, mci->mci_mailer->m_flags) &&
1812 (h->h_macro == '\0' ||
1813 (q = macvalue(bitidx(h->h_macro), e)) == NULL ||
1817 sm_dprintf(" (skipped)\n");
1821 /* handle Resent-... headers specially */
1822 if (bitset(H_RESENT, h->h_flags) && !bitset(EF_RESENT, e->e_flags))
1825 sm_dprintf(" (skipped (resent))\n");
1829 /* suppress return receipts if requested */
1830 if (bitset(H_RECEIPTTO, h->h_flags) &&
1831 (RrtImpliesDsn || bitset(EF_NORECEIPT, e->e_flags)))
1834 sm_dprintf(" (skipped (receipt))\n");
1838 /* macro expand value if generated internally */
1839 if (bitset(H_DEFAULT, h->h_flags) ||
1840 bitset(H_BINDLATE, h->h_flags))
1842 expand(p, buf, sizeof(buf), e);
1847 sm_dprintf(" (skipped -- null value)\n");
1852 if (bitset(H_BCC, h->h_flags))
1854 /* Bcc: field -- either truncate or delete */
1855 if (bitset(EF_DELETE_BCC, e->e_flags))
1858 sm_dprintf(" (skipped -- bcc)\n");
1862 /* no other recipient headers: truncate value */
1863 (void) sm_strlcpyn(obuf, sizeof(obuf), 2,
1865 if (!putline(obuf, mci))
1874 if (bitset(H_FROM|H_RCPT, h->h_flags))
1877 bool oldstyle = bitset(EF_OLDSTYLE, e->e_flags);
1879 if (bitset(H_FROM, h->h_flags))
1881 commaize(h, p, oldstyle, mci, e,
1882 PXLF_HEADER | PXLF_STRIPMQUOTE);
1886 if (!put_vanilla_header(h, p, mci))
1892 ** If we are converting this to a MIME message, add the
1893 ** MIME headers (but not in MIME mode!).
1897 if (bitset(MM_MIME8BIT, MimeMode) &&
1898 bitset(EF_HAS8BIT, e->e_flags) &&
1899 !bitset(EF_DONT_MIME, e->e_flags) &&
1900 !bitnset(M_8BITS, mci->mci_mailer->m_flags) &&
1901 !bitset(MCIF_CVT8TO7|MCIF_CVT7TO8|MCIF_INMIME, mci->mci_flags) &&
1902 hvalue("MIME-Version", e->e_header) == NULL)
1904 if (!putline("MIME-Version: 1.0", mci))
1906 if (hvalue("Content-Type", e->e_header) == NULL)
1908 (void) sm_snprintf(obuf, sizeof(obuf),
1909 "Content-Type: text/plain; charset=%s",
1911 if (!putline(obuf, mci))
1914 if (hvalue("Content-Transfer-Encoding", e->e_header) == NULL
1915 && !putline("Content-Transfer-Encoding: 8bit", mci))
1918 #endif /* MIME8TO7 */
1926 ** PUT_VANILLA_HEADER -- output a fairly ordinary header
1929 ** h -- the structure describing this header
1930 ** v -- the value of this header
1931 ** mci -- the connection info for output
1934 ** true iff header was written successfully
1938 put_vanilla_header(h, v, mci)
1946 char obuf[MAXLINE + 256]; /* additional length for h_field */
1948 putflags = PXLF_HEADER | PXLF_STRIPMQUOTE;
1949 if (bitnset(M_7BITHDRS, mci->mci_mailer->m_flags))
1950 putflags |= PXLF_STRIP8BIT;
1951 (void) sm_snprintf(obuf, sizeof(obuf), "%.200s:", h->h_field);
1952 obp = obuf + strlen(obuf);
1953 while ((nlp = strchr(v, '\n')) != NULL)
1960 ** XXX This is broken for SPACELEFT()==0
1961 ** However, SPACELEFT() is always > 0 unless MAXLINE==1.
1964 if (SPACELEFT(obuf, obp) - 1 < (size_t) l)
1965 l = SPACELEFT(obuf, obp) - 1;
1967 (void) sm_snprintf(obp, SPACELEFT(obuf, obp), "%.*s", l, v);
1968 if (!putxline(obuf, strlen(obuf), mci, putflags))
1972 if (*v != ' ' && *v != '\t')
1976 /* XXX This is broken for SPACELEFT()==0 */
1977 (void) sm_snprintf(obp, SPACELEFT(obuf, obp), "%.*s",
1978 (int) (SPACELEFT(obuf, obp) - 1), v);
1979 return putxline(obuf, strlen(obuf), mci, putflags);
1986 ** COMMAIZE -- output a header field, making a comma-translated list.
1989 ** h -- the header field to output.
1990 ** p -- the value to put in it.
1991 ** oldstyle -- true if this is an old style header.
1992 ** mci -- the connection information.
1993 ** e -- the envelope containing the message.
1994 ** putflags -- flags for putxline()
1997 ** true iff header field was written successfully
2000 ** outputs "p" to "mci".
2004 commaize(h, p, oldstyle, mci, e, putflags)
2009 register ENVELOPE *e;
2013 int opos, omax, spaces;
2014 bool firstone = true;
2016 char obuf[MAXLINE + 3];
2019 ** Output the address list translated by the
2020 ** mailer and with commas.
2024 sm_dprintf("commaize(%s:%s)\n", h->h_field, p);
2026 if (bitnset(M_7BITHDRS, mci->mci_mailer->m_flags))
2027 putflags |= PXLF_STRIP8BIT;
2030 (void) sm_snprintf(obp, SPACELEFT(obuf, obp), "%.200s:", h->h_field);
2031 /* opos = strlen(obp); instead of the next 3 lines? */
2032 opos = strlen(h->h_field) + 1;
2038 while (*p != '\0' && isascii(*p) && isspace(*p))
2045 SM_ASSERT(sizeof(obuf) > opos * 2);
2048 ** Restrict number of spaces to half the length of buffer
2049 ** so the header field body can be put in here too.
2050 ** Note: this is a hack...
2053 if (spaces > sizeof(obuf) / 2)
2054 spaces = sizeof(obuf) / 2;
2055 (void) sm_snprintf(obp, SPACELEFT(obuf, obp), "%*s", spaces,
2059 SM_ASSERT(obp < &obuf[MAXLINE]);
2062 omax = mci->mci_mailer->m_linelimit - 2;
2063 if (omax < 0 || omax > 78)
2067 ** Run through the list of values.
2072 register char *name;
2079 ** Find the end of the name. New style names
2080 ** end with a comma, old style names end with
2081 ** a space character. However, spaces do not
2082 ** necessarily delimit an old-style name -- at
2083 ** signs mean keep going.
2086 /* find end of name */
2087 while ((isascii(*p) && isspace(*p)) || *p == ',')
2094 char pvpbuf[PSBUFSIZE];
2096 res = prescan(p, oldstyle ? ' ' : ',', pvpbuf,
2097 sizeof(pvpbuf), &oldp, ExtTokenTab, false);
2099 #if _FFR_IGNORE_BOGUS_ADDR
2100 /* ignore addresses that can't be parsed */
2106 #endif /* _FFR_IGNORE_BOGUS_ADDR */
2108 /* look to see if we have an at sign */
2109 while (*p != '\0' && isascii(*p) && isspace(*p))
2118 while (*p != '\0' && isascii(*p) && isspace(*p))
2121 /* at the end of one complete name */
2123 /* strip off trailing white space */
2125 ((isascii(*p) && isspace(*p)) || *p == ',' || *p == '\0'))
2131 ** if prescan() failed go a bit backwards; this is a hack,
2132 ** there should be some better error recovery.
2135 if (res == NULL && p > name &&
2136 !((isascii(*p) && isspace(*p)) || *p == ',' || *p == '\0'))
2141 /* translate the name to be relative */
2142 flags = RF_HEADERADDR|RF_ADDDOMAIN;
2143 if (bitset(H_FROM, h->h_flags))
2144 flags |= RF_SENDERADDR;
2146 else if (e->e_from.q_mailer != NULL &&
2147 bitnset(M_UDBRECIPIENT, e->e_from.q_mailer->m_flags))
2151 q = udbsender(name, e->e_rpool);
2157 name = remotename(name, mci->mci_mailer, flags, &status, e);
2163 name = denlstring(name, false, true);
2165 /* output the name with nice formatting */
2166 opos += strlen(name);
2169 if (opos > omax && !firstone)
2171 (void) sm_strlcpy(obp, ",\n", SPACELEFT(obuf, obp));
2172 if (!putxline(obuf, strlen(obuf), mci, putflags))
2175 (void) sm_strlcpy(obp, " ", sizeof(obuf));
2178 opos += strlen(name);
2182 (void) sm_strlcpy(obp, ", ", SPACELEFT(obuf, obp));
2186 while ((c = *name++) != '\0' && obp < &obuf[MAXLINE])
2191 if (obp < &obuf[sizeof(obuf)])
2194 obuf[sizeof(obuf) - 1] = '\0';
2195 return putxline(obuf, strlen(obuf), mci, putflags);
2202 ** COPYHEADER -- copy header list
2204 ** This routine is the equivalent of newstr for header lists
2207 ** header -- list of header structures to copy.
2208 ** rpool -- resource pool, or NULL
2211 ** a copy of 'header'.
2218 copyheader(header, rpool)
2219 register HDR *header;
2222 register HDR *newhdr;
2224 register HDR **tail = &ret;
2226 while (header != NULL)
2228 newhdr = (HDR *) sm_rpool_malloc_x(rpool, sizeof(*newhdr));
2229 STRUCTCOPY(*header, *newhdr);
2231 tail = &newhdr->h_link;
2232 header = header->h_link;
2240 ** FIX_MIME_HEADER -- possibly truncate/rebalance parameters in a MIME header
2242 ** Run through all of the parameters of a MIME header and
2243 ** possibly truncate and rebalance the parameter according
2244 ** to MaxMimeFieldLength.
2247 ** h -- the header to truncate/rebalance
2248 ** e -- the current envelope
2251 ** length of last offending field, 0 if all ok.
2254 ** string modified in place
2258 fix_mime_header(h, e)
2262 char *begin = h->h_value;
2267 if (begin == NULL || *begin == '\0')
2270 /* Split on each ';' */
2271 /* find_character() never returns NULL */
2272 while ((end = find_character(begin, ';')) != NULL)
2279 len = strlen(begin);
2281 /* Shorten individual parameter */
2282 if (shorten_rfc822_string(begin, MaxMimeFieldLength))
2284 if (len < MaxMimeFieldLength)
2286 /* we only rebalanced a bogus field */
2287 sm_syslog(LOG_ALERT, e->e_id,
2288 "Fixed MIME %s header field (possible attack)",
2291 sm_dprintf(" fixed MIME %s header field (possible attack)\n",
2296 /* we actually shortened the header */
2301 /* Collapse the possibly shortened string with rest */
2302 bp = begin + strlen(begin);
2310 /* copy character by character due to overlap */