2 * Copyright (c) 1998-2007, 2009 Proofpoint, 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 SM_RCSID("@(#)$Id: util.c,v 8.427 2013-11-22 20:51:57 ca Exp $")
18 #include <sm/sendmail.h>
23 ** NEWSTR -- Create a copy of a C string
26 ** s -- the string to copy.
29 ** pointer to newly allocated string.
42 sm_strlcpy(n, s, l + 1);
47 ** ADDQUOTES -- Adds quotes & quote bits to a string.
49 ** Runs through a string and adds backslashes and quote bits.
52 ** s -- the string to modify.
53 ** rpool -- resource pool from which to allocate result
56 ** pointer to quoted string.
71 /* Find length of quoted string */
72 while ((c = *p++) != '\0')
75 if (c == '\\' || c == '"')
79 q = r = sm_rpool_malloc_x(rpool, len + 3);
82 /* add leading quote */
84 while ((c = *p++) != '\0')
87 if (c == '\\' || c == '"')
97 ** STRIPBACKSLASH -- Strip all leading backslashes from a string, provided
98 ** the following character is alpha-numerical.
100 ** This is done in place.
103 ** s -- the string to strip.
115 if (s == NULL || *s == '\0')
118 while (*p == '\\' && (p[1] == '\\' || (isascii(p[1]) && isalnum(p[1]))))
127 ** RFC822_STRING -- Checks string for proper RFC822 string quoting.
129 ** Runs through a string and verifies RFC822 special characters
130 ** are only found inside comments, quoted strings, or backslash
131 ** escaped. Also verified balanced quotes and parenthesis.
134 ** s -- the string to modify.
137 ** true iff the string is RFC822 compliant, false otherwise.
153 /* escaped character */
160 else if (commentlev == 0 && *c == '"')
174 else if (commentlev == 0 &&
175 strchr(MustQuoteChars, *c) != NULL)
181 /* unbalanced '"' or '(' */
182 return !quoted && commentlev == 0;
186 ** SHORTEN_RFC822_STRING -- Truncate and rebalance an RFC822 string
188 ** Arbitrarily shorten (in place) an RFC822 string and rebalance
189 ** comments and quotes.
192 ** string -- the string to shorten
193 ** length -- the maximum size, 0 if no maximum
196 ** true if string is changed, false otherwise
199 ** Changes string in place, possibly resulting
200 ** in a shorter string.
204 shorten_rfc822_string(string, length)
208 bool backslash = false;
209 bool modified = false;
216 ** If have to rebalance an already short enough string,
217 ** need to do it within allocated space.
220 slen = strlen(string);
221 if (length == 0 || slen < length)
234 else if (*ptr == '(')
239 else if (*ptr == ')')
241 if (--parencount < 0)
245 /* Inside a comment, quotes don't matter */
246 if (parencount <= 0 && *ptr == '"')
250 /* Check for sufficient space for next character */
251 if (length - (ptr - string) <= (size_t) ((backslash ? 1 : 0) +
255 /* Not enough, backtrack */
258 else if (*ptr == '(' && !quoted)
260 else if (*ptr == '"' && parencount == 0)
268 while (parencount-- > 0)
295 ** FIND_CHARACTER -- find an unquoted character in an RFC822 string
297 ** Find an unquoted, non-commented character in an RFC822
298 ** string and return a pointer to its location in the
302 ** string -- the string to search
303 ** character -- the character to find
306 ** pointer to the character, or
307 ** a pointer to the end of the line if character is not found
311 find_character(string, character)
315 bool backslash = false;
319 while (string != NULL && *string != '\0')
324 if (!quoted && character == '\\' && *string == '\\')
341 if (--parencount < 0)
346 /* Inside a comment, nothing matters */
355 else if (*string == character && !quoted)
360 /* Return pointer to the character */
365 ** CHECK_BODYTYPE -- check bodytype parameter
368 ** bodytype -- bodytype parameter
371 ** BODYTYPE_* according to parameter
376 check_bodytype(bodytype)
379 /* check body type for legality */
380 if (bodytype == NULL)
381 return BODYTYPE_NONE;
382 if (sm_strcasecmp(bodytype, "7BIT") == 0)
383 return BODYTYPE_7BIT;
384 if (sm_strcasecmp(bodytype, "8BITMIME") == 0)
385 return BODYTYPE_8BITMIME;
386 return BODYTYPE_ILLEGAL;
390 ** TRUNCATE_AT_DELIM -- truncate string at a delimiter and append "..."
393 ** str -- string to truncate
394 ** len -- maximum length (including '\0') (0 for unlimited)
395 ** delim -- delimiter character
402 truncate_at_delim(str, len, delim)
409 if (str == NULL || len == 0 || strlen(str) < len)
412 *(str + len - 1) = '\0';
413 while ((p = strrchr(str, delim)) != NULL)
416 if (p - str + 4 < len)
420 (void) sm_strlcat(str, "...", len);
425 /* Couldn't find a place to append "..." */
427 (void) sm_strlcpy(str, "...", len);
433 ** XALLOC -- Allocate memory, raise an exception on error
436 ** sz -- size of area to allocate.
439 ** pointer to data region.
442 ** SmHeapOutOfMemory (F:sm.heap) -- cannot allocate memory
445 ** Memory is allocated.
450 xalloc_tagged(sz, file, line)
454 #else /* SM_HEAP_CHECK */
457 #endif /* SM_HEAP_CHECK */
463 /* some systems can't handle size zero mallocs */
467 /* scaffolding for testing error handling code */
468 sm_xtrap_raise_x(&SmHeapOutOfMemory);
470 p = sm_malloc_tagged((unsigned) sz, file, line, sm_heap_group());
473 sm_exc_raise_x(&SmHeapOutOfMemory);
479 ** COPYPLIST -- copy list of pointers.
481 ** This routine is the equivalent of strdup for lists of
485 ** list -- list of pointers to copy.
486 ** Must be NULL terminated.
487 ** copycont -- if true, copy the contents of the vector
488 ** (which must be a string) also.
489 ** rpool -- resource pool from which to allocate storage,
497 copyplist(list, copycont, rpool)
503 register char **newvp;
505 for (vp = list; *vp != NULL; vp++)
510 newvp = (char **) sm_rpool_malloc_x(rpool, (vp - list) * sizeof(*vp));
511 memmove((char *) newvp, (char *) list, (int) (vp - list) * sizeof(*vp));
515 for (vp = newvp; *vp != NULL; vp++)
516 *vp = sm_rpool_strdup_x(rpool, *vp);
523 ** COPYQUEUE -- copy address queue.
525 ** This routine is the equivalent of strdup for address queues;
526 ** addresses marked as QS_IS_DEAD() aren't copied
529 ** addr -- list of address structures to copy.
530 ** rpool -- resource pool from which to allocate storage
537 copyqueue(addr, rpool)
541 register ADDRESS *newaddr;
543 register ADDRESS **tail = &ret;
547 if (!QS_IS_DEAD(addr->q_state))
549 newaddr = (ADDRESS *) sm_rpool_malloc_x(rpool,
551 STRUCTCOPY(*addr, *newaddr);
553 tail = &newaddr->q_next;
563 ** LOG_SENDMAIL_PID -- record sendmail pid and command line.
566 ** e -- the current envelope.
572 ** writes pidfile, logs command line.
573 ** keeps file open and locked to prevent overwrite of active file
576 static SM_FILE_T *Pidf = NULL;
583 char pidpath[MAXPATHLEN];
584 extern char *CommandLineArgs;
586 /* write the pid to the log file for posterity */
587 sff = SFF_NOLINK|SFF_ROOTOK|SFF_REGONLY|SFF_CREAT|SFF_NBLOCK;
588 if (TrustedUid != 0 && RealUid == TrustedUid)
589 sff |= SFF_OPENASROOT;
590 expand(PidFile, pidpath, sizeof(pidpath), e);
591 Pidf = safefopen(pidpath, O_WRONLY|O_TRUNC, FileMode, sff);
594 if (errno == EWOULDBLOCK)
595 sm_syslog(LOG_ERR, NOQID,
596 "unable to write pid to %s: file in use by another process",
599 sm_syslog(LOG_ERR, NOQID,
600 "unable to write pid to %s: %s",
601 pidpath, sm_errstring(errno));
605 PidFilePid = getpid();
607 /* write the process id on line 1 */
608 (void) sm_io_fprintf(Pidf, SM_TIME_DEFAULT, "%ld\n",
611 /* line 2 contains all command line flags */
612 (void) sm_io_fprintf(Pidf, SM_TIME_DEFAULT, "%s\n",
616 (void) sm_io_flush(Pidf, SM_TIME_DEFAULT);
619 ** Leave pid file open until process ends
620 ** so it's not overwritten by another
625 sm_syslog(LOG_INFO, NOQID, "started as: %s", CommandLineArgs);
629 ** CLOSE_SENDMAIL_PID -- close sendmail pid file
644 (void) sm_io_close(Pidf, SM_TIME_DEFAULT);
649 ** SET_DELIVERY_MODE -- set and record the delivery mode
652 ** mode -- delivery mode
653 ** e -- the current envelope.
659 ** sets {deliveryMode} macro
663 set_delivery_mode(mode, e)
669 e->e_sendmode = (char) mode;
670 buf[0] = (char) mode;
672 macdefine(&e->e_macro, A_TEMP, macid("{deliveryMode}"), buf);
676 ** SET_OP_MODE -- set and record the op mode
680 ** e -- the current envelope.
686 ** sets {opMode} macro
694 extern ENVELOPE BlankEnvelope;
696 OpMode = (char) mode;
697 buf[0] = (char) mode;
699 macdefine(&BlankEnvelope.e_macro, A_TEMP, MID_OPMODE, buf);
703 ** PRINTAV -- print argument vector.
706 ** fp -- output file pointer.
707 ** av -- argument vector.
724 sm_dprintf("\n\t%08lx=", (unsigned long) *av);
726 (void) sm_io_putc(fp, SM_TIME_DEFAULT, ' ');
728 sm_dprintf("%s", str2prt(*av++));
732 (void) sm_io_putc(fp, SM_TIME_DEFAULT, '\n');
736 ** XPUTS -- put string doing control escapes.
739 ** fp -- output file pointer.
740 ** s -- string to put.
756 bool shiftout = false;
757 extern struct metamac MetaMacros[];
758 static SM_DEBUG_T DebugANSI = SM_DEBUG_INITIALIZER("ANSI",
759 "@(#)$Debug: ANSI - enable reverse video in debug output $");
762 ** TermEscape is set here, rather than in main(),
763 ** because ANSI mode can be turned on or off at any time
764 ** if we are in -bt rule testing mode.
767 if (sm_debug_unknown(&DebugANSI))
769 if (sm_debug_active(&DebugANSI, 1))
771 TermEscape.te_rv_on = "\033[7m";
772 TermEscape.te_normal = "\033[0m";
776 TermEscape.te_rv_on = "";
777 TermEscape.te_normal = "";
783 (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s<null>%s",
784 TermEscape.te_rv_on, TermEscape.te_normal);
787 while ((c = (*s++ & 0377)) != '\0')
791 (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s",
792 TermEscape.te_normal);
795 if (!isascii(c) && !tTd(84, 1))
799 (void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
801 TermEscape.te_rv_on);
808 if (c == MACROEXPAND || c == MACRODEXPAND)
810 (void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
812 TermEscape.te_rv_on);
813 if (c == MACRODEXPAND)
814 (void) sm_io_putc(fp,
815 SM_TIME_DEFAULT, '&');
819 if (strchr("=~&?", *s) != NULL)
820 (void) sm_io_putc(fp,
823 if (bitset(0200, *s))
824 (void) sm_io_fprintf(fp,
827 macname(bitidx(*s++)));
829 (void) sm_io_fprintf(fp,
835 for (mp = MetaMacros; mp->metaname != '\0'; mp++)
837 if (bitidx(mp->metaval) == c)
839 (void) sm_io_fprintf(fp,
848 if (c == MATCHCLASS || c == MATCHNCLASS)
850 if (bitset(0200, *s))
851 (void) sm_io_fprintf(fp,
854 macname(bitidx(*s++)));
856 (void) sm_io_fprintf(fp,
861 if (mp->metaname != '\0')
864 /* unrecognized meta character */
865 (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%sM-",
866 TermEscape.te_rv_on);
871 if (isascii(c) && isprint(c))
873 (void) sm_io_putc(fp, SM_TIME_DEFAULT, c);
877 /* wasn't a meta-macro -- find another way to print it */
894 (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s",
895 TermEscape.te_rv_on);
898 if (isascii(c) && isprint(c))
900 (void) sm_io_putc(fp, SM_TIME_DEFAULT, '\\');
901 (void) sm_io_putc(fp, SM_TIME_DEFAULT, c);
904 (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " %o ", c);
906 (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " %#x ", c);
907 else if (!isascii(c) && !tTd(84, 1))
909 (void) sm_io_putc(fp, SM_TIME_DEFAULT, '^');
910 (void) sm_io_putc(fp, SM_TIME_DEFAULT, c ^ 0100);
914 (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s",
915 TermEscape.te_normal);
916 (void) sm_io_flush(fp, SM_TIME_DEFAULT);
920 ** MAKELOWER -- Translate a line into lower case
923 ** p -- the string to translate. If NULL, return is
930 ** String pointed to by p is translated to lower case.
941 for (; (c = *p) != '\0'; p++)
942 if (isascii(c) && isupper(c))
947 ** FIXCRLF -- fix <CR><LF> in line.
949 ** Looks for the <CR><LF> combination and turns it into the
950 ** UNIX canonical <NL> character. It only takes one line,
951 ** i.e., it is assumed that the first <NL> found is the end
955 ** line -- the line to fix.
956 ** stripnl -- if true, strip the newline also.
962 ** line is changed in place.
966 fixcrlf(line, stripnl)
972 p = strchr(line, '\n');
975 if (p > line && p[-1] == '\r')
983 ** PUTLINE -- put a line like fputs obeying SMTP conventions
985 ** This routine always guarantees outputing a newline (or CRLF,
986 ** as appropriate) at the end of the string.
990 ** mci -- the mailer connection information.
993 ** true iff line was written successfully
996 ** output of l to mci->mci_out.
1004 return putxline(l, strlen(l), mci, PXLF_MAPFROM);
1008 ** PUTXLINE -- putline with flags bits.
1010 ** This routine always guarantees outputing a newline (or CRLF,
1011 ** as appropriate) at the end of the string.
1014 ** l -- line to put.
1015 ** len -- the length of the line.
1016 ** mci -- the mailer connection information.
1017 ** pxflags -- flag bits:
1018 ** PXLF_MAPFROM -- map From_ to >From_.
1019 ** PXLF_STRIP8BIT -- strip 8th bit.
1020 ** PXLF_HEADER -- map bare newline in header to newline space.
1021 ** PXLF_NOADDEOL -- don't add an EOL if one wasn't present.
1022 ** PXLF_STRIPMQUOTE -- strip METAQUOTE bytes.
1025 ** true iff line was written successfully
1028 ** output of l to mci->mci_out.
1032 #define PUTX(limit) \
1035 quotenext = false; \
1038 unsigned char c = (unsigned char) *l++; \
1040 if (bitset(PXLF_STRIPMQUOTE, pxflags) && \
1041 !quotenext && c == METAQUOTE) \
1046 quotenext = false; \
1049 if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, \
1055 if (TrafficLogFile != NULL) \
1056 (void) sm_io_putc(TrafficLogFile, \
1063 putxline(l, len, mci, pxflags)
1069 register char *p, *end;
1071 bool dead, quotenext, strip8bit;
1073 /* strip out 0200 bits -- these can look like TELNET protocol */
1074 strip8bit = bitset(MCIF_7BIT, mci->mci_flags) ||
1075 bitset(PXLF_STRIP8BIT, pxflags);
1084 /* find the end of the line */
1085 p = memchr(l, '\n', end - l);
1092 if (TrafficLogFile != NULL)
1093 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT,
1094 "%05d >>> ", (int) CurrentPid);
1096 /* check for line overflow */
1097 while (mci->mci_mailer->m_linelimit > 0 &&
1098 (p - l + slop) > mci->mci_mailer->m_linelimit)
1100 register char *q = &l[mci->mci_mailer->m_linelimit - slop - 1];
1102 if (l[0] == '.' && slop == 0 &&
1103 bitnset(M_XDOT, mci->mci_mailer->m_flags))
1105 if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT,
1108 if (TrafficLogFile != NULL)
1109 (void) sm_io_putc(TrafficLogFile,
1110 SM_TIME_DEFAULT, '.');
1112 else if (l[0] == 'F' && slop == 0 &&
1113 bitset(PXLF_MAPFROM, pxflags) &&
1114 strncmp(l, "From ", 5) == 0 &&
1115 bitnset(M_ESCFROM, mci->mci_mailer->m_flags))
1117 if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT,
1120 if (TrafficLogFile != NULL)
1121 (void) sm_io_putc(TrafficLogFile,
1132 if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT,
1133 '!') == SM_IO_EOF ||
1134 sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT,
1135 mci->mci_mailer->m_eol) == SM_IO_EOF ||
1136 sm_io_putc(mci->mci_out, SM_TIME_DEFAULT,
1142 if (TrafficLogFile != NULL)
1144 (void) sm_io_fprintf(TrafficLogFile,
1155 /* output last part */
1156 if (l[0] == '.' && slop == 0 &&
1157 bitnset(M_XDOT, mci->mci_mailer->m_flags) &&
1158 !bitset(MCIF_INLONGLINE, mci->mci_flags))
1160 if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, '.') ==
1166 if (TrafficLogFile != NULL)
1167 (void) sm_io_putc(TrafficLogFile,
1168 SM_TIME_DEFAULT, '.');
1170 else if (l[0] == 'F' && slop == 0 &&
1171 bitset(PXLF_MAPFROM, pxflags) &&
1172 strncmp(l, "From ", 5) == 0 &&
1173 bitnset(M_ESCFROM, mci->mci_mailer->m_flags) &&
1174 !bitset(MCIF_INLONGLINE, mci->mci_flags))
1176 if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, '>') ==
1182 if (TrafficLogFile != NULL)
1183 (void) sm_io_putc(TrafficLogFile,
1184 SM_TIME_DEFAULT, '>');
1190 if (TrafficLogFile != NULL)
1191 (void) sm_io_putc(TrafficLogFile, SM_TIME_DEFAULT,
1193 if ((!bitset(PXLF_NOADDEOL, pxflags) || !noeol))
1195 mci->mci_flags &= ~MCIF_INLONGLINE;
1196 if (sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT,
1197 mci->mci_mailer->m_eol) == SM_IO_EOF)
1204 mci->mci_flags |= MCIF_INLONGLINE;
1206 if (l < end && *l == '\n')
1208 if (*++l != ' ' && *l != '\t' && *l != '\0' &&
1209 bitset(PXLF_HEADER, pxflags))
1211 if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT,
1218 if (TrafficLogFile != NULL)
1219 (void) sm_io_putc(TrafficLogFile,
1220 SM_TIME_DEFAULT, ' ');
1229 ** XUNLINK -- unlink a file, doing logging as appropriate.
1232 ** f -- name of file to unlink.
1235 ** return value of unlink()
1249 sm_syslog(LOG_DEBUG, CurEnv->e_id, "unlink %s", f);
1253 if (i < 0 && LogLevel > 97)
1254 sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s: unlink-fail %d",
1263 ** SFGETS -- "safe" fgets -- times out and ignores random interrupts.
1266 ** buf -- place to put the input line.
1267 ** siz -- size of buf.
1268 ** fp -- file to read from.
1269 ** timeout -- the timeout before error occurs.
1270 ** during -- what we are trying to read (for error messages).
1273 ** NULL on error (including timeout). This may also leave
1274 ** buf containing a null string.
1280 sfgets(buf, siz, fp, timeout, during)
1288 int save_errno, io_timeout, l;
1290 SM_REQUIRE(siz > 0);
1291 SM_REQUIRE(buf != NULL);
1304 /* convert the timeout to sm_io notation */
1305 io_timeout = (timeout <= 0) ? SM_TIME_DEFAULT : timeout * 1000;
1306 while (!sm_io_eof(fp) && !sm_io_error(fp))
1309 l = sm_io_fgets(fp, io_timeout, buf, siz);
1310 if (l < 0 && errno == EAGAIN)
1312 /* The sm_io_fgets() call timedout */
1314 sm_syslog(LOG_NOTICE, CurEnv->e_id,
1315 "timeout waiting for input from %.100s during %s",
1322 if (TrafficLogFile != NULL)
1323 (void) sm_io_fprintf(TrafficLogFile,
1325 "%05d <<< [TIMEOUT]\n",
1330 if (l >= 0 || errno != EINTR)
1332 (void) sm_io_clearerr(fp);
1336 /* clean up the books and exit */
1341 if (TrafficLogFile != NULL)
1342 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT,
1348 if (TrafficLogFile != NULL)
1349 (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT,
1350 "%05d <<< %s", (int) CurrentPid, buf);
1353 for (p = buf; *p != '\0'; p++)
1356 else if (!HasEightBits)
1358 for (p = buf; *p != '\0'; p++)
1360 if (bitset(0200, *p))
1362 HasEightBits = true;
1371 ** FGETFOLDED -- like fgets, but knows about folded lines.
1374 ** buf -- place to put result.
1375 ** np -- pointer to bytes available; will be updated with
1376 ** the actual buffer size (not number of bytes filled)
1378 ** f -- file to read from.
1381 ** input line(s) on success, NULL on error or SM_IO_EOF.
1382 ** This will normally be buf -- unless the line is too
1383 ** long, when it will be sm_malloc_x()ed.
1386 ** buf gets lines from f, with continuation lines (lines
1387 ** with leading white space) appended. CRLF's are mapped
1388 ** into single newlines. Any trailing NL is stripped.
1392 fgetfolded(buf, np, f)
1397 register char *p = buf;
1402 SM_REQUIRE(np != NULL);
1405 SM_REQUIRE(buf != NULL);
1414 while ((i = sm_io_getc(f, SM_TIME_DEFAULT)) != SM_IO_EOF)
1418 i = sm_io_getc(f, SM_TIME_DEFAULT);
1422 (void) sm_io_ungetc(f, SM_TIME_DEFAULT,
1429 /* allocate new space */
1434 if (nn < MEMCHUNKSIZE)
1438 nbp = sm_malloc_x(nn);
1439 memmove(nbp, bp, p - bp);
1451 i = sm_io_getc(f, SM_TIME_DEFAULT);
1453 (void) sm_io_ungetc(f, SM_TIME_DEFAULT, i);
1454 if (i != ' ' && i != '\t')
1467 ** CURTIME -- return current time.
1473 ** the current time.
1486 ** ATOBOOL -- convert a string representation to boolean.
1488 ** Defaults to false
1491 ** s -- string to convert. Takes "tTyY", empty, and NULL as true,
1495 ** A boolean representation of the string.
1502 if (s == NULL || *s == '\0' || strchr("tTyY", *s) != NULL)
1508 ** ATOOCT -- convert a string representation to octal.
1511 ** s -- string to convert.
1514 ** An integer representing the string interpreted as an
1524 while (*s >= '0' && *s <= '7')
1525 i = (i << 3) | (*s++ - '0');
1530 ** BITINTERSECT -- tell if two bitmaps intersect
1533 ** a, b -- the bitmaps in question
1536 ** true if they have a non-null intersection
1547 for (i = BITMAPBYTES / sizeof(int); --i >= 0; )
1549 if ((a[i] & b[i]) != 0)
1556 ** BITZEROP -- tell if a bitmap is all zero
1559 ** map -- the bit map to check
1562 ** true if map is all zero.
1563 ** false if there are any bits set in map.
1572 for (i = BITMAPBYTES / sizeof(int); --i >= 0; )
1581 ** STRCONTAINEDIN -- tell if one string is contained in another
1584 ** icase -- ignore case?
1585 ** a -- possible substring.
1586 ** b -- possible superstring.
1589 ** true if a is contained in b (case insensitive).
1594 strcontainedin(icase, a, b)
1606 if (icase && isascii(c) && isupper(c))
1608 for (; lb-- >= la; b++)
1613 isascii(*b) && isupper(*b) && tolower(*b) != c)
1615 if (sm_strncasecmp(a, b, la) == 0)
1622 if (strncmp(a, b, la) == 0)
1630 ** CHECKFD012 -- check low numbered file descriptors
1632 ** File descriptors 0, 1, and 2 should be open at all times.
1633 ** This routine verifies that, and fixes it if not true.
1636 ** where -- a tag printed if the assertion failed
1649 for (i = 0; i < 3; i++)
1655 ** CHECKFDOPEN -- make sure file descriptor is open -- for extended debugging
1658 ** fd -- file descriptor to check.
1659 ** where -- tag to print on failure.
1666 checkfdopen(fd, where)
1673 if (fstat(fd, &st) < 0 && errno == EBADF)
1675 syserr("checkfdopen(%d): %s not open as expected!", fd, where);
1682 ** CHECKFDS -- check for new or missing file descriptors
1685 ** where -- tag for printing. If null, take a base line.
1691 ** If where is set, shows changes since the last call.
1700 bool printhdr = true;
1701 int save_errno = errno;
1702 static BITMAP256 baseline;
1703 extern int DtableSize;
1705 if (DtableSize > BITMAPBITS)
1710 clrbitmap(baseline);
1712 for (fd = 0; fd < maxfd; fd++)
1716 if (fstat(fd, &stbuf) < 0 && errno != EOPNOTSUPP)
1718 if (!bitnset(fd, baseline))
1720 clrbitn(fd, baseline);
1722 else if (!bitnset(fd, baseline))
1723 setbitn(fd, baseline);
1727 /* file state has changed */
1732 sm_syslog(LOG_DEBUG, CurEnv->e_id,
1737 dumpfd(fd, true, true);
1743 ** PRINTOPENFDS -- print the open file descriptors (for debugging)
1746 ** logit -- if set, send output to syslog; otherwise
1747 ** print for debugging.
1753 #if NETINET || NETINET6
1754 # include <arpa/inet.h>
1755 #endif /* NETINET || NETINET6 */
1762 extern int DtableSize;
1764 for (fd = 0; fd < DtableSize; fd++)
1765 dumpfd(fd, false, logit);
1769 ** DUMPFD -- dump a file descriptor
1772 ** fd -- the file descriptor to dump.
1773 ** printclosed -- if set, print a notification even if
1774 ** it is closed; otherwise print nothing.
1775 ** logit -- if set, use sm_syslog instead of sm_dprintf()
1782 dumpfd(fd, printclosed, logit)
1791 #endif /* S_IFSOCK */
1792 auto SOCKADDR_LEN_T slen;
1796 #else /* STAT64 > 0 */
1798 #endif /* STAT64 > 0 */
1802 (void) sm_snprintf(p, SPACELEFT(buf, p), "%3d: ", fd);
1808 #else /* STAT64 > 0 */
1810 #endif /* STAT64 > 0 */
1815 (void) sm_snprintf(p, SPACELEFT(buf, p),
1817 sm_errstring(errno));
1820 else if (printclosed)
1822 (void) sm_snprintf(p, SPACELEFT(buf, p), "CLOSED");
1828 i = fcntl(fd, F_GETFL, 0);
1831 (void) sm_snprintf(p, SPACELEFT(buf, p), "fl=0x%x, ", i);
1835 (void) sm_snprintf(p, SPACELEFT(buf, p), "mode=%o: ",
1836 (unsigned int) st.st_mode);
1838 switch (st.st_mode & S_IFMT)
1842 (void) sm_snprintf(p, SPACELEFT(buf, p), "SOCK ");
1844 memset(&sa, '\0', sizeof(sa));
1846 if (getsockname(fd, &sa.sa, &slen) < 0)
1847 (void) sm_snprintf(p, SPACELEFT(buf, p), "(%s)",
1848 sm_errstring(errno));
1851 hp = hostnamebyanyaddr(&sa);
1858 else if (sa.sa.sa_family == AF_INET)
1859 (void) sm_snprintf(p, SPACELEFT(buf, p),
1860 "%s/%d", hp, ntohs(sa.sin.sin_port));
1861 # endif /* NETINET */
1863 else if (sa.sa.sa_family == AF_INET6)
1864 (void) sm_snprintf(p, SPACELEFT(buf, p),
1865 "%s/%d", hp, ntohs(sa.sin6.sin6_port));
1866 # endif /* NETINET6 */
1868 (void) sm_snprintf(p, SPACELEFT(buf, p),
1872 (void) sm_snprintf(p, SPACELEFT(buf, p), "->");
1875 if (getpeername(fd, &sa.sa, &slen) < 0)
1876 (void) sm_snprintf(p, SPACELEFT(buf, p), "(%s)",
1877 sm_errstring(errno));
1880 hp = hostnamebyanyaddr(&sa);
1887 else if (sa.sa.sa_family == AF_INET)
1888 (void) sm_snprintf(p, SPACELEFT(buf, p),
1889 "%s/%d", hp, ntohs(sa.sin.sin_port));
1890 # endif /* NETINET */
1892 else if (sa.sa.sa_family == AF_INET6)
1893 (void) sm_snprintf(p, SPACELEFT(buf, p),
1894 "%s/%d", hp, ntohs(sa.sin6.sin6_port));
1895 # endif /* NETINET6 */
1897 (void) sm_snprintf(p, SPACELEFT(buf, p),
1901 #endif /* S_IFSOCK */
1904 (void) sm_snprintf(p, SPACELEFT(buf, p), "CHR: ");
1910 (void) sm_snprintf(p, SPACELEFT(buf, p), "BLK: ");
1913 #endif /* S_IFBLK */
1915 #if defined(S_IFIFO) && (!defined(S_IFSOCK) || S_IFIFO != S_IFSOCK)
1917 (void) sm_snprintf(p, SPACELEFT(buf, p), "FIFO: ");
1920 #endif /* defined(S_IFIFO) && (!defined(S_IFSOCK) || S_IFIFO != S_IFSOCK) */
1924 (void) sm_snprintf(p, SPACELEFT(buf, p), "DIR: ");
1927 #endif /* S_IFDIR */
1931 (void) sm_snprintf(p, SPACELEFT(buf, p), "LNK: ");
1934 #endif /* S_IFLNK */
1938 (void) sm_snprintf(p, SPACELEFT(buf, p),
1939 "dev=%ld/%ld, ino=%llu, nlink=%d, u/gid=%ld/%ld, ",
1940 (long) major(st.st_dev), (long) minor(st.st_dev),
1941 (ULONGLONG_T) st.st_ino,
1942 (int) st.st_nlink, (long) st.st_uid,
1945 (void) sm_snprintf(p, SPACELEFT(buf, p), "size=%llu",
1946 (ULONGLONG_T) st.st_size);
1952 sm_syslog(LOG_DEBUG, CurEnv ? CurEnv->e_id : NULL,
1955 sm_dprintf("%s\n", buf);
1959 ** SHORTEN_HOSTNAME -- strip local domain information off of hostname.
1962 ** host -- the host to shorten (stripped in place).
1965 ** place where string was truncated, NULL if not truncated.
1969 shorten_hostname(host)
1977 /* strip off final dot */
1979 p = &host[(i == 0) ? 0 : i - 1];
1986 /* see if there is any domain at all -- if not, we are done */
1987 p = strchr(host, '.');
1991 /* yes, we have a domain -- see if it looks like us */
1992 mydom = macvalue('m', CurEnv);
1996 if ((canon ? sm_strcasecmp(p, mydom)
1997 : sm_strncasecmp(p, mydom, i)) == 0 &&
1998 (mydom[i] == '.' || mydom[i] == '\0'))
2007 ** PROG_OPEN -- open a program for reading
2010 ** argv -- the argument list.
2011 ** pfd -- pointer to a place to store the file descriptor.
2012 ** e -- the current envelope.
2015 ** pid of the process -- -1 if it failed.
2019 prog_open(argv, pfd, e)
2030 char buf[MAXPATHLEN];
2031 extern int DtableSize;
2035 syserr("%s: cannot create pipe for stdout", argv[0]);
2041 syserr("%s: cannot fork", argv[0]);
2042 (void) close(fdv[0]);
2043 (void) close(fdv[1]);
2049 (void) close(fdv[1]);
2054 /* Reset global flags */
2055 RestartRequest = NULL;
2056 RestartWorkGroup = false;
2057 ShutdownRequest = NULL;
2059 CurrentPid = getpid();
2062 ** Initialize exception stack and default exception
2063 ** handler for child process.
2066 sm_exc_newthread(fatal_error);
2068 /* child -- close stdin */
2071 /* stdout goes back to parent */
2072 (void) close(fdv[0]);
2073 if (dup2(fdv[1], 1) < 0)
2075 syserr("%s: cannot dup2 for stdout", argv[0]);
2078 (void) close(fdv[1]);
2080 /* stderr goes to transcript if available */
2081 if (e->e_xfp != NULL)
2085 xfd = sm_io_getinfo(e->e_xfp, SM_IO_WHAT_FD, NULL);
2086 if (xfd >= 0 && dup2(xfd, 2) < 0)
2088 syserr("%s: cannot dup2 for stderr", argv[0]);
2093 /* this process has no right to the queue file */
2094 if (e->e_lockfp != NULL)
2098 fd = sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL);
2102 syserr("%s: lockfp does not have a fd", argv[0]);
2105 /* chroot to the program mailer directory, if defined */
2106 if (ProgMailer != NULL && ProgMailer->m_rootdir != NULL)
2108 expand(ProgMailer->m_rootdir, buf, sizeof(buf), e);
2109 if (chroot(buf) < 0)
2111 syserr("prog_open: cannot chroot(%s)", buf);
2116 syserr("prog_open: cannot chdir(/)");
2121 /* run as default user */
2123 sm_mbdb_terminate();
2125 (void) sm_memstat_close();
2126 #endif /* _FFR_MEMSTAT */
2127 if (setgid(DefGid) < 0 && geteuid() == 0)
2129 syserr("prog_open: setgid(%ld) failed", (long) DefGid);
2132 if (setuid(DefUid) < 0 && geteuid() == 0)
2134 syserr("prog_open: setuid(%ld) failed", (long) DefUid);
2138 /* run in some directory */
2139 if (ProgMailer != NULL)
2140 p = ProgMailer->m_execdir;
2143 for (; p != NULL; p = q)
2148 expand(p, buf, sizeof(buf), e);
2151 if (buf[0] != '\0' && chdir(buf) >= 0)
2156 /* backup directories */
2157 if (chdir("/tmp") < 0)
2161 /* Check safety of program to be run */
2162 sff = SFF_ROOTOK|SFF_EXECOK;
2163 if (!bitnset(DBS_RUNWRITABLEPROGRAM, DontBlameSendmail))
2164 sff |= SFF_NOGWFILES|SFF_NOWWFILES;
2165 if (bitnset(DBS_RUNPROGRAMINUNSAFEDIRPATH, DontBlameSendmail))
2166 sff |= SFF_NOPATHCHECK;
2168 sff |= SFF_SAFEDIRPATH;
2169 ret = safefile(argv[0], DefUid, DefGid, DefUser, sff, 0, NULL);
2171 sm_syslog(LOG_INFO, e->e_id,
2172 "Warning: prog_open: program %s unsafe: %s",
2173 argv[0], sm_errstring(ret));
2175 /* arrange for all the files to be closed */
2176 sm_close_on_exec(STDERR_FILENO + 1, DtableSize);
2178 /* now exec the process */
2179 (void) execve(argv[0], (ARGV_T) argv, (ARGV_T) UserEnviron);
2183 syserr("%s: cannot exec", argv[0]);
2184 if (transienterror(save_errno))
2187 return -1; /* avoid compiler warning on IRIX */
2191 ** GET_COLUMN -- look up a Column in a line buffer
2194 ** line -- the raw text line to search.
2195 ** col -- the column number to fetch.
2196 ** delim -- the delimiter between columns. If null,
2198 ** buf -- the output buffer.
2199 ** buflen -- the length of buf.
2202 ** buf if successful.
2207 get_column(line, col, delim, buf, buflen)
2219 if ((char) delim == '\0')
2220 (void) sm_strlcpy(delimbuf, "\n\t ", sizeof(delimbuf));
2223 delimbuf[0] = (char) delim;
2229 return NULL; /* line empty */
2230 if (*p == (char) delim && col == 0)
2231 return NULL; /* first column empty */
2235 if (col == 0 && (char) delim == '\0')
2237 while (*begin != '\0' && isascii(*begin) && isspace(*begin))
2241 for (i = 0; i < col; i++)
2243 if ((begin = strpbrk(begin, delimbuf)) == NULL)
2244 return NULL; /* no such column */
2246 if ((char) delim == '\0')
2248 while (*begin != '\0' && isascii(*begin) && isspace(*begin))
2253 end = strpbrk(begin, delimbuf);
2260 (void) sm_strlcpy(buf, begin, i + 1);
2265 ** CLEANSTRCPY -- copy string keeping out bogus characters
2268 ** t -- "to" string.
2269 ** f -- "from" string.
2270 ** l -- length of space available in "to" string.
2277 cleanstrcpy(t, f, l)
2282 /* check for newlines and log if necessary */
2283 (void) denlstring(f, true, true);
2286 syserr("!cleanstrcpy: length == 0");
2289 while (l > 0 && *f != '\0')
2292 (isalnum(*f) || strchr("!#$%&'*+-./^_`{|}~", *f) != NULL))
2303 ** DENLSTRING -- convert newlines in a string to spaces
2306 ** s -- the input string
2307 ** strict -- if set, don't permit continuation lines.
2308 ** logattacks -- if set, log attempted attacks.
2311 ** A pointer to a version of the string with newlines
2312 ** mapped to spaces. This should be copied.
2316 denlstring(s, strict, logattacks)
2323 static char *bp = NULL;
2327 while ((p = strchr(p, '\n')) != NULL)
2328 if (strict || (*++p != ' ' && *p != '\t'))
2336 /* allocate more space */
2337 char *nbp = sm_pmalloc_x(l);
2344 (void) sm_strlcpy(bp, s, l);
2345 for (p = bp; (p = strchr(p, '\n')) != NULL; )
2350 sm_syslog(LOG_NOTICE, CurEnv ? CurEnv->e_id : NULL,
2351 "POSSIBLE ATTACK from %.100s: newline in string \"%s\"",
2352 RealHostName == NULL ? "[UNKNOWN]" : RealHostName,
2353 shortenstring(bp, MAXSHORTSTR));
2360 ** STRREPLNONPRT -- replace "unprintable" characters in a string with subst
2363 ** s -- string to manipulate (in place)
2364 ** subst -- character to use as replacement
2367 ** true iff string did not contain "unprintable" characters
2382 if (!(isascii(*s) && isprint(*s)))
2393 ** PATH_IS_DIR -- check to see if file exists and is a directory.
2395 ** There are some additional checks for security violations in
2396 ** here. This routine is intended to be used for the host status
2400 ** pathname -- pathname to check for directory-ness.
2401 ** createflag -- if set, create directory if needed.
2404 ** true -- if the indicated pathname is a directory
2405 ** false -- otherwise
2409 path_is_dir(pathname, createflag)
2413 struct stat statbuf;
2416 if (lstat(pathname, &statbuf) < 0)
2417 #else /* HASLSTAT */
2418 if (stat(pathname, &statbuf) < 0)
2419 #endif /* HASLSTAT */
2421 if (errno != ENOENT || !createflag)
2423 if (mkdir(pathname, 0755) < 0)
2427 if (!S_ISDIR(statbuf.st_mode))
2433 /* security: don't allow writable directories */
2434 if (bitset(S_IWGRP|S_IWOTH, statbuf.st_mode))
2443 ** PROC_LIST_ADD -- add process id to list of our children
2446 ** pid -- pid to add to list.
2447 ** task -- task of pid.
2448 ** type -- type of process.
2449 ** count -- number of processes.
2450 ** other -- other information for this type.
2456 ** May increase CurChildren. May grow ProcList.
2459 typedef struct procs PROCS_T;
2468 SOCKADDR proc_hostaddr;
2471 static PROCS_T *volatile ProcListVec = NULL;
2472 static int ProcListSize = 0;
2475 proc_list_add(pid, task, type, count, other, hostaddr)
2485 for (i = 0; i < ProcListSize; i++)
2487 if (ProcListVec[i].proc_pid == NO_PID)
2490 if (i >= ProcListSize)
2492 /* probe the existing vector to avoid growing infinitely */
2495 /* now scan again */
2496 for (i = 0; i < ProcListSize; i++)
2498 if (ProcListVec[i].proc_pid == NO_PID)
2502 if (i >= ProcListSize)
2504 /* grow process list */
2508 SM_ASSERT(ProcListSize < INT_MAX - PROC_LIST_SEG);
2509 npv = (PROCS_T *) sm_pmalloc_x((sizeof(*npv)) *
2510 (ProcListSize + PROC_LIST_SEG));
2512 /* Block SIGCHLD so reapchild() doesn't mess with us */
2513 chldwasblocked = sm_blocksignal(SIGCHLD);
2514 if (ProcListSize > 0)
2516 memmove(npv, ProcListVec,
2517 ProcListSize * sizeof(PROCS_T));
2518 sm_free(ProcListVec);
2521 /* XXX just use memset() to initialize this part? */
2522 for (i = ProcListSize; i < ProcListSize + PROC_LIST_SEG; i++)
2524 npv[i].proc_pid = NO_PID;
2525 npv[i].proc_task = NULL;
2526 npv[i].proc_type = PROC_NONE;
2529 ProcListSize += PROC_LIST_SEG;
2531 if (chldwasblocked == 0)
2532 (void) sm_releasesignal(SIGCHLD);
2534 ProcListVec[i].proc_pid = pid;
2535 PSTRSET(ProcListVec[i].proc_task, task);
2536 ProcListVec[i].proc_type = type;
2537 ProcListVec[i].proc_count = count;
2538 ProcListVec[i].proc_other = other;
2539 if (hostaddr != NULL)
2540 ProcListVec[i].proc_hostaddr = *hostaddr;
2542 memset(&ProcListVec[i].proc_hostaddr, 0,
2543 sizeof(ProcListVec[i].proc_hostaddr));
2545 /* if process adding itself, it's not a child */
2546 if (pid != CurrentPid)
2548 SM_ASSERT(CurChildren < INT_MAX);
2554 ** PROC_LIST_SET -- set pid task in process list
2557 ** pid -- pid to set
2558 ** task -- task of pid
2565 proc_list_set(pid, task)
2571 for (i = 0; i < ProcListSize; i++)
2573 if (ProcListVec[i].proc_pid == pid)
2575 PSTRSET(ProcListVec[i].proc_task, task);
2582 ** PROC_LIST_DROP -- drop pid from process list
2585 ** pid -- pid to drop
2586 ** st -- process status
2587 ** other -- storage for proc_other (return).
2593 ** May decrease CurChildren, CurRunners, or
2594 ** set RestartRequest or ShutdownRequest.
2596 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
2597 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2602 proc_list_drop(pid, st, other)
2608 int type = PROC_NONE;
2610 for (i = 0; i < ProcListSize; i++)
2612 if (ProcListVec[i].proc_pid == pid)
2614 ProcListVec[i].proc_pid = NO_PID;
2615 type = ProcListVec[i].proc_type;
2617 *other = ProcListVec[i].proc_other;
2618 if (CurChildren > 0)
2625 if (type == PROC_CONTROL && WIFEXITED(st))
2627 /* if so, see if we need to restart or shutdown */
2628 if (WEXITSTATUS(st) == EX_RESTART)
2629 RestartRequest = "control socket";
2630 else if (WEXITSTATUS(st) == EX_SHUTDOWN)
2631 ShutdownRequest = "control socket";
2633 else if (type == PROC_QUEUE_CHILD && !WIFSTOPPED(st) &&
2634 ProcListVec[i].proc_other > -1)
2636 /* restart this persistent runner */
2637 mark_work_group_restart(ProcListVec[i].proc_other, st);
2639 else if (type == PROC_QUEUE)
2641 CurRunners -= ProcListVec[i].proc_count;
2643 /* CHK_CUR_RUNNERS() can't be used here: uses syslog() */
2650 ** PROC_LIST_CLEAR -- clear the process list
2659 ** Sets CurChildren to zero.
2667 /* start from 1 since 0 is the daemon itself */
2668 for (i = 1; i < ProcListSize; i++)
2669 ProcListVec[i].proc_pid = NO_PID;
2674 ** PROC_LIST_PROBE -- probe processes in the list to see if they still exist
2683 ** May decrease CurChildren.
2694 chldwasblocked = sm_blocksignal(SIGCHLD);
2696 /* start from 1 since 0 is the daemon itself */
2697 for (i = 1; i < ProcListSize; i++)
2699 pid = ProcListVec[i].proc_pid;
2700 if (pid == NO_PID || pid == CurrentPid)
2702 if (kill(pid, 0) < 0)
2705 sm_syslog(LOG_DEBUG, CurEnv->e_id,
2706 "proc_list_probe: lost pid %d",
2707 (int) ProcListVec[i].proc_pid);
2708 ProcListVec[i].proc_pid = NO_PID;
2709 SM_FREE_CLR(ProcListVec[i].proc_task);
2711 if (ProcListVec[i].proc_type == PROC_QUEUE)
2713 CurRunners -= ProcListVec[i].proc_count;
2714 CHK_CUR_RUNNERS("proc_list_probe", i,
2715 ProcListVec[i].proc_count);
2725 if (CurChildren < 0)
2727 if (chldwasblocked == 0)
2728 (void) sm_releasesignal(SIGCHLD);
2729 if (LogLevel > 10 && children != CurChildren && CurrentPid == DaemonPid)
2731 sm_syslog(LOG_ERR, NOQID,
2732 "proc_list_probe: found %d children, expected %d",
2733 children, CurChildren);
2738 ** PROC_LIST_DISPLAY -- display the process list
2741 ** out -- output file pointer
2742 ** prefix -- string to output in front of each line.
2749 proc_list_display(out, prefix)
2755 for (i = 0; i < ProcListSize; i++)
2757 if (ProcListVec[i].proc_pid == NO_PID)
2760 (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "%s%d %s%s\n",
2762 (int) ProcListVec[i].proc_pid,
2763 ProcListVec[i].proc_task != NULL ?
2764 ProcListVec[i].proc_task : "(unknown)",
2765 (OpMode == MD_SMTP ||
2766 OpMode == MD_DAEMON ||
2767 OpMode == MD_ARPAFTP) ? "\r" : "");
2772 ** PROC_LIST_SIGNAL -- send a signal to a type of process in the list
2775 ** type -- type of process to signal
2776 ** signal -- the type of signal to send
2781 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
2782 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2787 proc_list_signal(type, signal)
2794 pid_t mypid = getpid();
2796 /* block these signals so that we may signal cleanly */
2797 chldwasblocked = sm_blocksignal(SIGCHLD);
2798 alrmwasblocked = sm_blocksignal(SIGALRM);
2800 /* Find all processes of type and send signal */
2801 for (i = 0; i < ProcListSize; i++)
2803 if (ProcListVec[i].proc_pid == NO_PID ||
2804 ProcListVec[i].proc_pid == mypid)
2806 if (ProcListVec[i].proc_type != type)
2808 (void) kill(ProcListVec[i].proc_pid, signal);
2811 /* restore the signals */
2812 if (alrmwasblocked == 0)
2813 (void) sm_releasesignal(SIGALRM);
2814 if (chldwasblocked == 0)
2815 (void) sm_releasesignal(SIGCHLD);
2819 ** COUNT_OPEN_CONNECTIONS
2822 ** hostaddr - ClientAddress
2825 ** the number of open connections for this client
2830 count_open_connections(hostaddr)
2835 if (hostaddr == NULL)
2839 ** This code gets called before proc_list_add() gets called,
2840 ** so we (the daemon child for this connection) have not yet
2841 ** counted ourselves. Hence initialize the counter to 1
2842 ** instead of 0 to compensate.
2846 for (i = 0; i < ProcListSize; i++)
2848 if (ProcListVec[i].proc_pid == NO_PID)
2850 if (hostaddr->sa.sa_family !=
2851 ProcListVec[i].proc_hostaddr.sa.sa_family)
2854 if (hostaddr->sa.sa_family == AF_INET &&
2855 (hostaddr->sin.sin_addr.s_addr ==
2856 ProcListVec[i].proc_hostaddr.sin.sin_addr.s_addr))
2858 #endif /* NETINET */
2860 if (hostaddr->sa.sa_family == AF_INET6 &&
2861 IN6_ARE_ADDR_EQUAL(&(hostaddr->sin6.sin6_addr),
2862 &(ProcListVec[i].proc_hostaddr.sin6.sin6_addr)))
2864 #endif /* NETINET6 */
2871 ** XCONNECT -- get X-CONNECT info
2874 ** inchannel -- FILE to check
2878 ** 0 if X-CONNECT was not given
2879 ** >0 if X-CONNECT was used successfully (D_XCNCT*)
2884 SM_FILE_T *inchannel;
2887 char *p, *b, delim, inp[MAXINPLINE];
2890 char pvpbuf[PSBUFSIZE];
2891 char *peerhostname; /* name of SMTP peer or "localhost" */
2892 extern ENVELOPE BlankEnvelope;
2894 #define XCONNECT "X-CONNECT "
2895 #define XCNNCTLEN (sizeof(XCONNECT) - 1)
2897 /* Ask the ruleset whether to use x-connect */
2899 peerhostname = RealHostName;
2900 if (peerhostname == NULL)
2901 peerhostname = "localhost";
2902 r = rscap("x_connect", peerhostname,
2903 anynet_ntoa(&RealHostAddr), &BlankEnvelope,
2904 &pvp, pvpbuf, sizeof(pvpbuf));
2906 sm_syslog(LOG_INFO, NOQID, "x-connect: rscap=%d", r);
2907 if (r == EX_UNAVAILABLE)
2912 sm_syslog(LOG_INFO, NOQID, "x-connect: rscap=%d", r);
2915 if (pvp != NULL && pvp[0] != NULL && (pvp[0][0] & 0377) == CANONNET)
2917 /* $#: no x-connect */
2919 sm_syslog(LOG_INFO, NOQID, "x-connect: nope");
2923 p = sfgets(inp, sizeof(inp), InChannel, TimeOuts.to_nextcommand, "pre");
2925 sm_syslog(LOG_INFO, NOQID, "x-connect: input=%s", p);
2926 if (p == NULL || strncasecmp(p, XCONNECT, XCNNCTLEN) != 0)
2929 while (isascii(*p) && isspace(*p))
2932 /* parameters: IPAddress [Hostname[ M]] */
2934 while (*p != '\0' && isascii(*p) &&
2935 (isalnum(*p) || *p == '.' || *p== ':'))
2940 memset(&addr, '\0', sizeof(addr));
2941 addr.sin.sin_addr.s_addr = inet_addr(b);
2942 if (addr.sin.sin_addr.s_addr != INADDR_NONE)
2944 addr.sa.sa_family = AF_INET;
2945 memcpy(&RealHostAddr, &addr, sizeof(addr));
2947 sm_syslog(LOG_INFO, NOQID, "x-connect: addr=%s",
2948 anynet_ntoa(&RealHostAddr));
2951 else if ((r = inet_pton(AF_INET6, b, &addr.sin6.sin6_addr)) == 1)
2953 addr.sa.sa_family = AF_INET6;
2954 memcpy(&RealHostAddr, &addr, sizeof(addr));
2956 # endif /* NETINET6 */
2960 /* more parameters? */
2963 while (*p != '\0' && isascii(*p) && isspace(*p))
2966 for (b = ++p, i = 0;
2967 *p != '\0' && isascii(*p) && (isalnum(*p) || *p == '.' || *p == '-');
2977 SM_FREE_CLR(RealHostName);
2978 RealHostName = newstr(b);
2980 sm_syslog(LOG_INFO, NOQID, "x-connect: host=%s", b);
2987 while (*p != '\0' && isascii(*p) && isspace(*p))
2994 e = strpbrk(p, "\r\n");
2997 sm_syslog(LOG_INFO, NOQID, "x-connect: rest=%s", p);
3004 #endif /* _FFR_XCNCT */