2 * Copyright (c) 1998-2005 Sendmail, 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.
17 SM_RCSID("@(#)$Id: mci.c,v 8.216 2005/07/12 22:27:44 ca Exp $")
19 #if NETINET || NETINET6
20 # include <arpa/inet.h>
21 #endif /* NETINET || NETINET6 */
25 static int mci_generate_persistent_path __P((const char *, char *,
27 static bool mci_load_persistent __P((MCI *));
28 static void mci_uncache __P((MCI **, bool));
29 static int mci_lock_host_statfile __P((MCI *));
30 static int mci_read_persistent __P((SM_FILE_T *, MCI *));
33 ** Mail Connection Information (MCI) Caching Module.
35 ** There are actually two separate things cached. The first is
36 ** the set of all open connections -- these are stored in a
37 ** (small) list. The second is stored in the symbol table; it
38 ** has the overall status for all hosts, whether or not there
39 ** is a connection open currently.
41 ** There should never be too many connections open (since this
42 ** could flood the socket table), nor should a connection be
43 ** allowed to sit idly for too long.
45 ** MaxMciCache is the maximum number of open connections that
48 ** MciCacheTimeout is the time (in seconds) that a connection
49 ** is permitted to survive without activity.
51 ** We actually try any cached connections by sending a RSET
52 ** before we use them; if the RSET fails we close down the
53 ** connection and reopen it (see smtpprobe()).
55 ** The persistent MCI code is donated by Mark Lovell and Paul
56 ** Vixie. It is based on the long term host status code in KJS
57 ** written by Paul but has been adapted by Mark to fit into the
61 static MCI **MciCache; /* the open connection cache */
64 ** MCI_CACHE -- enter a connection structure into the open connection cache
66 ** This may cause something else to be flushed.
69 ** mci -- the connection to cache.
79 register MCI **mcislot;
82 ** Find the best slot. This may cause expired connections
86 mcislot = mci_scan(mci);
89 /* we don't support caching */
93 if (mci->mci_host == NULL)
96 /* if this is already cached, we are done */
97 if (bitset(MCIF_CACHED, mci->mci_flags))
100 /* otherwise we may have to clear the slot */
101 if (*mcislot != NULL)
102 mci_uncache(mcislot, true);
105 sm_dprintf("mci_cache: caching %p (%s) in slot %d\n",
106 mci, mci->mci_host, (int) (mcislot - MciCache));
108 sm_syslog(LOG_DEBUG, CurEnv->e_id,
109 "mci_cache: caching %lx (%.100s) in slot %d",
110 (unsigned long) mci, mci->mci_host,
111 (int) (mcislot - MciCache));
114 mci->mci_flags |= MCIF_CACHED;
117 ** MCI_SCAN -- scan the cache, flush junk, and return best slot
120 ** savemci -- never flush this one. Can be null.
123 ** The LRU (or empty) slot.
131 register MCI **bestmci;
135 if (MaxMciCache <= 0)
137 /* we don't support caching */
141 if (MciCache == NULL)
144 MciCache = (MCI **) sm_pmalloc_x(MaxMciCache * sizeof *MciCache);
145 memset((char *) MciCache, '\0', MaxMciCache * sizeof *MciCache);
150 bestmci = &MciCache[0];
151 for (i = 0; i < MaxMciCache; i++)
154 if (mci == NULL || mci->mci_state == MCIS_CLOSED)
156 bestmci = &MciCache[i];
159 if ((mci->mci_lastuse + MciCacheTimeout <= now ||
160 (mci->mci_mailer != NULL &&
161 mci->mci_mailer->m_maxdeliveries > 0 &&
162 mci->mci_deliveries + 1 >= mci->mci_mailer->m_maxdeliveries))&&
165 /* connection idle too long or too many deliveries */
166 bestmci = &MciCache[i];
169 mci_uncache(bestmci, true);
172 if (*bestmci == NULL)
174 if (mci->mci_lastuse < (*bestmci)->mci_lastuse)
175 bestmci = &MciCache[i];
180 ** MCI_UNCACHE -- remove a connection from a slot.
182 ** May close a connection.
185 ** mcislot -- the slot to empty.
186 ** doquit -- if true, send QUIT protocol on this connection.
187 ** if false, we are assumed to be in a forked child;
188 ** all we want to do is close the file(s).
195 mci_uncache(mcislot, doquit)
196 register MCI **mcislot;
200 extern ENVELOPE BlankEnvelope;
206 if (mci->mci_host == NULL)
209 mci_unlock_host(mci);
212 sm_dprintf("mci_uncache: uncaching %p (%s) from slot %d (%d)\n",
213 mci, mci->mci_host, (int) (mcislot - MciCache),
216 sm_syslog(LOG_DEBUG, CurEnv->e_id,
217 "mci_uncache: uncaching %lx (%.100s) from slot %d (%d)",
218 (unsigned long) mci, mci->mci_host,
219 (int) (mcislot - MciCache), doquit);
221 mci->mci_deliveries = 0;
224 message("Closing connection to %s", mci->mci_host);
226 mci->mci_flags &= ~MCIF_CACHED;
228 /* only uses the envelope to flush the transcript file */
229 if (mci->mci_state != MCIS_CLOSED)
230 smtpquit(mci->mci_mailer, mci, &BlankEnvelope);
232 xla_host_end(mci->mci_host);
237 if (mci->mci_in != NULL)
238 (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT);
239 if (mci->mci_out != NULL)
240 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
241 mci->mci_in = mci->mci_out = NULL;
242 mci->mci_state = MCIS_CLOSED;
243 mci->mci_exitstat = EX_OK;
247 mci->mci_retryrcpt = false;
248 mci->mci_tolist = NULL;
250 mci->mci_okrcpts = 0;
251 #endif /* PIPELINING */
254 SM_FREE_CLR(mci->mci_status);
255 SM_FREE_CLR(mci->mci_rstatus);
256 SM_FREE_CLR(mci->mci_heloname);
257 if (mci->mci_rpool != NULL)
259 sm_rpool_free(mci->mci_rpool);
260 mci->mci_macro.mac_rpool = NULL;
261 mci->mci_rpool = NULL;
265 ** MCI_FLUSH -- flush the entire cache
268 ** doquit -- if true, send QUIT protocol.
269 ** if false, just close the connection.
270 ** allbut -- but leave this one open.
277 mci_flush(doquit, allbut)
283 if (MciCache == NULL)
286 for (i = 0; i < MaxMciCache; i++)
288 if (allbut != MciCache[i])
289 mci_uncache(&MciCache[i], doquit);
293 ** MCI_GET -- get information about a particular host
296 ** host -- host to look for.
300 ** mci for this host (might be new).
310 extern SOCKADDR CurHostAddr;
312 /* clear CurHostAddr so we don't get a bogus address with this name */
313 memset(&CurHostAddr, '\0', sizeof CurHostAddr);
315 /* clear out any expired connections */
316 (void) mci_scan(NULL);
319 syserr("!negative mno %d (%s)", m->m_mno, m->m_name);
321 s = stab(host, ST_MCI + m->m_mno, ST_ENTER);
324 /* initialize per-message data */
325 mci->mci_retryrcpt = false;
326 mci->mci_tolist = NULL;
328 mci->mci_okrcpts = 0;
329 #endif /* PIPELINING */
331 if (mci->mci_rpool == NULL)
332 mci->mci_rpool = sm_rpool_new_x(NULL);
334 if (mci->mci_macro.mac_rpool == NULL)
335 mci->mci_macro.mac_rpool = mci->mci_rpool;
338 ** We don't need to load the persistent data if we have data
339 ** already loaded in the cache.
342 if (mci->mci_host == NULL &&
343 (mci->mci_host = s->s_name) != NULL &&
344 !mci_load_persistent(mci))
347 sm_dprintf("mci_get(%s %s): lock failed\n",
349 mci->mci_exitstat = EX_TEMPFAIL;
350 mci->mci_state = MCIS_CLOSED;
351 mci->mci_statfile = NULL;
357 sm_dprintf("mci_get(%s %s): mci_state=%d, _flags=%lx, _exitstat=%d, _errno=%d\n",
358 host, m->m_name, mci->mci_state, mci->mci_flags,
359 mci->mci_exitstat, mci->mci_errno);
362 if (mci->mci_state == MCIS_OPEN)
364 /* poke the connection to see if it's still alive */
365 (void) smtpprobe(mci);
367 /* reset the stored state in the event of a timeout */
368 if (mci->mci_state != MCIS_OPEN)
371 mci->mci_exitstat = EX_OK;
372 mci->mci_state = MCIS_CLOSED;
376 /* get peer host address */
377 /* (this should really be in the mci struct) */
378 SOCKADDR_LEN_T socklen = sizeof CurHostAddr;
380 (void) getpeername(sm_io_getinfo(mci->mci_in,
381 SM_IO_WHAT_FD, NULL),
382 (struct sockaddr *) &CurHostAddr, &socklen);
385 if (mci->mci_state == MCIS_CLOSED)
387 time_t now = curtime();
389 /* if this info is stale, ignore it */
390 if (mci->mci_lastuse + MciInfoTimeout <= now)
392 mci->mci_lastuse = now;
394 mci->mci_exitstat = EX_OK;
402 ** MCI_CLOSE -- (forcefully) close files used for a connection.
403 ** Note: this is a last resort, usually smtpquit() or endmailer()
404 ** should be used to close a connection.
407 ** mci -- the connection to close.
408 ** where -- where has this been called?
415 mci_close(mci, where)
424 if (mci->mci_out != NULL)
428 sm_dprintf("mci_close: mci_out!=NULL, where=%s\n",
430 mci_dump(sm_debug_file(), mci, false);
433 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
436 if (mci->mci_in != NULL)
440 sm_dprintf("mci_close: mci_in!=NULL, where=%s\n",
443 mci_dump(sm_debug_file(), mci, false);
445 (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT);
448 mci->mci_state = MCIS_CLOSED;
452 ** MCI_NEW -- allocate new MCI structure
455 ** rpool -- if non-NULL: allocate from that rpool.
468 mci = (MCI *) sm_malloc_x(sizeof *mci);
470 mci = (MCI *) sm_rpool_malloc_x(rpool, sizeof *mci);
471 memset((char *) mci, '\0', sizeof *mci);
472 mci->mci_rpool = sm_rpool_new_x(NULL);
473 mci->mci_macro.mac_rpool = mci->mci_rpool;
477 ** MCI_MATCH -- check connection cache for a particular host
480 ** host -- host to look for.
484 ** true iff open connection exists.
495 if (m->m_mno < 0 || m->m_mno > MAXMAILERS)
497 s = stab(host, ST_MCI + m->m_mno, ST_FIND);
502 return mci->mci_state == MCIS_OPEN;
505 ** MCI_SETSTAT -- set status codes in MCI structure.
508 ** mci -- the MCI structure to set.
509 ** xstat -- the exit status code.
510 ** dstat -- the DSN status code.
511 ** rstat -- the SMTP status code.
518 mci_setstat(mci, xstat, dstat, rstat)
524 /* protocol errors should never be interpreted as sticky */
525 if (xstat != EX_NOTSTICKY && xstat != EX_PROTOCOL)
526 mci->mci_exitstat = xstat;
528 SM_FREE_CLR(mci->mci_status);
530 mci->mci_status = sm_strdup_x(dstat);
532 SM_FREE_CLR(mci->mci_rstatus);
534 mci->mci_rstatus = sm_strdup_x(rstat);
537 ** MCI_DUMP -- dump the contents of an MCI structure.
540 ** fp -- output file pointer
541 ** mci -- the MCI structure to dump.
552 int mcif_bit; /* flag bit */
553 char *mcif_name; /* flag name */
555 static struct mcifbits MciFlags[] =
557 { MCIF_VALID, "VALID" },
558 { MCIF_CACHED, "CACHED" },
559 { MCIF_ESMTP, "ESMTP" },
560 { MCIF_EXPN, "EXPN" },
561 { MCIF_SIZE, "SIZE" },
562 { MCIF_8BITMIME, "8BITMIME" },
563 { MCIF_7BIT, "7BIT" },
564 { MCIF_INHEADER, "INHEADER" },
565 { MCIF_CVT8TO7, "CVT8TO7" },
567 { MCIF_8BITOK, "8BITOK" },
568 { MCIF_CVT7TO8, "CVT7TO8" },
569 { MCIF_INMIME, "INMIME" },
570 { MCIF_AUTH, "AUTH" },
571 { MCIF_AUTHACT, "AUTHACT" },
572 { MCIF_ENHSTAT, "ENHSTAT" },
573 { MCIF_PIPELINED, "PIPELINED" },
576 { MCIF_TLSACT, "TLSACT" },
577 #endif /* STARTTLS */
578 { MCIF_DLVR_BY, "DLVR_BY" },
583 mci_dump(fp, mci, logit)
592 sep = logit ? " " : "\n\t";
594 (void) sm_snprintf(p, SPACELEFT(buf, p), "MCI@%p: ", mci);
598 (void) sm_snprintf(p, SPACELEFT(buf, p), "NULL");
601 (void) sm_snprintf(p, SPACELEFT(buf, p), "flags=%lx", mci->mci_flags);
605 ** The following check is just for paranoia. It protects the
606 ** assignment in the if() clause. If there's not some minimum
607 ** amount of space we can stop right now. The check will not
608 ** trigger as long as sizeof(buf)=4000.
611 if (p >= buf + sizeof(buf) - 4)
613 if (mci->mci_flags != 0)
617 *p++ = '<'; /* protected above */
618 for (f = MciFlags; f->mcif_bit != 0; f++)
620 if (!bitset(f->mcif_bit, mci->mci_flags))
622 (void) sm_strlcpyn(p, SPACELEFT(buf, p), 2,
629 /* Note: sm_snprintf() takes care of NULL arguments for %s */
630 (void) sm_snprintf(p, SPACELEFT(buf, p),
631 ",%serrno=%d, herrno=%d, exitstat=%d, state=%d, pid=%d,%s",
632 sep, mci->mci_errno, mci->mci_herrno,
633 mci->mci_exitstat, mci->mci_state, (int) mci->mci_pid, sep);
635 (void) sm_snprintf(p, SPACELEFT(buf, p),
636 "maxsize=%ld, phase=%s, mailer=%s,%s",
637 mci->mci_maxsize, mci->mci_phase,
638 mci->mci_mailer == NULL ? "NULL" : mci->mci_mailer->m_name,
641 (void) sm_snprintf(p, SPACELEFT(buf, p),
642 "status=%s, rstatus=%s,%s",
643 mci->mci_status, mci->mci_rstatus, sep);
645 (void) sm_snprintf(p, SPACELEFT(buf, p),
646 "host=%s, lastuse=%s",
647 mci->mci_host, ctime(&mci->mci_lastuse));
650 sm_syslog(LOG_DEBUG, CurEnv->e_id, "%.1000s", buf);
652 (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s\n", buf);
655 ** MCI_DUMP_ALL -- print the entire MCI cache
658 ** fp -- output file pointer
659 ** logit -- if set, log the result instead of printing
667 mci_dump_all(fp, logit)
673 if (MciCache == NULL)
676 for (i = 0; i < MaxMciCache; i++)
677 mci_dump(fp, MciCache[i], logit);
680 ** MCI_LOCK_HOST -- Lock host while sending.
682 ** If we are contacting a host, we'll need to
683 ** update the status information in the host status
684 ** file, and if we want to do that, we ought to have
685 ** locked it. This has the (according to some)
686 ** desirable effect of serializing connectivity with
687 ** remote hosts -- i.e.: one connection to a given
691 ** mci -- containing the host we want to lock.
694 ** EX_OK -- got the lock.
695 ** EX_TEMPFAIL -- didn't get the lock.
705 sm_dprintf("mci_lock_host: NULL mci\n");
709 if (!SingleThreadDelivery)
712 return mci_lock_host_statfile(mci);
716 mci_lock_host_statfile(mci)
719 int save_errno = errno;
721 char fname[MAXPATHLEN];
723 if (HostStatDir == NULL || mci->mci_host == NULL)
727 sm_dprintf("mci_lock_host: attempting to lock %s\n",
730 if (mci_generate_persistent_path(mci->mci_host, fname, sizeof fname,
733 /* of course this should never happen */
735 sm_dprintf("mci_lock_host: Failed to generate host path for %s\n",
738 retVal = EX_TEMPFAIL;
742 mci->mci_statfile = safefopen(fname, O_RDWR, FileMode,
743 SFF_NOLOCK|SFF_NOLINK|SFF_OPENASROOT|SFF_REGONLY|SFF_SAFEDIRPATH|SFF_CREAT);
745 if (mci->mci_statfile == NULL)
747 syserr("mci_lock_host: cannot create host lock file %s", fname);
751 if (!lockfile(sm_io_getinfo(mci->mci_statfile, SM_IO_WHAT_FD, NULL),
752 fname, "", LOCK_EX|LOCK_NB))
755 sm_dprintf("mci_lock_host: couldn't get lock on %s\n",
757 (void) sm_io_close(mci->mci_statfile, SM_TIME_DEFAULT);
758 mci->mci_statfile = NULL;
759 retVal = EX_TEMPFAIL;
763 if (tTd(56, 12) && mci->mci_statfile != NULL)
764 sm_dprintf("mci_lock_host: Sanity check -- lock is good\n");
771 ** MCI_UNLOCK_HOST -- unlock host
773 ** Clean up the lock on a host, close the file, let
774 ** someone else use it.
787 int save_errno = errno;
792 sm_dprintf("mci_unlock_host: NULL mci\n");
796 if (HostStatDir == NULL || mci->mci_host == NULL)
799 if (!SingleThreadDelivery && mci_lock_host_statfile(mci) == EX_TEMPFAIL)
802 sm_dprintf("mci_unlock_host: stat file already locked\n");
807 sm_dprintf("mci_unlock_host: store prior to unlock\n");
808 mci_store_persistent(mci);
811 if (mci->mci_statfile != NULL)
813 (void) sm_io_close(mci->mci_statfile, SM_TIME_DEFAULT);
814 mci->mci_statfile = NULL;
820 ** MCI_LOAD_PERSISTENT -- load persistent host info
822 ** Load information about host that is kept
823 ** in common for all running sendmails.
826 ** mci -- the host/connection to load persistent info for.
829 ** true -- lock was successful
830 ** false -- lock failed
834 mci_load_persistent(mci)
837 int save_errno = errno;
840 char fname[MAXPATHLEN];
845 sm_dprintf("mci_load_persistent: NULL mci\n");
849 if (IgnoreHostStatus || HostStatDir == NULL || mci->mci_host == NULL)
852 /* Already have the persistent information in memory */
853 if (SingleThreadDelivery && mci->mci_statfile != NULL)
857 sm_dprintf("mci_load_persistent: Attempting to load persistent information for %s\n",
860 if (mci_generate_persistent_path(mci->mci_host, fname, sizeof fname,
863 /* Not much we can do if the file isn't there... */
865 sm_dprintf("mci_load_persistent: Couldn't generate host path\n");
869 fp = safefopen(fname, O_RDONLY, FileMode,
870 SFF_NOLOCK|SFF_NOLINK|SFF_OPENASROOT|SFF_REGONLY|SFF_SAFEDIRPATH);
873 /* I can't think of any reason this should ever happen */
875 sm_dprintf("mci_load_persistent: open(%s): %s\n",
876 fname, sm_errstring(errno));
881 locked = lockfile(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), fname, "",
885 (void) mci_read_persistent(fp, mci);
886 (void) lockfile(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), fname,
890 (void) sm_io_close(fp, SM_TIME_DEFAULT);
897 ** MCI_READ_PERSISTENT -- read persistent host status file
900 ** fp -- the file pointer to read.
901 ** mci -- the pointer to fill in.
904 ** -1 -- if the file was corrupt.
908 ** This code makes the assumption that this data
909 ** will be read in an atomic fashion, and that the data
910 ** was written in an atomic fashion. Any other functioning
911 ** may lead to some form of insanity. This should be
912 ** perfectly safe due to underlying stdio buffering.
916 mci_read_persistent(fp, mci)
922 int saveLineNumber = LineNumber;
926 syserr("mci_read_persistent: NULL fp");
928 syserr("mci_read_persistent: NULL mci");
931 sm_dprintf("mci_read_persistent: fp=%lx, mci=",
935 SM_FREE_CLR(mci->mci_status);
936 SM_FREE_CLR(mci->mci_rstatus);
938 sm_io_rewind(fp, SM_TIME_DEFAULT);
941 while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf, sizeof buf) != NULL)
944 p = strchr(buf, '\n');
949 case 'V': /* version stamp */
951 if (ver < 0 || ver > 0)
952 syserr("Unknown host status version %d: %d max",
956 case 'E': /* UNIX error number */
957 mci->mci_errno = atoi(&buf[1]);
960 case 'H': /* DNS error number */
961 mci->mci_herrno = atoi(&buf[1]);
964 case 'S': /* UNIX exit status */
965 mci->mci_exitstat = atoi(&buf[1]);
968 case 'D': /* DSN status */
969 mci->mci_status = newstr(&buf[1]);
972 case 'R': /* SMTP status */
973 mci->mci_rstatus = newstr(&buf[1]);
976 case 'U': /* last usage time */
977 mci->mci_lastuse = atol(&buf[1]);
980 case '.': /* end of file */
982 mci_dump(sm_debug_file(), mci, false);
986 sm_syslog(LOG_CRIT, NOQID,
987 "%s: line %d: Unknown host status line \"%s\"",
988 FileName == NULL ? mci->mci_host : FileName,
990 LineNumber = saveLineNumber;
994 LineNumber = saveLineNumber;
996 sm_dprintf("incomplete (missing dot for EOF)\n");
1002 ** MCI_STORE_PERSISTENT -- Store persistent MCI information
1004 ** Store information about host that is kept
1005 ** in common for all running sendmails.
1008 ** mci -- the host/connection to store persistent info for.
1015 mci_store_persistent(mci)
1018 int save_errno = errno;
1023 sm_dprintf("mci_store_persistent: NULL mci\n");
1027 if (HostStatDir == NULL || mci->mci_host == NULL)
1031 sm_dprintf("mci_store_persistent: Storing information for %s\n",
1034 if (mci->mci_statfile == NULL)
1037 sm_dprintf("mci_store_persistent: no statfile\n");
1041 sm_io_rewind(mci->mci_statfile, SM_TIME_DEFAULT);
1043 (void) ftruncate(sm_io_getinfo(mci->mci_statfile, SM_IO_WHAT_FD, NULL),
1045 #endif /* !NOFTRUNCATE */
1047 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "V0\n");
1048 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "E%d\n",
1050 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "H%d\n",
1052 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "S%d\n",
1054 if (mci->mci_status != NULL)
1055 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT,
1057 denlstring(mci->mci_status, true, false));
1058 if (mci->mci_rstatus != NULL)
1059 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT,
1061 denlstring(mci->mci_rstatus, true, false));
1062 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "U%ld\n",
1063 (long)(mci->mci_lastuse));
1064 (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, ".\n");
1066 (void) sm_io_flush(mci->mci_statfile, SM_TIME_DEFAULT);
1072 ** MCI_TRAVERSE_PERSISTENT -- walk persistent status tree
1074 ** Recursively find all the mci host files in `pathname'. Default to
1075 ** main host status directory if no path is provided.
1076 ** Call (*action)(pathname, host) for each file found.
1078 ** Note: all information is collected in a list before it is processed.
1079 ** This may not be the best way to do it, but it seems safest, since
1080 ** the file system would be touched while we are attempting to traverse
1081 ** the directory tree otherwise (during purges).
1084 ** action -- function to call on each node. If returns < 0,
1085 ** return immediately.
1086 ** pathname -- root of tree. If null, use main host status
1090 ** < 0 -- if any action routine returns a negative value, that
1091 ** value is returned.
1092 ** 0 -- if we successfully went to completion.
1093 ** > 0 -- return status from action()
1097 mci_traverse_persistent(action, pathname)
1098 int (*action)__P((char *, char *));
1101 struct stat statbuf;
1105 if (pathname == NULL)
1106 pathname = HostStatDir;
1107 if (pathname == NULL)
1111 sm_dprintf("mci_traverse: pathname is %s\n", pathname);
1113 ret = stat(pathname, &statbuf);
1117 sm_dprintf("mci_traverse: Failed to stat %s: %s\n",
1118 pathname, sm_errstring(errno));
1121 if (S_ISDIR(statbuf.st_mode))
1123 bool leftone, removedone;
1127 char newpath[MAXPATHLEN];
1128 #if MAXPATHLEN <= MAXNAMLEN - 3
1129 ERROR "MAXPATHLEN <= MAXNAMLEN - 3"
1130 #endif /* MAXPATHLEN <= MAXNAMLEN - 3 */
1132 if ((d = opendir(pathname)) == NULL)
1135 sm_dprintf("mci_traverse: opendir %s: %s\n",
1136 pathname, sm_errstring(errno));
1139 len = sizeof(newpath) - MAXNAMLEN - 3;
1140 if (sm_strlcpy(newpath, pathname, len) >= len)
1143 sm_dprintf("mci_traverse: path \"%s\" too long",
1147 newptr = newpath + strlen(newpath);
1151 ** repeat until no file has been removed
1152 ** this may become ugly when several files "expire"
1153 ** during these loops, but it's better than doing
1154 ** a rewinddir() inside the inner loop
1159 leftone = removedone = false;
1160 while ((e = readdir(d)) != NULL)
1162 if (e->d_name[0] == '.')
1165 (void) sm_strlcpy(newptr, e->d_name,
1167 (newptr - newpath));
1171 ret = mci_traverse_persistent(action, newpath);
1176 if (!removedone && ret == 0 &&
1177 action == mci_purge_persistent)
1184 ** The following appears to be
1185 ** necessary during purges, since
1186 ** we modify the directory structure
1192 sm_dprintf("mci_traverse: path %s: ret %d removed %d left %d\n",
1193 pathname, ret, removedone, leftone);
1194 } while (removedone);
1196 /* purge (or whatever) the directory proper */
1200 ret = (*action)(newpath, NULL);
1204 else if (S_ISREG(statbuf.st_mode))
1206 char *end = pathname + strlen(pathname) - 1;
1209 char host[MAXHOSTNAMELEN];
1210 char *hostptr = host;
1213 ** Reconstruct the host name from the path to the
1214 ** persistent information.
1219 if (hostptr != host)
1222 while (start > pathname && *(start - 1) != '/')
1228 for (scan = start; scan <= end; scan++)
1229 *(hostptr++) = *scan;
1232 } while (end > pathname && *end == '.');
1237 ** Do something with the file containing the persistent
1241 ret = (*action)(pathname, host);
1247 ** MCI_PRINT_PERSISTENT -- print persistent info
1249 ** Dump the persistent information in the file 'pathname'
1252 ** pathname -- the pathname to the status file.
1253 ** hostname -- the corresponding host name.
1260 mci_print_persistent(pathname, hostname)
1264 static bool initflag = false;
1266 int width = Verbose ? 78 : 25;
1270 /* skip directories */
1271 if (hostname == NULL)
1280 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1281 " -------------- Hostname --------------- How long ago ---------Results---------\n");
1284 fp = safefopen(pathname, O_RDONLY, FileMode,
1285 SFF_NOLOCK|SFF_NOLINK|SFF_OPENASROOT|SFF_REGONLY|SFF_SAFEDIRPATH);
1290 sm_dprintf("mci_print_persistent: cannot open %s: %s\n",
1291 pathname, sm_errstring(errno));
1295 FileName = pathname;
1296 memset(&mcib, '\0', sizeof mcib);
1297 if (mci_read_persistent(fp, &mcib) < 0)
1299 syserr("%s: could not read status file", pathname);
1300 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1305 locked = !lockfile(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), pathname,
1306 "", LOCK_SH|LOCK_NB);
1307 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1310 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%c%-39s %12s ",
1311 locked ? '*' : ' ', hostname,
1312 pintvl(curtime() - mcib.mci_lastuse, true));
1313 if (mcib.mci_rstatus != NULL)
1314 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s\n", width,
1316 else if (mcib.mci_exitstat == EX_TEMPFAIL && mcib.mci_errno != 0)
1317 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1318 "Deferred: %.*s\n", width - 10,
1319 sm_errstring(mcib.mci_errno));
1320 else if (mcib.mci_exitstat != 0)
1322 char *exmsg = sm_sysexmsg(mcib.mci_exitstat);
1328 (void) sm_snprintf(buf, sizeof buf,
1329 "Unknown mailer error %d",
1331 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s\n",
1335 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s\n",
1338 else if (mcib.mci_errno == 0)
1339 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "OK\n");
1341 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "OK: %.*s\n",
1342 width - 4, sm_errstring(mcib.mci_errno));
1347 ** MCI_PURGE_PERSISTENT -- Remove a persistence status file.
1350 ** pathname -- path to the status file.
1351 ** hostname -- name of host corresponding to that file.
1352 ** NULL if this is a directory (domain).
1356 ** 1 -- file not deleted (too young, incorrect format)
1357 ** < 0 -- some error occurred
1361 mci_purge_persistent(pathname, hostname)
1365 struct stat statbuf;
1366 char *end = pathname + strlen(pathname) - 1;
1370 sm_dprintf("mci_purge_persistent: purging %s\n", pathname);
1372 ret = stat(pathname, &statbuf);
1376 sm_dprintf("mci_purge_persistent: Failed to stat %s: %s\n",
1377 pathname, sm_errstring(errno));
1380 if (curtime() - statbuf.st_mtime <= MciInfoTimeout)
1382 if (hostname != NULL)
1384 /* remove the file */
1385 ret = unlink(pathname);
1389 sm_syslog(LOG_ERR, NOQID,
1390 "mci_purge_persistent: failed to unlink %s: %s",
1391 pathname, sm_errstring(errno));
1393 sm_dprintf("mci_purge_persistent: failed to unlink %s: %s\n",
1394 pathname, sm_errstring(errno));
1400 /* remove the directory */
1405 sm_dprintf("mci_purge_persistent: dpurge %s\n", pathname);
1407 ret = rmdir(pathname);
1411 sm_dprintf("mci_purge_persistent: rmdir %s: %s\n",
1412 pathname, sm_errstring(errno));
1420 ** MCI_GENERATE_PERSISTENT_PATH -- generate path from hostname
1422 ** Given `host', convert from a.b.c to $HostStatDir/c./b./a,
1423 ** putting the result into `path'. if `createflag' is set, intervening
1424 ** directories will be created as needed.
1427 ** host -- host name to convert from.
1428 ** path -- place to store result.
1429 ** pathlen -- length of path buffer.
1430 ** createflag -- if set, create intervening directories as
1439 mci_generate_persistent_path(host, path, pathlen, createflag)
1445 char *elem, *p, *x, ch;
1448 char t_host[MAXHOSTNAMELEN];
1450 struct in6_addr in6_addr;
1451 #endif /* NETINET6 */
1454 ** Rationality check the arguments.
1459 syserr("mci_generate_persistent_path: null host");
1464 syserr("mci_generate_persistent_path: null path");
1469 sm_dprintf("mci_generate_persistent_path(%s): ", host);
1471 if (*host == '\0' || *host == '.')
1474 /* make certain this is not a bracketed host number */
1475 if (strlen(host) > sizeof t_host - 1)
1478 (void) sm_strlcpy(t_host, host + 1, sizeof t_host);
1480 (void) sm_strlcpy(t_host, host, sizeof t_host);
1483 ** Delete any trailing dots from the hostname.
1484 ** Leave 'elem' pointing at the \0.
1487 elem = t_host + strlen(t_host);
1488 while (elem > t_host &&
1489 (elem[-1] == '.' || (host[0] == '[' && elem[-1] == ']')))
1492 /* check for bogus bracketed address */
1497 if (anynet_pton(AF_INET6, t_host, &in6_addr) == 1)
1499 # endif /* NETINET6 */
1501 if (inet_addr(t_host) != INADDR_NONE)
1503 # endif /* NETINET */
1508 /* check for what will be the final length of the path */
1509 len = strlen(HostStatDir) + 2;
1510 for (p = (char *) t_host; *p != '\0'; p++)
1515 if (p[0] == '.' && p[1] == '.')
1518 if (len > pathlen || len < 1)
1520 (void) sm_strlcpy(path, HostStatDir, pathlen);
1521 p = path + strlen(path);
1522 while (elem > t_host)
1524 if (!path_is_dir(path, createflag))
1530 while (elem >= t_host && *elem != '.')
1534 while ((ch = *x++) != '\0' && ch != '.')
1536 if (isascii(ch) && isupper(ch))
1539 ch = ':'; /* / -> : */
1549 sm_dprintf("FAILURE %d\n", ret);
1551 sm_dprintf("SUCCESS %s\n", path);