2 * Copyright (c) 1998-2005, 2010 Proofpoint, Inc. and its suppliers.
4 * Copyright (c) 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: mci.c,v 8.225 2013-11-22 20:51:56 ca Exp $")
18 #if NETINET || NETINET6
19 # include <arpa/inet.h>
27 static int mci_generate_persistent_path __P((const char *, char *,
29 static bool mci_load_persistent __P((MCI *));
30 static void mci_uncache __P((MCI **, bool));
31 static void mci_clear __P((MCI *));
32 static int mci_lock_host_statfile __P((MCI *));
33 static int mci_read_persistent __P((SM_FILE_T *, MCI *));
36 ** Mail Connection Information (MCI) Caching Module.
38 ** There are actually two separate things cached. The first is
39 ** the set of all open connections -- these are stored in a
40 ** (small) list. The second is stored in the symbol table; it
41 ** has the overall status for all hosts, whether or not there
42 ** is a connection open currently.
44 ** There should never be too many connections open (since this
45 ** could flood the socket table), nor should a connection be
46 ** allowed to sit idly for too long.
48 ** MaxMciCache is the maximum number of open connections that
51 ** MciCacheTimeout is the time (in seconds) that a connection
52 ** is permitted to survive without activity.
54 ** We actually try any cached connections by sending a RSET
55 ** before we use them; if the RSET fails we close down the
56 ** connection and reopen it (see smtpprobe()).
58 ** The persistent MCI code is donated by Mark Lovell and Paul
59 ** Vixie. It is based on the long term host status code in KJS
60 ** written by Paul but has been adapted by Mark to fit into the
64 static MCI **MciCache; /* the open connection cache */
67 ** MCI_CACHE -- enter a connection structure into the open connection cache
69 ** This may cause something else to be flushed.
72 ** mci -- the connection to cache.
82 register MCI **mcislot;
85 ** Find the best slot. This may cause expired connections
89 mcislot = mci_scan(mci);
92 /* we don't support caching */
96 if (mci->mci_host == NULL)
99 /* if this is already cached, we are done */
100 if (bitset(MCIF_CACHED, mci->mci_flags))
103 /* otherwise we may have to clear the slot */
104 if (*mcislot != NULL)
105 mci_uncache(mcislot, true);
108 sm_dprintf("mci_cache: caching %p (%s) in slot %d\n",
109 (void *)mci, mci->mci_host, (int) (mcislot - MciCache));
111 sm_syslog(LOG_DEBUG, CurEnv->e_id,
112 "mci_cache: caching %lx (%.100s) in slot %d",
113 (unsigned long) mci, mci->mci_host,
114 (int) (mcislot - MciCache));
117 mci->mci_flags |= MCIF_CACHED;
120 ** MCI_SCAN -- scan the cache, flush junk, and return best slot
123 ** savemci -- never flush this one. Can be null.
126 ** The LRU (or empty) slot.
134 register MCI **bestmci;
138 if (MaxMciCache <= 0)
140 /* we don't support caching */
144 if (MciCache == NULL)
147 MciCache = (MCI **) sm_pmalloc_x(MaxMciCache * sizeof(*MciCache));
148 memset((char *) MciCache, '\0', MaxMciCache * sizeof(*MciCache));
153 bestmci = &MciCache[0];
154 for (i = 0; i < MaxMciCache; i++)
157 if (mci == NULL || mci->mci_state == MCIS_CLOSED)
159 bestmci = &MciCache[i];
162 if ((mci->mci_lastuse + MciCacheTimeout <= now ||
163 (mci->mci_mailer != NULL &&
164 mci->mci_mailer->m_maxdeliveries > 0 &&
165 mci->mci_deliveries + 1 >= mci->mci_mailer->m_maxdeliveries))&&
168 /* connection idle too long or too many deliveries */
169 bestmci = &MciCache[i];
172 mci_uncache(bestmci, true);
175 if (*bestmci == NULL)
177 if (mci->mci_lastuse < (*bestmci)->mci_lastuse)
178 bestmci = &MciCache[i];
183 ** MCI_UNCACHE -- remove a connection from a slot.
185 ** May close a connection.
188 ** mcislot -- the slot to empty.
189 ** doquit -- if true, send QUIT protocol on this connection.
190 ** if false, we are assumed to be in a forked child;
191 ** all we want to do is close the file(s).
198 mci_uncache(mcislot, doquit)
199 register MCI **mcislot;
203 extern ENVELOPE BlankEnvelope;
209 if (mci->mci_host == NULL)
212 mci_unlock_host(mci);
215 sm_dprintf("mci_uncache: uncaching %p (%s) from slot %d (%d)\n",
216 (void *)mci, mci->mci_host, (int) (mcislot - MciCache),
219 sm_syslog(LOG_DEBUG, CurEnv->e_id,
220 "mci_uncache: uncaching %lx (%.100s) from slot %d (%d)",
221 (unsigned long) mci, mci->mci_host,
222 (int) (mcislot - MciCache), doquit);
224 mci->mci_deliveries = 0;
227 message("Closing connection to %s", mci->mci_host);
229 mci->mci_flags &= ~MCIF_CACHED;
231 /* only uses the envelope to flush the transcript file */
232 if (mci->mci_state != MCIS_CLOSED)
233 smtpquit(mci->mci_mailer, mci, &BlankEnvelope);
235 xla_host_end(mci->mci_host);
240 if (mci->mci_in != NULL)
241 (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT);
242 if (mci->mci_out != NULL)
243 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
244 mci->mci_in = mci->mci_out = NULL;
245 mci->mci_state = MCIS_CLOSED;
246 mci->mci_exitstat = EX_OK;
250 mci->mci_retryrcpt = false;
251 mci->mci_tolist = NULL;
253 mci->mci_okrcpts = 0;
257 SM_FREE(mci->mci_status);
258 SM_FREE(mci->mci_rstatus);
259 SM_FREE(mci->mci_heloname);
261 if (mci->mci_rpool != NULL)
263 sm_rpool_free(mci->mci_rpool);
264 mci->mci_macro.mac_rpool = NULL;
265 mci->mci_rpool = NULL;
269 ** MCI_FLUSH -- flush the entire cache
272 ** doquit -- if true, send QUIT protocol.
273 ** if false, just close the connection.
274 ** allbut -- but leave this one open.
281 mci_flush(doquit, allbut)
287 if (MciCache == NULL)
290 for (i = 0; i < MaxMciCache; i++)
292 if (allbut != MciCache[i])
293 mci_uncache(&MciCache[i], doquit);
298 ** MCI_CLR_EXTENSIONS -- clear knowledge about SMTP extensions
301 ** mci -- the connection to clear.
308 mci_clr_extensions(mci)
314 mci->mci_flags &= ~MCIF_EXTENS;
315 mci->mci_maxsize = 0;
318 mci->mci_saslcap = NULL;
323 ** MCI_CLEAR -- clear mci
326 ** mci -- the connection to clear.
339 mci->mci_maxsize = 0;
341 mci->mci_deliveries = 0;
343 if (bitset(MCIF_AUTHACT, mci->mci_flags))
344 sasl_dispose(&mci->mci_conn);
347 if (bitset(MCIF_TLSACT, mci->mci_flags) && mci->mci_ssl != NULL)
348 SM_SSL_FREE(mci->mci_ssl);
351 /* which flags to preserve? */
352 mci->mci_flags &= MCIF_CACHED;
353 mactabclear(&mci->mci_macro);
358 ** MCI_GET -- get information about a particular host
361 ** host -- host to look for.
365 ** mci for this host (might be new).
375 extern SOCKADDR CurHostAddr;
377 /* clear CurHostAddr so we don't get a bogus address with this name */
378 memset(&CurHostAddr, '\0', sizeof(CurHostAddr));
380 /* clear out any expired connections */
381 (void) mci_scan(NULL);
384 syserr("!negative mno %d (%s)", m->m_mno, m->m_name);
386 s = stab(host, ST_MCI + m->m_mno, ST_ENTER);
389 /* initialize per-message data */
390 mci->mci_retryrcpt = false;
391 mci->mci_tolist = NULL;
393 mci->mci_okrcpts = 0;
395 mci->mci_flags &= ~MCIF_NOTSTICKY;
397 if (mci->mci_rpool == NULL)
398 mci->mci_rpool = sm_rpool_new_x(NULL);
400 if (mci->mci_macro.mac_rpool == NULL)
401 mci->mci_macro.mac_rpool = mci->mci_rpool;
404 ** We don't need to load the persistent data if we have data
405 ** already loaded in the cache.
408 if (mci->mci_host == NULL &&
409 (mci->mci_host = s->s_name) != NULL &&
410 !mci_load_persistent(mci))
413 sm_dprintf("mci_get(%s %s): lock failed\n",
415 mci->mci_exitstat = EX_TEMPFAIL;
416 mci->mci_state = MCIS_CLOSED;
417 mci->mci_statfile = NULL;
423 sm_dprintf("mci_get(%s %s): mci_state=%d, _flags=%lx, _exitstat=%d, _errno=%d\n",
424 host, m->m_name, mci->mci_state, mci->mci_flags,
425 mci->mci_exitstat, mci->mci_errno);
428 if (mci->mci_state == MCIS_OPEN)
430 /* poke the connection to see if it's still alive */
431 (void) smtpprobe(mci);
433 /* reset the stored state in the event of a timeout */
434 if (mci->mci_state != MCIS_OPEN)
437 mci->mci_exitstat = EX_OK;
438 mci->mci_state = MCIS_CLOSED;
442 /* get peer host address */
443 /* (this should really be in the mci struct) */
444 SOCKADDR_LEN_T socklen = sizeof(CurHostAddr);
446 (void) getpeername(sm_io_getinfo(mci->mci_in,
447 SM_IO_WHAT_FD, NULL),
448 (struct sockaddr *) &CurHostAddr, &socklen);
451 if (mci->mci_state == MCIS_CLOSED)
453 time_t now = curtime();
455 /* if this info is stale, ignore it */
456 if (mci->mci_lastuse + MciInfoTimeout <= now)
458 mci->mci_lastuse = now;
460 mci->mci_exitstat = EX_OK;
469 ** MCI_CLOSE -- (forcefully) close files used for a connection.
470 ** Note: this is a last resort, usually smtpquit() or endmailer()
471 ** should be used to close a connection.
474 ** mci -- the connection to close.
475 ** where -- where has this been called?
482 mci_close(mci, where)
491 if (mci->mci_out != NULL)
495 sm_dprintf("mci_close: mci_out!=NULL, where=%s\n",
497 mci_dump(sm_debug_file(), mci, false);
500 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
503 if (mci->mci_in != NULL)
507 sm_dprintf("mci_close: mci_in!=NULL, where=%s\n",
510 mci_dump(sm_debug_file(), mci, false);
512 (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT);
515 mci->mci_state = MCIS_CLOSED;
519 ** MCI_NEW -- allocate new MCI structure
522 ** rpool -- if non-NULL: allocate from that rpool.
535 mci = (MCI *) sm_malloc_x(sizeof(*mci));
537 mci = (MCI *) sm_rpool_malloc_x(rpool, sizeof(*mci));
538 memset((char *) mci, '\0', sizeof(*mci));
539 mci->mci_rpool = sm_rpool_new_x(NULL);
540 mci->mci_macro.mac_rpool = mci->mci_rpool;
544 ** MCI_MATCH -- check connection cache for a particular host
547 ** host -- host to look for.
551 ** true iff open connection exists.
562 if (m->m_mno < 0 || m->m_mno > MAXMAILERS)
564 s = stab(host, ST_MCI + m->m_mno, ST_FIND);
569 return mci->mci_state == MCIS_OPEN;
572 ** MCI_SETSTAT -- set status codes in MCI structure.
575 ** mci -- the MCI structure to set.
576 ** xstat -- the exit status code.
577 ** dstat -- the DSN status code.
578 ** rstat -- the SMTP status code.
585 mci_setstat(mci, xstat, dstat, rstat)
591 /* protocol errors should never be interpreted as sticky */
592 if (xstat != EX_NOTSTICKY && xstat != EX_PROTOCOL)
593 mci->mci_exitstat = xstat;
595 SM_FREE(mci->mci_status);
597 mci->mci_status = sm_strdup_x(dstat);
599 SM_FREE(mci->mci_rstatus);
601 mci->mci_rstatus = sm_strdup_x(rstat);
604 ** MCI_DUMP -- dump the contents of an MCI structure.
607 ** fp -- output file pointer
608 ** mci -- the MCI structure to dump.
619 int mcif_bit; /* flag bit */
620 char *mcif_name; /* flag name */
622 static struct mcifbits MciFlags[] =
624 { MCIF_CACHED, "CACHED" },
625 { MCIF_ESMTP, "ESMTP" },
626 { MCIF_EXPN, "EXPN" },
627 { MCIF_SIZE, "SIZE" },
628 { MCIF_8BITMIME, "8BITMIME" },
629 { MCIF_7BIT, "7BIT" },
630 { MCIF_INHEADER, "INHEADER" },
631 { MCIF_CVT8TO7, "CVT8TO7" },
633 { MCIF_8BITOK, "8BITOK" },
634 { MCIF_CVT7TO8, "CVT7TO8" },
635 { MCIF_INMIME, "INMIME" },
636 { MCIF_AUTH, "AUTH" },
637 { MCIF_AUTH2, "AUTH2" },
638 { MCIF_AUTHACT, "AUTHACT" },
639 { MCIF_ENHSTAT, "ENHSTAT" },
640 { MCIF_PIPELINED, "PIPELINED" },
641 { MCIF_VERB, "VERB" },
644 { MCIF_TLSACT, "TLSACT" },
646 { MCIF_DLVR_BY, "DLVR_BY" },
647 { MCIF_INLONGLINE, "INLONGLINE" },
648 { MCIF_NOTSTICKY, "NOTSTICKY" },
653 mci_dump(fp, mci, logit)
662 sep = logit ? " " : "\n\t";
664 (void) sm_snprintf(p, SPACELEFT(buf, p), "MCI@%p: ", (void *)mci);
668 (void) sm_snprintf(p, SPACELEFT(buf, p), "NULL");
671 (void) sm_snprintf(p, SPACELEFT(buf, p), "flags=%lx", mci->mci_flags);
675 ** The following check is just for paranoia. It protects the
676 ** assignment in the if() clause. If there's not some minimum
677 ** amount of space we can stop right now. The check will not
678 ** trigger as long as sizeof(buf)=4000.
681 if (p >= buf + sizeof(buf) - 4)
683 if (mci->mci_flags != 0)
687 *p++ = '<'; /* protected above */
688 for (f = MciFlags; f->mcif_bit != 0; f++)
690 if (!bitset(f->mcif_bit, mci->mci_flags))
692 (void) sm_strlcpyn(p, SPACELEFT(buf, p), 2,
699 /* Note: sm_snprintf() takes care of NULL arguments for %s */
700 (void) sm_snprintf(p, SPACELEFT(buf, p),
701 ",%serrno=%d, herrno=%d, exitstat=%d, state=%d, pid=%d,%s",
702 sep, mci->mci_errno, mci->mci_herrno,
703 mci->mci_exitstat, mci->mci_state, (int) mci->mci_pid, sep);
705 (void) sm_snprintf(p, SPACELEFT(buf, p),
706 "maxsize=%ld, phase=%s, mailer=%s,%s",
707 mci->mci_maxsize, mci->mci_phase,
708 mci->mci_mailer == NULL ? "NULL" : mci->mci_mailer->m_name,
711 (void) sm_snprintf(p, SPACELEFT(buf, p),
712 "status=%s, rstatus=%s,%s",
713 mci->mci_status, mci->mci_rstatus, sep);
715 (void) sm_snprintf(p, SPACELEFT(buf, p),
716 "host=%s, lastuse=%s",
717 mci->mci_host, ctime(&mci->mci_lastuse));
720 sm_syslog(LOG_DEBUG, CurEnv->e_id, "%.1000s", buf);
722 (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s\n", buf);
725 ** MCI_DUMP_ALL -- print the entire MCI cache
728 ** fp -- output file pointer
729 ** logit -- if set, log the result instead of printing
737 mci_dump_all(fp, logit)
743 if (MciCache == NULL)
746 for (i = 0; i < MaxMciCache; i++)
747 mci_dump(fp, MciCache[i], logit);
750 ** MCI_LOCK_HOST -- Lock host while sending.
752 ** If we are contacting a host, we'll need to
753 ** update the status information in the host status
754 ** file, and if we want to do that, we ought to have
755 ** locked it. This has the (according to some)
756 ** desirable effect of serializing connectivity with
757 ** remote hosts -- i.e.: one connection to a given
761 ** mci -- containing the host we want to lock.
764 ** EX_OK -- got the lock.
765 ** EX_TEMPFAIL -- didn't get the lock.
775 sm_dprintf("mci_lock_host: NULL mci\n");
779 if (!SingleThreadDelivery)
782 return mci_lock_host_statfile(mci);
786 mci_lock_host_statfile(mci)
789 int save_errno = errno;
791 char fname[MAXPATHLEN];
793 if (HostStatDir == NULL || mci->mci_host == NULL)
797 sm_dprintf("mci_lock_host: attempting to lock %s\n",
800 if (mci_generate_persistent_path(mci->mci_host, fname, sizeof(fname),
803 /* of course this should never happen */
805 sm_dprintf("mci_lock_host: Failed to generate host path for %s\n",
808 retVal = EX_TEMPFAIL;
812 mci->mci_statfile = safefopen(fname, O_RDWR, FileMode,
813 SFF_NOLOCK|SFF_NOLINK|SFF_OPENASROOT|SFF_REGONLY|SFF_SAFEDIRPATH|SFF_CREAT);
815 if (mci->mci_statfile == NULL)
817 syserr("mci_lock_host: cannot create host lock file %s", fname);
821 if (!lockfile(sm_io_getinfo(mci->mci_statfile, SM_IO_WHAT_FD, NULL),
822 fname, "", LOCK_EX|LOCK_NB))
825 sm_dprintf("mci_lock_host: couldn't get lock on %s\n",
827 (void) sm_io_close(mci->mci_statfile, SM_TIME_DEFAULT);
828 mci->mci_statfile = NULL;
829 retVal = EX_TEMPFAIL;
833 if (tTd(56, 12) && mci->mci_statfile != NULL)
834 sm_dprintf("mci_lock_host: Sanity check -- lock is good\n");
841 ** MCI_UNLOCK_HOST -- unlock host
843 ** Clean up the lock on a host, close the file, let
844 ** someone else use it.
857 int save_errno = errno;
862 sm_dprintf("mci_unlock_host: NULL mci\n");
866 if (HostStatDir == NULL || mci->mci_host == NULL)
869 if (!SingleThreadDelivery && mci_lock_host_statfile(mci) == EX_TEMPFAIL)
872 sm_dprintf("mci_unlock_host: stat file already locked\n");
877 sm_dprintf("mci_unlock_host: store prior to unlock\n");
878 mci_store_persistent(mci);
881 if (mci->mci_statfile != NULL)
883 (void) sm_io_close(mci->mci_statfile, SM_TIME_DEFAULT);
884 mci->mci_statfile = NULL;
890 ** MCI_LOAD_PERSISTENT -- load persistent host info
892 ** Load information about host that is kept
893 ** in common for all running sendmails.
896 ** mci -- the host/connection to load persistent info for.
899 ** true -- lock was successful
900 ** false -- lock failed
904 mci_load_persistent(mci)
907 int save_errno = errno;
910 char fname[MAXPATHLEN];
915 sm_dprintf("mci_load_persistent: NULL mci\n");
919 if (IgnoreHostStatus || HostStatDir == NULL || mci->mci_host == NULL)
922 /* Already have the persistent information in memory */
923 if (SingleThreadDelivery && mci->mci_statfile != NULL)
927 sm_dprintf("mci_load_persistent: Attempting to load persistent information for %s\n",
930 if (mci_generate_persistent_path(mci->mci_host, fname, sizeof(fname),
933 /* Not much we can do if the file isn't there... */
935 sm_dprintf("mci_load_persistent: Couldn't generate host path\n");
939 fp = safefopen(fname, O_RDONLY, FileMode,
940 SFF_NOLOCK|SFF_NOLINK|SFF_OPENASROOT|SFF_REGONLY|SFF_SAFEDIRPATH);
943 /* I can't think of any reason this should ever happen */
945 sm_dprintf("mci_load_persistent: open(%s): %s\n",
946 fname, sm_errstring(errno));
951 locked = lockfile(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), fname, "",
955 (void) mci_read_persistent(fp, mci);
956 (void) lockfile(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), fname,
960 (void) sm_io_close(fp, SM_TIME_DEFAULT);
967 ** MCI_READ_PERSISTENT -- read persistent host status file
970 ** fp -- the file pointer to read.
971 ** mci -- the pointer to fill in.
974 ** -1 -- if the file was corrupt.
978 ** This code makes the assumption that this data
979 ** will be read in an atomic fashion, and that the data
980 ** was written in an atomic fashion. Any other functioning
981 ** may lead to some form of insanity. This should be
982 ** perfectly safe due to underlying stdio buffering.
986 mci_read_persistent(fp, mci)
992 int saveLineNumber = LineNumber;
997 syserr("mci_read_persistent: NULL fp");
1003 syserr("mci_read_persistent: NULL mci");
1009 sm_dprintf("mci_read_persistent: fp=%lx, mci=",
1010 (unsigned long) fp);
1013 SM_FREE(mci->mci_status);
1014 SM_FREE(mci->mci_rstatus);
1016 sm_io_rewind(fp, SM_TIME_DEFAULT);
1019 while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0)
1022 p = strchr(buf, '\n');
1027 case 'V': /* version stamp */
1028 ver = atoi(&buf[1]);
1029 if (ver < 0 || ver > 0)
1030 syserr("Unknown host status version %d: %d max",
1034 case 'E': /* UNIX error number */
1035 mci->mci_errno = atoi(&buf[1]);
1038 case 'H': /* DNS error number */
1039 mci->mci_herrno = atoi(&buf[1]);
1042 case 'S': /* UNIX exit status */
1043 mci->mci_exitstat = atoi(&buf[1]);
1046 case 'D': /* DSN status */
1047 mci->mci_status = newstr(&buf[1]);
1050 case 'R': /* SMTP status */
1051 mci->mci_rstatus = newstr(&buf[1]);
1054 case 'U': /* last usage time */
1055 mci->mci_lastuse = atol(&buf[1]);
1058 case '.': /* end of file */
1060 mci_dump(sm_debug_file(), mci, false);
1064 sm_syslog(LOG_CRIT, NOQID,
1065 "%s: line %d: Unknown host status line \"%s\"",
1066 FileName == NULL ? mci->mci_host : FileName,
1068 LineNumber = saveLineNumber;
1072 LineNumber = saveLineNumber;
1074 sm_dprintf("incomplete (missing dot for EOF)\n");
1080 ** MCI_STORE_PERSISTENT -- Store persistent MCI information
1082 ** Store information about host that is kept
1083 ** in common for all running sendmails.
1086 ** mci -- the host/connection to store persistent info for.
1093 mci_store_persistent(mci)
1096 int save_errno = errno;
1101 sm_dprintf("mci_store_persistent: NULL mci\n");
1105 if (HostStatDir == NULL || mci->mci_host == NULL)
1109 sm_dprintf("mci_store_persistent: Storing information for %s\n",
1112 if (mci->mci_statfile == NULL)
1115 sm_dprintf("mci_store_persistent: no statfile\n");
1119 sm_io_rewind(mci->mci_statfile, SM_TIME_DEFAULT);
1121 (void) ftruncate(sm_io_getinfo(mci->mci_statfile, SM_IO_WHAT_FD, NULL),
1125 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "V0\n");
1126 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "E%d\n",
1128 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "H%d\n",
1130 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "S%d\n",
1132 if (mci->mci_status != NULL)
1133 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT,
1135 denlstring(mci->mci_status, true, false));
1136 if (mci->mci_rstatus != NULL)
1137 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT,
1139 denlstring(mci->mci_rstatus, true, false));
1140 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "U%ld\n",
1141 (long)(mci->mci_lastuse));
1142 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, ".\n");
1144 (void) sm_io_flush(mci->mci_statfile, SM_TIME_DEFAULT);
1150 ** MCI_TRAVERSE_PERSISTENT -- walk persistent status tree
1152 ** Recursively find all the mci host files in `pathname'. Default to
1153 ** main host status directory if no path is provided.
1154 ** Call (*action)(pathname, host) for each file found.
1156 ** Note: all information is collected in a list before it is processed.
1157 ** This may not be the best way to do it, but it seems safest, since
1158 ** the file system would be touched while we are attempting to traverse
1159 ** the directory tree otherwise (during purges).
1162 ** action -- function to call on each node. If returns < 0,
1163 ** return immediately.
1164 ** pathname -- root of tree. If null, use main host status
1168 ** < 0 -- if any action routine returns a negative value, that
1169 ** value is returned.
1170 ** 0 -- if we successfully went to completion.
1171 ** > 0 -- return status from action()
1175 mci_traverse_persistent(action, pathname)
1176 int (*action)__P((char *, char *));
1179 struct stat statbuf;
1183 if (pathname == NULL)
1184 pathname = HostStatDir;
1185 if (pathname == NULL)
1189 sm_dprintf("mci_traverse: pathname is %s\n", pathname);
1191 ret = stat(pathname, &statbuf);
1195 sm_dprintf("mci_traverse: Failed to stat %s: %s\n",
1196 pathname, sm_errstring(errno));
1199 if (S_ISDIR(statbuf.st_mode))
1201 bool leftone, removedone;
1205 char newpath[MAXPATHLEN];
1206 #if MAXPATHLEN <= MAXNAMLEN - 3
1207 ERROR "MAXPATHLEN <= MAXNAMLEN - 3"
1210 if ((d = opendir(pathname)) == NULL)
1213 sm_dprintf("mci_traverse: opendir %s: %s\n",
1214 pathname, sm_errstring(errno));
1219 ** Reserve space for trailing '/', at least one
1220 ** character, and '\0'
1223 len = sizeof(newpath) - 3;
1224 if (sm_strlcpy(newpath, pathname, len) >= len)
1226 int save_errno = errno;
1229 sm_dprintf("mci_traverse: path \"%s\" too long",
1235 newptr = newpath + strlen(newpath);
1237 len = sizeof(newpath) - (newptr - newpath);
1240 ** repeat until no file has been removed
1241 ** this may become ugly when several files "expire"
1242 ** during these loops, but it's better than doing
1243 ** a rewinddir() inside the inner loop
1248 leftone = removedone = false;
1249 while ((e = readdir(d)) != NULL)
1251 if (e->d_name[0] == '.')
1254 if (sm_strlcpy(newptr, e->d_name, len) >= len)
1256 /* Skip truncated copies */
1260 sm_dprintf("mci_traverse: path \"%s%s\" too long",
1261 newpath, e->d_name);
1268 ret = mci_traverse_persistent(action, newpath);
1273 if (!removedone && ret == 0 &&
1274 action == mci_purge_persistent)
1281 ** The following appears to be
1282 ** necessary during purges, since
1283 ** we modify the directory structure
1289 sm_dprintf("mci_traverse: path %s: ret %d removed %d left %d\n",
1290 pathname, ret, removedone, leftone);
1291 } while (removedone);
1293 /* purge (or whatever) the directory proper */
1297 ret = (*action)(newpath, NULL);
1301 else if (S_ISREG(statbuf.st_mode))
1303 char *end = pathname + strlen(pathname) - 1;
1306 char host[MAXHOSTNAMELEN];
1307 char *hostptr = host;
1310 ** Reconstruct the host name from the path to the
1311 ** persistent information.
1316 if (hostptr != host)
1319 while (start > pathname && *(start - 1) != '/')
1325 for (scan = start; scan <= end; scan++)
1326 *(hostptr++) = *scan;
1329 } while (end > pathname && *end == '.');
1334 ** Do something with the file containing the persistent
1338 ret = (*action)(pathname, host);
1344 ** MCI_PRINT_PERSISTENT -- print persistent info
1346 ** Dump the persistent information in the file 'pathname'
1349 ** pathname -- the pathname to the status file.
1350 ** hostname -- the corresponding host name.
1357 mci_print_persistent(pathname, hostname)
1361 static bool initflag = false;
1363 int width = Verbose ? 78 : 25;
1367 /* skip directories */
1368 if (hostname == NULL)
1377 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1378 " -------------- Hostname --------------- How long ago ---------Results---------\n");
1381 fp = safefopen(pathname, O_RDONLY, FileMode,
1382 SFF_NOLOCK|SFF_NOLINK|SFF_OPENASROOT|SFF_REGONLY|SFF_SAFEDIRPATH);
1387 sm_dprintf("mci_print_persistent: cannot open %s: %s\n",
1388 pathname, sm_errstring(errno));
1392 FileName = pathname;
1393 memset(&mcib, '\0', sizeof(mcib));
1394 if (mci_read_persistent(fp, &mcib) < 0)
1396 syserr("%s: could not read status file", pathname);
1397 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1402 locked = !lockfile(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), pathname,
1403 "", LOCK_SH|LOCK_NB);
1404 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1407 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%c%-39s %12s ",
1408 locked ? '*' : ' ', hostname,
1409 pintvl(curtime() - mcib.mci_lastuse, true));
1410 if (mcib.mci_rstatus != NULL)
1411 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s\n", width,
1413 else if (mcib.mci_exitstat == EX_TEMPFAIL && mcib.mci_errno != 0)
1414 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1415 "Deferred: %.*s\n", width - 10,
1416 sm_errstring(mcib.mci_errno));
1417 else if (mcib.mci_exitstat != 0)
1419 char *exmsg = sm_sysexmsg(mcib.mci_exitstat);
1425 (void) sm_snprintf(buf, sizeof(buf),
1426 "Unknown mailer error %d",
1428 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s\n",
1432 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s\n",
1435 else if (mcib.mci_errno == 0)
1436 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "OK\n");
1438 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "OK: %.*s\n",
1439 width - 4, sm_errstring(mcib.mci_errno));
1444 ** MCI_PURGE_PERSISTENT -- Remove a persistence status file.
1447 ** pathname -- path to the status file.
1448 ** hostname -- name of host corresponding to that file.
1449 ** NULL if this is a directory (domain).
1453 ** 1 -- file not deleted (too young, incorrect format)
1454 ** < 0 -- some error occurred
1458 mci_purge_persistent(pathname, hostname)
1462 struct stat statbuf;
1463 char *end = pathname + strlen(pathname) - 1;
1467 sm_dprintf("mci_purge_persistent: purging %s\n", pathname);
1469 ret = stat(pathname, &statbuf);
1473 sm_dprintf("mci_purge_persistent: Failed to stat %s: %s\n",
1474 pathname, sm_errstring(errno));
1477 if (curtime() - statbuf.st_mtime <= MciInfoTimeout)
1479 if (hostname != NULL)
1481 /* remove the file */
1482 ret = unlink(pathname);
1486 sm_syslog(LOG_ERR, NOQID,
1487 "mci_purge_persistent: failed to unlink %s: %s",
1488 pathname, sm_errstring(errno));
1490 sm_dprintf("mci_purge_persistent: failed to unlink %s: %s\n",
1491 pathname, sm_errstring(errno));
1497 /* remove the directory */
1502 sm_dprintf("mci_purge_persistent: dpurge %s\n", pathname);
1504 ret = rmdir(pathname);
1508 sm_dprintf("mci_purge_persistent: rmdir %s: %s\n",
1509 pathname, sm_errstring(errno));
1517 ** MCI_GENERATE_PERSISTENT_PATH -- generate path from hostname
1519 ** Given `host', convert from a.b.c to $HostStatDir/c./b./a,
1520 ** putting the result into `path'. if `createflag' is set, intervening
1521 ** directories will be created as needed.
1524 ** host -- host name to convert from.
1525 ** path -- place to store result.
1526 ** pathlen -- length of path buffer.
1527 ** createflag -- if set, create intervening directories as
1536 mci_generate_persistent_path(host, path, pathlen, createflag)
1542 char *elem, *p, *x, ch;
1545 char t_host[MAXHOSTNAMELEN];
1547 struct in6_addr in6_addr;
1551 ** Rationality check the arguments.
1556 syserr("mci_generate_persistent_path: null host");
1561 syserr("mci_generate_persistent_path: null path");
1566 sm_dprintf("mci_generate_persistent_path(%s): ", host);
1568 if (*host == '\0' || *host == '.')
1571 /* make certain this is not a bracketed host number */
1572 if (strlen(host) > sizeof(t_host) - 1)
1575 (void) sm_strlcpy(t_host, host + 1, sizeof(t_host));
1577 (void) sm_strlcpy(t_host, host, sizeof(t_host));
1580 ** Delete any trailing dots from the hostname.
1581 ** Leave 'elem' pointing at the \0.
1584 elem = t_host + strlen(t_host);
1585 while (elem > t_host &&
1586 (elem[-1] == '.' || (host[0] == '[' && elem[-1] == ']')))
1589 /* check for bogus bracketed address */
1594 if (anynet_pton(AF_INET6, t_host, &in6_addr) == 1)
1598 if (inet_addr(t_host) != INADDR_NONE)
1605 /* check for what will be the final length of the path */
1606 len = strlen(HostStatDir) + 2;
1607 for (p = (char *) t_host; *p != '\0'; p++)
1612 if (p[0] == '.' && p[1] == '.')
1615 if (len > pathlen || len < 1)
1617 (void) sm_strlcpy(path, HostStatDir, pathlen);
1618 p = path + strlen(path);
1619 while (elem > t_host)
1621 if (!path_is_dir(path, createflag))
1627 while (elem >= t_host && *elem != '.')
1631 while ((ch = *x++) != '\0' && ch != '.')
1633 if (isascii(ch) && isupper(ch))
1636 ch = ':'; /* / -> : */
1646 sm_dprintf("FAILURE %d\n", ret);
1648 sm_dprintf("SUCCESS %s\n", path);