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>
25 #include <netinet/in.h>
30 #include <afs/assert.h>
33 #include <afs/afsint.h>
34 #define FSINT_COMMON_XG
35 #include <afs/afscbint.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);
90 static int h_threadquota(int);
92 #define CESPERBLOCK 73
93 struct CEBlock { /* block of CESPERBLOCK file entries */
94 struct client entry[CESPERBLOCK];
97 void h_TossStuff_r(register struct host *host);
100 * Make sure the subnet macros have been defined.
103 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
106 #ifndef IN_CLASSA_SUBNET
107 #define IN_CLASSA_SUBNET 0xffff0000
111 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
114 #ifndef IN_CLASSB_SUBNET
115 #define IN_CLASSB_SUBNET 0xffffff00
119 /* get a new block of CEs and chain it on CEFree */
123 register struct CEBlock *block;
126 block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
128 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
129 ShutDownAndCore(PANIC);
132 for (i = 0; i < (CESPERBLOCK - 1); i++) {
133 Lock_Init(&block->entry[i].lock);
134 block->entry[i].next = &(block->entry[i + 1]);
136 block->entry[CESPERBLOCK - 1].next = 0;
137 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
138 CEFree = (struct client *)block;
144 /* get the next available CE */
145 static struct client *
148 register struct client *entry;
153 ViceLog(0, ("CEFree NULL in GetCE\n"));
154 ShutDownAndCore(PANIC);
158 CEFree = entry->next;
160 memset(entry, 0, CLIENT_TO_ZERO(entry));
166 /* return an entry to the free list */
168 FreeCE(register struct client *entry)
170 entry->VenusEpoch = 0;
172 entry->next = CEFree;
179 * The HTs and HTBlocks variables were formerly static, but they are
180 * now referenced elsewhere in the FileServer.
182 int HTs = 0; /* active file entries */
183 int HTBlocks = 0; /* number of blocks of HTs */
184 static struct host *HTFree = 0; /* first free file entry */
187 * Hash tables of host pointers. We need two tables, one
188 * to map IP addresses onto host pointers, and another
189 * to map host UUIDs onto host pointers.
191 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
192 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
193 #define h_HashIndex(hostip) (ntohl(hostip) & (h_HASHENTRIES-1))
194 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
196 struct HTBlock { /* block of HTSPERBLOCK file entries */
197 struct host entry[h_HTSPERBLOCK];
201 /* get a new block of HTs and chain it on HTFree */
205 register struct HTBlock *block;
207 static int index = 0;
209 if (HTBlocks == h_MAXHOSTTABLES) {
210 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
211 ShutDownAndCore(PANIC);
214 block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
216 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
217 ShutDownAndCore(PANIC);
219 #ifdef AFS_PTHREAD_ENV
220 for (i = 0; i < (h_HTSPERBLOCK); i++)
221 assert(pthread_cond_init(&block->entry[i].cond, NULL) == 0);
222 #endif /* AFS_PTHREAD_ENV */
223 for (i = 0; i < (h_HTSPERBLOCK); i++)
224 Lock_Init(&block->entry[i].lock);
225 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
226 block->entry[i].next = &(block->entry[i + 1]);
227 for (i = 0; i < (h_HTSPERBLOCK); i++)
228 block->entry[i].index = index++;
229 block->entry[h_HTSPERBLOCK - 1].next = 0;
230 HTFree = (struct host *)block;
231 hosttableptrs[HTBlocks++] = block->entry;
236 /* get the next available HT */
240 register struct host *entry;
244 assert(HTFree != NULL);
246 HTFree = entry->next;
248 memset(entry, 0, HOST_TO_ZERO(entry));
254 /* return an entry to the free list */
256 FreeHT(register struct host *entry)
258 entry->next = HTFree;
265 hpr_Initialize(struct ubik_client **uclient)
268 struct rx_connection *serverconns[MAXSERVERS];
269 struct rx_securityClass *sc;
270 struct afsconf_dir *tdir;
272 struct afsconf_cell info;
276 tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
278 ViceLog(0, ("hpr_Initialize: Could not open configuration directory: %s", AFSDIR_SERVER_ETC_DIRPATH));
282 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
284 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
289 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
291 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s",
292 cellstr, confDir->name, AFSDIR_CELLSERVDB_FILE));
299 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
304 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
305 * to force use of the KeyFile. secLevel == 0 implies -noauth was
307 if ((afsconf_GetLatestKey(tdir, 0, 0) == 0)) {
308 code = afsconf_ClientAuthSecure(tdir, &sc, &scIndex);
310 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s (so trying noauth)", code, afs_error_message(code)));
312 scIndex = RX_SECIDX_NULL;
314 afsconf_ClientAuthToken(&info, 0, &sc, &scIndex, NULL);
316 if ((scIndex == RX_SECIDX_NULL) && (sc == NULL))
317 sc = rxnull_NewClientSecurityObject();
318 if (scIndex == RX_SECIDX_NULL)
319 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, running unauthenticated. [%d]", code));
321 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
322 for (i = 0; i < info.numServers; i++) {
324 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
325 info.hostAddr[i].sin_port, PRSRV,
329 code = ubik_ClientInit(serverconns, uclient);
331 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
334 code = rxs_Release(sc);
339 hpr_End(struct ubik_client *uclient)
344 code = ubik_ClientDestroy(uclient);
350 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
352 #ifdef AFS_PTHREAD_ENV
353 register afs_int32 code;
355 struct ubik_client *uclient =
356 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
359 code = hpr_Initialize(&uclient);
361 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
367 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
368 if (code != PRSUCCESS)
371 /* do something about this, probably make a new call */
372 /* don't forget there's a hard limit in the interface */
374 "membership list for host id %d exceeds display limit\n",
379 return pr_GetHostCPS(host, CPS);
384 hpr_NameToId(namelist *names, idlist *ids)
386 #ifdef AFS_PTHREAD_ENV
387 register afs_int32 code;
388 register afs_int32 i;
389 struct ubik_client *uclient =
390 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
393 code = hpr_Initialize(&uclient);
395 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
400 for (i = 0; i < names->namelist_len; i++)
401 stolower(names->namelist_val[i]);
402 code = ubik_PR_NameToID(uclient, 0, names, ids);
405 return pr_NameToId(names, ids);
410 hpr_IdToName(idlist *ids, namelist *names)
412 #ifdef AFS_PTHREAD_ENV
413 register afs_int32 code;
414 struct ubik_client *uclient =
415 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
418 code = hpr_Initialize(&uclient);
420 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
425 code = ubik_PR_IDToName(uclient, 0, ids, names);
428 return pr_IdToName(ids, names);
433 hpr_GetCPS(afs_int32 id, prlist *CPS)
435 #ifdef AFS_PTHREAD_ENV
436 register afs_int32 code;
438 struct ubik_client *uclient =
439 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
442 code = hpr_Initialize(&uclient);
444 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
450 code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
451 if (code != PRSUCCESS)
454 /* do something about this, probably make a new call */
455 /* don't forget there's a hard limit in the interface */
456 fprintf(stderr, "membership list for id %d exceeds display limit\n",
461 return pr_GetCPS(id, CPS);
465 static short consolePort = 0;
468 h_Lock_r(register struct host *host)
478 * returns 1 if already locked
479 * else returns locks and returns 0
483 h_NBLock_r(register struct host *host)
485 struct Lock *hostLock = &host->lock;
490 if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
491 hostLock->excl_locked = WRITE_LOCK;
495 LOCK_UNLOCK(hostLock);
504 #if FS_STATS_DETAILED
505 /*------------------------------------------------------------------------
506 * PRIVATE h_AddrInSameNetwork
509 * Given a target IP address and a candidate IP address (both
510 * in host byte order), return a non-zero value (1) if the
511 * candidate address is in a different network from the target
515 * a_targetAddr : Target address.
516 * a_candAddr : Candidate address.
519 * 1 if the candidate address is in the same net as the target,
523 * The target and candidate addresses are both in host byte
524 * order, NOT network byte order, when passed in. We return
525 * our value as a character, since that's the type of field in
526 * the host structure, where this info will be stored.
530 *------------------------------------------------------------------------*/
533 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
534 { /*h_AddrInSameNetwork */
536 afs_uint32 targetNet;
540 * Pull out the network and subnetwork numbers from the target
541 * and candidate addresses. We can short-circuit this whole
542 * affair if the target and candidate addresses are not of the
545 if (IN_CLASSA(a_targetAddr)) {
546 if (!(IN_CLASSA(a_candAddr))) {
549 targetNet = a_targetAddr & IN_CLASSA_NET;
550 candNet = a_candAddr & IN_CLASSA_NET;
551 } else if (IN_CLASSB(a_targetAddr)) {
552 if (!(IN_CLASSB(a_candAddr))) {
555 targetNet = a_targetAddr & IN_CLASSB_NET;
556 candNet = a_candAddr & IN_CLASSB_NET;
557 } /*Class B target */
558 else if (IN_CLASSC(a_targetAddr)) {
559 if (!(IN_CLASSC(a_candAddr))) {
562 targetNet = a_targetAddr & IN_CLASSC_NET;
563 candNet = a_candAddr & IN_CLASSC_NET;
564 } /*Class C target */
566 targetNet = a_targetAddr;
567 candNet = a_candAddr;
568 } /*Class D address */
571 * Now, simply compare the extracted net values for the two addresses
572 * (which at this point are known to be of the same class)
574 if (targetNet == candNet)
579 } /*h_AddrInSameNetwork */
580 #endif /* FS_STATS_DETAILED */
583 /* Assumptions: called with held host */
585 h_gethostcps_r(register struct host *host, register afs_int32 now)
590 /* wait if somebody else is already doing the getCPS call */
591 while (host->hostFlags & HCPS_INPROGRESS) {
592 slept = 1; /* I did sleep */
593 host->hostFlags |= HCPS_WAITING; /* I am sleeping now */
594 #ifdef AFS_PTHREAD_ENV
595 pthread_cond_wait(&host->cond, &host_glock_mutex);
596 #else /* AFS_PTHREAD_ENV */
597 if ((code = LWP_WaitProcess(&(host->hostFlags))) != LWP_SUCCESS)
598 ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
599 #endif /* AFS_PTHREAD_ENV */
603 host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
604 if (host->hcps.prlist_val)
605 free(host->hcps.prlist_val); /* this is for hostaclRefresh */
606 host->hcps.prlist_val = NULL;
607 host->hcps.prlist_len = 0;
608 host->cpsCall = slept ? (FT_ApproxTime()) : (now);
611 code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
616 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
617 * and reevaluates things if no sync server or quorum is found we could still end up
618 * with one of these errors. In such case we would like to reevaluate the rpc call to
619 * find if there's cps for this guy. We treat other errors (except network failures
620 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
621 * we could like to deal this problem the other way around (i.e. if code == NOCPS
622 * ignore else retry next time) but the problem is that there're other errors (i.e.
623 * EPERM) for which we don't want to retry and we don't know the whole code list!
625 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
627 * We would have preferred to use a while loop and try again since ops in protected
628 * acls for this host will fail now but they'll be reevaluated on any subsequent
629 * call. The attempt to wait for a quorum/sync site or network error won't work
630 * since this problems really should only occurs during a complete fileserver
631 * restart. Since the fileserver will start before the ptservers (and thus before
632 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
634 host->hcpsfailed = 1;
636 ("Warning: GetHostCPS failed (%d) for %p (%s:%d); will retry\n",
637 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
639 host->hcpsfailed = 0;
641 ("gethost: GetHostCPS failed (%d) for %p (%s:%d); ignored\n",
642 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
644 if (host->hcps.prlist_val)
645 free(host->hcps.prlist_val);
646 host->hcps.prlist_val = NULL;
647 host->hcps.prlist_len = 0; /* Make sure it's zero */
649 host->hcpsfailed = 0;
651 host->hostFlags &= ~HCPS_INPROGRESS;
652 /* signal all who are waiting */
653 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
654 host->hostFlags &= ~HCPS_WAITING;
655 #ifdef AFS_PTHREAD_ENV
656 assert(pthread_cond_broadcast(&host->cond) == 0);
657 #else /* AFS_PTHREAD_ENV */
658 if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
659 ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
660 #endif /* AFS_PTHREAD_ENV */
664 /* args in net byte order */
666 h_flushhostcps(register afs_uint32 hostaddr, register afs_uint16 hport)
671 h_Lookup_r(hostaddr, hport, &host);
673 host->hcpsfailed = 1;
682 * Allocate a host. It will be identified by the peer (ip,port) info in the
683 * rx connection provided. The host is returned held and locked
685 #define DEF_ROPCONS 2115
688 h_Alloc_r(register struct rx_connection *r_con)
690 struct servent *serverentry;
693 #if FS_STATS_DETAILED
694 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
695 #endif /* FS_STATS_DETAILED */
699 host->host = rxr_HostOf(r_con);
700 host->port = rxr_PortOf(r_con);
702 h_AddHostToAddrHashTable_r(host->host, host->port, host);
704 if (consolePort == 0) { /* find the portal number for console */
705 #if defined(AFS_OSF_ENV)
706 serverentry = getservbyname("ropcons", "");
708 serverentry = getservbyname("ropcons", 0);
711 consolePort = serverentry->s_port;
713 consolePort = htons(DEF_ROPCONS); /* Use a default */
715 if (host->port == consolePort)
717 /* Make a callback channel even for the console, on the off chance that it
718 * makes a request that causes a break call back. It shouldn't. */
719 h_SetupCallbackConn_r(host);
720 now = host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
722 host->hcps.prlist_val = NULL;
723 host->hcps.prlist_len = 0;
724 host->interface = NULL;
726 host->hcpsfailed = 0; /* save cycles */
727 h_gethostcps(host); /* do this under host hold/lock */
729 host->FirstClient = NULL;
732 h_InsertList_r(host); /* update global host List */
733 #if FS_STATS_DETAILED
735 * Compare the new host's IP address (in host byte order) with ours
736 * (the File Server's), remembering if they are in the same network.
738 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
739 host->InSameNetwork =
740 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
741 #endif /* FS_STATS_DETAILED */
748 /* Make a callback channel even for the console, on the off chance that it
749 * makes a request that causes a break call back. It shouldn't. */
751 h_SetupCallbackConn_r(struct host * host)
754 sc = rxnull_NewClientSecurityObject();
755 host->callback_rxcon =
756 rx_NewConnection(host->host, host->port, 1, sc, 0);
757 rx_SetConnDeadTime(host->callback_rxcon, 50);
758 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
762 * Lookup a host given an IP address and UDP port number.
763 * hostaddr and hport are in network order
764 * hostaddr and hport are in network order
765 * On return, refCount is incremented.
768 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, struct host **hostp)
771 struct host *host = NULL;
772 struct h_AddrHashChain *chain;
773 int index = h_HashIndex(haddr);
774 extern int hostaclRefresh;
777 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
778 host = chain->hostPtr;
780 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
781 && chain->port == hport) {
782 if ((host->hostFlags & HWHO_INPROGRESS) &&
783 h_threadquota(host->lock.num_waiting)) {
789 if (host->hostFlags & HOSTDELETED) {
796 now = FT_ApproxTime(); /* always evaluate "now" */
797 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
799 * Every hostaclRefresh period (def 2 hrs) get the new
800 * membership list for the host. Note this could be the
801 * first time that the host is added to a group. Also
802 * here we also retry on previous legitimate hcps failures.
804 * If we get here refCount is elevated.
806 h_gethostcps_r(host, now);
816 /* Lookup a host given its UUID. */
818 h_LookupUuid_r(afsUUID * uuidp)
820 struct host *host = 0;
821 struct h_UuidHashChain *chain;
822 int index = h_UuidHashIndex(uuidp);
824 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
825 host = chain->hostPtr;
827 if (!(host->hostFlags & HOSTDELETED) && host->interface
828 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
836 /* h_TossStuff_r: Toss anything in the host structure (the host or
837 * clients marked for deletion. Called from h_Release_r ONLY.
838 * To be called, there must be no holds, and either host->deleted
839 * or host->clientDeleted must be set.
842 h_TossStuff_r(register struct host *host)
844 register struct client **cp, *client;
847 /* make sure host doesn't go away over h_NBLock_r */
850 code = h_NBLock_r(host);
852 /* don't use h_Release_r, since that may call h_TossStuff_r again */
855 /* if somebody still has this host locked */
859 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was locked.\n",
860 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
866 /* if somebody still has this host held */
867 /* we must check this _after_ h_NBLock_r, since h_NBLock_r can drop and
868 * reacquire H_LOCK */
869 if (host->refCount > 0) {
872 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was held.\n",
873 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
877 /* ASSUMPTION: rxi_FreeConnection() does not yield */
878 for (cp = &host->FirstClient; (client = *cp);) {
879 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
881 ObtainWriteLockNoBlock(&client->lock, code);
885 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
886 "client %p was locked.\n",
887 host, afs_inet_ntoa_r(host->host, hoststr),
888 ntohs(host->port), client));
892 if (client->refCount) {
895 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
896 "client %p refcount %d.\n",
897 host, afs_inet_ntoa_r(host->host, hoststr),
898 ntohs(host->port), client, client->refCount));
899 /* This is the same thing we do if the host is locked */
900 ReleaseWriteLock(&client->lock);
903 client->CPS.prlist_len = 0;
904 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
905 free(client->CPS.prlist_val);
906 client->CPS.prlist_val = NULL;
907 CurrentConnections--;
909 ReleaseWriteLock(&client->lock);
915 /* We've just cleaned out all the deleted clients; clear the flag */
916 host->hostFlags &= ~CLIENTDELETED;
918 if (host->hostFlags & HOSTDELETED) {
919 register struct rx_connection *rxconn;
920 struct AddrPort hostAddrPort;
923 if (host->Console & 1)
925 if ((rxconn = host->callback_rxcon)) {
926 host->callback_rxcon = (struct rx_connection *)0;
927 rx_DestroyConnection(rxconn);
929 if (host->hcps.prlist_val)
930 free(host->hcps.prlist_val);
931 host->hcps.prlist_val = NULL;
932 host->hcps.prlist_len = 0;
933 DeleteAllCallBacks_r(host, 1);
934 host->hostFlags &= ~RESETDONE; /* just to be safe */
936 /* if alternate addresses do not exist */
937 if (!(host->interface)) {
938 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
940 h_DeleteHostFromUuidHashTable_r(host);
941 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
942 /* delete the hash entry for each valid alternate addresses */
943 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
944 hostAddrPort = host->interface->interface[i];
946 * if the interface addr/port is the primary, we already
947 * removed it. If the addr/port is not valid, its not
950 if (hostAddrPort.valid &&
951 (host->host != hostAddrPort.addr ||
952 host->port != hostAddrPort.port))
953 h_DeleteHostFromAddrHashTable_r(hostAddrPort.addr, hostAddrPort.port, host);
955 free(host->interface);
956 host->interface = NULL;
957 } /* if alternate address exists */
959 h_DeleteList_r(host); /* remove host from global host List */
966 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
967 * system at the start of the enumeration (perhaps more). Hosts may be deleted
968 * (have delete flag set); ditto for clients. refCount is always incremented
969 * before (*proc) is called. The param flags is passed to (*proc) as the
970 * param flags, permitting (*proc) to stop the enumeration (BAIL).
972 * Needed? Why not always h_Hold_r and h_Release_r in (*proc), or even -never-
973 * h_Hold_r or h_Release_r in (*proc)?
975 * **The proc should return 0 if the host should be released, 1 if it should
976 * be held after enumeration.
979 h_Enumerate(int (*proc) (struct host*, int, void *), void *param)
981 register struct host *host, **list;
983 register int i, count;
987 if (hostCount == 0) {
991 list = (struct host **)malloc(hostCount * sizeof(struct host *));
993 ViceLog(0, ("Failed malloc in h_Enumerate (list)\n"));
996 flags = (int *)malloc(hostCount * sizeof(int));
998 ViceLog(0, ("Failed malloc in h_Enumerate (flags)\n"));
1001 for (totalCount = count = 0, host = hostList;
1002 host && totalCount < hostCount;
1003 host = host->next, totalCount++) {
1005 if (!(host->hostFlags & HOSTDELETED)) {
1011 if (totalCount != hostCount) {
1012 ViceLog(0, ("h_Enumerate found %d of %d hosts\n", totalCount, hostCount));
1013 } else if (host != NULL) {
1014 ViceLog(0, ("h_Enumerate found more than %d hosts\n", hostCount));
1015 ShutDownAndCore(PANIC);
1018 for (i = 0; i < count; i++) {
1019 flags[i] = (*proc) (list[i], flags[i], param);
1020 h_Release_r(list[i]);
1021 /* bail out of the enumeration early */
1022 if (H_ENUMERATE_ISSET_BAIL(flags[i]))
1026 free((void *)flags);
1030 /* h_Enumerate_r (revised):
1031 * Calls (*proc)(host, flags, param) for each host in hostList, starting
1032 * at enumstart. Called only under H_LOCK. Hosts may be deleted (have
1033 * delete flag set); ditto for clients. refCount is always incremented
1034 * before (*proc) is called. The param flags is passed to (*proc) as the
1035 * param flags, permitting (*proc) to stop the enumeration (BAIL).
1037 * Needed? Why not always h_Hold_r and h_Release_r in (*proc), or even -never-
1038 * h_Hold_r or h_Release_r in (*proc)?
1040 * @note Assumes that hostList is only prepended to, that a host is never
1041 * inserted into the middle. Otherwise this would not be guaranteed to
1044 * **The proc should return 0 if the host should be released, 1 if it should
1045 * be held after enumeration.
1048 h_Enumerate_r(int (*proc) (struct host *, int, void *),
1049 struct host *enumstart, void *param)
1051 register struct host *host, *next;
1057 if (hostCount == 0) {
1064 /* find the first non-deleted host, so we know where to actually start
1066 for (count = 0; host && count < hostCount; count++) {
1067 if (!(host->hostFlags & HOSTDELETED)) {
1074 /* we didn't find a non-deleted host... */
1076 if (host && count >= hostCount) {
1077 /* ...because we found a loop */
1078 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", hostCount));
1079 ShutDownAndCore(PANIC);
1082 /* ...because the hostList is full of deleted hosts */
1086 h_Hold_r(enumstart);
1088 /* remember hostCount, lest it change over the potential H_LOCK drop in
1090 origHostCount = hostCount;
1092 for (count = 0, host = enumstart; host && count < origHostCount; host = next, flags = nflags, count++) {
1095 /* find the next non-deleted host */
1096 while (next && (next->hostFlags & HOSTDELETED)) {
1098 /* inc count for the skipped-over host */
1099 if (++count > origHostCount) {
1100 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1101 ShutDownAndCore(PANIC);
1104 if (next && !H_ENUMERATE_ISSET_BAIL(flags))
1107 if (!(host->hostFlags & HOSTDELETED)) {
1108 flags = (*proc) (host, flags, param);
1109 if (H_ENUMERATE_ISSET_BAIL(flags)) {
1110 h_Release_r(host); /* this might free up the host */
1114 h_Release_r(host); /* this might free up the host */
1116 if (host != NULL && count >= origHostCount) {
1117 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1118 ShutDownAndCore(PANIC);
1120 } /*h_Enumerate_r */
1123 /* inserts a new HashChain structure corresponding to this UUID */
1125 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1128 struct h_UuidHashChain *chain;
1129 char uuid1[128], uuid2[128];
1132 /* hash into proper bucket */
1133 index = h_UuidHashIndex(uuid);
1135 /* don't add the same entry multiple times */
1136 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1137 if (!chain->hostPtr)
1140 if (chain->hostPtr->interface &&
1141 afs_uuid_equal(&chain->hostPtr->interface->uuid, uuid)) {
1142 if (LogLevel >= 125) {
1143 afsUUID_to_string(&chain->hostPtr->interface->uuid, uuid1,
1145 afsUUID_to_string(uuid, uuid2, 127);
1146 ViceLog(125, ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s) exists as %s:%d (uuid %s)\n",
1148 afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1149 ntohs(chain->hostPtr->port), uuid2));
1155 /* insert into beginning of list for this bucket */
1156 chain = (struct h_UuidHashChain *)malloc(sizeof(struct h_UuidHashChain));
1158 ViceLog(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1161 chain->hostPtr = host;
1162 chain->next = hostUuidHashTable[index];
1163 hostUuidHashTable[index] = chain;
1166 afsUUID_to_string(uuid, uuid2, 127);
1168 ("h_AddHostToUuidHashTable_r: host %p (%s:%d) added as uuid %s\n",
1169 host, afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1170 ntohs(chain->hostPtr->port), uuid2));
1173 /* deletes a HashChain structure corresponding to this host */
1175 h_DeleteHostFromUuidHashTable_r(struct host *host)
1178 register struct h_UuidHashChain **uhp, *uth;
1182 if (!host->interface)
1185 /* hash into proper bucket */
1186 index = h_UuidHashIndex(&host->interface->uuid);
1188 if (LogLevel >= 125)
1189 afsUUID_to_string(&host->interface->uuid, uuid1, 127);
1190 for (uhp = &hostUuidHashTable[index]; (uth = *uhp); uhp = &uth->next) {
1191 assert(uth->hostPtr);
1192 if (uth->hostPtr == host) {
1194 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d)\n",
1195 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1196 ntohs(host->port)));
1203 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d) not found\n",
1204 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1205 ntohs(host->port)));
1209 /* inserts a new HashChain structure corresponding to this address */
1211 h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1214 struct h_AddrHashChain *chain;
1217 /* hash into proper bucket */
1218 index = h_HashIndex(addr);
1220 /* don't add the same address:port pair entry multiple times */
1221 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1222 if (chain->addr == addr && chain->port == port) {
1223 if (chain->hostPtr == host) {
1225 ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
1226 host, afs_inet_ntoa_r(chain->addr, hoststr),
1227 ntohs(chain->port)));
1230 if (!(chain->hostPtr->hostFlags & HOSTDELETED)) {
1232 ("h_AddHostToAddrHashTable_r: refusing to hash host %" AFS_PTR_FMT ", %"
1233 AFS_PTR_FMT " (%s:%d) already hashed\n",
1234 host, chain->hostPtr, afs_inet_ntoa_r(chain->addr, hoststr),
1235 ntohs(chain->port)));
1241 /* insert into beginning of list for this bucket */
1242 chain = (struct h_AddrHashChain *)malloc(sizeof(struct h_AddrHashChain));
1244 ViceLog(0, ("Failed malloc in h_AddHostToAddrHashTable_r\n"));
1247 chain->hostPtr = host;
1248 chain->next = hostAddrHashTable[index];
1251 hostAddrHashTable[index] = chain;
1252 ViceLog(125, ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " added as %s:%d\n",
1253 host, afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1257 * This is called with host locked and held.
1258 * It is called to either validate or add an additional interface
1259 * address/port on the specified host.
1261 * All addresses are in network byte order.
1264 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1268 struct Interface *interface;
1269 char hoststr[16], hoststr2[16];
1272 assert(host->interface);
1275 * Make sure this address is on the list of known addresses
1278 number = host->interface->numberOfInterfaces;
1279 for (i = 0; i < number; i++) {
1280 if (host->interface->interface[i].addr == addr &&
1281 host->interface->interface[i].port == port) {
1283 ("addInterfaceAddr : found host %" AFS_PTR_FMT " (%s:%d) adding %s:%d%s\n",
1284 host, afs_inet_ntoa_r(host->host, hoststr),
1285 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1286 ntohs(port), host->interface->interface[i].valid ? "" :
1289 if (host->interface->interface[i].valid == 0) {
1290 host->interface->interface[i].valid = 1;
1291 h_AddHostToAddrHashTable_r(addr, port, host);
1297 ViceLog(125, ("addInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) adding %s:%d\n",
1298 host, afs_inet_ntoa_r(host->host, hoststr),
1299 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1302 interface = (struct Interface *)
1303 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1305 ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
1308 interface->numberOfInterfaces = number + 1;
1309 interface->uuid = host->interface->uuid;
1310 for (i = 0; i < number; i++)
1311 interface->interface[i] = host->interface->interface[i];
1313 /* Add the new valid interface */
1314 interface->interface[number].addr = addr;
1315 interface->interface[number].port = port;
1316 interface->interface[number].valid = 1;
1317 h_AddHostToAddrHashTable_r(addr, port, host);
1318 free(host->interface);
1319 host->interface = interface;
1326 * This is called with host locked and held.
1328 * All addresses are in network byte order.
1331 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1335 struct Interface *interface;
1336 char hoststr[16], hoststr2[16];
1339 assert(host->interface);
1341 ViceLog(125, ("removeInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1342 host, afs_inet_ntoa_r(host->host, hoststr),
1343 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1347 * Make sure this address is on the list of known addresses
1350 interface = host->interface;
1351 number = host->interface->numberOfInterfaces;
1352 for (i = 0; i < number; i++) {
1353 if (interface->interface[i].addr == addr &&
1354 interface->interface[i].port == port) {
1355 if (interface->interface[i].valid)
1356 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1358 for (; i < number; i++) {
1359 interface->interface[i] = interface->interface[i+1];
1361 interface->numberOfInterfaces = number;
1370 * This is called with host locked and held.
1372 * All addresses are in network byte order.
1375 invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1379 struct Interface *interface;
1380 char hoststr[16], hoststr2[16];
1383 assert(host->interface);
1385 ViceLog(125, ("invalidateInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1386 host, afs_inet_ntoa_r(host->host, hoststr),
1387 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1391 * Make sure this address is on the list of known addresses
1394 interface = host->interface;
1395 number = host->interface->numberOfInterfaces;
1396 for (i = 0; i < number; i++) {
1397 if (interface->interface[i].addr == addr &&
1398 interface->interface[i].port == port) {
1399 if (interface->interface[i].valid) {
1400 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1401 interface->interface[i].valid = 0;
1412 * This is called with host locked and held. This function differs
1413 * from removeInterfaceAddr_r in that it is called when the address
1414 * is being removed from the host regardless of whether or not there
1415 * is an interface list for the host. This function will delete the
1416 * host if there are no addresses left on it.
1418 * All addresses are in network byte order.
1421 removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1424 char hoststr[16], hoststr2[16];
1425 struct rx_connection *rxconn;
1427 if (!host->interface || host->interface->numberOfInterfaces == 1) {
1428 if (host->host == addr && host->port == port) {
1430 ("Removing only address for host %" AFS_PTR_FMT " (%s:%d), deleting host.\n",
1431 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1432 host->hostFlags |= HOSTDELETED;
1434 * Do not remove the primary addr/port from the hash table.
1435 * It will be ignored due to the HOSTDELETED flag and will
1436 * be removed when h_TossStuff_r() cleans up the HOSTDELETED
1437 * host. Removing it here will only result in a search for
1438 * the host/addr/port in the hash chain which will fail.
1442 ("Removing address that does not belong to host %" AFS_PTR_FMT " (%s:%d).\n",
1443 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1446 if (host->host == addr && host->port == port) {
1447 removeInterfaceAddr_r(host, addr, port);
1449 for (i=0; i < host->interface->numberOfInterfaces; i++) {
1450 if (host->interface->interface[i].valid) {
1452 ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
1453 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1454 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
1455 ntohs(host->interface->interface[i].port)));
1456 host->host = host->interface->interface[i].addr;
1457 host->port = host->interface->interface[i].port;
1458 h_AddHostToAddrHashTable_r(host->host, host->port, host);
1463 if (i == host->interface->numberOfInterfaces) {
1465 ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
1466 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1467 host->hostFlags |= HOSTDELETED;
1468 /* addr/port was removed from the hash table */
1472 rxconn = host->callback_rxcon;
1473 host->callback_rxcon = NULL;
1476 rx_DestroyConnection(rxconn);
1481 sc = rxnull_NewClientSecurityObject();
1482 host->callback_rxcon =
1483 rx_NewConnection(host->host, host->port, 1, sc, 0);
1484 rx_SetConnDeadTime(host->callback_rxcon, 50);
1485 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
1488 /* not the primary addr/port, just invalidate it */
1489 invalidateInterfaceAddr_r(host, addr, port);
1496 h_threadquota(int waiting)
1501 } else if (lwps > 32) {
1504 } else if (lwps > 16) {
1514 /* If found, host is returned with refCount incremented */
1516 h_GetHost_r(struct rx_connection *tcon)
1519 struct host *oldHost;
1521 struct interfaceAddr interf;
1522 int interfValid = 0;
1523 struct Identity *identP = NULL;
1526 char hoststr[16], hoststr2[16];
1528 struct rx_connection *cb_conn = NULL;
1529 struct rx_connection *cb_in = NULL;
1531 caps.Capabilities_val = NULL;
1533 haddr = rxr_HostOf(tcon);
1534 hport = rxr_PortOf(tcon);
1537 rx_DestroyConnection(cb_in);
1540 if (caps.Capabilities_val)
1541 free(caps.Capabilities_val);
1542 caps.Capabilities_val = NULL;
1543 caps.Capabilities_len = 0;
1546 if (h_Lookup_r(haddr, hport, &host))
1548 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1549 if (host && !identP && !(host->Console & 1)) {
1550 /* This is a new connection, and we already have a host
1551 * structure for this address. Verify that the identity
1552 * of the caller matches the identity in the host structure.
1554 if ((host->hostFlags & HWHO_INPROGRESS) &&
1555 h_threadquota(host->lock.num_waiting)) {
1561 if (!(host->hostFlags & ALTADDR) ||
1562 (host->hostFlags & HOSTDELETED)) {
1563 /* Another thread is doing initialization
1564 * or this host was deleted while we
1565 * waited for the lock. */
1568 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1569 host, afs_inet_ntoa_r(host->host, hoststr),
1570 ntohs(host->port)));
1574 host->hostFlags |= HWHO_INPROGRESS;
1575 host->hostFlags &= ~ALTADDR;
1577 /* We received a new connection from an IP address/port
1578 * that is associated with 'host' but the address/port of
1579 * the callback connection does not have to match it.
1580 * If there is a match, we can use the existing callback
1581 * connection to verify the UUID. If they do not match
1582 * we need to use a new callback connection to verify the
1583 * UUID of the incoming caller and perhaps use the old
1584 * callback connection to verify that the old address/port
1588 cb_conn = host->callback_rxcon;
1589 rx_GetConnection(cb_conn);
1591 if (haddr == host->host && hport == host->port) {
1592 /* The existing callback connection matches the
1593 * incoming connection so just use it.
1596 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1597 if (code == RXGEN_OPCODE)
1598 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1600 /* We do not have a match. Create a new connection
1601 * for the new addr/port and use multi_Rx to probe
1602 * both of them simultaneously.
1605 sc = rxnull_NewClientSecurityObject();
1606 cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1607 rx_SetConnDeadTime(cb_in, 50);
1608 rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1611 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1612 if (code == RXGEN_OPCODE)
1613 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1615 rx_PutConnection(cb_conn);
1618 if ((code == RXGEN_OPCODE) ||
1619 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1620 identP = (struct Identity *)malloc(sizeof(struct Identity));
1622 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1626 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1627 if (cb_in == NULL) {
1628 /* The host on this connection was unable to respond to
1629 * the WhoAreYou. We will treat this as a new connection
1630 * from the existing host. The worst that can happen is
1631 * that we maintain some extra callback state information */
1632 if (host->interface) {
1634 ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1636 afs_inet_ntoa_r(host->host, hoststr),
1637 ntohs(host->port)));
1638 host->hostFlags |= HOSTDELETED;
1639 host->hostFlags &= ~HWHO_INPROGRESS;
1646 /* The incoming connection does not support WhoAreYou but
1647 * the original one might have. Use removeAddress_r() to
1648 * remove this addr/port from the host that was found.
1649 * If there are no more addresses left for the host it
1650 * will be deleted. Then we retry.
1652 removeAddress_r(host, haddr, hport);
1653 host->hostFlags &= ~HWHO_INPROGRESS;
1654 host->hostFlags |= ALTADDR;
1660 } else if (code == 0) {
1662 identP = (struct Identity *)malloc(sizeof(struct Identity));
1664 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1668 identP->uuid = interf.uuid;
1669 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1670 /* Check whether the UUID on this connection matches
1671 * the UUID in the host structure. If they don't match
1672 * then this is not the same host as before. */
1673 if (!host->interface
1674 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1677 ("Uuid doesn't match connection (%s:%d).\n",
1678 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1679 removeAddress_r(host, haddr, hport);
1682 ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1683 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1685 removeAddress_r(host, host->host, host->port);
1687 host->hostFlags &= ~HWHO_INPROGRESS;
1688 host->hostFlags |= ALTADDR;
1694 /* the UUID matched the client at the incoming addr/port
1695 * but this is not the address of the active callback
1696 * connection. Try that connection and see if the client
1697 * is still there and if the reported UUID is the same.
1700 afsUUID uuid = host->interface->uuid;
1701 cb_conn = host->callback_rxcon;
1702 rx_GetConnection(cb_conn);
1703 rx_SetConnDeadTime(cb_conn, 2);
1704 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1706 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1708 rx_SetConnDeadTime(cb_conn, 50);
1709 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1710 rx_PutConnection(cb_conn);
1713 /* The primary address is either not responding or
1714 * is not the client we are looking for. Need to
1715 * remove the primary address and add swap in the new
1716 * callback connection, and destroy the old one.
1718 struct rx_connection *rxconn;
1719 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1721 afs_inet_ntoa_r(host->host, hoststr),
1722 ntohs(host->port),code2));
1725 * make sure we add and then remove. otherwise, we
1726 * might end up with no valid interfaces after the
1727 * remove and the host will have been marked deleted.
1729 addInterfaceAddr_r(host, haddr, hport);
1730 removeInterfaceAddr_r(host, host->host, host->port);
1733 rxconn = host->callback_rxcon;
1734 host->callback_rxcon = cb_in;
1739 * If rx_DestroyConnection calls h_FreeConnection we
1740 * will deadlock on the host_glock_mutex. Work around
1741 * the problem by unhooking the client from the
1742 * connection before destroying the connection.
1744 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1745 rx_DestroyConnection(rxconn);
1751 /* A callback to the incoming connection address is failing.
1752 * Assume that the addr/port is no longer associated with the host
1753 * returned by h_Lookup_r.
1756 ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1757 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1758 removeAddress_r(host, haddr, hport);
1759 host->hostFlags &= ~HWHO_INPROGRESS;
1760 host->hostFlags |= ALTADDR;
1764 rx_DestroyConnection(cb_in);
1769 ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1770 host, afs_inet_ntoa_r(host->host, hoststr),
1771 ntohs(host->port), code));
1772 host->hostFlags |= VENUSDOWN;
1775 if (caps.Capabilities_val
1776 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1777 host->hostFlags |= HERRORTRANS;
1779 host->hostFlags &= ~(HERRORTRANS);
1780 host->hostFlags |= ALTADDR;
1781 host->hostFlags &= ~HWHO_INPROGRESS;
1784 if (!(host->hostFlags & ALTADDR)) {
1785 /* another thread is doing the initialisation */
1787 ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1788 host, afs_inet_ntoa_r(host->host, hoststr),
1789 ntohs(host->port)));
1793 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1794 host, afs_inet_ntoa_r(host->host, hoststr),
1795 ntohs(host->port)));
1799 /* We need to check whether the identity in the host structure
1800 * matches the identity on the connection. If they don't match
1801 * then treat this a new host. */
1802 if (!(host->Console & 1)
1803 && ((!identP->valid && host->interface)
1804 || (identP->valid && !host->interface)
1806 && !afs_uuid_equal(&identP->uuid,
1807 &host->interface->uuid)))) {
1808 char uuid1[128], uuid2[128];
1810 afsUUID_to_string(&identP->uuid, uuid1, 127);
1811 if (host->interface)
1812 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1814 ("CB: new identity for host %p (%s:%d), "
1815 "deleting(%x %p %s %s)\n",
1816 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1817 identP->valid, host->interface,
1818 identP->valid ? uuid1 : "no_uuid",
1819 host->interface ? uuid2 : "no_uuid"));
1821 /* The host in the cache is not the host for this connection */
1823 host->hostFlags |= HOSTDELETED;
1829 host = h_Alloc_r(tcon); /* returned held and locked */
1830 h_gethostcps_r(host, FT_ApproxTime());
1831 if (!(host->Console & 1)) {
1833 cb_conn = host->callback_rxcon;
1834 rx_GetConnection(cb_conn);
1835 host->hostFlags |= HWHO_INPROGRESS;
1838 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1839 if (code == RXGEN_OPCODE)
1840 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1841 rx_PutConnection(cb_conn);
1844 if ((code == RXGEN_OPCODE) ||
1845 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1848 (struct Identity *)malloc(sizeof(struct Identity));
1853 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1858 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1860 ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1861 host, afs_inet_ntoa_r(host->host, hoststr),
1862 ntohs(host->port)));
1864 } else if (code == 0) {
1867 (struct Identity *)malloc(sizeof(struct Identity));
1872 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1877 identP->uuid = interf.uuid;
1879 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1881 ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
1882 host, afs_inet_ntoa_r(host->host, hoststr),
1883 ntohs(host->port)));
1885 if (code == 0 && !identP->valid) {
1886 cb_conn = host->callback_rxcon;
1887 rx_GetConnection(cb_conn);
1889 code = RXAFSCB_InitCallBackState(cb_conn);
1890 rx_PutConnection(cb_conn);
1893 } else if (code == 0) {
1894 oldHost = h_LookupUuid_r(&identP->uuid);
1899 if (oldHost->hostFlags & HOSTDELETED) {
1900 h_Unlock_r(oldHost);
1901 h_Release_r(oldHost);
1909 oldHost->hostFlags |= HWHO_INPROGRESS;
1911 if (oldHost->interface) {
1913 afsUUID uuid = oldHost->interface->uuid;
1914 cb_conn = oldHost->callback_rxcon;
1915 rx_GetConnection(cb_conn);
1916 rx_SetConnDeadTime(cb_conn, 2);
1917 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1919 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1921 rx_SetConnDeadTime(cb_conn, 50);
1922 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1923 rx_PutConnection(cb_conn);
1926 /* The primary address is either not responding or
1927 * is not the client we are looking for.
1928 * MultiProbeAlternateAddress_r() will remove the
1929 * alternate interfaces that do not have the same
1931 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1933 afs_inet_ntoa_r(oldHost->host, hoststr),
1934 ntohs(oldHost->port),code2));
1935 MultiProbeAlternateAddress_r(oldHost);
1942 /* This is a new address for an existing host. Update
1943 * the list of interfaces for the existing host and
1944 * delete the host structure we just allocated. */
1946 /* prevent warnings while manipulating interface lists */
1947 host->hostFlags |= HOSTDELETED;
1949 if (oldHost->host != haddr || oldHost->port != hport) {
1950 struct rx_connection *rxconn;
1953 ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
1955 afs_inet_ntoa_r(oldHost->host, hoststr2),
1956 ntohs(oldHost->port),
1957 afs_inet_ntoa_r(haddr, hoststr),
1960 * add then remove. otherwise the host may get marked
1961 * deleted if we removed the only valid address.
1963 addInterfaceAddr_r(oldHost, haddr, hport);
1964 if (probefail || oldHost->host == haddr) {
1966 * The probe failed which means that the old
1967 * address is either unreachable or is not the
1968 * same host we were just contacted by. We will
1969 * also remove addresses if only the port has
1970 * changed because that indicates the client
1973 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
1976 struct Interface *interface = oldHost->interface;
1977 int number = oldHost->interface->numberOfInterfaces;
1978 for (i = 0; i < number; i++) {
1979 if (interface->interface[i].addr == haddr &&
1980 interface->interface[i].port != hport) {
1982 * We have just been contacted by a client
1983 * that has been seen from behind a NAT
1984 * and at least one other address.
1986 removeInterfaceAddr_r(oldHost, haddr,
1987 interface->interface[i].port);
1992 h_AddHostToAddrHashTable_r(haddr, hport, oldHost);
1993 oldHost->host = haddr;
1994 oldHost->port = hport;
1995 rxconn = oldHost->callback_rxcon;
1996 oldHost->callback_rxcon = host->callback_rxcon;
1997 host->callback_rxcon = rxconn;
1999 /* don't destroy rxconn here; let h_TossStuff_r
2000 * take care of that via h_Release_r below */
2002 host->hostFlags &= ~HWHO_INPROGRESS;
2004 /* release host because it was allocated by h_Alloc_r */
2007 /* the new host is held and locked */
2009 /* This really is a new host */
2010 h_AddHostToUuidHashTable_r(&identP->uuid, host);
2011 cb_conn = host->callback_rxcon;
2012 rx_GetConnection(cb_conn);
2015 RXAFSCB_InitCallBackState3(cb_conn,
2017 rx_PutConnection(cb_conn);
2022 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2023 host, afs_inet_ntoa_r(host->host, hoststr),
2024 ntohs(host->port)));
2025 assert(interfValid == 1);
2026 initInterfaceAddr_r(host, &interf);
2032 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2033 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2034 host->hostFlags |= VENUSDOWN;
2037 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2038 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2039 host->hostFlags |= RESETDONE;
2042 if (caps.Capabilities_val
2043 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2044 host->hostFlags |= HERRORTRANS;
2046 host->hostFlags &= ~(HERRORTRANS);
2047 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2048 host->hostFlags &= ~HWHO_INPROGRESS;
2053 if (caps.Capabilities_val)
2054 free(caps.Capabilities_val);
2055 caps.Capabilities_val = NULL;
2056 caps.Capabilities_len = 0;
2058 rx_DestroyConnection(cb_in);
2066 static char localcellname[PR_MAXNAMELEN + 1];
2067 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
2068 int num_lrealms = -1;
2072 h_InitHostPackage(void)
2074 memset(&nulluuid, 0, sizeof(afsUUID));
2075 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
2076 if (num_lrealms == -1) {
2078 for (i=0; i<AFS_NUM_LREALMS; i++) {
2079 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
2085 ("afs_krb_get_lrealm failed, using %s.\n",
2087 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
2093 /* initialize the rest of the local realms to nullstring for debugging */
2094 for (; i<AFS_NUM_LREALMS; i++)
2095 local_realms[i][0] = '\0';
2097 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2098 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2099 #ifdef AFS_PTHREAD_ENV
2100 assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
2101 #endif /* AFS_PTHREAD_ENV */
2105 MapName_r(char *aname, char *acell, afs_int32 * aval)
2110 afs_int32 anamelen, cnamelen;
2114 anamelen = strlen(aname);
2115 if (anamelen >= PR_MAXNAMELEN)
2116 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
2118 lnames.namelist_len = 1;
2119 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
2120 lids.idlist_len = 0;
2121 lids.idlist_val = NULL;
2123 cnamelen = strlen(acell);
2125 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2127 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2128 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2129 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2131 ("MapName: Name too long, using AnonymousID for %s@%s\n",
2133 *aval = AnonymousID;
2136 foreign = 1; /* attempt cross-cell authentication */
2137 tname = (char *)malloc(PR_MAXNAMELEN);
2139 ViceLog(0, ("Failed malloc in MapName_r\n"));
2142 strcpy(tname, aname);
2143 tname[anamelen] = '@';
2144 strcpy(tname + anamelen + 1, acell);
2145 lnames.namelist_val = (prname *) tname;
2150 code = hpr_NameToId(&lnames, &lids);
2153 if (lids.idlist_val) {
2154 *aval = lids.idlist_val[0];
2155 if (*aval == AnonymousID) {
2157 ("MapName: NameToId on %s returns anonymousID\n",
2158 lnames.namelist_val[0]));
2160 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2163 ("MapName: NameToId on '%s' is unknown\n",
2164 lnames.namelist_val[0]));
2170 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
2178 /* NOTE: this returns the client with a Write lock and a refCount */
2180 h_ID2Client(afs_int32 vid)
2182 register struct client *client;
2183 register struct host *host;
2187 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
2188 if (host->hostFlags & HOSTDELETED)
2190 for (client = host->FirstClient; client; client = client->next) {
2191 if (!client->deleted && client->ViceId == vid) {
2194 ObtainWriteLock(&client->lock);
2199 if (count != hostCount) {
2200 ViceLog(0, ("h_ID2Client found %d of %d hosts\n", count, hostCount));
2201 } else if (host != NULL) {
2202 ViceLog(0, ("h_ID2Client found more than %d hosts\n", hostCount));
2203 ShutDownAndCore(PANIC);
2211 * Called by the server main loop. Returns a h_Held client, which must be
2212 * released later the main loop. Allocates a client if the matching one
2213 * isn't around. The client is returned with its reference count incremented
2214 * by one. The caller must call h_ReleaseClient_r when finished with
2217 * The refCount on client->host is returned incremented. h_ReleaseClient_r
2218 * does not decrement the refCount on client->host.
2221 h_FindClient_r(struct rx_connection *tcon)
2223 register struct client *client;
2224 struct host *host = NULL;
2225 struct client *oldClient;
2226 afs_int32 viceid = 0;
2230 #if (64-MAXKTCNAMELEN)
2231 ticket name length != 64
2235 char uname[PR_MAXNAMELEN];
2236 char tcell[MAXKTCREALMLEN];
2240 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2241 if (client && client->sid == rxr_CidOf(tcon)
2242 && client->VenusEpoch == rxr_GetEpoch(tcon)
2243 && !(client->host->hostFlags & HOSTDELETED)) {
2246 h_Hold_r(client->host);
2247 if (!client->deleted && client->prfail != 2) {
2248 /* Could add shared lock on client here */
2249 /* note that we don't have to lock entry in this path to
2250 * ensure CPS is initialized, since we don't call rx_SetSpecific
2251 * until initialization is done, and we only get here if
2252 * rx_GetSpecific located the client structure.
2257 ObtainWriteLock(&client->lock); /* released at end */
2263 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2265 ("FindClient: authenticating connection: authClass=%d\n",
2267 if (authClass == 1) {
2268 /* A bcrypt tickets, no longer supported */
2269 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2270 viceid = AnonymousID;
2271 expTime = 0x7fffffff;
2272 } else if (authClass == 2) {
2275 /* kerberos ticket */
2276 code = rxkad_GetServerInfo(tcon, /*level */ 0, (afs_uint32 *)&expTime,
2277 tname, tinst, tcell, &kvno);
2279 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2280 viceid = AnonymousID;
2281 expTime = 0x7fffffff;
2283 int ilen = strlen(tinst);
2285 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2286 tname, tinst, tcell, expTime, kvno));
2287 strncpy(uname, tname, sizeof(uname));
2289 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2292 strcat(uname, tinst);
2294 /* translate the name to a vice id */
2295 code = MapName_r(uname, tcell, &viceid);
2299 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2302 viceid = AnonymousID;
2303 expTime = 0x7fffffff;
2307 viceid = AnonymousID; /* unknown security class */
2308 expTime = 0x7fffffff;
2311 if (!client) { /* loop */
2312 host = h_GetHost_r(tcon); /* Returns with incremented refCount */
2318 /* First try to find the client structure */
2319 for (client = host->FirstClient; client; client = client->next) {
2320 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2321 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2324 ObtainWriteLock(&client->lock);
2330 /* Still no client structure - get one */
2333 if (host->hostFlags & HOSTDELETED) {
2338 /* Retry to find the client structure */
2339 for (client = host->FirstClient; client; client = client->next) {
2340 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2341 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2343 goto retryfirstclient;
2348 ObtainWriteLock(&client->lock);
2349 client->refCount = 1;
2350 client->host = host;
2351 #if FS_STATS_DETAILED
2352 client->InSameNetwork = host->InSameNetwork;
2353 #endif /* FS_STATS_DETAILED */
2354 client->ViceId = viceid;
2355 client->expTime = expTime; /* rx only */
2356 client->authClass = authClass; /* rx only */
2357 client->sid = rxr_CidOf(tcon);
2358 client->VenusEpoch = rxr_GetEpoch(tcon);
2359 client->CPS.prlist_val = NULL;
2360 client->CPS.prlist_len = 0;
2364 client->prfail = fail;
2366 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2367 client->CPS.prlist_len = 0;
2368 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2369 free(client->CPS.prlist_val);
2370 client->CPS.prlist_val = NULL;
2371 client->ViceId = viceid;
2372 client->expTime = expTime;
2374 if (viceid == ANONYMOUSID) {
2375 client->CPS.prlist_len = AnonCPS.prlist_len;
2376 client->CPS.prlist_val = AnonCPS.prlist_val;
2379 code = hpr_GetCPS(viceid, &client->CPS);
2384 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2385 code, viceid, client->host,
2386 afs_inet_ntoa_r(client->host->host,hoststr),
2387 ntohs(client->host->port)));
2389 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2390 * all protection servers and reevaluates things if no
2391 * sync server or quorum is found we could still end up
2392 * with one of these errors. In such case we would like to
2393 * reevaluate the rpc call to find if there's cps for this
2394 * guy. We treat other errors (except network failures
2395 * ones - i.e. code < 0) as an indication that there is no
2396 * CPS for this host. Ideally we could like to deal this
2397 * problem the other way around (i.e. if code == NOCPS
2398 * ignore else retry next time) but the problem is that
2399 * there're other errors (i.e. EPERM) for which we don't
2400 * want to retry and we don't know the whole code list!
2402 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2406 /* the disabling of system:administrators is so iffy and has so many
2407 * possible failure modes that we will disable it again */
2408 /* Turn off System:Administrator for safety
2409 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2410 * assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2413 /* Now, tcon may already be set to a rock, since we blocked with no host
2414 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2415 * required). So, before setting the RPC's rock, we should disconnect
2416 * the RPC from the other client structure's rock.
2418 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2419 if (oldClient && oldClient != client && oldClient->sid == rxr_CidOf(tcon)
2420 && oldClient->VenusEpoch == rxr_GetEpoch(tcon)) {
2422 if (!oldClient->deleted) {
2423 /* if we didn't create it, it's not ours to put back */
2425 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2426 "conn %p (host %s:%d) had client %p(%x)\n",
2427 client, client->sid, tcon,
2428 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2429 ntohs(rxr_PortOf(tcon)),
2430 oldClient, oldClient->sid));
2431 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2432 free(client->CPS.prlist_val);
2433 client->CPS.prlist_val = NULL;
2434 client->CPS.prlist_len = 0;
2436 /* We should perhaps check for 0 here */
2438 ReleaseWriteLock(&client->lock);
2443 oldClient->refCount++;
2445 ObtainWriteLock(&oldClient->lock);
2449 ViceLog(0, ("FindClient: deleted client %p(%x) already had "
2450 "conn %p (host %s:%d), stolen by client %p(%x)\n",
2451 oldClient, oldClient->sid, tcon,
2452 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2453 ntohs(rxr_PortOf(tcon)),
2454 client, client->sid));
2455 /* rx_SetSpecific will be done immediately below */
2458 /* Avoid chaining in more than once. */
2462 if (host->hostFlags & HOSTDELETED) {
2467 client->host = NULL;
2469 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2470 free(client->CPS.prlist_val);
2471 client->CPS.prlist_val = NULL;
2472 client->CPS.prlist_len = 0;
2475 ReleaseWriteLock(&client->lock);
2480 client->next = host->FirstClient;
2481 host->FirstClient = client;
2483 CurrentConnections++; /* increment number of connections */
2485 rx_SetSpecific(tcon, rxcon_client_key, client);
2486 ReleaseWriteLock(&client->lock);
2490 } /*h_FindClient_r */
2493 h_ReleaseClient_r(struct client *client)
2495 assert(client->refCount > 0);
2502 * Sigh: this one is used to get the client AGAIN within the individual
2503 * server routines. This does not bother h_Holding the host, since
2504 * this is assumed already have been done by the server main loop.
2505 * It does check tokens, since only the server routines can return the
2506 * VICETOKENDEAD error code
2509 GetClient(struct rx_connection *tcon, struct client **cp)
2511 register struct client *client;
2516 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2517 if (client == NULL) {
2519 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2520 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2521 ntohs(rxr_PortOf(tcon))));
2525 if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2527 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2528 tcon, rxr_CidOf(tcon), client->sid));
2532 if (client && client->LastCall > client->expTime && client->expTime) {
2534 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2535 afs_inet_ntoa_r(client->host->host, hoststr),
2536 ntohs(client->host->port), client->expTime));
2538 return VICETOKENDEAD;
2548 PutClient(struct client **cp)
2554 h_ReleaseClient_r(*cp);
2561 /* Client user name for short term use. Note that this is NOT inexpensive */
2563 h_UserName(struct client *client)
2565 static char User[PR_MAXNAMELEN + 1];
2569 lids.idlist_len = 1;
2570 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2571 if (!lids.idlist_val) {
2572 ViceLog(0, ("Failed malloc in h_UserName\n"));
2575 lnames.namelist_len = 0;
2576 lnames.namelist_val = (prname *) 0;
2577 lids.idlist_val[0] = client->ViceId;
2578 if (hpr_IdToName(&lids, &lnames)) {
2579 /* We need to free id we alloced above! */
2580 free(lids.idlist_val);
2581 return "*UNKNOWN USER NAME*";
2583 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2584 free(lids.idlist_val);
2585 free(lnames.namelist_val);
2594 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2595 CEs, CEBlocks, HTs, HTBlocks));
2601 h_PrintClient(register struct host *host, int flags, void *rock)
2603 StreamHandle_t *file = (StreamHandle_t *)rock;
2604 register struct client *client;
2609 time_t LastCall, expTime;
2612 LastCall = host->LastCall;
2613 if (host->hostFlags & HOSTDELETED) {
2617 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2618 "Host %s:%d down = %d, LastCall %s",
2619 afs_inet_ntoa_r(host->host, hoststr),
2620 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2621 afs_ctime(&LastCall, tbuffer,
2623 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2624 for (client = host->FirstClient; client; client = client->next) {
2625 if (!client->deleted) {
2626 expTime = client->expTime;
2627 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2628 " user id=%d, name=%s, sl=%s till %s",
2629 client->ViceId, h_UserName(client),
2631 authClass ? "Authenticated" :
2632 "Not authenticated",
2634 authClass ? afs_ctime(&expTime, tbuffer,
2637 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2638 (void)afs_snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2639 client->CPS.prlist_len);
2640 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2641 if (client->CPS.prlist_val) {
2642 for (i = 0; i > client->CPS.prlist_len; i++) {
2643 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2644 client->CPS.prlist_val[i]);
2645 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2648 sprintf(tmpStr, "]\n");
2649 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2655 } /*h_PrintClient */
2660 * Print a list of clients, with last security level and token value seen,
2664 h_PrintClients(void)
2670 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2674 ("Couldn't create client dump file %s\n",
2675 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2678 now = FT_ApproxTime();
2679 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
2680 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2681 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2682 h_Enumerate(h_PrintClient, (char *)file);
2683 STREAM_REALLYCLOSE(file);
2684 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2691 h_DumpHost(register struct host *host, int flags, void *rock)
2693 StreamHandle_t *file = (StreamHandle_t *)rock;
2700 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2701 "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 [",
2702 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), host->index,
2703 host->cblist, CheckLock(&host->lock), host->LastCall,
2704 host->ActiveCall, (host->hostFlags & VENUSDOWN),
2705 host->hostFlags & HOSTDELETED, host->Console,
2706 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2708 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2709 if (host->hcps.prlist_val)
2710 for (i = 0; i < host->hcps.prlist_len; i++) {
2711 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2712 host->hcps.prlist_val[i]);
2713 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2715 sprintf(tmpStr, "] [");
2716 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2717 if (host->interface)
2718 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2720 sprintf(tmpStr, " %s:%d",
2721 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2722 ntohs(host->interface->interface[i].port));
2723 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2725 sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2726 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2738 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2744 ("Couldn't create host dump file %s\n",
2745 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2748 now = FT_ApproxTime();
2749 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
2750 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2751 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2752 h_Enumerate(h_DumpHost, (char *)file);
2753 STREAM_REALLYCLOSE(file);
2754 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2758 #ifdef AFS_DEMAND_ATTACH_FS
2761 * host state serialization
2763 static int h_stateFillHeader(struct host_state_header * hdr);
2764 static int h_stateCheckHeader(struct host_state_header * hdr);
2765 static int h_stateAllocMap(struct fs_dump_state * state);
2766 static int h_stateSaveHost(struct host * host, int flags, void *rock);
2767 static int h_stateRestoreHost(struct fs_dump_state * state);
2768 static int h_stateRestoreIndex(struct host * h, int flags, void *rock);
2769 static int h_stateVerifyHost(struct host * h, int flags, void *rock);
2770 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port);
2771 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2772 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2773 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2776 /* this procedure saves all host state to disk for fast startup */
2778 h_stateSave(struct fs_dump_state * state)
2780 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2783 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2785 /* invalidate host state header */
2786 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2788 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2789 sizeof(struct host_state_header))) {
2794 fs_stateIncEOF(state, sizeof(struct host_state_header));
2796 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2801 h_stateFillHeader(state->h_hdr);
2803 /* write the real header to disk */
2804 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2805 sizeof(struct host_state_header));
2812 * host state serialization
2814 * this procedure restores all host state from a disk for fast startup
2817 h_stateRestore(struct fs_dump_state * state)
2821 /* seek to the right position and read in the host state header */
2822 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2823 sizeof(struct host_state_header))) {
2828 /* check the validity of the header */
2829 if (h_stateCheckHeader(state->h_hdr)) {
2834 records = state->h_hdr->records;
2836 if (h_stateAllocMap(state)) {
2841 /* iterate over records restoring host state */
2842 for (i=0; i < records; i++) {
2843 if (h_stateRestoreHost(state) != 0) {
2854 h_stateRestoreIndices(struct fs_dump_state * state)
2856 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
2861 h_stateRestoreIndex(struct host * h, int flags, void *rock)
2863 struct fs_dump_state *state = (struct fs_dump_state *)rock;
2864 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
2865 return H_ENUMERATE_BAIL(flags);
2871 h_stateVerify(struct fs_dump_state * state)
2873 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
2878 h_stateVerifyHost(struct host * h, int flags, void* rock)
2880 struct fs_dump_state *state = (struct fs_dump_state *)rock;
2884 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
2885 return H_ENUMERATE_BAIL(flags);
2889 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
2890 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
2891 h->interface->interface[i].port)) {
2895 if (h_stateVerifyUuidHash(state, h)) {
2898 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port)) {
2902 if (cb_stateVerifyHCBList(state, h)) {
2910 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port)
2912 int ret = 0, found = 0;
2913 struct host *host = NULL;
2914 struct h_AddrHashChain *chain;
2915 int index = h_HashIndex(addr);
2919 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
2920 host = chain->hostPtr;
2922 afs_inet_ntoa_r(addr, tmp);
2923 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
2927 if ((chain->addr == addr) && (chain->port == port)) {
2929 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry points to different host struct (%d, %d)\n",
2930 h->index, host->index));
2931 state->flags.warnings_generated = 1;
2936 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
2937 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2938 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
2946 afs_inet_ntoa_r(addr, tmp);
2947 if (state->mode == FS_STATE_LOAD_MODE) {
2948 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s not found in hash\n", tmp));
2952 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s not found in hash\n", tmp));
2953 state->flags.warnings_generated = 1;
2962 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
2964 int ret = 0, found = 0;
2965 struct host *host = NULL;
2966 struct h_UuidHashChain *chain;
2967 afsUUID * uuidp = &h->interface->uuid;
2968 int index = h_UuidHashIndex(uuidp);
2972 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
2973 host = chain->hostPtr;
2975 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2976 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
2980 if (host->interface &&
2981 afs_uuid_equal(&host->interface->uuid, uuidp)) {
2983 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
2984 h->index, host->index));
2985 state->flags.warnings_generated = 1;
2990 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
2991 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2992 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3000 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3001 if (state->mode == FS_STATE_LOAD_MODE) {
3002 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3006 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3007 state->flags.warnings_generated = 1;
3015 /* create the host state header structure */
3017 h_stateFillHeader(struct host_state_header * hdr)
3019 hdr->stamp.magic = HOST_STATE_MAGIC;
3020 hdr->stamp.version = HOST_STATE_VERSION;
3024 /* check the contents of the host state header structure */
3026 h_stateCheckHeader(struct host_state_header * hdr)
3030 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3031 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3034 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3035 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3041 /* allocate the host id mapping table */
3043 h_stateAllocMap(struct fs_dump_state * state)
3045 state->h_map.len = state->h_hdr->index_max + 1;
3046 state->h_map.entries = (struct idx_map_entry_t *)
3047 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3048 return (state->h_map.entries != NULL) ? 0 : 1;
3051 /* function called by h_Enumerate to save a host to disk */
3053 h_stateSaveHost(struct host * host, int flags, void* rock)
3055 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3056 int if_len=0, hcps_len=0;
3057 struct hostDiskEntry hdsk;
3058 struct host_state_entry_header hdr;
3059 struct Interface * ifp = NULL;
3060 afs_int32 * hcps = NULL;
3061 struct iovec iov[4];
3064 memset(&hdr, 0, sizeof(hdr));
3066 if (state->h_hdr->index_max < host->index) {
3067 state->h_hdr->index_max = host->index;
3070 h_hostToDiskEntry_r(host, &hdsk);
3071 if (host->interface) {
3072 if_len = sizeof(struct Interface) +
3073 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3074 ifp = (struct Interface *) malloc(if_len);
3075 assert(ifp != NULL);
3076 memcpy(ifp, host->interface, if_len);
3077 hdr.interfaces = host->interface->numberOfInterfaces;
3078 iov[iovcnt].iov_base = (char *) ifp;
3079 iov[iovcnt].iov_len = if_len;
3082 if (host->hcps.prlist_val) {
3083 hdr.hcps = host->hcps.prlist_len;
3084 hcps_len = hdr.hcps * sizeof(afs_int32);
3085 hcps = (afs_int32 *) malloc(hcps_len);
3086 assert(hcps != NULL);
3087 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3088 iov[iovcnt].iov_base = (char *) hcps;
3089 iov[iovcnt].iov_len = hcps_len;
3093 if (hdsk.index > state->h_hdr->index_max)
3094 state->h_hdr->index_max = hdsk.index;
3096 hdr.len = sizeof(struct host_state_entry_header) +
3097 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3098 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3100 iov[0].iov_base = (char *) &hdr;
3101 iov[0].iov_len = sizeof(hdr);
3102 iov[1].iov_base = (char *) &hdsk;
3103 iov[1].iov_len = sizeof(struct hostDiskEntry);
3105 if (fs_stateWriteV(state, iov, iovcnt)) {
3106 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3110 fs_stateIncEOF(state, hdr.len);
3112 state->h_hdr->records++;
3119 return H_ENUMERATE_BAIL(flags);
3124 /* restores a host from disk */
3126 h_stateRestoreHost(struct fs_dump_state * state)
3128 int ifp_len=0, hcps_len=0, bail=0;
3129 struct host_state_entry_header hdr;
3130 struct hostDiskEntry hdsk;
3131 struct host *host = NULL;
3132 struct Interface *ifp = NULL;
3133 afs_int32 * hcps = NULL;
3134 struct iovec iov[3];
3137 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3138 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3144 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3145 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3151 iov[0].iov_base = (char *) &hdsk;
3152 iov[0].iov_len = sizeof(struct hostDiskEntry);
3154 if (hdr.interfaces) {
3155 ifp_len = sizeof(struct Interface) +
3156 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3157 ifp = (struct Interface *) malloc(ifp_len);
3158 assert(ifp != NULL);
3159 iov[iovcnt].iov_base = (char *) ifp;
3160 iov[iovcnt].iov_len = ifp_len;
3164 hcps_len = hdr.hcps * sizeof(afs_int32);
3165 hcps = (afs_int32 *) malloc(hcps_len);
3166 assert(hcps != NULL);
3167 iov[iovcnt].iov_base = (char *) hcps;
3168 iov[iovcnt].iov_len = hcps_len;
3172 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3173 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3178 if (fs_stateReadV(state, iov, iovcnt)) {
3179 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3184 if (!hdr.hcps && hdsk.hcps_valid) {
3185 /* valid, zero-length host cps ; does this ever happen? */
3186 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3187 assert(hcps != NULL);
3191 assert(host != NULL);
3194 host->interface = ifp;
3197 host->hcps.prlist_val = hcps;
3198 host->hcps.prlist_len = hdr.hcps;
3201 h_diskEntryToHost_r(&hdsk, host);
3202 h_SetupCallbackConn_r(host);
3204 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3207 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3208 if (ifp->interface[i].valid &&
3209 !(ifp->interface[i].addr == host->host &&
3210 ifp->interface[i].port == host->port)) {
3211 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3212 ifp->interface[i].port,
3216 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3218 h_InsertList_r(host);
3220 /* setup host id map entry */
3221 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3222 state->h_map.entries[hdsk.index].new_idx = host->index;
3234 /* serialize a host structure to disk */
3236 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3238 out->host = in->host;
3239 out->port = in->port;
3240 out->hostFlags = in->hostFlags;
3241 out->Console = in->Console;
3242 out->hcpsfailed = in->hcpsfailed;
3243 out->LastCall = in->LastCall;
3244 out->ActiveCall = in->ActiveCall;
3245 out->cpsCall = in->cpsCall;
3246 out->cblist = in->cblist;
3247 #ifdef FS_STATS_DETAILED
3248 out->InSameNetwork = in->InSameNetwork;
3251 /* special fields we save, but are not memcpy'd back on restore */
3252 out->index = in->index;
3253 out->hcps_len = in->hcps.prlist_len;
3254 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3257 /* restore a host structure from disk */
3259 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3261 out->host = in->host;
3262 out->port = in->port;
3263 out->hostFlags = in->hostFlags;
3264 out->Console = in->Console;
3265 out->hcpsfailed = in->hcpsfailed;
3266 out->LastCall = in->LastCall;
3267 out->ActiveCall = in->ActiveCall;
3268 out->cpsCall = in->cpsCall;
3269 out->cblist = in->cblist;
3270 #ifdef FS_STATS_DETAILED
3271 out->InSameNetwork = in->InSameNetwork;
3275 /* index translation routines */
3277 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3281 /* hosts use a zero-based index, so old==0 is valid */
3283 if (old >= state->h_map.len) {
3284 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3286 } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
3287 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3290 *new = state->h_map.entries[old].new_idx;
3295 #endif /* AFS_DEMAND_ATTACH_FS */
3299 * This counts the number of workstations, the number of active workstations,
3300 * and the number of workstations declared "down" (i.e. not heard from
3301 * recently). An active workstation has received a call since the cutoff
3302 * time argument passed.
3305 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3307 register struct host *host;
3308 register int num = 0, active = 0, del = 0;
3312 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3313 if (!(host->hostFlags & HOSTDELETED)) {
3315 if (host->ActiveCall > cutofftime)
3317 if (host->hostFlags & VENUSDOWN)
3321 if (count != hostCount) {
3322 ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3323 } else if (host != NULL) {
3324 ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3325 ShutDownAndCore(PANIC);
3335 } /*h_GetWorkStats */
3338 /*------------------------------------------------------------------------
3339 * PRIVATE h_ClassifyAddress
3342 * Given a target IP address and a candidate IP address (both
3343 * in host byte order), classify the candidate into one of three
3344 * buckets in relation to the target by bumping the counters passed
3348 * a_targetAddr : Target address.
3349 * a_candAddr : Candidate address.
3350 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3351 * addresses are either in the same network
3352 * or the same subnet.
3353 * a_diffSubnetP : ...when the candidate is in a different
3355 * a_diffNetworkP : ...when the candidate is in a different
3362 * The target and candidate addresses are both in host byte
3363 * order, NOT network byte order, when passed in.
3367 *------------------------------------------------------------------------*/
3370 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3371 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3372 afs_int32 * a_diffNetworkP)
3373 { /*h_ClassifyAddress */
3375 afs_uint32 targetNet;
3376 afs_uint32 targetSubnet;
3378 afs_uint32 candSubnet;
3381 * Put bad values into the subnet info to start with.
3383 targetSubnet = (afs_uint32) 0;
3384 candSubnet = (afs_uint32) 0;
3387 * Pull out the network and subnetwork numbers from the target
3388 * and candidate addresses. We can short-circuit this whole
3389 * affair if the target and candidate addresses are not of the
3392 if (IN_CLASSA(a_targetAddr)) {
3393 if (!(IN_CLASSA(a_candAddr))) {
3394 (*a_diffNetworkP)++;
3397 targetNet = a_targetAddr & IN_CLASSA_NET;
3398 candNet = a_candAddr & IN_CLASSA_NET;
3399 if (IN_SUBNETA(a_targetAddr))
3400 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3401 if (IN_SUBNETA(a_candAddr))
3402 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3403 } else if (IN_CLASSB(a_targetAddr)) {
3404 if (!(IN_CLASSB(a_candAddr))) {
3405 (*a_diffNetworkP)++;
3408 targetNet = a_targetAddr & IN_CLASSB_NET;
3409 candNet = a_candAddr & IN_CLASSB_NET;
3410 if (IN_SUBNETB(a_targetAddr))
3411 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3412 if (IN_SUBNETB(a_candAddr))
3413 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3414 } /*Class B target */
3415 else if (IN_CLASSC(a_targetAddr)) {
3416 if (!(IN_CLASSC(a_candAddr))) {
3417 (*a_diffNetworkP)++;
3420 targetNet = a_targetAddr & IN_CLASSC_NET;
3421 candNet = a_candAddr & IN_CLASSC_NET;
3424 * Note that class C addresses can't have subnets,
3425 * so we leave the defaults untouched.
3427 } /*Class C target */
3429 targetNet = a_targetAddr;
3430 candNet = a_candAddr;
3431 } /*Class D address */
3434 * Now, simply compare the extracted net and subnet values for
3435 * the two addresses (which at this point are known to be of the
3438 if (targetNet == candNet) {
3439 if (targetSubnet == candSubnet)
3440 (*a_sameNetOrSubnetP)++;
3444 (*a_diffNetworkP)++;
3446 } /*h_ClassifyAddress */
3449 /*------------------------------------------------------------------------
3450 * EXPORTED h_GetHostNetStats
3453 * Iterate through the host table, and classify each (non-deleted)
3454 * host entry into ``proximity'' categories (same net or subnet,
3455 * different subnet, different network).
3458 * a_numHostsP : Set to total number of (non-deleted) hosts.
3459 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3460 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3461 * a_diffNetworkP : Set to # hosts on diff network as server.
3467 * We only count non-deleted hosts. The storage pointed to by our
3468 * parameters is zeroed upon entry.
3472 *------------------------------------------------------------------------*/
3475 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3476 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3477 { /*h_GetHostNetStats */
3479 register struct host *hostP; /*Ptr to current host entry */
3480 register afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3484 * Clear out the storage pointed to by our parameters.
3486 *a_numHostsP = (afs_int32) 0;
3487 *a_sameNetOrSubnetP = (afs_int32) 0;
3488 *a_diffSubnetP = (afs_int32) 0;
3489 *a_diffNetworkP = (afs_int32) 0;
3492 for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3493 if (!(hostP->hostFlags & HOSTDELETED)) {
3495 * Bump the number of undeleted host entries found.
3496 * In classifying the current entry's address, make
3497 * sure to first convert to host byte order.
3500 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3501 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3502 a_sameNetOrSubnetP, a_diffSubnetP,
3504 } /*Only look at non-deleted hosts */
3505 } /*For each host record hashed to this index */
3506 if (count != hostCount) {
3507 ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3508 } else if (hostP != NULL) {
3509 ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3510 ShutDownAndCore(PANIC);
3513 } /*h_GetHostNetStats */
3515 static afs_uint32 checktime;
3516 static afs_uint32 clientdeletetime;
3517 static struct AFSFid zerofid;
3521 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3522 * Since it can serialize them, and pile up, it should be a separate LWP
3523 * from other events.
3527 CheckHost(register struct host *host, int flags, void *rock)
3529 register struct client *client;
3530 struct rx_connection *cb_conn = NULL;
3533 #ifdef AFS_DEMAND_ATTACH_FS
3534 /* kill the checkhost lwp ASAP during shutdown */
3536 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3538 return H_ENUMERATE_BAIL(flags);
3543 /* Host is held by h_Enumerate */
3545 for (client = host->FirstClient; client; client = client->next) {
3546 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3547 client->deleted = 1;
3548 host->hostFlags |= CLIENTDELETED;
3551 if (host->LastCall < checktime) {
3553 if (!(host->hostFlags & HOSTDELETED)) {
3554 host->hostFlags |= HWHO_INPROGRESS;
3555 cb_conn = host->callback_rxcon;
3556 rx_GetConnection(cb_conn);
3557 if (host->LastCall < clientdeletetime) {
3558 host->hostFlags |= HOSTDELETED;
3559 if (!(host->hostFlags & VENUSDOWN)) {
3560 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3561 if (host->interface) {
3564 RXAFSCB_InitCallBackState3(cb_conn,
3570 RXAFSCB_InitCallBackState(cb_conn);
3573 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3576 (void)afs_inet_ntoa_r(host->host, hoststr);
3578 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3579 hoststr, ntohs(host->port)));
3580 host->hostFlags |= VENUSDOWN;
3582 /* Note: it's safe to delete hosts even if they have call
3583 * back state, because break delayed callbacks (called when a
3584 * message is received from the workstation) will always send a
3585 * break all call backs to the workstation if there is no
3590 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3592 (void)afs_inet_ntoa_r(host->host, hoststr);
3593 if (host->interface) {
3594 afsUUID uuid = host->interface->uuid;
3596 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3599 if (MultiProbeAlternateAddress_r(host)) {
3600 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3601 hoststr, ntohs(host->port), code));
3602 host->hostFlags |= VENUSDOWN;
3607 code = RXAFSCB_Probe(cb_conn);
3611 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3612 hoststr, ntohs(host->port), code));
3613 host->hostFlags |= VENUSDOWN;
3619 rx_PutConnection(cb_conn);
3622 host->hostFlags &= ~HWHO_INPROGRESS;
3633 CheckHost_r(register struct host *host, int flags, void *dummy)
3635 register struct client *client;
3636 struct rx_connection *cb_conn = NULL;
3639 #ifdef AFS_DEMAND_ATTACH_FS
3640 /* kill the checkhost lwp ASAP during shutdown */
3642 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3644 return H_ENUMERATE_BAIL(flags);
3649 /* Host is held by h_Enumerate_r */
3650 for (client = host->FirstClient; client; client = client->next) {
3651 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3652 client->deleted = 1;
3653 host->hostFlags |= CLIENTDELETED;
3656 if (host->LastCall < checktime) {
3658 if (!(host->hostFlags & HOSTDELETED)) {
3659 cb_conn = host->callback_rxcon;
3660 rx_GetConnection(cb_conn);
3661 if (host->LastCall < clientdeletetime) {
3662 host->hostFlags |= HOSTDELETED;
3663 if (!(host->hostFlags & VENUSDOWN)) {
3664 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3665 if (host->interface) {
3668 RXAFSCB_InitCallBackState3(cb_conn,
3674 RXAFSCB_InitCallBackState(cb_conn);
3677 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3680 (void)afs_inet_ntoa_r(host->host, hoststr);
3682 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3683 hoststr, ntohs(host->port)));
3684 host->hostFlags |= VENUSDOWN;
3686 /* Note: it's safe to delete hosts even if they have call
3687 * back state, because break delayed callbacks (called when a
3688 * message is received from the workstation) will always send a
3689 * break all call backs to the workstation if there is no
3694 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3696 (void)afs_inet_ntoa_r(host->host, hoststr);
3697 if (host->interface) {
3698 afsUUID uuid = host->interface->uuid;
3700 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3703 if (MultiProbeAlternateAddress_r(host)) {
3704 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3705 hoststr, ntohs(host->port), code));
3706 host->hostFlags |= VENUSDOWN;
3711 code = RXAFSCB_Probe(cb_conn);
3715 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3716 hoststr, ntohs(host->port), code));
3717 host->hostFlags |= VENUSDOWN;
3723 rx_PutConnection(cb_conn);
3735 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3736 * don't respond to a probe. Note that VenusDown can only be cleared if
3737 * a message is received from the host (see ServerLWP in file.c).
3738 * Delete hosts that have not had any calls in 1 hour, clients that
3739 * have not had any calls in 15 minutes.
3741 * This routine is called roughly every 5 minutes.
3746 afs_uint32 now = FT_ApproxTime();
3748 memset(&zerofid, 0, sizeof(zerofid));
3750 * Send a probe to the workstation if it hasn't been heard from in
3753 checktime = now - 15 * 60;
3754 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3757 h_Enumerate_r(CheckHost_r, hostList, NULL);
3762 * This is called with host locked and held. At this point, the
3763 * hostAddrHashTable has an entry for the primary addr/port inserted
3764 * by h_Alloc_r(). No other interfaces should be considered valid.
3766 * The addresses in the interfaceAddr list are in host byte order.
3769 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3776 struct Interface *interface;
3779 afs_uint16 port7001 = htons(7001);
3784 number = interf->numberOfInterfaces;
3785 myAddr = host->host; /* current interface address */
3786 myPort = host->port; /* current port */
3789 ("initInterfaceAddr : host %s:%d numAddr %d\n",
3790 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3792 /* validation checks */
3793 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3795 ("Invalid number of alternate addresses is %d\n", number));
3800 * The client's notion of its own IP addresses is not reliable.
3802 * 1. The client list might contain private address ranges which
3803 * are likely to be re-used by many clients allocated addresses
3806 * 2. The client list will not include any public addresses that
3807 * are hidden by a NAT.
3809 * 3. Private address ranges that are exposed to the server will
3810 * be obtained from the rx connections that use them.
3812 * 4. Lists provided by the client are not necessarily truthful.
3813 * Many existing clients (UNIX) do not refresh the IP address
3814 * list as the actual assigned addresses change. The end result
3815 * is that they report the initial address list for the lifetime
3816 * of the process. In other words, a client can report addresses
3817 * that they are in fact not using. Adding these addresses to
3818 * the host interface list without verification is not only
3819 * pointless, it is downright dangerous.
3821 * We therefore do not add alternate addresses to the addr hash table.
3822 * We only use them for multi-rx callback breaks.
3826 * Convert IP addresses to network byte order, and remove
3827 * duplicate IP addresses from the interface list, and
3828 * determine whether or not the incoming addr/port is
3829 * listed. Note that if the address matches it is not
3830 * truly a match because the port number for the entries
3831 * in the interface list are port 7001 and the port number
3832 * for this connection might not be 7001.
3834 for (i = 0, count = 0, found = 0; i < number; i++) {
3835 interf->addr_in[i] = htonl(interf->addr_in[i]);
3836 for (j = 0; j < count; j++) {
3837 if (interf->addr_in[j] == interf->addr_in[i])
3841 interf->addr_in[count] = interf->addr_in[i];
3842 if (interf->addr_in[count] == myAddr &&
3850 * Allocate and initialize an interface structure for this host.
3853 interface = (struct Interface *)
3854 malloc(sizeof(struct Interface) +
3855 (sizeof(struct AddrPort) * (count - 1)));
3857 ViceLog(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
3860 interface->numberOfInterfaces = count;
3862 interface = (struct Interface *)
3863 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
3865 ViceLog(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
3868 interface->numberOfInterfaces = count + 1;
3869 interface->interface[count].addr = myAddr;
3870 interface->interface[count].port = myPort;
3871 interface->interface[count].valid = 1;
3874 for (i = 0; i < count; i++) {
3876 interface->interface[i].addr = interf->addr_in[i];
3877 /* We store the port as 7001 because the addresses reported by
3878 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
3879 * are coming from fully connected hosts (no NAT/PATs)
3881 interface->interface[i].port = port7001;
3882 interface->interface[i].valid =
3883 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
3886 interface->uuid = interf->uuid;
3888 assert(!host->interface);
3889 host->interface = interface;
3891 if (LogLevel >= 125) {
3892 afsUUID_to_string(&interface->uuid, uuidstr, 127);
3894 ViceLog(125, ("--- uuid %s\n", uuidstr));
3895 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
3896 ViceLog(125, ("--- alt address %s:%d\n",
3897 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3898 ntohs(host->interface->interface[i].port)));
3905 /* deleted a HashChain structure for this address and host */
3906 /* returns 1 on success */
3908 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
3912 register struct h_AddrHashChain **hp, *th;
3914 if (addr == 0 && port == 0)
3917 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
3919 assert(th->hostPtr);
3920 if (th->hostPtr == host && th->addr == addr && th->port == port) {
3921 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
3922 host, afs_inet_ntoa_r(host->host, hoststr),
3923 ntohs(host->port)));
3930 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
3931 host, afs_inet_ntoa_r(host->host, hoststr),
3932 ntohs(host->port)));
3938 ** prints out all alternate interface address for the host. The 'level'
3939 ** parameter indicates what level of debugging sets this output
3942 printInterfaceAddr(struct host *host, int level)
3947 if (host->interface) {
3948 /* check alternate addresses */
3949 number = host->interface->numberOfInterfaces;
3951 ViceLog(level, ("no-addresses "));
3953 for (i = 0; i < number; i++)
3954 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3955 ntohs(host->interface->interface[i].port)));
3958 ViceLog(level, ("\n"));