2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
9 * Portions Copyright (c) 2006 Sine Nomine Associates
12 #include <afsconfig.h>
13 #include <afs/param.h>
27 #include <netinet/in.h>
32 #include <afs/assert.h>
35 #include <afs/afsint.h>
36 #include <afs/rxgen_consts.h>
38 #include <afs/errors.h>
39 #include <afs/ihandle.h>
40 #include <afs/vnode.h>
41 #include <afs/volume.h>
42 #ifdef AFS_ATHENA_STDENV
46 #include <afs/ptclient.h>
47 #include <afs/ptuser.h>
48 #include <afs/prs_fs.h>
50 #include <afs/afsutil.h>
51 #include <afs/com_err.h>
53 #include <afs/cellconfig.h>
55 #include "viced_prototypes.h"
59 #ifdef AFS_DEMAND_ATTACH_FS
60 #include "../util/afsutil_prototypes.h"
61 #include "../tviced/serialize_state.h"
62 #endif /* AFS_DEMAND_ATTACH_FS */
64 #ifdef AFS_PTHREAD_ENV
65 pthread_mutex_t host_glock_mutex;
66 #endif /* AFS_PTHREAD_ENV */
69 extern int CurrentConnections;
71 extern int AnonymousID;
72 extern prlist AnonCPS;
74 extern struct afsconf_dir *confDir; /* config dir object */
75 extern int lwps; /* the max number of server threads */
76 extern afsUUID FS_HostUUID;
79 int CEs = 0; /* active clients */
80 int CEBlocks = 0; /* number of blocks of CEs */
81 struct client *CEFree = 0; /* first free client */
82 struct host *hostList = 0; /* linked list of all hosts */
83 int hostCount = 0; /* number of hosts in hostList */
87 static struct rx_securityClass *sc = NULL;
89 static void h_SetupCallbackConn_r(struct host * host);
91 #define CESPERBLOCK 73
92 struct CEBlock { /* block of CESPERBLOCK file entries */
93 struct client entry[CESPERBLOCK];
96 static void h_TossStuff_r(register struct host *host);
99 * Make sure the subnet macros have been defined.
102 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
105 #ifndef IN_CLASSA_SUBNET
106 #define IN_CLASSA_SUBNET 0xffff0000
110 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
113 #ifndef IN_CLASSB_SUBNET
114 #define IN_CLASSB_SUBNET 0xffffff00
118 /* get a new block of CEs and chain it on CEFree */
122 register struct CEBlock *block;
125 block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
127 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
128 ShutDownAndCore(PANIC);
131 for (i = 0; i < (CESPERBLOCK - 1); i++) {
132 Lock_Init(&block->entry[i].lock);
133 block->entry[i].next = &(block->entry[i + 1]);
135 block->entry[CESPERBLOCK - 1].next = 0;
136 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
137 CEFree = (struct client *)block;
143 /* get the next available CE */
144 static struct client *
147 register struct client *entry;
152 ViceLog(0, ("CEFree NULL in GetCE\n"));
153 ShutDownAndCore(PANIC);
157 CEFree = entry->next;
159 memset((char *)entry, 0, CLIENT_TO_ZERO(entry));
165 /* return an entry to the free list */
167 FreeCE(register struct client *entry)
169 entry->VenusEpoch = 0;
171 entry->next = CEFree;
178 * The HTs and HTBlocks variables were formerly static, but they are
179 * now referenced elsewhere in the FileServer.
181 int HTs = 0; /* active file entries */
182 int HTBlocks = 0; /* number of blocks of HTs */
183 static struct host *HTFree = 0; /* first free file entry */
186 * Hash tables of host pointers. We need two tables, one
187 * to map IP addresses onto host pointers, and another
188 * to map host UUIDs onto host pointers.
190 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
191 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
192 #define h_HashIndex(hostip) ((hostip) & (h_HASHENTRIES-1))
193 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
195 struct HTBlock { /* block of HTSPERBLOCK file entries */
196 struct host entry[h_HTSPERBLOCK];
200 /* get a new block of HTs and chain it on HTFree */
204 register struct HTBlock *block;
206 static int index = 0;
208 if (HTBlocks == h_MAXHOSTTABLES) {
209 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
210 ShutDownAndCore(PANIC);
213 block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
215 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
216 ShutDownAndCore(PANIC);
218 #ifdef AFS_PTHREAD_ENV
219 for (i = 0; i < (h_HTSPERBLOCK); i++)
220 assert(pthread_cond_init(&block->entry[i].cond, NULL) == 0);
221 #endif /* AFS_PTHREAD_ENV */
222 for (i = 0; i < (h_HTSPERBLOCK); i++)
223 Lock_Init(&block->entry[i].lock);
224 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
225 block->entry[i].next = &(block->entry[i + 1]);
226 for (i = 0; i < (h_HTSPERBLOCK); i++)
227 block->entry[i].index = index++;
228 block->entry[h_HTSPERBLOCK - 1].next = 0;
229 HTFree = (struct host *)block;
230 hosttableptrs[HTBlocks++] = block->entry;
235 /* get the next available HT */
239 register struct host *entry;
243 assert(HTFree != NULL);
245 HTFree = entry->next;
247 memset((char *)entry, 0, HOST_TO_ZERO(entry));
253 /* return an entry to the free list */
255 FreeHT(register struct host *entry)
257 entry->next = HTFree;
264 hpr_Initialize(struct ubik_client **uclient)
267 struct rx_connection *serverconns[MAXSERVERS];
268 struct rx_securityClass *sc[3];
269 struct afsconf_dir *tdir;
270 char tconfDir[100] = "";
272 struct ktc_token ttoken;
274 struct afsconf_cell info;
278 tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
280 ViceLog(0, ("hpr_Initialize: Could not open configuration directory: %s", AFSDIR_SERVER_ETC_DIRPATH));
284 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
286 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
291 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
293 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s", cellstr, confDir, AFSDIR_CELLSERVDB_FILE));
300 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
309 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
310 * to force use of the KeyFile. secLevel == 0 implies -noauth was
312 if ((afsconf_GetLatestKey(tdir, 0, 0) == 0)) {
313 code = afsconf_ClientAuthSecure(tdir, &sc[2], &scIndex);
315 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s (so trying noauth)", code, afs_error_message(code)));
317 scIndex = 0; /* use noauth */
319 /* if there was a problem, an unauthenticated conn is returned */
322 struct ktc_principal sname;
323 strcpy(sname.cell, info.name);
324 sname.instance[0] = 0;
325 strcpy(sname.name, "afs");
326 code = ktc_GetToken(&sname, &ttoken, sizeof(ttoken), NULL);
330 if (ttoken.kvno >= 0 && ttoken.kvno <= 256)
331 /* this is a kerberos ticket, set scIndex accordingly */
334 ViceLog(0, ("hpr_Initialize: funny kvno (%d) in ticket, proceeding", ttoken.kvno));
338 rxkad_NewClientSecurityObject(rxkad_clear, &ttoken.sessionKey,
339 ttoken.kvno, ttoken.ticketLen,
343 if ((scIndex == 0) && (sc[0] == 0))
344 sc[0] = rxnull_NewClientSecurityObject();
346 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, running unauthenticated. [%d]", code));
348 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
349 for (i = 0; i < info.numServers; i++) {
351 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
352 info.hostAddr[i].sin_port, PRSRV, sc[scIndex],
356 code = ubik_ClientInit(serverconns, uclient);
358 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
361 code = rxs_Release(sc[scIndex]);
366 hpr_End(struct ubik_client *uclient)
371 code = ubik_ClientDestroy(uclient);
377 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
379 #ifdef AFS_PTHREAD_ENV
380 register afs_int32 code;
382 struct ubik_client *uclient =
383 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
386 code = hpr_Initialize(&uclient);
388 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
394 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
395 if (code != PRSUCCESS)
398 /* do something about this, probably make a new call */
399 /* don't forget there's a hard limit in the interface */
401 "membership list for host id %d exceeds display limit\n",
406 return pr_GetHostCPS(host, CPS);
411 hpr_NameToId(namelist *names, idlist *ids)
413 #ifdef AFS_PTHREAD_ENV
414 register afs_int32 code;
415 register afs_int32 i;
416 struct ubik_client *uclient =
417 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
420 code = hpr_Initialize(&uclient);
422 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
427 for (i = 0; i < names->namelist_len; i++)
428 stolower(names->namelist_val[i]);
429 code = ubik_PR_NameToID(uclient, 0, names, ids);
432 return pr_NameToId(names, ids);
437 hpr_IdToName(idlist *ids, namelist *names)
439 #ifdef AFS_PTHREAD_ENV
440 register afs_int32 code;
441 struct ubik_client *uclient =
442 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
445 code = hpr_Initialize(&uclient);
447 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
452 code = ubik_PR_IDToName(uclient, 0, ids, names);
455 return pr_IdToName(ids, names);
460 hpr_GetCPS(afs_int32 id, prlist *CPS)
462 #ifdef AFS_PTHREAD_ENV
463 register afs_int32 code;
465 struct ubik_client *uclient =
466 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
469 code = hpr_Initialize(&uclient);
471 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
477 code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
478 if (code != PRSUCCESS)
481 /* do something about this, probably make a new call */
482 /* don't forget there's a hard limit in the interface */
483 fprintf(stderr, "membership list for id %d exceeds display limit\n",
488 return pr_GetCPS(id, CPS);
492 static short consolePort = 0;
495 h_Release(register struct host *host)
504 * If this thread does not have a hold on this host AND
505 * if other threads also dont have any holds on this host AND
506 * If either the HOSTDELETED or CLIENTDELETED flags are set
510 h_Release_r(register struct host *host)
513 if (!((host)->holds[h_holdSlot()] & ~h_holdbit())) {
514 if (!h_OtherHolds_r(host)) {
515 /* must avoid masking this until after h_OtherHolds_r runs
516 * but it should be run before h_TossStuff_r */
517 (host)->holds[h_holdSlot()] &= ~h_holdbit();
518 if ((host->hostFlags & HOSTDELETED)
519 || (host->hostFlags & CLIENTDELETED)) {
523 (host)->holds[h_holdSlot()] &= ~h_holdbit();
525 (host)->holds[h_holdSlot()] &= ~h_holdbit();
531 h_OtherHolds_r(register struct host *host)
533 register int i, bit, slot;
536 for (i = 0; i < h_maxSlots; i++) {
537 if (host->holds[i] != ((i == slot) ? bit : 0)) {
545 h_Lock_r(register struct host *host)
555 * returns 1 if already locked
556 * else returns locks and returns 0
560 h_NBLock_r(register struct host *host)
562 struct Lock *hostLock = &host->lock;
567 if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
568 hostLock->excl_locked = WRITE_LOCK;
572 LOCK_UNLOCK(hostLock);
581 #if FS_STATS_DETAILED
582 /*------------------------------------------------------------------------
583 * PRIVATE h_AddrInSameNetwork
586 * Given a target IP address and a candidate IP address (both
587 * in host byte order), return a non-zero value (1) if the
588 * candidate address is in a different network from the target
592 * a_targetAddr : Target address.
593 * a_candAddr : Candidate address.
596 * 1 if the candidate address is in the same net as the target,
600 * The target and candidate addresses are both in host byte
601 * order, NOT network byte order, when passed in. We return
602 * our value as a character, since that's the type of field in
603 * the host structure, where this info will be stored.
607 *------------------------------------------------------------------------*/
610 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
611 { /*h_AddrInSameNetwork */
613 afs_uint32 targetNet;
617 * Pull out the network and subnetwork numbers from the target
618 * and candidate addresses. We can short-circuit this whole
619 * affair if the target and candidate addresses are not of the
622 if (IN_CLASSA(a_targetAddr)) {
623 if (!(IN_CLASSA(a_candAddr))) {
626 targetNet = a_targetAddr & IN_CLASSA_NET;
627 candNet = a_candAddr & IN_CLASSA_NET;
628 } else if (IN_CLASSB(a_targetAddr)) {
629 if (!(IN_CLASSB(a_candAddr))) {
632 targetNet = a_targetAddr & IN_CLASSB_NET;
633 candNet = a_candAddr & IN_CLASSB_NET;
634 } /*Class B target */
635 else if (IN_CLASSC(a_targetAddr)) {
636 if (!(IN_CLASSC(a_candAddr))) {
639 targetNet = a_targetAddr & IN_CLASSC_NET;
640 candNet = a_candAddr & IN_CLASSC_NET;
641 } /*Class C target */
643 targetNet = a_targetAddr;
644 candNet = a_candAddr;
645 } /*Class D address */
648 * Now, simply compare the extracted net values for the two addresses
649 * (which at this point are known to be of the same class)
651 if (targetNet == candNet)
656 } /*h_AddrInSameNetwork */
657 #endif /* FS_STATS_DETAILED */
660 /* Assumptions: called with held host */
662 h_gethostcps_r(register struct host *host, register afs_int32 now)
667 /* wait if somebody else is already doing the getCPS call */
668 while (host->hostFlags & HCPS_INPROGRESS) {
669 slept = 1; /* I did sleep */
670 host->hostFlags |= HCPS_WAITING; /* I am sleeping now */
671 #ifdef AFS_PTHREAD_ENV
672 pthread_cond_wait(&host->cond, &host_glock_mutex);
673 #else /* AFS_PTHREAD_ENV */
674 if ((code = LWP_WaitProcess(&(host->hostFlags))) != LWP_SUCCESS)
675 ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
676 #endif /* AFS_PTHREAD_ENV */
680 host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
681 if (host->hcps.prlist_val)
682 free(host->hcps.prlist_val); /* this is for hostaclRefresh */
683 host->hcps.prlist_val = NULL;
684 host->hcps.prlist_len = 0;
685 host->cpsCall = slept ? (FT_ApproxTime()) : (now);
688 code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
693 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
694 * and reevaluates things if no sync server or quorum is found we could still end up
695 * with one of these errors. In such case we would like to reevaluate the rpc call to
696 * find if there's cps for this guy. We treat other errors (except network failures
697 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
698 * we could like to deal this problem the other way around (i.e. if code == NOCPS
699 * ignore else retry next time) but the problem is that there're other errors (i.e.
700 * EPERM) for which we don't want to retry and we don't know the whole code list!
702 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
704 * We would have preferred to use a while loop and try again since ops in protected
705 * acls for this host will fail now but they'll be reevaluated on any subsequent
706 * call. The attempt to wait for a quorum/sync site or network error won't work
707 * since this problems really should only occurs during a complete fileserver
708 * restart. Since the fileserver will start before the ptservers (and thus before
709 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
711 host->hcpsfailed = 1;
713 ("Warning: GetHostCPS failed (%d) for %x (%s:%d); will retry\n",
714 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
716 host->hcpsfailed = 0;
718 ("gethost: GetHostCPS failed (%d) for %x (%s:%d); ignored\n",
719 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
721 if (host->hcps.prlist_val)
722 free(host->hcps.prlist_val);
723 host->hcps.prlist_val = NULL;
724 host->hcps.prlist_len = 0; /* Make sure it's zero */
726 host->hcpsfailed = 0;
728 host->hostFlags &= ~HCPS_INPROGRESS;
729 /* signal all who are waiting */
730 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
731 host->hostFlags &= ~HCPS_WAITING;
732 #ifdef AFS_PTHREAD_ENV
733 assert(pthread_cond_broadcast(&host->cond) == 0);
734 #else /* AFS_PTHREAD_ENV */
735 if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
736 ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
737 #endif /* AFS_PTHREAD_ENV */
741 /* args in net byte order */
743 h_flushhostcps(register afs_uint32 hostaddr, register afs_uint16 hport)
749 h_Lookup_r(hostaddr, hport, &held, &host);
751 host->hcpsfailed = 1;
761 * Allocate a host. It will be identified by the peer (ip,port) info in the
762 * rx connection provided. The host is returned held and locked
764 #define DEF_ROPCONS 2115
767 h_Alloc_r(register struct rx_connection *r_con)
769 struct servent *serverentry;
772 #if FS_STATS_DETAILED
773 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
774 #endif /* FS_STATS_DETAILED */
778 host->host = rxr_HostOf(r_con);
779 host->port = rxr_PortOf(r_con);
781 h_AddHostToAddrHashTable_r(host->host, host->port, host);
783 if (consolePort == 0) { /* find the portal number for console */
784 #if defined(AFS_OSF_ENV)
785 serverentry = getservbyname("ropcons", "");
787 serverentry = getservbyname("ropcons", 0);
790 consolePort = serverentry->s_port;
792 consolePort = htons(DEF_ROPCONS); /* Use a default */
794 if (host->port == consolePort)
796 /* Make a callback channel even for the console, on the off chance that it
797 * makes a request that causes a break call back. It shouldn't. */
798 h_SetupCallbackConn_r(host);
799 now = host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
801 host->hcps.prlist_val = NULL;
802 host->hcps.prlist_len = 0;
803 host->interface = NULL;
805 host->hcpsfailed = 0; /* save cycles */
806 h_gethostcps(host); /* do this under host hold/lock */
808 host->FirstClient = NULL;
811 h_InsertList_r(host); /* update global host List */
812 #if FS_STATS_DETAILED
814 * Compare the new host's IP address (in host byte order) with ours
815 * (the File Server's), remembering if they are in the same network.
817 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
818 host->InSameNetwork =
819 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
820 #endif /* FS_STATS_DETAILED */
827 /* Make a callback channel even for the console, on the off chance that it
828 * makes a request that causes a break call back. It shouldn't. */
830 h_SetupCallbackConn_r(struct host * host)
833 sc = rxnull_NewClientSecurityObject();
834 host->callback_rxcon =
835 rx_NewConnection(host->host, host->port, 1, sc, 0);
836 rx_SetConnDeadTime(host->callback_rxcon, 50);
837 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
840 /* Lookup a host given an IP address and UDP port number. */
841 /* hostaddr and hport are in network order */
842 /* Note: host should be released by caller if 0 == *heldp and non-null */
843 /* hostaddr and hport are in network order */
845 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, int *heldp, struct host **hostp)
848 struct host *host = NULL;
849 struct h_AddrHashChain *chain;
850 int index = h_HashIndex(haddr);
851 extern int hostaclRefresh;
854 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
855 host = chain->hostPtr;
857 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
858 && chain->port == hport) {
859 if ((host->hostFlags & HWHO_INPROGRESS) &&
860 h_threadquota(host->lock.num_waiting)) {
864 *heldp = h_Held_r(host);
868 if (host->hostFlags & HOSTDELETED) {
875 now = FT_ApproxTime(); /* always evaluate "now" */
876 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
878 * Every hostaclRefresh period (def 2 hrs) get the new
879 * membership list for the host. Note this could be the
880 * first time that the host is added to a group. Also
881 * here we also retry on previous legitimate hcps failures.
883 * If we get here we still have a host hold.
885 h_gethostcps_r(host, now);
895 /* Lookup a host given its UUID. */
897 h_LookupUuid_r(afsUUID * uuidp)
899 struct host *host = 0;
900 struct h_UuidHashChain *chain;
901 int index = h_UuidHashIndex(uuidp);
903 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
904 host = chain->hostPtr;
906 if (!(host->hostFlags & HOSTDELETED) && host->interface
907 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
918 * h_Hold_r: Establish a hold by the current LWP on this host--the host
919 * or its clients will not be physically deleted until all holds have
921 * NOTE: h_Hold_r is a macro defined in host.h.
924 /* h_TossStuff_r: Toss anything in the host structure (the host or
925 * clients marked for deletion. Called from h_Release_r ONLY.
926 * To be called, there must be no holds, and either host->deleted
927 * or host->clientDeleted must be set.
930 h_TossStuff_r(register struct host *host)
932 register struct client **cp, *client;
935 /* if somebody still has this host held */
936 for (i = 0; (i < h_maxSlots) && (!(host)->holds[i]); i++);
940 /* if somebody still has this host locked */
941 if (h_NBLock_r(host) != 0) {
944 ("Warning: h_TossStuff_r failed; Host %x (%s:%d) was locked.\n",
945 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
951 /* ASSUMPTION: rxi_FreeConnection() does not yield */
952 for (cp = &host->FirstClient; (client = *cp);) {
953 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
955 ObtainWriteLockNoBlock(&client->lock, code);
959 ("Warning: h_TossStuff_r failed: Host %x (%s:%d) client %x was locked.\n",
960 host, afs_inet_ntoa_r(host->host, hoststr),
961 ntohs(host->port), client));
965 if (client->refCount) {
968 ("Warning: h_TossStuff_r failed: Host %x (%s:%d) client %x refcount %d.\n",
969 host, afs_inet_ntoa_r(host->host, hoststr),
970 ntohs(host->port), client, client->refCount));
971 /* This is the same thing we do if the host is locked */
972 ReleaseWriteLock(&client->lock);
975 client->CPS.prlist_len = 0;
976 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
977 free(client->CPS.prlist_val);
978 client->CPS.prlist_val = NULL;
979 CurrentConnections--;
981 ReleaseWriteLock(&client->lock);
987 /* We've just cleaned out all the deleted clients; clear the flag */
988 host->hostFlags &= ~CLIENTDELETED;
990 if (host->hostFlags & HOSTDELETED) {
991 register struct h_AddrHashChain **ahp, *ath;
992 register struct rx_connection *rxconn;
994 struct AddrPort hostAddrPort;
997 if (host->Console & 1)
999 if ((rxconn = host->callback_rxcon)) {
1000 host->callback_rxcon = (struct rx_connection *)0;
1001 rx_DestroyConnection(rxconn);
1003 if (host->hcps.prlist_val)
1004 free(host->hcps.prlist_val);
1005 host->hcps.prlist_val = NULL;
1006 host->hcps.prlist_len = 0;
1007 DeleteAllCallBacks_r(host, 1);
1008 host->hostFlags &= ~RESETDONE; /* just to be safe */
1010 /* if alternate addresses do not exist */
1011 if (!(host->interface)) {
1012 for (ahp = &hostAddrHashTable[h_HashIndex(host->host)]; (ath = *ahp);
1014 assert(ath->hostPtr);
1015 if (ath->hostPtr == host) {
1022 register struct h_UuidHashChain **uhp, *uth;
1023 /* delete the hash entry for the UUID */
1024 uuidp = &host->interface->uuid;
1025 for (uhp = &hostUuidHashTable[h_UuidHashIndex(uuidp)]; (uth = *uhp);
1027 assert(uth->hostPtr);
1028 if (uth->hostPtr == host) {
1034 /* delete the hash entry for each alternate addresses */
1035 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
1036 hostAddrPort = host->interface->interface[i];
1038 if (!hostAddrPort.valid)
1041 for (ahp = &hostAddrHashTable[h_HashIndex(hostAddrPort.addr)]; (ath = *ahp);
1043 assert(ath->hostPtr);
1044 if (ath->hostPtr == host) {
1051 free(host->interface);
1052 host->interface = NULL;
1053 } /* if alternate address exists */
1055 h_DeleteList_r(host); /* remove host from global host List */
1058 } /*h_TossStuff_r */
1061 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
1062 * system at the start of the enumeration (perhaps more). Hosts may be deleted
1063 * (have delete flag set); ditto for clients. (*proc) is always called with
1064 * host h_held(). The hold state of the host with respect to this lwp is passed
1065 * to (*proc) as the param held. The proc should return 0 if the host should be
1066 * released, 1 if it should be held after enumeration.
1069 h_Enumerate(int (*proc) (), char *param)
1071 register struct host *host, **list;
1073 register int i, count;
1076 if (hostCount == 0) {
1080 list = (struct host **)malloc(hostCount * sizeof(struct host *));
1082 ViceLog(0, ("Failed malloc in h_Enumerate\n"));
1085 held = (int *)malloc(hostCount * sizeof(int));
1087 ViceLog(0, ("Failed malloc in h_Enumerate\n"));
1090 for (count = 0, host = hostList; host; host = host->next, count++) {
1092 if (!(held[count] = h_Held_r(host)))
1095 if (count != hostCount) {
1096 ViceLog(0, ("h_Enumerate found %d of %d hosts\n", count, hostCount));
1098 assert(count <= hostCount);
1100 for (i = 0; i < count; i++) {
1101 held[i] = (*proc) (list[i], held[i], param);
1102 if (!H_ENUMERATE_ISSET_HELD(held[i]))
1103 h_Release(list[i]); /* this might free up the host */
1104 /* bail out of the enumeration early */
1105 if (H_ENUMERATE_ISSET_BAIL(held[i]))
1112 /* h_Enumerate_r (revised):
1113 * Calls (*proc)(host, held, param) for each host in hostList, starting
1115 * Hosts may be deleted (have delete flag set); ditto for clients.
1116 * (*proc) is always called with
1117 * host h_held() and the global host lock (H_LOCK) locked.The hold state of the
1118 * host with respect to this lwp is passed to (*proc) as the param held.
1119 * The proc should return 0 if the host should be released, 1 if it should
1120 * be held after enumeration.
1123 h_Enumerate_r(int (*proc) (), struct host *enumstart, char *param)
1125 register struct host *host, *next;
1126 register int held, nheld;
1128 if (hostCount == 0) {
1131 if (enumstart && !(held = h_Held_r(enumstart)))
1132 h_Hold_r(enumstart);
1133 for (host = enumstart; host; host = next, held = nheld) {
1135 if (next && !(nheld = h_Held_r(next)) && !H_ENUMERATE_ISSET_BAIL(held))
1137 held = (*proc) (host, held, param);
1138 if (!H_ENUMERATE_ISSET_HELD(held))
1139 h_Release_r(host); /* this might free up the host */
1140 if (H_ENUMERATE_ISSET_BAIL(held)) {
1141 if (!H_ENUMERATE_ISSET_HELD(nheld))
1142 h_Release_r(next); /* this might free up the host */
1146 } /*h_Enumerate_r */
1148 /* inserts a new HashChain structure corresponding to this UUID */
1150 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1153 struct h_UuidHashChain *chain;
1155 /* hash into proper bucket */
1156 index = h_UuidHashIndex(uuid);
1158 /* don't add the same entry multiple times */
1159 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1160 if (chain->hostPtr->interface &&
1161 afs_uuid_equal(&chain->hostPtr->interface->uuid, uuid))
1165 /* insert into beginning of list for this bucket */
1166 chain = (struct h_UuidHashChain *)malloc(sizeof(struct h_UuidHashChain));
1168 ViceLog(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1172 chain->hostPtr = host;
1173 chain->next = hostUuidHashTable[index];
1174 hostUuidHashTable[index] = chain;
1178 /* inserts a new HashChain structure corresponding to this address */
1180 h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1183 struct h_AddrHashChain *chain;
1187 /* hash into proper bucket */
1188 index = h_HashIndex(addr);
1190 /* don't add the same entry multiple times */
1191 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1192 if (chain->addr == addr && chain->port == port) {
1193 if (chain->hostPtr == host)
1195 else if (!(host->hostFlags & HOSTDELETED))
1196 ViceLog(125, ("Addr %s:%d assigned to %x and %x.\n",
1197 afs_inet_ntoa_r(addr, hoststr), ntohs(port),
1205 /* insert into beginning of list for this bucket */
1206 chain = (struct h_AddrHashChain *)malloc(sizeof(struct h_AddrHashChain));
1208 ViceLog(0, ("Failed malloc in h_AddHostToAddrHashTable_r\n"));
1211 chain->hostPtr = host;
1212 chain->next = hostAddrHashTable[index];
1215 hostAddrHashTable[index] = chain;
1219 * This is called with host locked and held. At this point, the
1220 * hostAddrHashTable should not have entries for the alternate
1221 * interfaces. This function has to insert these entries in the
1222 * hostAddrHashTable.
1224 * All addresses are in network byte order.
1227 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1232 struct Interface *interface;
1233 char hoststr[16], hoststr2[16];
1236 assert(host->interface);
1239 * Make sure this address is on the list of known addresses
1242 number = host->interface->numberOfInterfaces;
1243 for (i = 0, found = 0; i < number && !found; i++) {
1244 if (host->interface->interface[i].addr == addr &&
1245 host->interface->interface[i].port == port) {
1247 host->interface->interface[i].valid = 1;
1251 ViceLog(125, ("addInterfaceAddr : host %s:%d addr %s:%d : found:%d\n",
1252 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1253 afs_inet_ntoa_r(addr, hoststr2), ntohs(port), found));
1256 interface = (struct Interface *)
1257 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1259 ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
1262 interface->numberOfInterfaces = number + 1;
1263 interface->uuid = host->interface->uuid;
1264 for (i = 0; i < number; i++)
1265 interface->interface[i] = host->interface->interface[i];
1266 interface->interface[number].addr = addr;
1267 interface->interface[number].port = port;
1268 interface->interface[number].valid = 1;
1269 free(host->interface);
1270 host->interface = interface;
1278 * This is called with host locked and held. At this point, the
1279 * hostAddrHashTable should not be having entries for the alternate
1280 * interfaces. This function has to insert these entries in the
1281 * hostAddrHashTable.
1283 * All addresses are in network byte order.
1286 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1291 struct Interface *interface;
1292 char hoststr[16], hoststr2[16];
1295 assert(host->interface);
1297 ViceLog(125, ("removeInterfaceAddr : host %s:%d addr %s:%d\n",
1298 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1299 afs_inet_ntoa_r(addr, hoststr2), ntohs(port)));
1302 * Make sure this address is on the list of known addresses
1305 interface = host->interface;
1306 number = host->interface->numberOfInterfaces;
1307 for (i = 0, found = 0; i < number && !found; i++) {
1308 if (interface->interface[i].addr == addr &&
1309 interface->interface[i].port == port) {
1311 interface->interface[i].valid = 0;
1316 for (; i < number; i++) {
1317 interface->interface[i] = interface->interface[i+1];
1319 interface->numberOfInterfaces = number;
1323 * Remove the hash table entry for this address
1325 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1331 * This is called with host locked and held. This function differs
1332 * from removeInterfaceAddr_r in that it is called when the address
1333 * is being removed from the host regardless of whether or not there
1334 * is an interface list for the host. This function will delete the
1335 * host if there are no addresses left on it.
1337 * All addresses are in network byte order.
1340 removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1343 char hoststr[16], hoststr2[16];
1345 if (!host->interface) {
1346 if (host->host == addr && host->port == port) {
1348 ("Removing only address for host %x (%s:%d), deleting host.\n",
1349 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1350 host->hostFlags |= HOSTDELETED;
1353 removeInterfaceAddr_r(host, host->host, host->port);
1354 if (host->interface->numberOfInterfaces == 0) {
1356 ("Removed only address for host %x (%s:%d), no alternate interfaces, deleting host.\n",
1357 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1358 host->hostFlags |= HOSTDELETED;
1360 struct rx_connection *rxconn;
1362 rxconn = host->callback_rxcon;
1363 host->callback_rxcon = NULL;
1366 struct client *client;
1368 * If rx_DestroyConnection calls h_FreeConnection we will
1369 * deadlock on the host_glock_mutex. Work around the problem
1370 * by unhooking the client from the connection before
1371 * destroying the connection.
1373 client = rx_GetSpecific(rxconn, rxcon_client_key);
1374 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1375 rx_DestroyConnection(rxconn);
1378 for (i=0; i < host->interface->numberOfInterfaces; i++) {
1379 if (host->interface->interface[i].valid) {
1381 ("Removed address for host %x (%s:%d), new primary interface %s:%d.\n",
1382 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1383 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
1384 ntohs(host->interface->interface[i].port)));
1385 host->host = host->interface->interface[i].addr;
1386 host->port = host->interface->interface[i].port;
1387 h_AddHostToAddrHashTable_r(host->host, host->port, host);
1392 if (i == host->interface->numberOfInterfaces) {
1394 ("Removed only address for host %x (%s:%d), no valid alternate interfaces, deleting host.\n",
1395 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1396 host->hostFlags |= HOSTDELETED;
1399 sc = rxnull_NewClientSecurityObject();
1400 host->callback_rxcon =
1401 rx_NewConnection(host->host, host->port, 1, sc, 0);
1402 rx_SetConnDeadTime(host->callback_rxcon, 50);
1403 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
1411 h_threadquota(int waiting)
1416 } else if (lwps > 32) {
1419 } else if (lwps > 16) {
1429 /* Host is returned held */
1431 h_GetHost_r(struct rx_connection *tcon)
1434 struct host *oldHost;
1437 struct interfaceAddr interf;
1438 int interfValid = 0;
1439 struct Identity *identP = NULL;
1442 char hoststr[16], hoststr2[16];
1444 struct rx_connection *cb_conn = NULL;
1445 struct rx_connection *cb_in = NULL;
1447 caps.Capabilities_val = NULL;
1449 haddr = rxr_HostOf(tcon);
1450 hport = rxr_PortOf(tcon);
1453 rx_DestroyConnection(cb_in);
1456 if (caps.Capabilities_val)
1457 free(caps.Capabilities_val);
1458 caps.Capabilities_val = NULL;
1459 caps.Capabilities_len = 0;
1462 if (h_Lookup_r(haddr, hport, &held, &host))
1464 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1465 if (host && !identP && !(host->Console & 1)) {
1466 /* This is a new connection, and we already have a host
1467 * structure for this address. Verify that the identity
1468 * of the caller matches the identity in the host structure.
1470 if ((host->hostFlags & HWHO_INPROGRESS) &&
1471 h_threadquota(host->lock.num_waiting)) {
1477 if (!(host->hostFlags & ALTADDR)) {
1478 /* Another thread is doing initialization */
1483 ("Host %x (%s:%d) starting h_Lookup again\n",
1484 host, afs_inet_ntoa_r(host->host, hoststr),
1485 ntohs(host->port)));
1488 host->hostFlags |= HWHO_INPROGRESS;
1489 host->hostFlags &= ~ALTADDR;
1491 /* We received a new connection from an IP address/port
1492 * that is associated with 'host' but the address/port of
1493 * the callback connection does not have to match it.
1494 * If there is a match, we can use the existing callback
1495 * connection to verify the UUID. If they do not match
1496 * we need to use a new callback connection to verify the
1497 * UUID of the incoming caller and perhaps use the old
1498 * callback connection to verify that the old address/port
1502 cb_conn = host->callback_rxcon;
1503 rx_GetConnection(cb_conn);
1505 if (haddr == host->host && hport == host->port) {
1506 /* The existing callback connection matches the
1507 * incoming connection so just use it.
1510 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1511 if (code == RXGEN_OPCODE)
1512 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1514 /* We do not have a match. Create a new connection
1515 * for the new addr/port and use multi_Rx to probe
1516 * both of them simultaneously.
1519 sc = rxnull_NewClientSecurityObject();
1520 cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1521 rx_SetConnDeadTime(cb_in, 50);
1522 rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1525 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1526 if (code == RXGEN_OPCODE)
1527 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1529 rx_PutConnection(cb_conn);
1532 if ((code == RXGEN_OPCODE) ||
1533 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1534 identP = (struct Identity *)malloc(sizeof(struct Identity));
1536 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1540 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1541 if (cb_in == NULL) {
1542 /* The host on this connection was unable to respond to
1543 * the WhoAreYou. We will treat this as a new connection
1544 * from the existing host. The worst that can happen is
1545 * that we maintain some extra callback state information */
1546 if (host->interface) {
1548 ("Host %x (%s:%d) used to support WhoAreYou, deleting.\n",
1550 afs_inet_ntoa_r(host->host, hoststr),
1551 ntohs(host->port)));
1552 host->hostFlags |= HOSTDELETED;
1553 host->hostFlags &= ~HWHO_INPROGRESS;
1561 /* The incoming connection does not support WhoAreYou but
1562 * the original one might have. Use removeAddress_r() to
1563 * remove this addr/port from the host that was found.
1564 * If there are no more addresses left for the host it
1565 * will be deleted. Then we retry.
1567 removeAddress_r(host, haddr, hport);
1568 host->hostFlags &= ~HWHO_INPROGRESS;
1569 host->hostFlags |= ALTADDR;
1576 } else if (code == 0) {
1578 identP = (struct Identity *)malloc(sizeof(struct Identity));
1580 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1584 identP->uuid = interf.uuid;
1585 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1586 /* Check whether the UUID on this connection matches
1587 * the UUID in the host structure. If they don't match
1588 * then this is not the same host as before. */
1589 if (!host->interface
1590 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1593 ("Uuid doesn't match connection (%s:%d).\n",
1594 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1596 removeAddress_r(host, haddr, hport);
1599 ("Uuid doesn't match host %x (%s:%d).\n",
1600 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1602 removeAddress_r(host, host->host, host->port);
1604 host->hostFlags &= ~HWHO_INPROGRESS;
1605 host->hostFlags |= ALTADDR;
1612 /* the UUID matched the client at the incoming addr/port
1613 * but this is not the address of the active callback
1614 * connection. Try that connection and see if the client
1615 * is still there and if the reported UUID is the same.
1618 afsUUID uuid = host->interface->uuid;
1619 cb_conn = host->callback_rxcon;
1620 rx_GetConnection(cb_conn);
1621 rx_SetConnDeadTime(cb_conn, 2);
1622 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1624 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1626 rx_SetConnDeadTime(cb_conn, 50);
1627 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1628 rx_PutConnection(cb_conn);
1631 /* The primary address is either not responding or
1632 * is not the client we are looking for. Need to
1633 * remove the primary address and add swap in the new
1634 * callback connection, and destroy the old one.
1636 struct rx_connection *rxconn;
1637 ViceLog(0,("CB: ProbeUuid for host %x (%s:%d) failed %d\n",
1639 afs_inet_ntoa_r(host->host, hoststr),
1640 ntohs(host->port),code2));
1642 removeInterfaceAddr_r(host, host->host, host->port);
1643 addInterfaceAddr_r(host, haddr, hport);
1646 rxconn = host->callback_rxcon;
1647 host->callback_rxcon = cb_in;
1651 struct client *client;
1653 * If rx_DestroyConnection calls h_FreeConnection we will
1654 * deadlock on the host_glock_mutex. Work around the problem
1655 * by unhooking the client from the connection before
1656 * destroying the connection.
1658 client = rx_GetSpecific(rxconn, rxcon_client_key);
1659 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1660 rx_DestroyConnection(rxconn);
1666 /* A callback to the incoming connection address is failing.
1667 * Assume that the addr/port is no longer associated with the host
1668 * returned by h_Lookup_r.
1671 ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1672 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1673 removeAddress_r(host, haddr, hport);
1674 host->hostFlags &= ~HWHO_INPROGRESS;
1675 host->hostFlags |= ALTADDR;
1680 rx_DestroyConnection(cb_in);
1684 ("CB: WhoAreYou failed for host %x (%s:%d), error %d\n",
1685 host, afs_inet_ntoa_r(host->host, hoststr),
1686 ntohs(host->port), code));
1687 host->hostFlags |= VENUSDOWN;
1690 if (caps.Capabilities_val
1691 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1692 host->hostFlags |= HERRORTRANS;
1694 host->hostFlags &= ~(HERRORTRANS);
1695 host->hostFlags |= ALTADDR;
1696 host->hostFlags &= ~HWHO_INPROGRESS;
1699 if (!(host->hostFlags & ALTADDR)) {
1700 /* another thread is doing the initialisation */
1702 ("Host %x (%s:%d) waiting for host-init to complete\n",
1703 host, afs_inet_ntoa_r(host->host, hoststr),
1704 ntohs(host->port)));
1710 ("Host %x (%s:%d) starting h_Lookup again\n",
1711 host, afs_inet_ntoa_r(host->host, hoststr),
1712 ntohs(host->port)));
1715 /* We need to check whether the identity in the host structure
1716 * matches the identity on the connection. If they don't match
1717 * then treat this a new host. */
1718 if (!(host->Console & 1)
1719 && ((!identP->valid && host->interface)
1720 || (identP->valid && !host->interface)
1722 && !afs_uuid_equal(&identP->uuid,
1723 &host->interface->uuid)))) {
1724 char uuid1[128], uuid2[128];
1726 afsUUID_to_string(&identP->uuid, uuid1, 127);
1727 if (host->interface)
1728 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1730 ("CB: new identity for host %x (%s:%d), deleting(%x %x %s %s)\n",
1731 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1732 identP->valid, host->interface,
1733 identP->valid ? uuid1 : "no_uuid",
1734 host->interface ? uuid2 : "no_uuid"));
1736 /* The host in the cache is not the host for this connection */
1738 host->hostFlags |= HOSTDELETED;
1745 host = h_Alloc_r(tcon); /* returned held and locked */
1746 h_gethostcps_r(host, FT_ApproxTime());
1747 if (!(host->Console & 1)) {
1749 cb_conn = host->callback_rxcon;
1750 rx_GetConnection(cb_conn);
1751 host->hostFlags |= HWHO_INPROGRESS;
1754 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1755 if (code == RXGEN_OPCODE)
1756 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1757 rx_PutConnection(cb_conn);
1760 if ((code == RXGEN_OPCODE) ||
1761 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1764 (struct Identity *)malloc(sizeof(struct Identity));
1769 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1774 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1776 ("Host %x (%s:%d) does not support WhoAreYou.\n",
1777 host, afs_inet_ntoa_r(host->host, hoststr),
1778 ntohs(host->port)));
1780 } else if (code == 0) {
1783 (struct Identity *)malloc(sizeof(struct Identity));
1788 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1793 identP->uuid = interf.uuid;
1795 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1797 ("WhoAreYou success on host %x (%s:%d)\n",
1798 host, afs_inet_ntoa_r(host->host, hoststr),
1799 ntohs(host->port)));
1801 if (code == 0 && !identP->valid) {
1802 cb_conn = host->callback_rxcon;
1803 rx_GetConnection(cb_conn);
1805 code = RXAFSCB_InitCallBackState(cb_conn);
1806 rx_PutConnection(cb_conn);
1809 } else if (code == 0) {
1810 oldHost = h_LookupUuid_r(&identP->uuid);
1814 if (!h_Held_r(oldHost))
1817 oldHost->hostFlags |= HWHO_INPROGRESS;
1819 if (oldHost->interface) {
1821 afsUUID uuid = oldHost->interface->uuid;
1822 cb_conn = oldHost->callback_rxcon;
1823 rx_GetConnection(cb_conn);
1824 rx_SetConnDeadTime(cb_conn, 2);
1825 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1827 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1829 rx_SetConnDeadTime(cb_conn, 50);
1830 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1831 rx_PutConnection(cb_conn);
1834 /* The primary address is either not responding or
1835 * is not the client we are looking for.
1836 * MultiProbeAlternateAddress_r() will remove the
1837 * alternate interfaces that do not have the same
1839 ViceLog(0,("CB: ProbeUuid for host %x (%s:%d) failed %d\n",
1841 afs_inet_ntoa_r(oldHost->host, hoststr),
1842 ntohs(oldHost->port),code2));
1843 MultiProbeAlternateAddress_r(oldHost);
1850 /* This is a new address for an existing host. Update
1851 * the list of interfaces for the existing host and
1852 * delete the host structure we just allocated. */
1854 /* prevent warnings while manipulating interface lists */
1855 host->hostFlags |= HOSTDELETED;
1857 if (oldHost->host != haddr || oldHost->port != hport) {
1858 struct rx_connection *rxconn;
1861 ("CB: Host %x (%s:%d) has new addr %s:%d\n",
1863 afs_inet_ntoa_r(oldHost->host, hoststr2),
1864 ntohs(oldHost->port),
1865 afs_inet_ntoa_r(haddr, hoststr),
1867 if (probefail || oldHost->host == haddr) {
1868 /* The probe failed which means that the old address is
1869 * either unreachable or is not the same host we were just
1870 * contacted by. We will also remove addresses if only
1871 * the port has changed because that indicates the client
1874 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
1877 struct Interface *interface = oldHost->interface;
1878 int number = oldHost->interface->numberOfInterfaces;
1879 for (i = 0, found = 0; i < number; i++) {
1880 if (interface->interface[i].addr == haddr &&
1881 interface->interface[i].port != hport) {
1887 /* We have just been contacted by a client that has been
1888 * seen from behind a NAT and at least one other address.
1890 removeInterfaceAddr_r(oldHost, haddr, interface->interface[i].port);
1893 addInterfaceAddr_r(oldHost, haddr, hport);
1894 oldHost->host = haddr;
1895 oldHost->port = hport;
1896 rxconn = oldHost->callback_rxcon;
1897 oldHost->callback_rxcon = host->callback_rxcon;
1898 host->callback_rxcon = NULL;
1901 struct client *client;
1903 * If rx_DestroyConnection calls h_FreeConnection we will
1904 * deadlock on the host_glock_mutex. Work around the problem
1905 * by unhooking the client from the connection before
1906 * destroying the connection.
1908 client = rx_GetSpecific(rxconn, rxcon_client_key);
1909 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1910 rx_DestroyConnection(rxconn);
1913 host->hostFlags &= ~HWHO_INPROGRESS;
1915 /* release host because it was allocated by h_Alloc_r */
1918 /* the new host is held and locked */
1920 /* This really is a new host */
1921 h_AddHostToUuidHashTable_r(&identP->uuid, host);
1922 cb_conn = host->callback_rxcon;
1923 rx_GetConnection(cb_conn);
1926 RXAFSCB_InitCallBackState3(cb_conn,
1928 rx_PutConnection(cb_conn);
1933 ("InitCallBackState3 success on host %x (%s:%d)\n",
1934 host, afs_inet_ntoa_r(host->host, hoststr),
1935 ntohs(host->port)));
1936 assert(interfValid == 1);
1937 initInterfaceAddr_r(host, &interf);
1943 ("CB: RCallBackConnectBack failed for %x (%s:%d)\n",
1944 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1945 host->hostFlags |= VENUSDOWN;
1948 ("CB: RCallBackConnectBack succeeded for %x (%s:%d)\n",
1949 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1950 host->hostFlags |= RESETDONE;
1953 if (caps.Capabilities_val
1954 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1955 host->hostFlags |= HERRORTRANS;
1957 host->hostFlags &= ~(HERRORTRANS);
1958 host->hostFlags |= ALTADDR; /* host structure initialization complete */
1959 host->hostFlags &= ~HWHO_INPROGRESS;
1962 if (caps.Capabilities_val)
1963 free(caps.Capabilities_val);
1964 caps.Capabilities_val = NULL;
1965 caps.Capabilities_len = 0;
1971 static char localcellname[PR_MAXNAMELEN + 1];
1972 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
1973 int num_lrealms = -1;
1979 memset(&nulluuid, 0, sizeof(afsUUID));
1980 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
1981 if (num_lrealms == -1) {
1983 for (i=0; i<AFS_NUM_LREALMS; i++) {
1984 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
1990 ("afs_krb_get_lrealm failed, using %s.\n",
1992 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
1998 /* initialize the rest of the local realms to nullstring for debugging */
1999 for (; i<AFS_NUM_LREALMS; i++)
2000 local_realms[i][0] = '\0';
2002 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2003 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2004 #ifdef AFS_PTHREAD_ENV
2005 assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
2006 #endif /* AFS_PTHREAD_ENV */
2010 MapName_r(char *aname, char *acell, afs_int32 * aval)
2015 afs_int32 anamelen, cnamelen;
2019 anamelen = strlen(aname);
2020 if (anamelen >= PR_MAXNAMELEN)
2021 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
2023 lnames.namelist_len = 1;
2024 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
2025 lids.idlist_len = 0;
2026 lids.idlist_val = NULL;
2028 cnamelen = strlen(acell);
2030 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2032 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2033 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2034 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2036 ("MapName: Name too long, using AnonymousID for %s@%s\n",
2038 *aval = AnonymousID;
2041 foreign = 1; /* attempt cross-cell authentication */
2042 tname = (char *)malloc(PR_MAXNAMELEN);
2044 ViceLog(0, ("Failed malloc in MapName_r\n"));
2047 strcpy(tname, aname);
2048 tname[anamelen] = '@';
2049 strcpy(tname + anamelen + 1, acell);
2050 lnames.namelist_val = (prname *) tname;
2055 code = hpr_NameToId(&lnames, &lids);
2058 if (lids.idlist_val) {
2059 *aval = lids.idlist_val[0];
2060 if (*aval == AnonymousID) {
2062 ("MapName: NameToId on %s returns anonymousID\n",
2063 lnames.namelist_val));
2065 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2068 ("MapName: NameToId on '%s' is unknown\n",
2069 lnames.namelist_val));
2075 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
2083 /* NOTE: this returns the client with a Write lock and a refCount */
2085 h_ID2Client(afs_int32 vid)
2087 register struct client *client;
2088 register struct host *host;
2091 for (host = hostList; host; host = host->next) {
2092 if (host->hostFlags & HOSTDELETED)
2094 for (client = host->FirstClient; client; client = client->next) {
2095 if (!client->deleted && client->ViceId == vid) {
2098 ObtainWriteLock(&client->lock);
2109 * Called by the server main loop. Returns a h_Held client, which must be
2110 * released later the main loop. Allocates a client if the matching one
2111 * isn't around. The client is returned with its reference count incremented
2112 * by one. The caller must call h_ReleaseClient_r when finished with
2115 * the client->host is returned held. h_ReleaseClient_r does not release
2116 * the hold on client->host.
2119 h_FindClient_r(struct rx_connection *tcon)
2121 register struct client *client;
2122 register struct host *host;
2123 struct client *oldClient;
2128 #if (64-MAXKTCNAMELEN)
2129 ticket name length != 64
2133 char uname[PR_MAXNAMELEN];
2134 char tcell[MAXKTCREALMLEN];
2138 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2139 if (client && client->sid == rxr_CidOf(tcon)
2140 && client->VenusEpoch == rxr_GetEpoch(tcon)) {
2142 h_Hold_r(client->host);
2143 if (!client->deleted && client->prfail != 2) {
2144 /* Could add shared lock on client here */
2145 /* note that we don't have to lock entry in this path to
2146 * ensure CPS is initialized, since we don't call rx_SetSpecific
2147 * until initialization is done, and we only get here if
2148 * rx_GetSpecific located the client structure.
2153 ObtainWriteLock(&client->lock); /* released at end */
2159 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2161 ("FindClient: authenticating connection: authClass=%d\n",
2163 if (authClass == 1) {
2164 /* A bcrypt tickets, no longer supported */
2165 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2166 viceid = AnonymousID;
2167 expTime = 0x7fffffff;
2168 } else if (authClass == 2) {
2171 /* kerberos ticket */
2172 code = rxkad_GetServerInfo(tcon, /*level */ 0, &expTime,
2173 tname, tinst, tcell, &kvno);
2175 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2176 viceid = AnonymousID;
2177 expTime = 0x7fffffff;
2179 int ilen = strlen(tinst);
2181 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2182 tname, tinst, tcell, expTime, kvno));
2183 strncpy(uname, tname, sizeof(uname));
2185 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2188 strcat(uname, tinst);
2190 /* translate the name to a vice id */
2191 code = MapName_r(uname, tcell, &viceid);
2195 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2198 viceid = AnonymousID;
2199 expTime = 0x7fffffff;
2203 viceid = AnonymousID; /* unknown security class */
2204 expTime = 0x7fffffff;
2207 if (!client) { /* loop */
2208 host = h_GetHost_r(tcon); /* Returns it h_Held */
2214 /* First try to find the client structure */
2215 for (client = host->FirstClient; client; client = client->next) {
2216 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2217 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2220 ObtainWriteLock(&client->lock);
2226 /* Still no client structure - get one */
2229 /* Retry to find the client structure */
2230 for (client = host->FirstClient; client; client = client->next) {
2231 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2232 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2234 goto retryfirstclient;
2239 ObtainWriteLock(&client->lock);
2240 client->refCount = 1;
2241 client->host = host;
2242 #if FS_STATS_DETAILED
2243 client->InSameNetwork = host->InSameNetwork;
2244 #endif /* FS_STATS_DETAILED */
2245 client->ViceId = viceid;
2246 client->expTime = expTime; /* rx only */
2247 client->authClass = authClass; /* rx only */
2248 client->sid = rxr_CidOf(tcon);
2249 client->VenusEpoch = rxr_GetEpoch(tcon);
2250 client->CPS.prlist_val = NULL;
2251 client->CPS.prlist_len = 0;
2255 client->prfail = fail;
2257 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2258 client->CPS.prlist_len = 0;
2259 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2260 free(client->CPS.prlist_val);
2261 client->CPS.prlist_val = NULL;
2262 client->ViceId = viceid;
2263 client->expTime = expTime;
2265 if (viceid == ANONYMOUSID) {
2266 client->CPS.prlist_len = AnonCPS.prlist_len;
2267 client->CPS.prlist_val = AnonCPS.prlist_val;
2270 code = hpr_GetCPS(viceid, &client->CPS);
2275 ("pr_GetCPS failed(%d) for user %d, host %x (%s:%d)\n",
2276 code, viceid, client->host,
2277 afs_inet_ntoa_r(client->host->host,hoststr),
2278 ntohs(client->host->port)));
2280 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2281 * all protection servers and reevaluates things if no
2282 * sync server or quorum is found we could still end up
2283 * with one of these errors. In such case we would like to
2284 * reevaluate the rpc call to find if there's cps for this
2285 * guy. We treat other errors (except network failures
2286 * ones - i.e. code < 0) as an indication that there is no
2287 * CPS for this host. Ideally we could like to deal this
2288 * problem the other way around (i.e. if code == NOCPS
2289 * ignore else retry next time) but the problem is that
2290 * there're other errors (i.e. EPERM) for which we don't
2291 * want to retry and we don't know the whole code list!
2293 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2297 /* the disabling of system:administrators is so iffy and has so many
2298 * possible failure modes that we will disable it again */
2299 /* Turn off System:Administrator for safety
2300 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2301 * assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2304 /* Now, tcon may already be set to a rock, since we blocked with no host
2305 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2306 * required). So, before setting the RPC's rock, we should disconnect
2307 * the RPC from the other client structure's rock.
2309 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2310 if (oldClient && oldClient != client && oldClient->sid == rxr_CidOf(tcon)
2311 && oldClient->VenusEpoch == rxr_GetEpoch(tcon)) {
2313 if (!oldClient->deleted) {
2314 /* if we didn't create it, it's not ours to put back */
2316 ViceLog(0, ("FindClient: stillborn client %x(%x); conn %x (host %s:%d) had client %x(%x)\n",
2317 client, client->sid, tcon,
2318 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2319 ntohs(rxr_PortOf(tcon)),
2320 oldClient, oldClient->sid));
2321 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2322 free(client->CPS.prlist_val);
2323 client->CPS.prlist_val = NULL;
2324 client->CPS.prlist_len = 0;
2326 /* We should perhaps check for 0 here */
2328 ReleaseWriteLock(&client->lock);
2333 oldClient->refCount++;
2335 ObtainWriteLock(&oldClient->lock);
2339 ViceLog(0, ("FindClient: deleted client %x(%x) already had conn %x (host %s:%d), stolen by client %x(%x)\n",
2340 oldClient, oldClient->sid, tcon,
2341 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2342 ntohs(rxr_PortOf(tcon)),
2343 client, client->sid));
2344 /* rx_SetSpecific will be done immediately below */
2347 /* Avoid chaining in more than once. */
2350 client->next = host->FirstClient;
2351 host->FirstClient = client;
2353 CurrentConnections++; /* increment number of connections */
2355 rx_SetSpecific(tcon, rxcon_client_key, client);
2356 ReleaseWriteLock(&client->lock);
2360 } /*h_FindClient_r */
2363 h_ReleaseClient_r(struct client *client)
2365 assert(client->refCount > 0);
2372 * Sigh: this one is used to get the client AGAIN within the individual
2373 * server routines. This does not bother h_Holding the host, since
2374 * this is assumed already have been done by the server main loop.
2375 * It does check tokens, since only the server routines can return the
2376 * VICETOKENDEAD error code
2379 GetClient(struct rx_connection *tcon, struct client **cp)
2381 register struct client *client;
2386 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2387 if (client == NULL) {
2389 ("GetClient: no client in conn %x (host %s:%d), VBUSYING\n",
2390 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2391 ntohs(rxr_PortOf(tcon))));
2395 if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2397 ("GetClient: tcon %x tcon sid %d client sid %d\n",
2398 tcon, rxr_CidOf(tcon), client->sid));
2402 if (client && client->LastCall > client->expTime && client->expTime) {
2404 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2405 afs_inet_ntoa_r(client->host->host, hoststr),
2406 ntohs(client->host->port), client->expTime));
2408 return VICETOKENDEAD;
2418 PutClient(struct client **cp)
2424 h_ReleaseClient_r(*cp);
2431 /* Client user name for short term use. Note that this is NOT inexpensive */
2433 h_UserName(struct client *client)
2435 static char User[PR_MAXNAMELEN + 1];
2439 lids.idlist_len = 1;
2440 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2441 if (!lids.idlist_val) {
2442 ViceLog(0, ("Failed malloc in h_UserName\n"));
2445 lnames.namelist_len = 0;
2446 lnames.namelist_val = (prname *) 0;
2447 lids.idlist_val[0] = client->ViceId;
2448 if (hpr_IdToName(&lids, &lnames)) {
2449 /* We need to free id we alloced above! */
2450 free(lids.idlist_val);
2451 return "*UNKNOWN USER NAME*";
2453 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2454 free(lids.idlist_val);
2455 free(lnames.namelist_val);
2464 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2465 CEs, CEBlocks, HTs, HTBlocks));
2471 h_PrintClient(register struct host *host, int held, StreamHandle_t * file)
2473 register struct client *client;
2478 time_t LastCall, expTime;
2481 LastCall = host->LastCall;
2482 if (host->hostFlags & HOSTDELETED) {
2486 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2487 "Host %s:%d down = %d, LastCall %s",
2488 afs_inet_ntoa_r(host->host, hoststr),
2489 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2490 afs_ctime(&LastCall, tbuffer,
2492 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2493 for (client = host->FirstClient; client; client = client->next) {
2494 if (!client->deleted) {
2495 expTime = client->expTime;
2496 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2497 " user id=%d, name=%s, sl=%s till %s",
2498 client->ViceId, h_UserName(client),
2500 authClass ? "Authenticated" :
2501 "Not authenticated",
2503 authClass ? afs_ctime(&expTime, tbuffer,
2506 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2507 (void)afs_snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2508 client->CPS.prlist_len);
2509 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2510 if (client->CPS.prlist_val) {
2511 for (i = 0; i > client->CPS.prlist_len; i++) {
2512 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2513 client->CPS.prlist_val[i]);
2514 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2517 sprintf(tmpStr, "]\n");
2518 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2524 } /*h_PrintClient */
2529 * Print a list of clients, with last security level and token value seen,
2539 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2543 ("Couldn't create client dump file %s\n",
2544 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2547 now = FT_ApproxTime();
2548 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
2549 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2550 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2551 h_Enumerate(h_PrintClient, (char *)file);
2552 STREAM_REALLYCLOSE(file);
2553 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2560 h_DumpHost(register struct host *host, int held, StreamHandle_t * file)
2567 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2568 "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u hcps [",
2569 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), host->index,
2570 host->cblist, CheckLock(&host->lock), host->LastCall,
2571 host->ActiveCall, (host->hostFlags & VENUSDOWN),
2572 host->hostFlags & HOSTDELETED, host->Console,
2573 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2575 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2576 if (host->hcps.prlist_val)
2577 for (i = 0; i < host->hcps.prlist_len; i++) {
2578 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2579 host->hcps.prlist_val[i]);
2580 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2582 sprintf(tmpStr, "] [");
2583 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2584 if (host->interface)
2585 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2587 sprintf(tmpStr, " %s:%d",
2588 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2589 ntohs(host->interface->interface[i].port));
2590 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2592 sprintf(tmpStr, "] holds: ");
2593 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2595 for (i = 0; i < h_maxSlots; i++) {
2596 sprintf(tmpStr, "%04x", host->holds[i]);
2597 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2599 sprintf(tmpStr, " slot/bit: %d/%d\n", h_holdSlot(), h_holdbit());
2600 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2612 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2618 ("Couldn't create host dump file %s\n",
2619 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2622 now = FT_ApproxTime();
2623 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
2624 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2625 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2626 h_Enumerate(h_DumpHost, (char *)file);
2627 STREAM_REALLYCLOSE(file);
2628 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2632 #ifdef AFS_DEMAND_ATTACH_FS
2635 * host state serialization
2637 static int h_stateFillHeader(struct host_state_header * hdr);
2638 static int h_stateCheckHeader(struct host_state_header * hdr);
2639 static int h_stateAllocMap(struct fs_dump_state * state);
2640 static int h_stateSaveHost(register struct host * host, int held, struct fs_dump_state * state);
2641 static int h_stateRestoreHost(struct fs_dump_state * state);
2642 static int h_stateRestoreIndex(struct host * h, int held, struct fs_dump_state * state);
2643 static int h_stateVerifyHost(struct host * h, int held, struct fs_dump_state * state);
2644 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port);
2645 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2646 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2647 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2650 /* this procedure saves all host state to disk for fast startup */
2652 h_stateSave(struct fs_dump_state * state)
2654 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2657 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2659 /* invalidate host state header */
2660 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2662 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2663 sizeof(struct host_state_header))) {
2668 fs_stateIncEOF(state, sizeof(struct host_state_header));
2670 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2675 h_stateFillHeader(state->h_hdr);
2677 /* write the real header to disk */
2678 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2679 sizeof(struct host_state_header));
2686 * host state serialization
2688 * this procedure restores all host state from a disk for fast startup
2691 h_stateRestore(struct fs_dump_state * state)
2695 /* seek to the right position and read in the host state header */
2696 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2697 sizeof(struct host_state_header))) {
2702 /* check the validity of the header */
2703 if (h_stateCheckHeader(state->h_hdr)) {
2708 records = state->h_hdr->records;
2710 if (h_stateAllocMap(state)) {
2715 /* iterate over records restoring host state */
2716 for (i=0; i < records; i++) {
2717 if (h_stateRestoreHost(state) != 0) {
2728 h_stateRestoreIndices(struct fs_dump_state * state)
2730 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
2735 h_stateRestoreIndex(struct host * h, int held, struct fs_dump_state * state)
2737 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
2738 return H_ENUMERATE_BAIL(held);
2744 h_stateVerify(struct fs_dump_state * state)
2746 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
2751 h_stateVerifyHost(struct host * h, int held, struct fs_dump_state * state)
2756 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
2757 return H_ENUMERATE_BAIL(held);
2761 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
2762 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
2763 h->interface->interface[i].port)) {
2767 if (h_stateVerifyUuidHash(state, h)) {
2770 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port)) {
2774 if (cb_stateVerifyHCBList(state, h)) {
2783 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port)
2785 int ret = 0, found = 0;
2786 struct host *host = NULL;
2787 struct h_AddrHashChain *chain;
2788 int index = h_HashIndex(addr);
2792 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
2793 host = chain->hostPtr;
2795 afs_inet_ntoa_r(addr, tmp);
2796 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
2800 if ((chain->addr == addr) && (chain->port == port)) {
2802 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry points to different host struct (%d, %d)\n",
2803 h->index, host->index));
2804 state->flags.warnings_generated = 1;
2809 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
2810 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2811 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
2819 afs_inet_ntoa_r(addr, tmp);
2820 if (state->mode == FS_STATE_LOAD_MODE) {
2821 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s not found in hash\n", tmp));
2825 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s not found in hash\n", tmp));
2826 state->flags.warnings_generated = 1;
2835 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
2837 int ret = 0, found = 0;
2838 struct host *host = NULL;
2839 struct h_UuidHashChain *chain;
2840 afsUUID * uuidp = &h->interface->uuid;
2841 int index = h_UuidHashIndex(uuidp);
2845 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
2846 host = chain->hostPtr;
2848 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2849 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
2853 if (host->interface &&
2854 afs_uuid_equal(&host->interface->uuid, uuidp)) {
2856 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
2857 h->index, host->index));
2858 state->flags.warnings_generated = 1;
2863 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
2864 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2865 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
2873 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2874 if (state->mode == FS_STATE_LOAD_MODE) {
2875 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
2879 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
2880 state->flags.warnings_generated = 1;
2888 /* create the host state header structure */
2890 h_stateFillHeader(struct host_state_header * hdr)
2892 hdr->stamp.magic = HOST_STATE_MAGIC;
2893 hdr->stamp.version = HOST_STATE_VERSION;
2896 /* check the contents of the host state header structure */
2898 h_stateCheckHeader(struct host_state_header * hdr)
2902 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
2903 ViceLog(0, ("check_host_state_header: invalid state header\n"));
2906 else if (hdr->stamp.version != HOST_STATE_VERSION) {
2907 ViceLog(0, ("check_host_state_header: unknown version number\n"));
2913 /* allocate the host id mapping table */
2915 h_stateAllocMap(struct fs_dump_state * state)
2917 state->h_map.len = state->h_hdr->index_max + 1;
2918 state->h_map.entries = (struct idx_map_entry_t *)
2919 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
2920 return (state->h_map.entries != NULL) ? 0 : 1;
2923 /* function called by h_Enumerate to save a host to disk */
2925 h_stateSaveHost(register struct host * host, int held, struct fs_dump_state * state)
2927 int i, if_len=0, hcps_len=0;
2928 struct hostDiskEntry hdsk;
2929 struct host_state_entry_header hdr;
2930 struct Interface * ifp = NULL;
2931 afs_int32 * hcps = NULL;
2932 struct iovec iov[4];
2935 memset(&hdr, 0, sizeof(hdr));
2937 if (state->h_hdr->index_max < host->index) {
2938 state->h_hdr->index_max = host->index;
2941 h_hostToDiskEntry_r(host, &hdsk);
2942 if (host->interface) {
2943 if_len = sizeof(struct Interface) +
2944 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
2945 ifp = (struct Interface *) malloc(if_len);
2946 assert(ifp != NULL);
2947 memcpy(ifp, host->interface, if_len);
2948 hdr.interfaces = host->interface->numberOfInterfaces;
2949 iov[iovcnt].iov_base = (char *) ifp;
2950 iov[iovcnt].iov_len = if_len;
2953 if (host->hcps.prlist_val) {
2954 hdr.hcps = host->hcps.prlist_len;
2955 hcps_len = hdr.hcps * sizeof(afs_int32);
2956 hcps = (afs_int32 *) malloc(hcps_len);
2957 assert(hcps != NULL);
2958 memcpy(hcps, host->hcps.prlist_val, hcps_len);
2959 iov[iovcnt].iov_base = (char *) hcps;
2960 iov[iovcnt].iov_len = hcps_len;
2964 if (hdsk.index > state->h_hdr->index_max)
2965 state->h_hdr->index_max = hdsk.index;
2967 hdr.len = sizeof(struct host_state_entry_header) +
2968 sizeof(struct hostDiskEntry) + if_len + hcps_len;
2969 hdr.magic = HOST_STATE_ENTRY_MAGIC;
2971 iov[0].iov_base = (char *) &hdr;
2972 iov[0].iov_len = sizeof(hdr);
2973 iov[1].iov_base = (char *) &hdsk;
2974 iov[1].iov_len = sizeof(struct hostDiskEntry);
2976 if (fs_stateWriteV(state, iov, iovcnt)) {
2977 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
2981 fs_stateIncEOF(state, hdr.len);
2983 state->h_hdr->records++;
2991 return H_ENUMERATE_BAIL(held);
2996 /* restores a host from disk */
2998 h_stateRestoreHost(struct fs_dump_state * state)
3000 int ifp_len=0, hcps_len=0, bail=0;
3001 struct host_state_entry_header hdr;
3002 struct hostDiskEntry hdsk;
3003 struct host *host = NULL;
3004 struct Interface *ifp = NULL;
3005 afs_int32 * hcps = NULL;
3006 struct iovec iov[3];
3009 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3010 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3016 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3017 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3023 iov[0].iov_base = (char *) &hdsk;
3024 iov[0].iov_len = sizeof(struct hostDiskEntry);
3026 if (hdr.interfaces) {
3027 ifp_len = sizeof(struct Interface) +
3028 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3029 ifp = (struct Interface *) malloc(ifp_len);
3030 assert(ifp != NULL);
3031 iov[iovcnt].iov_base = (char *) ifp;
3032 iov[iovcnt].iov_len = ifp_len;
3036 hcps_len = hdr.hcps * sizeof(afs_int32);
3037 hcps = (afs_int32 *) malloc(hcps_len);
3038 assert(hcps != NULL);
3039 iov[iovcnt].iov_base = (char *) hcps;
3040 iov[iovcnt].iov_len = hcps_len;
3044 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3045 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3050 if (fs_stateReadV(state, iov, iovcnt)) {
3051 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3056 if (!hdr.hcps && hdsk.hcps_valid) {
3057 /* valid, zero-length host cps ; does this ever happen? */
3058 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3059 assert(hcps != NULL);
3063 assert(host != NULL);
3066 host->interface = ifp;
3069 host->hcps.prlist_val = hcps;
3070 host->hcps.prlist_len = hdr.hcps;
3073 h_diskEntryToHost_r(&hdsk, host);
3074 h_SetupCallbackConn_r(host);
3078 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3080 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3082 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3083 h_InsertList_r(host);
3085 /* setup host id map entry */
3086 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3087 state->h_map.entries[hdsk.index].new_idx = host->index;
3099 /* serialize a host structure to disk */
3101 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3103 out->host = in->host;
3104 out->port = in->port;
3105 out->hostFlags = in->hostFlags;
3106 out->Console = in->Console;
3107 out->hcpsfailed = in->hcpsfailed;
3108 out->LastCall = in->LastCall;
3109 out->ActiveCall = in->ActiveCall;
3110 out->cpsCall = in->cpsCall;
3111 out->cblist = in->cblist;
3112 #ifdef FS_STATS_DETAILED
3113 out->InSameNetwork = in->InSameNetwork;
3116 /* special fields we save, but are not memcpy'd back on restore */
3117 out->index = in->index;
3118 out->hcps_len = in->hcps.prlist_len;
3119 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3122 /* restore a host structure from disk */
3124 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3126 out->host = in->host;
3127 out->port = in->port;
3128 out->hostFlags = in->hostFlags;
3129 out->Console = in->Console;
3130 out->hcpsfailed = in->hcpsfailed;
3131 out->LastCall = in->LastCall;
3132 out->ActiveCall = in->ActiveCall;
3133 out->cpsCall = in->cpsCall;
3134 out->cblist = in->cblist;
3135 #ifdef FS_STATS_DETAILED
3136 out->InSameNetwork = in->InSameNetwork;
3140 /* index translation routines */
3142 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3146 /* hosts use a zero-based index, so old==0 is valid */
3148 if (old >= state->h_map.len) {
3149 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3151 } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
3152 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3155 *new = state->h_map.entries[old].new_idx;
3161 #endif /* AFS_DEMAND_ATTACH_FS */
3165 * This counts the number of workstations, the number of active workstations,
3166 * and the number of workstations declared "down" (i.e. not heard from
3167 * recently). An active workstation has received a call since the cutoff
3168 * time argument passed.
3171 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3173 register struct host *host;
3174 register int num = 0, active = 0, del = 0;
3177 for (host = hostList; host; host = host->next) {
3178 if (!(host->hostFlags & HOSTDELETED)) {
3180 if (host->ActiveCall > cutofftime)
3182 if (host->hostFlags & VENUSDOWN)
3194 } /*h_GetWorkStats */
3197 /*------------------------------------------------------------------------
3198 * PRIVATE h_ClassifyAddress
3201 * Given a target IP address and a candidate IP address (both
3202 * in host byte order), classify the candidate into one of three
3203 * buckets in relation to the target by bumping the counters passed
3207 * a_targetAddr : Target address.
3208 * a_candAddr : Candidate address.
3209 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3210 * addresses are either in the same network
3211 * or the same subnet.
3212 * a_diffSubnetP : ...when the candidate is in a different
3214 * a_diffNetworkP : ...when the candidate is in a different
3221 * The target and candidate addresses are both in host byte
3222 * order, NOT network byte order, when passed in.
3226 *------------------------------------------------------------------------*/
3229 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3230 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3231 afs_int32 * a_diffNetworkP)
3232 { /*h_ClassifyAddress */
3234 afs_uint32 targetNet;
3235 afs_uint32 targetSubnet;
3237 afs_uint32 candSubnet;
3240 * Put bad values into the subnet info to start with.
3242 targetSubnet = (afs_uint32) 0;
3243 candSubnet = (afs_uint32) 0;
3246 * Pull out the network and subnetwork numbers from the target
3247 * and candidate addresses. We can short-circuit this whole
3248 * affair if the target and candidate addresses are not of the
3251 if (IN_CLASSA(a_targetAddr)) {
3252 if (!(IN_CLASSA(a_candAddr))) {
3253 (*a_diffNetworkP)++;
3256 targetNet = a_targetAddr & IN_CLASSA_NET;
3257 candNet = a_candAddr & IN_CLASSA_NET;
3258 if (IN_SUBNETA(a_targetAddr))
3259 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3260 if (IN_SUBNETA(a_candAddr))
3261 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3262 } else if (IN_CLASSB(a_targetAddr)) {
3263 if (!(IN_CLASSB(a_candAddr))) {
3264 (*a_diffNetworkP)++;
3267 targetNet = a_targetAddr & IN_CLASSB_NET;
3268 candNet = a_candAddr & IN_CLASSB_NET;
3269 if (IN_SUBNETB(a_targetAddr))
3270 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3271 if (IN_SUBNETB(a_candAddr))
3272 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3273 } /*Class B target */
3274 else if (IN_CLASSC(a_targetAddr)) {
3275 if (!(IN_CLASSC(a_candAddr))) {
3276 (*a_diffNetworkP)++;
3279 targetNet = a_targetAddr & IN_CLASSC_NET;
3280 candNet = a_candAddr & IN_CLASSC_NET;
3283 * Note that class C addresses can't have subnets,
3284 * so we leave the defaults untouched.
3286 } /*Class C target */
3288 targetNet = a_targetAddr;
3289 candNet = a_candAddr;
3290 } /*Class D address */
3293 * Now, simply compare the extracted net and subnet values for
3294 * the two addresses (which at this point are known to be of the
3297 if (targetNet == candNet) {
3298 if (targetSubnet == candSubnet)
3299 (*a_sameNetOrSubnetP)++;
3303 (*a_diffNetworkP)++;
3305 } /*h_ClassifyAddress */
3308 /*------------------------------------------------------------------------
3309 * EXPORTED h_GetHostNetStats
3312 * Iterate through the host table, and classify each (non-deleted)
3313 * host entry into ``proximity'' categories (same net or subnet,
3314 * different subnet, different network).
3317 * a_numHostsP : Set to total number of (non-deleted) hosts.
3318 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3319 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3320 * a_diffNetworkP : Set to # hosts on diff network as server.
3326 * We only count non-deleted hosts. The storage pointed to by our
3327 * parameters is zeroed upon entry.
3331 *------------------------------------------------------------------------*/
3334 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3335 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3336 { /*h_GetHostNetStats */
3338 register struct host *hostP; /*Ptr to current host entry */
3339 register afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3342 * Clear out the storage pointed to by our parameters.
3344 *a_numHostsP = (afs_int32) 0;
3345 *a_sameNetOrSubnetP = (afs_int32) 0;
3346 *a_diffSubnetP = (afs_int32) 0;
3347 *a_diffNetworkP = (afs_int32) 0;
3350 for (hostP = hostList; hostP; hostP = hostP->next) {
3351 if (!(hostP->hostFlags & HOSTDELETED)) {
3353 * Bump the number of undeleted host entries found.
3354 * In classifying the current entry's address, make
3355 * sure to first convert to host byte order.
3358 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3359 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3360 a_sameNetOrSubnetP, a_diffSubnetP,
3362 } /*Only look at non-deleted hosts */
3363 } /*For each host record hashed to this index */
3365 } /*h_GetHostNetStats */
3367 static afs_uint32 checktime;
3368 static afs_uint32 clientdeletetime;
3369 static struct AFSFid zerofid;
3373 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3374 * Since it can serialize them, and pile up, it should be a separate LWP
3375 * from other events.
3378 CheckHost(register struct host *host, int held)
3380 register struct client *client;
3381 struct rx_connection *cb_conn = NULL;
3384 #ifdef AFS_DEMAND_ATTACH_FS
3385 /* kill the checkhost lwp ASAP during shutdown */
3387 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3389 return H_ENUMERATE_BAIL(held);
3394 /* Host is held by h_Enumerate */
3396 for (client = host->FirstClient; client; client = client->next) {
3397 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3398 client->deleted = 1;
3399 host->hostFlags |= CLIENTDELETED;
3402 if (host->LastCall < checktime) {
3404 host->hostFlags |= HWHO_INPROGRESS;
3405 if (!(host->hostFlags & HOSTDELETED)) {
3406 cb_conn = host->callback_rxcon;
3407 rx_GetConnection(cb_conn);
3408 if (host->LastCall < clientdeletetime) {
3409 host->hostFlags |= HOSTDELETED;
3410 if (!(host->hostFlags & VENUSDOWN)) {
3411 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3412 if (host->interface) {
3415 RXAFSCB_InitCallBackState3(cb_conn,
3421 RXAFSCB_InitCallBackState(cb_conn);
3424 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3427 (void)afs_inet_ntoa_r(host->host, hoststr);
3429 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3430 hoststr, ntohs(host->port)));
3431 host->hostFlags |= VENUSDOWN;
3433 /* Note: it's safe to delete hosts even if they have call
3434 * back state, because break delayed callbacks (called when a
3435 * message is received from the workstation) will always send a
3436 * break all call backs to the workstation if there is no
3441 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3443 (void)afs_inet_ntoa_r(host->host, hoststr);
3444 if (host->interface) {
3445 afsUUID uuid = host->interface->uuid;
3447 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3450 if (MultiProbeAlternateAddress_r(host)) {
3451 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3452 hoststr, ntohs(host->port), code));
3453 host->hostFlags |= VENUSDOWN;
3458 code = RXAFSCB_Probe(cb_conn);
3462 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3463 hoststr, ntohs(host->port), code));
3464 host->hostFlags |= VENUSDOWN;
3470 rx_PutConnection(cb_conn);
3474 host->hostFlags &= ~HWHO_INPROGRESS;
3483 CheckHost_r(register struct host *host, int held, char *dummy)
3485 register struct client *client;
3486 struct rx_connection *cb_conn = NULL;
3489 #ifdef AFS_DEMAND_ATTACH_FS
3490 /* kill the checkhost lwp ASAP during shutdown */
3492 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3494 return H_ENUMERATE_BAIL(held);
3499 /* Host is held by h_Enumerate_r */
3500 for (client = host->FirstClient; client; client = client->next) {
3501 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3502 client->deleted = 1;
3503 host->hostFlags |= CLIENTDELETED;
3506 if (host->LastCall < checktime) {
3508 if (!(host->hostFlags & HOSTDELETED)) {
3509 cb_conn = host->callback_rxcon;
3510 rx_GetConnection(cb_conn);
3511 if (host->LastCall < clientdeletetime) {
3512 host->hostFlags |= HOSTDELETED;
3513 if (!(host->hostFlags & VENUSDOWN)) {
3514 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3515 if (host->interface) {
3518 RXAFSCB_InitCallBackState3(cb_conn,
3524 RXAFSCB_InitCallBackState(cb_conn);
3527 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3530 (void)afs_inet_ntoa_r(host->host, hoststr);
3532 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3533 hoststr, ntohs(host->port)));
3534 host->hostFlags |= VENUSDOWN;
3536 /* Note: it's safe to delete hosts even if they have call
3537 * back state, because break delayed callbacks (called when a
3538 * message is received from the workstation) will always send a
3539 * break all call backs to the workstation if there is no
3544 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3546 (void)afs_inet_ntoa_r(host->host, hoststr);
3547 if (host->interface) {
3548 afsUUID uuid = host->interface->uuid;
3550 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3553 if (MultiProbeAlternateAddress_r(host)) {
3554 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3555 hoststr, ntohs(host->port), code));
3556 host->hostFlags |= VENUSDOWN;
3561 code = RXAFSCB_Probe(cb_conn);
3565 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3566 hoststr, ntohs(host->port), code));
3567 host->hostFlags |= VENUSDOWN;
3573 rx_PutConnection(cb_conn);
3585 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3586 * don't respond to a probe. Note that VenusDown can only be cleared if
3587 * a message is received from the host (see ServerLWP in file.c).
3588 * Delete hosts that have not had any calls in 1 hour, clients that
3589 * have not had any calls in 15 minutes.
3591 * This routine is called roughly every 5 minutes.
3596 afs_uint32 now = FT_ApproxTime();
3598 memset((char *)&zerofid, 0, sizeof(zerofid));
3600 * Send a probe to the workstation if it hasn't been heard from in
3603 checktime = now - 15 * 60;
3604 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3607 h_Enumerate_r(CheckHost_r, hostList, NULL);
3612 * This is called with host locked and held. At this point, the
3613 * hostAddrHashTable should not have any entries for the alternate
3614 * interfaces. This function has to insert these entries in the
3615 * hostAddrHashTable.
3617 * The addresses in the interfaceAddr list are in host byte order.
3620 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3627 struct Interface *interface;
3630 afs_uint16 port7001 = htons(7001);
3635 number = interf->numberOfInterfaces;
3636 myAddr = host->host; /* current interface address */
3637 myPort = host->port; /* current port */
3640 ("initInterfaceAddr : host %s:%d numAddr %d\n",
3641 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3643 /* validation checks */
3644 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3646 ("Invalid number of alternate addresses is %d\n", number));
3651 * The client's notion of its own IP addresses is not reliable.
3653 * 1. The client list might contain private address ranges which
3654 * are likely to be re-used by many clients allocated addresses
3657 * 2. The client list will not include any public addresses that
3658 * are hidden by a NAT.
3660 * 3. Private address ranges that are exposed to the server will
3661 * be obtained from the rx connections that use them.
3663 * 4. Lists provided by the client are not necessarily truthful.
3664 * Many existing clients (UNIX) do not refresh the IP address
3665 * list as the actual assigned addresses change. The end result
3666 * is that they report the initial address list for the lifetime
3667 * of the process. In other words, a client can report addresses
3668 * that they are in fact not using. Adding these addresses to
3669 * the host interface list without verification is not only
3670 * pointless, it is downright dangerous.
3672 * We therefore do not add alternate addresses to the addr hash table.
3673 * We only use them for multi-rx callback breaks.
3677 * Convert IP addresses to network byte order, and remove
3678 * duplicate IP addresses from the interface list, and
3679 * determine whether or not the incoming addr/port is
3680 * listed. Note that if the address matches it is not
3681 * truly a match because the port number for the entries
3682 * in the interface list are port 7001 and the port number
3683 * for this connection might not be 7001.
3685 for (i = 0, count = 0, found = 0; i < number; i++) {
3686 interf->addr_in[i] = htonl(interf->addr_in[i]);
3687 for (j = 0; j < count; j++) {
3688 if (interf->addr_in[j] == interf->addr_in[i])
3692 interf->addr_in[count] = interf->addr_in[i];
3693 if (interf->addr_in[count] == myAddr &&
3701 * Allocate and initialize an interface structure for this host.
3704 interface = (struct Interface *)
3705 malloc(sizeof(struct Interface) +
3706 (sizeof(struct AddrPort) * (count - 1)));
3708 ViceLog(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
3711 interface->numberOfInterfaces = count;
3713 interface = (struct Interface *)
3714 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
3716 ViceLog(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
3719 interface->numberOfInterfaces = count + 1;
3720 interface->interface[count].addr = myAddr;
3721 interface->interface[count].port = myPort;
3722 interface->interface[count].valid = 1;
3725 for (i = 0; i < count; i++) {
3727 interface->interface[i].addr = interf->addr_in[i];
3728 /* We store the port as 7001 because the addresses reported by
3729 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
3730 * are coming from fully connected hosts (no NAT/PATs)
3732 interface->interface[i].port = port7001;
3733 interface->interface[i].valid = 1; /* valid until a conflict is found */
3736 interface->uuid = interf->uuid;
3738 assert(!host->interface);
3739 host->interface = interface;
3741 afsUUID_to_string(&interface->uuid, uuidstr, 127);
3743 ViceLog(125, ("--- uuid %s\n", uuidstr));
3744 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
3745 ViceLog(125, ("--- alt address %s:%d\n",
3746 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3747 ntohs(host->interface->interface[i].port)));
3753 /* deleted a HashChain structure for this address and host */
3754 /* returns 1 on success */
3756 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
3759 register struct h_AddrHashChain **hp, *th;
3761 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);) {
3762 assert(th->hostPtr);
3763 if (th->hostPtr == host && th->addr == addr && th->port == port) {
3777 ** prints out all alternate interface address for the host. The 'level'
3778 ** parameter indicates what level of debugging sets this output
3781 printInterfaceAddr(struct host *host, int level)
3786 if (host->interface) {
3787 /* check alternate addresses */
3788 number = host->interface->numberOfInterfaces;
3790 ViceLog(level, ("no-addresses "));
3792 for (i = 0; i < number; i++)
3793 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3794 ntohs(host->interface->interface[i].port)));
3797 ViceLog(level, ("\n"));