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;
252 mci->mci_okrcpts = 0;
255 SM_FREE(mci->mci_status);
256 SM_FREE(mci->mci_rstatus);
257 SM_FREE(mci->mci_heloname);
259 if (mci->mci_rpool != NULL)
261 sm_rpool_free(mci->mci_rpool);
262 mci->mci_macro.mac_rpool = NULL;
263 mci->mci_rpool = NULL;
267 ** MCI_FLUSH -- flush the entire cache
270 ** doquit -- if true, send QUIT protocol.
271 ** if false, just close the connection.
272 ** allbut -- but leave this one open.
279 mci_flush(doquit, allbut)
285 if (MciCache == NULL)
288 for (i = 0; i < MaxMciCache; i++)
290 if (allbut != MciCache[i])
291 mci_uncache(&MciCache[i], doquit);
296 ** MCI_CLR_EXTENSIONS -- clear knowledge about SMTP extensions
299 ** mci -- the connection to clear.
306 mci_clr_extensions(mci)
312 mci->mci_flags &= ~MCIF_EXTENS;
313 mci->mci_maxsize = 0;
316 mci->mci_saslcap = NULL;
321 ** MCI_CLEAR -- clear mci
324 ** mci -- the connection to clear.
337 mci->mci_maxsize = 0;
339 mci->mci_deliveries = 0;
341 if (bitset(MCIF_AUTHACT, mci->mci_flags))
342 sasl_dispose(&mci->mci_conn);
345 if (bitset(MCIF_TLSACT, mci->mci_flags) && mci->mci_ssl != NULL)
346 SM_SSL_FREE(mci->mci_ssl);
349 /* which flags to preserve? */
350 mci->mci_flags &= MCIF_CACHED;
351 mactabclear(&mci->mci_macro);
355 ** MCI_GET -- get information about a particular host
358 ** host -- host to look for.
362 ** mci for this host (might be new).
372 extern SOCKADDR CurHostAddr;
374 /* clear CurHostAddr so we don't get a bogus address with this name */
375 memset(&CurHostAddr, '\0', sizeof(CurHostAddr));
377 /* clear out any expired connections */
378 (void) mci_scan(NULL);
381 syserr("!negative mno %d (%s)", m->m_mno, m->m_name);
383 s = stab(host, ST_MCI + m->m_mno, ST_ENTER);
386 /* initialize per-message data */
387 mci->mci_retryrcpt = false;
388 mci->mci_tolist = NULL;
389 mci->mci_okrcpts = 0;
390 mci->mci_flags &= ~MCIF_NOTSTICKY;
392 if (mci->mci_rpool == NULL)
393 mci->mci_rpool = sm_rpool_new_x(NULL);
395 if (mci->mci_macro.mac_rpool == NULL)
396 mci->mci_macro.mac_rpool = mci->mci_rpool;
399 ** We don't need to load the persistent data if we have data
400 ** already loaded in the cache.
403 if (mci->mci_host == NULL &&
404 (mci->mci_host = s->s_name) != NULL &&
405 !mci_load_persistent(mci))
408 sm_dprintf("mci_get(%s %s): lock failed\n",
410 mci->mci_exitstat = EX_TEMPFAIL;
411 mci->mci_state = MCIS_CLOSED;
412 mci->mci_statfile = NULL;
418 sm_dprintf("mci_get(%s %s): mci_state=%d, _flags=%lx, _exitstat=%d, _errno=%d\n",
419 host, m->m_name, mci->mci_state, mci->mci_flags,
420 mci->mci_exitstat, mci->mci_errno);
423 if (mci->mci_state == MCIS_OPEN)
425 /* poke the connection to see if it's still alive */
426 (void) smtpprobe(mci);
428 /* reset the stored state in the event of a timeout */
429 if (mci->mci_state != MCIS_OPEN)
432 mci->mci_exitstat = EX_OK;
433 mci->mci_state = MCIS_CLOSED;
437 /* get peer host address */
438 /* (this should really be in the mci struct) */
439 SOCKADDR_LEN_T socklen = sizeof(CurHostAddr);
441 (void) getpeername(sm_io_getinfo(mci->mci_in,
442 SM_IO_WHAT_FD, NULL),
443 (struct sockaddr *) &CurHostAddr, &socklen);
446 if (mci->mci_state == MCIS_CLOSED)
448 time_t now = curtime();
450 /* if this info is stale, ignore it */
451 if (mci->mci_lastuse + MciInfoTimeout <= now)
453 mci->mci_lastuse = now;
455 mci->mci_exitstat = EX_OK;
464 ** MCI_CLOSE -- (forcefully) close files used for a connection.
465 ** Note: this is a last resort, usually smtpquit() or endmailer()
466 ** should be used to close a connection.
469 ** mci -- the connection to close.
470 ** where -- where has this been called?
477 mci_close(mci, where)
486 if (mci->mci_out != NULL)
490 sm_dprintf("mci_close: mci_out!=NULL, where=%s\n",
492 mci_dump(sm_debug_file(), mci, false);
495 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
498 if (mci->mci_in != NULL)
502 sm_dprintf("mci_close: mci_in!=NULL, where=%s\n",
505 mci_dump(sm_debug_file(), mci, false);
507 (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT);
510 mci->mci_state = MCIS_CLOSED;
514 ** MCI_NEW -- allocate new MCI structure
517 ** rpool -- if non-NULL: allocate from that rpool.
530 mci = (MCI *) sm_malloc_x(sizeof(*mci));
532 mci = (MCI *) sm_rpool_malloc_x(rpool, sizeof(*mci));
533 memset((char *) mci, '\0', sizeof(*mci));
534 mci->mci_rpool = sm_rpool_new_x(NULL);
535 mci->mci_macro.mac_rpool = mci->mci_rpool;
539 ** MCI_MATCH -- check connection cache for a particular host
542 ** host -- host to look for.
546 ** true iff open connection exists.
557 if (m->m_mno < 0 || m->m_mno > MAXMAILERS)
559 s = stab(host, ST_MCI + m->m_mno, ST_FIND);
564 return mci->mci_state == MCIS_OPEN;
567 ** MCI_SETSTAT -- set status codes in MCI structure.
570 ** mci -- the MCI structure to set.
571 ** xstat -- the exit status code.
572 ** dstat -- the DSN status code.
573 ** rstat -- the SMTP status code.
580 mci_setstat(mci, xstat, dstat, rstat)
586 /* protocol errors should never be interpreted as sticky */
587 if (xstat != EX_NOTSTICKY && xstat != EX_PROTOCOL)
588 mci->mci_exitstat = xstat;
590 SM_FREE(mci->mci_status);
592 mci->mci_status = sm_strdup_x(dstat);
594 SM_FREE(mci->mci_rstatus);
596 mci->mci_rstatus = sm_strdup_x(rstat);
599 ** MCI_DUMP -- dump the contents of an MCI structure.
602 ** fp -- output file pointer
603 ** mci -- the MCI structure to dump.
614 int mcif_bit; /* flag bit */
615 char *mcif_name; /* flag name */
617 static struct mcifbits MciFlags[] =
619 { MCIF_OCC_INCR, "OCC_INCR" },
620 { MCIF_CACHED, "CACHED" },
621 { MCIF_ESMTP, "ESMTP" },
622 { MCIF_EXPN, "EXPN" },
623 { MCIF_SIZE, "SIZE" },
624 { MCIF_8BITMIME, "8BITMIME" },
625 { MCIF_7BIT, "7BIT" },
626 { MCIF_INHEADER, "INHEADER" },
627 { MCIF_CVT8TO7, "CVT8TO7" },
629 { MCIF_8BITOK, "8BITOK" },
630 { MCIF_CVT7TO8, "CVT7TO8" },
631 { MCIF_INMIME, "INMIME" },
632 { MCIF_AUTH, "AUTH" },
633 { MCIF_AUTHACT, "AUTHACT" },
634 { MCIF_ENHSTAT, "ENHSTAT" },
635 { MCIF_PIPELINED, "PIPELINED" },
636 { MCIF_VERB, "VERB" },
639 { MCIF_TLSACT, "TLSACT" },
641 { MCIF_DLVR_BY, "DLVR_BY" },
642 #if _FFR_IGNORE_EXT_ON_HELO
643 { MCIF_HELO, "HELO" },
645 { MCIF_INLONGLINE, "INLONGLINE" },
646 { MCIF_AUTH2, "AUTH2" },
647 { MCIF_ONLY_EHLO, "ONLY_EHLO" },
648 { MCIF_NOTSTICKY, "NOTSTICKY" },
656 mci_dump(fp, mci, logit)
665 sep = logit ? " " : "\n\t";
667 (void) sm_snprintf(p, SPACELEFT(buf, p), "MCI@%p: ", (void *)mci);
671 (void) sm_snprintf(p, SPACELEFT(buf, p), "NULL");
674 (void) sm_snprintf(p, SPACELEFT(buf, p), "flags=%lx", mci->mci_flags);
678 ** The following check is just for paranoia. It protects the
679 ** assignment in the if() clause. If there's not some minimum
680 ** amount of space we can stop right now. The check will not
681 ** trigger as long as sizeof(buf)=4000.
684 if (p >= buf + sizeof(buf) - 4)
686 if (mci->mci_flags != 0)
690 *p++ = '<'; /* protected above */
691 for (f = MciFlags; f->mcif_bit != 0; f++)
693 if (!bitset(f->mcif_bit, mci->mci_flags))
695 (void) sm_strlcpyn(p, SPACELEFT(buf, p), 2,
702 /* Note: sm_snprintf() takes care of NULL arguments for %s */
703 (void) sm_snprintf(p, SPACELEFT(buf, p),
704 ",%serrno=%d, herrno=%d, exitstat=%d, state=%d, pid=%d,%s",
705 sep, mci->mci_errno, mci->mci_herrno,
706 mci->mci_exitstat, mci->mci_state, (int) mci->mci_pid, sep);
708 (void) sm_snprintf(p, SPACELEFT(buf, p),
709 "maxsize=%ld, phase=%s, mailer=%s,%s",
710 mci->mci_maxsize, mci->mci_phase,
711 mci->mci_mailer == NULL ? "NULL" : mci->mci_mailer->m_name,
714 (void) sm_snprintf(p, SPACELEFT(buf, p),
715 "status=%s, rstatus=%s,%s",
716 mci->mci_status, mci->mci_rstatus, sep);
718 (void) sm_snprintf(p, SPACELEFT(buf, p),
719 "host=%s, lastuse=%s",
720 mci->mci_host, ctime(&mci->mci_lastuse));
723 sm_syslog(LOG_DEBUG, CurEnv->e_id, "%.1000s", buf);
725 (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s\n", buf);
728 ** MCI_DUMP_ALL -- print the entire MCI cache
731 ** fp -- output file pointer
732 ** logit -- if set, log the result instead of printing
740 mci_dump_all(fp, logit)
746 if (MciCache == NULL)
749 for (i = 0; i < MaxMciCache; i++)
750 mci_dump(fp, MciCache[i], logit);
753 ** MCI_LOCK_HOST -- Lock host while sending.
755 ** If we are contacting a host, we'll need to
756 ** update the status information in the host status
757 ** file, and if we want to do that, we ought to have
758 ** locked it. This has the (according to some)
759 ** desirable effect of serializing connectivity with
760 ** remote hosts -- i.e.: one connection to a given
764 ** mci -- containing the host we want to lock.
767 ** EX_OK -- got the lock.
768 ** EX_TEMPFAIL -- didn't get the lock.
778 sm_dprintf("mci_lock_host: NULL mci\n");
782 if (!SingleThreadDelivery)
785 return mci_lock_host_statfile(mci);
789 mci_lock_host_statfile(mci)
792 int save_errno = errno;
794 char fname[MAXPATHLEN];
796 if (HostStatDir == NULL || mci->mci_host == NULL)
800 sm_dprintf("mci_lock_host: attempting to lock %s\n",
803 if (mci_generate_persistent_path(mci->mci_host, fname, sizeof(fname),
806 /* of course this should never happen */
808 sm_dprintf("mci_lock_host: Failed to generate host path for %s\n",
811 retVal = EX_TEMPFAIL;
815 mci->mci_statfile = safefopen(fname, O_RDWR, FileMode,
816 SFF_NOLOCK|SFF_NOLINK|SFF_OPENASROOT|SFF_REGONLY|SFF_SAFEDIRPATH|SFF_CREAT);
818 if (mci->mci_statfile == NULL)
820 syserr("mci_lock_host: cannot create host lock file %s", fname);
824 if (!lockfile(sm_io_getinfo(mci->mci_statfile, SM_IO_WHAT_FD, NULL),
825 fname, "", LOCK_EX|LOCK_NB))
828 sm_dprintf("mci_lock_host: couldn't get lock on %s\n",
830 (void) sm_io_close(mci->mci_statfile, SM_TIME_DEFAULT);
831 mci->mci_statfile = NULL;
832 retVal = EX_TEMPFAIL;
836 if (tTd(56, 12) && mci->mci_statfile != NULL)
837 sm_dprintf("mci_lock_host: Sanity check -- lock is good\n");
844 ** MCI_UNLOCK_HOST -- unlock host
846 ** Clean up the lock on a host, close the file, let
847 ** someone else use it.
860 int save_errno = errno;
865 sm_dprintf("mci_unlock_host: NULL mci\n");
869 if (HostStatDir == NULL || mci->mci_host == NULL)
872 if (!SingleThreadDelivery && mci_lock_host_statfile(mci) == EX_TEMPFAIL)
875 sm_dprintf("mci_unlock_host: stat file already locked\n");
880 sm_dprintf("mci_unlock_host: store prior to unlock\n");
881 mci_store_persistent(mci);
884 if (mci->mci_statfile != NULL)
886 (void) sm_io_close(mci->mci_statfile, SM_TIME_DEFAULT);
887 mci->mci_statfile = NULL;
893 ** MCI_LOAD_PERSISTENT -- load persistent host info
895 ** Load information about host that is kept
896 ** in common for all running sendmails.
899 ** mci -- the host/connection to load persistent info for.
902 ** true -- lock was successful
903 ** false -- lock failed
907 mci_load_persistent(mci)
910 int save_errno = errno;
913 char fname[MAXPATHLEN];
918 sm_dprintf("mci_load_persistent: NULL mci\n");
922 if (IgnoreHostStatus || HostStatDir == NULL || mci->mci_host == NULL)
925 /* Already have the persistent information in memory */
926 if (SingleThreadDelivery && mci->mci_statfile != NULL)
930 sm_dprintf("mci_load_persistent: Attempting to load persistent information for %s\n",
933 if (mci_generate_persistent_path(mci->mci_host, fname, sizeof(fname),
936 /* Not much we can do if the file isn't there... */
938 sm_dprintf("mci_load_persistent: Couldn't generate host path\n");
942 fp = safefopen(fname, O_RDONLY, FileMode,
943 SFF_NOLOCK|SFF_NOLINK|SFF_OPENASROOT|SFF_REGONLY|SFF_SAFEDIRPATH);
946 /* I can't think of any reason this should ever happen */
948 sm_dprintf("mci_load_persistent: open(%s): %s\n",
949 fname, sm_errstring(errno));
954 locked = lockfile(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), fname, "",
958 (void) mci_read_persistent(fp, mci);
959 (void) lockfile(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), fname,
963 (void) sm_io_close(fp, SM_TIME_DEFAULT);
970 ** MCI_READ_PERSISTENT -- read persistent host status file
973 ** fp -- the file pointer to read.
974 ** mci -- the pointer to fill in.
977 ** -1 -- if the file was corrupt.
981 ** This code makes the assumption that this data
982 ** will be read in an atomic fashion, and that the data
983 ** was written in an atomic fashion. Any other functioning
984 ** may lead to some form of insanity. This should be
985 ** perfectly safe due to underlying stdio buffering.
989 mci_read_persistent(fp, mci)
995 int saveLineNumber = LineNumber;
1000 syserr("mci_read_persistent: NULL fp");
1006 syserr("mci_read_persistent: NULL mci");
1012 sm_dprintf("mci_read_persistent: fp=%lx, mci=",
1013 (unsigned long) fp);
1016 SM_FREE(mci->mci_status);
1017 SM_FREE(mci->mci_rstatus);
1019 sm_io_rewind(fp, SM_TIME_DEFAULT);
1022 while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0)
1025 p = strchr(buf, '\n');
1030 case 'V': /* version stamp */
1031 ver = atoi(&buf[1]);
1032 if (ver < 0 || ver > 0)
1033 syserr("Unknown host status version %d: %d max",
1037 case 'E': /* UNIX error number */
1038 mci->mci_errno = atoi(&buf[1]);
1041 case 'H': /* DNS error number */
1042 mci->mci_herrno = atoi(&buf[1]);
1045 case 'S': /* UNIX exit status */
1046 mci->mci_exitstat = atoi(&buf[1]);
1049 case 'D': /* DSN status */
1050 mci->mci_status = newstr(&buf[1]);
1053 case 'R': /* SMTP status */
1054 mci->mci_rstatus = newstr(&buf[1]);
1057 case 'U': /* last usage time */
1058 mci->mci_lastuse = atol(&buf[1]);
1061 case '.': /* end of file */
1063 mci_dump(sm_debug_file(), mci, false);
1067 sm_syslog(LOG_CRIT, NOQID,
1068 "%s: line %d: Unknown host status line \"%s\"",
1069 FileName == NULL ? mci->mci_host : FileName,
1071 LineNumber = saveLineNumber;
1075 LineNumber = saveLineNumber;
1077 sm_dprintf("incomplete (missing dot for EOF)\n");
1083 ** MCI_STORE_PERSISTENT -- Store persistent MCI information
1085 ** Store information about host that is kept
1086 ** in common for all running sendmails.
1089 ** mci -- the host/connection to store persistent info for.
1096 mci_store_persistent(mci)
1099 int save_errno = errno;
1104 sm_dprintf("mci_store_persistent: NULL mci\n");
1108 if (HostStatDir == NULL || mci->mci_host == NULL)
1112 sm_dprintf("mci_store_persistent: Storing information for %s\n",
1115 if (mci->mci_statfile == NULL)
1118 sm_dprintf("mci_store_persistent: no statfile\n");
1122 sm_io_rewind(mci->mci_statfile, SM_TIME_DEFAULT);
1124 (void) ftruncate(sm_io_getinfo(mci->mci_statfile, SM_IO_WHAT_FD, NULL),
1128 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "V0\n");
1129 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "E%d\n",
1131 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "H%d\n",
1133 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "S%d\n",
1135 if (mci->mci_status != NULL)
1136 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT,
1138 denlstring(mci->mci_status, true, false));
1139 if (mci->mci_rstatus != NULL)
1140 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT,
1142 denlstring(mci->mci_rstatus, true, false));
1143 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "U%ld\n",
1144 (long)(mci->mci_lastuse));
1145 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, ".\n");
1147 (void) sm_io_flush(mci->mci_statfile, SM_TIME_DEFAULT);
1153 ** MCI_TRAVERSE_PERSISTENT -- walk persistent status tree
1155 ** Recursively find all the mci host files in `pathname'. Default to
1156 ** main host status directory if no path is provided.
1157 ** Call (*action)(pathname, host) for each file found.
1159 ** Note: all information is collected in a list before it is processed.
1160 ** This may not be the best way to do it, but it seems safest, since
1161 ** the file system would be touched while we are attempting to traverse
1162 ** the directory tree otherwise (during purges).
1165 ** action -- function to call on each node. If returns < 0,
1166 ** return immediately.
1167 ** pathname -- root of tree. If null, use main host status
1171 ** < 0 -- if any action routine returns a negative value, that
1172 ** value is returned.
1173 ** 0 -- if we successfully went to completion.
1174 ** > 0 -- return status from action()
1178 mci_traverse_persistent(action, pathname)
1179 int (*action)__P((char *, char *));
1182 struct stat statbuf;
1186 if (pathname == NULL)
1187 pathname = HostStatDir;
1188 if (pathname == NULL)
1192 sm_dprintf("mci_traverse: pathname is %s\n", pathname);
1194 ret = stat(pathname, &statbuf);
1198 sm_dprintf("mci_traverse: Failed to stat %s: %s\n",
1199 pathname, sm_errstring(errno));
1202 if (S_ISDIR(statbuf.st_mode))
1204 bool leftone, removedone;
1208 char newpath[MAXPATHLEN];
1209 #if MAXPATHLEN <= MAXNAMLEN - 3
1210 # error "MAXPATHLEN <= MAXNAMLEN - 3"
1213 if ((d = opendir(pathname)) == NULL)
1216 sm_dprintf("mci_traverse: opendir %s: %s\n",
1217 pathname, sm_errstring(errno));
1222 ** Reserve space for trailing '/', at least one
1223 ** character, and '\0'
1226 len = sizeof(newpath) - 3;
1227 if (sm_strlcpy(newpath, pathname, len) >= len)
1229 int save_errno = errno;
1232 sm_dprintf("mci_traverse: path \"%s\" too long",
1238 newptr = newpath + strlen(newpath);
1240 len = sizeof(newpath) - (newptr - newpath);
1243 ** repeat until no file has been removed
1244 ** this may become ugly when several files "expire"
1245 ** during these loops, but it's better than doing
1246 ** a rewinddir() inside the inner loop
1251 leftone = removedone = false;
1252 while ((e = readdir(d)) != NULL)
1254 if (e->d_name[0] == '.')
1257 if (sm_strlcpy(newptr, e->d_name, len) >= len)
1259 /* Skip truncated copies */
1263 sm_dprintf("mci_traverse: path \"%s%s\" too long",
1264 newpath, e->d_name);
1271 ret = mci_traverse_persistent(action, newpath);
1276 if (!removedone && ret == 0 &&
1277 action == mci_purge_persistent)
1284 ** The following appears to be
1285 ** necessary during purges, since
1286 ** we modify the directory structure
1292 sm_dprintf("mci_traverse: path %s: ret %d removed %d left %d\n",
1293 pathname, ret, removedone, leftone);
1294 } while (removedone);
1296 /* purge (or whatever) the directory proper */
1300 ret = (*action)(newpath, NULL);
1304 else if (S_ISREG(statbuf.st_mode))
1306 char *end = pathname + strlen(pathname) - 1;
1309 char host[MAXHOSTNAMELEN];
1310 char *hostptr = host;
1313 ** Reconstruct the host name from the path to the
1314 ** persistent information.
1319 if (hostptr != host)
1322 while (start > pathname && *(start - 1) != '/')
1328 for (scan = start; scan <= end; scan++)
1329 *(hostptr++) = *scan;
1332 } while (end > pathname && *end == '.');
1337 ** Do something with the file containing the persistent
1341 ret = (*action)(pathname, host);
1347 ** MCI_PRINT_PERSISTENT -- print persistent info
1349 ** Dump the persistent information in the file 'pathname'
1352 ** pathname -- the pathname to the status file.
1353 ** hostname -- the corresponding host name.
1360 mci_print_persistent(pathname, hostname)
1364 static bool initflag = false;
1366 int width = Verbose ? 78 : 25;
1370 /* skip directories */
1371 if (hostname == NULL)
1380 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1381 " -------------- Hostname --------------- How long ago ---------Results---------\n");
1384 fp = safefopen(pathname, O_RDONLY, FileMode,
1385 SFF_NOLOCK|SFF_NOLINK|SFF_OPENASROOT|SFF_REGONLY|SFF_SAFEDIRPATH);
1390 sm_dprintf("mci_print_persistent: cannot open %s: %s\n",
1391 pathname, sm_errstring(errno));
1395 FileName = pathname;
1396 memset(&mcib, '\0', sizeof(mcib));
1397 if (mci_read_persistent(fp, &mcib) < 0)
1399 syserr("%s: could not read status file", pathname);
1400 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1405 locked = !lockfile(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), pathname,
1406 "", LOCK_SH|LOCK_NB);
1407 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1410 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%c%-39s %12s ",
1411 locked ? '*' : ' ', hostname,
1412 pintvl(curtime() - mcib.mci_lastuse, true));
1413 if (mcib.mci_rstatus != NULL)
1414 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s\n", width,
1416 else if (mcib.mci_exitstat == EX_TEMPFAIL && mcib.mci_errno != 0)
1417 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1418 "Deferred: %.*s\n", width - 10,
1419 sm_errstring(mcib.mci_errno));
1420 else if (mcib.mci_exitstat != 0)
1422 char *exmsg = sm_sysexmsg(mcib.mci_exitstat);
1428 (void) sm_snprintf(buf, sizeof(buf),
1429 "Unknown mailer error %d",
1431 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s\n",
1435 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s\n",
1438 else if (mcib.mci_errno == 0)
1439 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "OK\n");
1441 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "OK: %.*s\n",
1442 width - 4, sm_errstring(mcib.mci_errno));
1447 ** MCI_PURGE_PERSISTENT -- Remove a persistence status file.
1450 ** pathname -- path to the status file.
1451 ** hostname -- name of host corresponding to that file.
1452 ** NULL if this is a directory (domain).
1456 ** 1 -- file not deleted (too young, incorrect format)
1457 ** < 0 -- some error occurred
1461 mci_purge_persistent(pathname, hostname)
1465 struct stat statbuf;
1466 char *end = pathname + strlen(pathname) - 1;
1470 sm_dprintf("mci_purge_persistent: purging %s\n", pathname);
1472 ret = stat(pathname, &statbuf);
1476 sm_dprintf("mci_purge_persistent: Failed to stat %s: %s\n",
1477 pathname, sm_errstring(errno));
1480 if (curtime() - statbuf.st_mtime <= MciInfoTimeout)
1482 if (hostname != NULL)
1484 /* remove the file */
1485 ret = unlink(pathname);
1489 sm_syslog(LOG_ERR, NOQID,
1490 "mci_purge_persistent: failed to unlink %s: %s",
1491 pathname, sm_errstring(errno));
1493 sm_dprintf("mci_purge_persistent: failed to unlink %s: %s\n",
1494 pathname, sm_errstring(errno));
1500 /* remove the directory */
1505 sm_dprintf("mci_purge_persistent: dpurge %s\n", pathname);
1507 ret = rmdir(pathname);
1511 sm_dprintf("mci_purge_persistent: rmdir %s: %s\n",
1512 pathname, sm_errstring(errno));
1520 ** MCI_GENERATE_PERSISTENT_PATH -- generate path from hostname
1522 ** Given `host', convert from a.b.c to $HostStatDir/c./b./a,
1523 ** putting the result into `path'. if `createflag' is set, intervening
1524 ** directories will be created as needed.
1527 ** host -- host name to convert from.
1528 ** path -- place to store result.
1529 ** pathlen -- length of path buffer.
1530 ** createflag -- if set, create intervening directories as
1539 mci_generate_persistent_path(host, path, pathlen, createflag)
1545 char *elem, *p, *x, ch;
1548 char t_host[MAXHOSTNAMELEN];
1550 struct in6_addr in6_addr;
1554 ** Rationality check the arguments.
1559 syserr("mci_generate_persistent_path: null host");
1564 syserr("mci_generate_persistent_path: null path");
1569 sm_dprintf("mci_generate_persistent_path(%s): ", host);
1571 if (*host == '\0' || *host == '.')
1574 /* make certain this is not a bracketed host number */
1575 if (strlen(host) > sizeof(t_host) - 1)
1578 (void) sm_strlcpy(t_host, host + 1, sizeof(t_host));
1580 (void) sm_strlcpy(t_host, host, sizeof(t_host));
1583 ** Delete any trailing dots from the hostname.
1584 ** Leave 'elem' pointing at the \0.
1587 elem = t_host + strlen(t_host);
1588 while (elem > t_host &&
1589 (elem[-1] == '.' || (host[0] == '[' && elem[-1] == ']')))
1592 /* check for bogus bracketed address */
1597 if (anynet_pton(AF_INET6, t_host, &in6_addr) == 1)
1601 if (inet_addr(t_host) != INADDR_NONE)
1608 /* check for what will be the final length of the path */
1609 len = strlen(HostStatDir) + 2;
1610 for (p = (char *) t_host; *p != '\0'; p++)
1615 if (p[0] == '.' && p[1] == '.')
1618 if (len > pathlen || len < 1)
1620 (void) sm_strlcpy(path, HostStatDir, pathlen);
1621 p = path + strlen(path);
1622 while (elem > t_host)
1624 if (!path_is_dir(path, createflag))
1630 while (elem >= t_host && *elem != '.')
1634 while ((ch = *x++) != '\0' && ch != '.')
1636 if (isascii(ch) && isupper(ch))
1639 ch = ':'; /* / -> : */
1649 sm_dprintf("FAILURE %d\n", ret);
1651 sm_dprintf("SUCCESS %s\n", path);