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>
19 #ifdef HAVE_SYS_FILE_H
26 #include <afs/afsint.h>
27 #define FSINT_COMMON_XG
28 #include <afs/afscbint.h>
29 #include <afs/rxgen_consts.h>
31 #include <afs/errors.h>
32 #include <afs/ihandle.h>
33 #include <afs/vnode.h>
34 #include <afs/volume.h>
35 #ifdef AFS_ATHENA_STDENV
39 #include <afs/ptclient.h>
40 #include <afs/ptuser.h>
41 #include <afs/prs_fs.h>
43 #include <afs/afsutil.h>
44 #include <afs/com_err.h>
46 #include <afs/cellconfig.h>
47 #include "viced_prototypes.h"
51 #ifdef AFS_DEMAND_ATTACH_FS
52 #include "../util/afsutil_prototypes.h"
53 #include "serialize_state.h"
54 #endif /* AFS_DEMAND_ATTACH_FS */
56 pthread_mutex_t host_glock_mutex;
59 extern int CurrentConnections;
61 extern int AnonymousID;
62 extern prlist AnonCPS;
64 extern struct afsconf_dir *confDir; /* config dir object */
65 extern int lwps; /* the max number of server threads */
66 extern afsUUID FS_HostUUID;
69 int CEs = 0; /* active clients */
70 int CEBlocks = 0; /* number of blocks of CEs */
71 struct client *CEFree = 0; /* first free client */
72 struct host *hostList = 0; /* linked list of all hosts */
73 int hostCount = 0; /* number of hosts in hostList */
77 static struct rx_securityClass *sc = NULL;
79 static void h_SetupCallbackConn_r(struct host * host);
80 static int h_threadquota(int);
82 #define CESPERBLOCK 73
83 struct CEBlock { /* block of CESPERBLOCK file entries */
84 struct client entry[CESPERBLOCK];
87 void h_TossStuff_r(struct host *host);
90 * Make sure the subnet macros have been defined.
93 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
96 #ifndef IN_CLASSA_SUBNET
97 #define IN_CLASSA_SUBNET 0xffff0000
101 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
104 #ifndef IN_CLASSB_SUBNET
105 #define IN_CLASSB_SUBNET 0xffffff00
109 /* get a new block of CEs and chain it on CEFree */
113 struct CEBlock *block;
116 block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
118 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
119 ShutDownAndCore(PANIC);
122 for (i = 0; i < (CESPERBLOCK - 1); i++) {
123 Lock_Init(&block->entry[i].lock);
124 block->entry[i].next = &(block->entry[i + 1]);
126 block->entry[CESPERBLOCK - 1].next = 0;
127 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
128 CEFree = (struct client *)block;
134 /* get the next available CE */
135 static struct client *
138 struct client *entry;
143 ViceLog(0, ("CEFree NULL in GetCE\n"));
144 ShutDownAndCore(PANIC);
148 CEFree = entry->next;
150 memset(entry, 0, CLIENT_TO_ZERO(entry));
156 /* return an entry to the free list */
158 FreeCE(struct client *entry)
160 entry->VenusEpoch = 0;
162 entry->next = CEFree;
169 * The HTs and HTBlocks variables were formerly static, but they are
170 * now referenced elsewhere in the FileServer.
172 int HTs = 0; /* active file entries */
173 int HTBlocks = 0; /* number of blocks of HTs */
174 static struct host *HTFree = 0; /* first free file entry */
177 * Hash tables of host pointers. We need two tables, one
178 * to map IP addresses onto host pointers, and another
179 * to map host UUIDs onto host pointers.
181 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
182 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
183 #define h_HashIndex(hostip) (ntohl(hostip) & (h_HASHENTRIES-1))
184 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
186 struct HTBlock { /* block of HTSPERBLOCK file entries */
187 struct host entry[h_HTSPERBLOCK];
191 /* get a new block of HTs and chain it on HTFree */
195 struct HTBlock *block;
197 static int index = 0;
199 if (HTBlocks == h_MAXHOSTTABLES) {
200 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
204 block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
206 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
207 ShutDownAndCore(PANIC);
209 for (i = 0; i < (h_HTSPERBLOCK); i++)
210 CV_INIT(&block->entry[i].cond, "block entry", CV_DEFAULT, 0);
211 for (i = 0; i < (h_HTSPERBLOCK); i++)
212 Lock_Init(&block->entry[i].lock);
213 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
214 block->entry[i].next = &(block->entry[i + 1]);
215 for (i = 0; i < (h_HTSPERBLOCK); i++)
216 block->entry[i].index = index++;
217 block->entry[h_HTSPERBLOCK - 1].next = 0;
218 HTFree = (struct host *)block;
219 hosttableptrs[HTBlocks++] = block->entry;
224 /* get the next available HT */
235 HTFree = entry->next;
237 memset(entry, 0, HOST_TO_ZERO(entry));
243 /* return an entry to the free list */
245 FreeHT(struct host *entry)
247 entry->next = HTFree;
254 hpr_Initialize(struct ubik_client **uclient)
257 struct rx_connection *serverconns[MAXSERVERS];
258 struct rx_securityClass *sc;
259 struct afsconf_dir *tdir;
261 struct afsconf_cell info;
265 tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
267 ViceLog(0, ("hpr_Initialize: Could not open configuration directory: %s", AFSDIR_SERVER_ETC_DIRPATH));
271 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
273 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
278 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
280 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s",
281 cellstr, confDir->name, AFSDIR_CELLSERVDB_FILE));
288 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
293 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
294 * to force use of the KeyFile. secLevel == 0 implies -noauth was
296 code = afsconf_ClientAuthSecure(tdir, &sc, &scIndex);
298 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s "
299 "(so trying noauth)", code, afs_error_message(code)));
300 scIndex = RX_SECIDX_NULL;
301 sc = rxnull_NewClientSecurityObject();
304 if (scIndex == RX_SECIDX_NULL)
305 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, "
306 "running unauthenticated. [%d]", code));
308 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
309 for (i = 0; i < info.numServers; i++) {
311 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
312 info.hostAddr[i].sin_port, PRSRV,
316 code = ubik_ClientInit(serverconns, uclient);
318 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
321 code = rxs_Release(sc);
326 hpr_End(struct ubik_client *uclient)
331 code = ubik_ClientDestroy(uclient);
337 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
341 struct ubik_client *uclient =
342 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
345 code = hpr_Initialize(&uclient);
347 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
353 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
354 if (code != PRSUCCESS)
357 /* do something about this, probably make a new call */
358 /* don't forget there's a hard limit in the interface */
360 "membership list for host id %d exceeds display limit\n",
367 hpr_NameToId(namelist *names, idlist *ids)
371 struct ubik_client *uclient =
372 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
375 code = hpr_Initialize(&uclient);
377 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
382 for (i = 0; i < names->namelist_len; i++)
383 stolower(names->namelist_val[i]);
384 code = ubik_PR_NameToID(uclient, 0, names, ids);
389 hpr_IdToName(idlist *ids, namelist *names)
392 struct ubik_client *uclient =
393 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
396 code = hpr_Initialize(&uclient);
398 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
403 code = ubik_PR_IDToName(uclient, 0, ids, names);
408 hpr_GetCPS(afs_int32 id, prlist *CPS)
412 struct ubik_client *uclient =
413 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
416 code = hpr_Initialize(&uclient);
418 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
424 code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
425 if (code != PRSUCCESS)
428 /* do something about this, probably make a new call */
429 /* don't forget there's a hard limit in the interface */
430 fprintf(stderr, "membership list for id %d exceeds display limit\n",
436 static short consolePort = 0;
439 h_Lock_r(struct host *host)
449 * returns 1 if already locked
450 * else returns locks and returns 0
454 h_NBLock_r(struct host *host)
456 struct Lock *hostLock = &host->lock;
461 if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
462 hostLock->excl_locked = WRITE_LOCK;
466 LOCK_UNLOCK(hostLock);
475 /*------------------------------------------------------------------------
476 * PRIVATE h_AddrInSameNetwork
479 * Given a target IP address and a candidate IP address (both
480 * in host byte order), return a non-zero value (1) if the
481 * candidate address is in a different network from the target
485 * a_targetAddr : Target address.
486 * a_candAddr : Candidate address.
489 * 1 if the candidate address is in the same net as the target,
493 * The target and candidate addresses are both in host byte
494 * order, NOT network byte order, when passed in. We return
495 * our value as a character, since that's the type of field in
496 * the host structure, where this info will be stored.
500 *------------------------------------------------------------------------*/
503 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
504 { /*h_AddrInSameNetwork */
506 afs_uint32 targetNet;
510 * Pull out the network and subnetwork numbers from the target
511 * and candidate addresses. We can short-circuit this whole
512 * affair if the target and candidate addresses are not of the
515 if (IN_CLASSA(a_targetAddr)) {
516 if (!(IN_CLASSA(a_candAddr))) {
519 targetNet = a_targetAddr & IN_CLASSA_NET;
520 candNet = a_candAddr & IN_CLASSA_NET;
521 } else if (IN_CLASSB(a_targetAddr)) {
522 if (!(IN_CLASSB(a_candAddr))) {
525 targetNet = a_targetAddr & IN_CLASSB_NET;
526 candNet = a_candAddr & IN_CLASSB_NET;
527 } /*Class B target */
528 else if (IN_CLASSC(a_targetAddr)) {
529 if (!(IN_CLASSC(a_candAddr))) {
532 targetNet = a_targetAddr & IN_CLASSC_NET;
533 candNet = a_candAddr & IN_CLASSC_NET;
534 } /*Class C target */
536 targetNet = a_targetAddr;
537 candNet = a_candAddr;
538 } /*Class D address */
541 * Now, simply compare the extracted net values for the two addresses
542 * (which at this point are known to be of the same class)
544 if (targetNet == candNet)
549 } /*h_AddrInSameNetwork */
552 /* Assumptions: called with held host */
554 h_gethostcps_r(struct host *host, afs_int32 now)
559 /* wait if somebody else is already doing the getCPS call */
560 while (host->hostFlags & HCPS_INPROGRESS) {
561 slept = 1; /* I did sleep */
562 host->hostFlags |= HCPS_WAITING; /* I am sleeping now */
563 CV_WAIT(&host->cond, &host_glock_mutex);
567 host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
568 if (host->hcps.prlist_val)
569 free(host->hcps.prlist_val); /* this is for hostaclRefresh */
570 host->hcps.prlist_val = NULL;
571 host->hcps.prlist_len = 0;
572 host->cpsCall = slept ? (FT_ApproxTime()) : (now);
575 code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
580 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
581 * and reevaluates things if no sync server or quorum is found we could still end up
582 * with one of these errors. In such case we would like to reevaluate the rpc call to
583 * find if there's cps for this guy. We treat other errors (except network failures
584 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
585 * we could like to deal this problem the other way around (i.e. if code == NOCPS
586 * ignore else retry next time) but the problem is that there're other errors (i.e.
587 * EPERM) for which we don't want to retry and we don't know the whole code list!
589 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
591 * We would have preferred to use a while loop and try again since ops in protected
592 * acls for this host will fail now but they'll be reevaluated on any subsequent
593 * call. The attempt to wait for a quorum/sync site or network error won't work
594 * since this problems really should only occurs during a complete fileserver
595 * restart. Since the fileserver will start before the ptservers (and thus before
596 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
598 host->hcpsfailed = 1;
600 ("Warning: GetHostCPS failed (%d) for %p (%s:%d); will retry\n",
601 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
603 host->hcpsfailed = 0;
605 ("gethost: GetHostCPS failed (%d) for %p (%s:%d); ignored\n",
606 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
608 if (host->hcps.prlist_val)
609 free(host->hcps.prlist_val);
610 host->hcps.prlist_val = NULL;
611 host->hcps.prlist_len = 0; /* Make sure it's zero */
613 host->hcpsfailed = 0;
615 host->hostFlags &= ~HCPS_INPROGRESS;
616 /* signal all who are waiting */
617 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
618 host->hostFlags &= ~HCPS_WAITING;
619 CV_BROADCAST(&host->cond);
623 /* args in net byte order */
625 h_flushhostcps(afs_uint32 hostaddr, afs_uint16 hport)
630 h_Lookup_r(hostaddr, hport, &host);
632 host->hcpsfailed = 1;
641 * Allocate a host. It will be identified by the peer (ip,port) info in the
642 * rx connection provided. The host is returned held and locked
644 #define DEF_ROPCONS 2115
647 h_Alloc_r(struct rx_connection *r_con)
649 struct servent *serverentry;
651 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
657 host->host = rxr_HostOf(r_con);
658 host->port = rxr_PortOf(r_con);
660 h_AddHostToAddrHashTable_r(host->host, host->port, host);
662 if (consolePort == 0) { /* find the portal number for console */
663 #if defined(AFS_OSF_ENV)
664 serverentry = getservbyname("ropcons", "");
666 serverentry = getservbyname("ropcons", 0);
669 consolePort = serverentry->s_port;
671 consolePort = htons(DEF_ROPCONS); /* Use a default */
673 if (host->port == consolePort)
675 /* Make a callback channel even for the console, on the off chance that it
676 * makes a request that causes a break call back. It shouldn't. */
677 h_SetupCallbackConn_r(host);
678 host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
680 host->hcps.prlist_val = NULL;
681 host->hcps.prlist_len = 0;
682 host->interface = NULL;
684 host->hcpsfailed = 0; /* save cycles */
685 h_gethostcps(host); /* do this under host hold/lock */
687 host->FirstClient = NULL;
690 h_InsertList_r(host); /* update global host List */
692 * Compare the new host's IP address (in host byte order) with ours
693 * (the File Server's), remembering if they are in the same network.
695 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
696 host->InSameNetwork =
697 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
704 /* Make a callback channel even for the console, on the off chance that it
705 * makes a request that causes a break call back. It shouldn't. */
707 h_SetupCallbackConn_r(struct host * host)
710 sc = rxnull_NewClientSecurityObject();
711 host->callback_rxcon =
712 rx_NewConnection(host->host, host->port, 1, sc, 0);
713 rx_SetConnDeadTime(host->callback_rxcon, 50);
714 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
715 rx_SetConnSecondsUntilNatPing(host->callback_rxcon, 20);
719 * Lookup a host given an IP address and UDP port number.
720 * hostaddr and hport are in network order
721 * hostaddr and hport are in network order
722 * On return, refCount is incremented.
725 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, struct host **hostp)
728 struct host *host = NULL;
729 struct h_AddrHashChain *chain;
730 int index = h_HashIndex(haddr);
731 extern int hostaclRefresh;
734 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
735 host = chain->hostPtr;
737 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
738 && chain->port == hport) {
739 if ((host->hostFlags & HWHO_INPROGRESS) &&
740 h_threadquota(host->lock.num_waiting)) {
746 if (host->hostFlags & HOSTDELETED) {
753 now = FT_ApproxTime(); /* always evaluate "now" */
754 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
756 * Every hostaclRefresh period (def 2 hrs) get the new
757 * membership list for the host. Note this could be the
758 * first time that the host is added to a group. Also
759 * here we also retry on previous legitimate hcps failures.
761 * If we get here refCount is elevated.
763 h_gethostcps_r(host, now);
773 /* Lookup a host given its UUID. */
775 h_LookupUuid_r(afsUUID * uuidp)
777 struct host *host = 0;
778 struct h_UuidHashChain *chain;
779 int index = h_UuidHashIndex(uuidp);
781 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
782 host = chain->hostPtr;
784 if (!(host->hostFlags & HOSTDELETED) && host->interface
785 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
793 /* h_TossStuff_r: Toss anything in the host structure (the host or
794 * clients marked for deletion. Called from h_Release_r ONLY.
795 * To be called, there must be no holds, and either host->deleted
796 * or host->clientDeleted must be set.
799 h_TossStuff_r(struct host *host)
801 struct client **cp, *client;
804 /* make sure host doesn't go away over h_NBLock_r */
807 code = h_NBLock_r(host);
809 /* don't use h_Release_r, since that may call h_TossStuff_r again */
812 /* if somebody still has this host locked */
816 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was locked.\n",
817 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
823 /* if somebody still has this host held */
824 /* we must check this _after_ h_NBLock_r, since h_NBLock_r can drop and
825 * reacquire H_LOCK */
826 if (host->refCount > 0) {
829 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was held.\n",
830 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
834 /* ASSUMPTION: rxi_FreeConnection() does not yield */
835 for (cp = &host->FirstClient; (client = *cp);) {
836 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
838 ObtainWriteLockNoBlock(&client->lock, code);
842 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
843 "client %p was locked.\n",
844 host, afs_inet_ntoa_r(host->host, hoststr),
845 ntohs(host->port), client));
849 if (client->refCount) {
852 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
853 "client %p refcount %d.\n",
854 host, afs_inet_ntoa_r(host->host, hoststr),
855 ntohs(host->port), client, client->refCount));
856 /* This is the same thing we do if the host is locked */
857 ReleaseWriteLock(&client->lock);
860 client->CPS.prlist_len = 0;
861 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
862 free(client->CPS.prlist_val);
863 client->CPS.prlist_val = NULL;
864 CurrentConnections--;
866 ReleaseWriteLock(&client->lock);
872 /* We've just cleaned out all the deleted clients; clear the flag */
873 host->hostFlags &= ~CLIENTDELETED;
875 if (host->hostFlags & HOSTDELETED) {
876 struct rx_connection *rxconn;
877 struct AddrPort hostAddrPort;
880 if (host->Console & 1)
882 if ((rxconn = host->callback_rxcon)) {
883 host->callback_rxcon = (struct rx_connection *)0;
884 rx_DestroyConnection(rxconn);
886 if (host->hcps.prlist_val)
887 free(host->hcps.prlist_val);
888 host->hcps.prlist_val = NULL;
889 host->hcps.prlist_len = 0;
890 DeleteAllCallBacks_r(host, 1);
891 host->hostFlags &= ~RESETDONE; /* just to be safe */
893 /* if alternate addresses do not exist */
894 if (!(host->interface)) {
895 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
897 h_DeleteHostFromUuidHashTable_r(host);
898 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
899 /* delete the hash entry for each valid alternate addresses */
900 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
901 hostAddrPort = host->interface->interface[i];
903 * if the interface addr/port is the primary, we already
904 * removed it. If the addr/port is not valid, its not
907 if (hostAddrPort.valid &&
908 (host->host != hostAddrPort.addr ||
909 host->port != hostAddrPort.port))
910 h_DeleteHostFromAddrHashTable_r(hostAddrPort.addr, hostAddrPort.port, host);
912 free(host->interface);
913 host->interface = NULL;
914 } /* if alternate address exists */
916 h_DeleteList_r(host); /* remove host from global host List */
923 /* h_Enumerate: Calls (*proc)(host, param) for at least each host in the
924 * system at the start of the enumeration (perhaps more). Hosts may be deleted
925 * (have delete flag set); ditto for clients. refCount is always incremented
926 * before (*proc) is called.
928 * The return value of the proc is a set of flags. The proc should set
929 * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
932 h_Enumerate(int (*proc) (struct host*, void *), void *param)
934 struct host *host, **list;
939 if (hostCount == 0) {
943 list = (struct host **)malloc(hostCount * sizeof(struct host *));
945 ViceLogThenPanic(0, ("Failed malloc in h_Enumerate (list)\n"));
947 for (totalCount = count = 0, host = hostList;
948 host && totalCount < hostCount;
949 host = host->next, totalCount++) {
951 if (!(host->hostFlags & HOSTDELETED)) {
957 if (totalCount != hostCount) {
958 ViceLog(0, ("h_Enumerate found %d of %d hosts\n", totalCount, hostCount));
959 } else if (host != NULL) {
960 ViceLog(0, ("h_Enumerate found more than %d hosts\n", hostCount));
961 ShutDownAndCore(PANIC);
964 for (i = 0; i < count; i++) {
966 flags = (*proc) (list[i], param);
968 h_Release_r(list[i]);
970 /* bail out of the enumeration early */
971 if (H_ENUMERATE_ISSET_BAIL(flags)) {
974 ViceLog(0, ("h_Enumerate got back invalid return value %d\n", flags));
975 ShutDownAndCore(PANIC);
979 /* we bailed out of enumerating hosts early; we still have holds on
980 * some of the hosts in 'list', so release them */
983 for ( ; i < count; i++) {
984 h_Release_r(list[i]);
992 /* h_Enumerate_r (revised):
993 * Calls (*proc)(host, param) for each host in hostList, starting
994 * at enumstart. Called only under H_LOCK. Hosts may be deleted (have
995 * delete flag set); ditto for clients. refCount is always incremented
996 * before (*proc) is called.
998 * @note Assumes that hostList is only prepended to, that a host is never
999 * inserted into the middle. Otherwise this would not be guaranteed to
1002 * The return value of the proc is a set of flags. The proc should set
1003 * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
1006 h_Enumerate_r(int (*proc) (struct host *, void *),
1007 struct host *enumstart, void *param)
1009 struct host *host, *next;
1013 if (hostCount == 0) {
1020 /* find the first non-deleted host, so we know where to actually start
1022 for (count = 0; host && count < hostCount; count++) {
1023 if (!(host->hostFlags & HOSTDELETED)) {
1030 /* we didn't find a non-deleted host... */
1032 if (host && count >= hostCount) {
1033 /* ...because we found a loop */
1034 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", hostCount));
1035 ShutDownAndCore(PANIC);
1038 /* ...because the hostList is full of deleted hosts */
1042 h_Hold_r(enumstart);
1044 /* remember hostCount, lest it change over the potential H_LOCK drop in
1046 origHostCount = hostCount;
1048 for (count = 0, host = enumstart; host && count < origHostCount; host = next, count++) {
1051 /* find the next non-deleted host */
1052 while (next && (next->hostFlags & HOSTDELETED)) {
1054 /* inc count for the skipped-over host */
1055 if (++count > origHostCount) {
1056 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1057 ShutDownAndCore(PANIC);
1063 if (!(host->hostFlags & HOSTDELETED)) {
1065 flags = (*proc) (host, param);
1066 if (H_ENUMERATE_ISSET_BAIL(flags)) {
1067 h_Release_r(host); /* this might free up the host */
1073 ViceLog(0, ("h_Enumerate_r got back invalid return value %d\n", flags));
1074 ShutDownAndCore(PANIC);
1077 h_Release_r(host); /* this might free up the host */
1079 if (host != NULL && count >= origHostCount) {
1080 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1081 ShutDownAndCore(PANIC);
1083 } /*h_Enumerate_r */
1086 /* inserts a new HashChain structure corresponding to this UUID */
1088 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1091 struct h_UuidHashChain *chain;
1092 char uuid1[128], uuid2[128];
1095 /* hash into proper bucket */
1096 index = h_UuidHashIndex(uuid);
1098 /* don't add the same entry multiple times */
1099 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1100 if (!chain->hostPtr)
1103 if (chain->hostPtr->interface &&
1104 afs_uuid_equal(&chain->hostPtr->interface->uuid, uuid)) {
1105 if (LogLevel >= 125) {
1106 afsUUID_to_string(&chain->hostPtr->interface->uuid, uuid1,
1108 afsUUID_to_string(uuid, uuid2, 127);
1109 ViceLog(125, ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s) exists as %s:%d (uuid %s)\n",
1111 afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1112 ntohs(chain->hostPtr->port), uuid2));
1118 /* insert into beginning of list for this bucket */
1119 chain = (struct h_UuidHashChain *)malloc(sizeof(struct h_UuidHashChain));
1121 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1123 chain->hostPtr = host;
1124 chain->next = hostUuidHashTable[index];
1125 hostUuidHashTable[index] = chain;
1128 afsUUID_to_string(uuid, uuid2, 127);
1130 ("h_AddHostToUuidHashTable_r: host %p (%s:%d) added as uuid %s\n",
1131 host, afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1132 ntohs(chain->hostPtr->port), uuid2));
1135 /* deletes a HashChain structure corresponding to this host */
1137 h_DeleteHostFromUuidHashTable_r(struct host *host)
1140 struct h_UuidHashChain **uhp, *uth;
1144 if (!host->interface)
1147 /* hash into proper bucket */
1148 index = h_UuidHashIndex(&host->interface->uuid);
1150 if (LogLevel >= 125)
1151 afsUUID_to_string(&host->interface->uuid, uuid1, 127);
1152 for (uhp = &hostUuidHashTable[index]; (uth = *uhp); uhp = &uth->next) {
1153 osi_Assert(uth->hostPtr);
1154 if (uth->hostPtr == host) {
1156 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d)\n",
1157 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1158 ntohs(host->port)));
1165 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d) not found\n",
1166 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1167 ntohs(host->port)));
1172 * This is called with host locked and held.
1174 * All addresses are in network byte order.
1177 invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1181 struct Interface *interface;
1182 char hoststr[16], hoststr2[16];
1185 osi_Assert(host->interface);
1187 ViceLog(125, ("invalidateInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1188 host, afs_inet_ntoa_r(host->host, hoststr),
1189 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1193 * Make sure this address is on the list of known addresses
1196 interface = host->interface;
1197 number = host->interface->numberOfInterfaces;
1198 for (i = 0; i < number; i++) {
1199 if (interface->interface[i].addr == addr &&
1200 interface->interface[i].port == port) {
1201 if (interface->interface[i].valid) {
1202 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1203 interface->interface[i].valid = 0;
1214 * This is called with host locked and held. This function differs
1215 * from removeInterfaceAddr_r in that it is called when the address
1216 * is being removed from the host regardless of whether or not there
1217 * is an interface list for the host. This function will delete the
1218 * host if there are no addresses left on it.
1220 * All addresses are in network byte order.
1223 removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1226 char hoststr[16], hoststr2[16];
1227 struct rx_connection *rxconn;
1229 if (!host->interface || host->interface->numberOfInterfaces == 1) {
1230 if (host->host == addr && host->port == port) {
1232 ("Removing only address for host %" AFS_PTR_FMT " (%s:%d), deleting host.\n",
1233 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1234 host->hostFlags |= HOSTDELETED;
1236 * Do not remove the primary addr/port from the hash table.
1237 * It will be ignored due to the HOSTDELETED flag and will
1238 * be removed when h_TossStuff_r() cleans up the HOSTDELETED
1239 * host. Removing it here will only result in a search for
1240 * the host/addr/port in the hash chain which will fail.
1244 ("Removing address that does not belong to host %" AFS_PTR_FMT " (%s:%d).\n",
1245 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1248 if (host->host == addr && host->port == port) {
1249 removeInterfaceAddr_r(host, addr, port);
1251 for (i=0; i < host->interface->numberOfInterfaces; i++) {
1252 if (host->interface->interface[i].valid) {
1254 ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
1255 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1256 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
1257 ntohs(host->interface->interface[i].port)));
1258 host->host = host->interface->interface[i].addr;
1259 host->port = host->interface->interface[i].port;
1260 h_AddHostToAddrHashTable_r(host->host, host->port, host);
1265 if (i == host->interface->numberOfInterfaces) {
1267 ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
1268 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1269 host->hostFlags |= HOSTDELETED;
1270 /* addr/port was removed from the hash table */
1274 rxconn = host->callback_rxcon;
1275 host->callback_rxcon = NULL;
1278 rx_DestroyConnection(rxconn);
1282 h_SetupCallbackConn_r(host);
1285 /* not the primary addr/port, just invalidate it */
1286 invalidateInterfaceAddr_r(host, addr, port);
1294 createHostAddrHashChain_r(int index, afs_uint32 addr, afs_uint16 port, struct host *host)
1296 struct h_AddrHashChain *chain;
1299 /* insert into beginning of list for this bucket */
1300 chain = (struct h_AddrHashChain *)malloc(sizeof(struct h_AddrHashChain));
1302 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToAddrHashTable_r\n"));
1304 chain->hostPtr = host;
1305 chain->next = hostAddrHashTable[index];
1308 hostAddrHashTable[index] = chain;
1309 ViceLog(125, ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " added as %s:%d\n",
1310 host, afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1314 * Resolve host address conflicts when hashing by address.
1316 * @param[in] addr an ip address of the interface
1317 * @param[in] port the port of the interface
1318 * @param[in] newHost the host being added with this address
1319 * @param[in] oldHost the host previously added with this address
1322 reconcileHosts_r(afs_uint32 addr, afs_uint16 port, struct host *newHost,
1323 struct host *oldHost)
1325 struct rx_connection *cb = NULL;
1327 struct interfaceAddr interf;
1329 afsUUID *newHostUuid = &nulluuid;
1330 afsUUID *oldHostUuid = &nulluuid;
1334 ("reconcileHosts_r: addr %s:%d newHost %" AFS_PTR_FMT " oldHost %"
1335 AFS_PTR_FMT, afs_inet_ntoa_r(addr, hoststr), ntohs(port),
1338 osi_Assert(oldHost != newHost);
1339 caps.Capabilities_val = NULL;
1342 sc = rxnull_NewClientSecurityObject();
1345 cb = rx_NewConnection(addr, port, 1, sc, 0);
1346 rx_SetConnDeadTime(cb, 50);
1347 rx_SetConnHardDeadTime(cb, AFS_HARDDEADTIME);
1352 code = RXAFSCB_TellMeAboutYourself(cb, &interf, &caps);
1353 if (code == RXGEN_OPCODE) {
1354 code = RXAFSCB_WhoAreYou(cb, &interf);
1358 if (code == RXGEN_OPCODE ||
1359 (code == 0 && afs_uuid_equal(&interf.uuid, &nulluuid))) {
1361 ("reconcileHosts_r: WhoAreYou not supported for connection (%s:%d), error %d\n",
1362 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1367 ("reconcileHosts_r: WhoAreYou failed for connection (%s:%d), error %d\n",
1368 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1372 /* Since lock was dropped, the hosts may have been deleted during the rpcs. */
1373 if ((newHost->hostFlags & HOSTDELETED)
1374 && (oldHost->hostFlags & HOSTDELETED)) {
1376 ("reconcileHosts_r: new and old hosts were deleted during probe.\n"));
1380 /* A check can be done if at least one of the hosts has a uuid. It
1381 * is an error if the hosts have the same (not null) uuid. */
1382 if ((!(newHost->hostFlags & HOSTDELETED)) && newHost->interface) {
1383 newHostUuid = &(newHost->interface->uuid);
1385 if ((!(oldHost->hostFlags & HOSTDELETED)) && oldHost->interface) {
1386 oldHostUuid = &(oldHost->interface->uuid);
1388 if (afs_uuid_equal(newHostUuid, &nulluuid) &&
1389 afs_uuid_equal(oldHostUuid, &nulluuid)) {
1391 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), no uuids\n",
1392 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1395 if (afs_uuid_equal(newHostUuid, oldHostUuid)) {
1397 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), same uuids\n",
1398 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1402 /* Determine which host should be hashed */
1403 if ((!(newHost->hostFlags & HOSTDELETED))
1404 && afs_uuid_equal(newHostUuid, &(interf.uuid))) {
1405 /* Install the new host into the hash before removing the stale
1406 * addresses. Walk the hash chain again since the hash table may have
1407 * been changed when the host lock was dropped to get the uuid. */
1408 struct h_AddrHashChain *chain;
1409 int index = h_HashIndex(addr);
1410 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1411 if (chain->addr == addr && chain->port == port) {
1412 chain->hostPtr = newHost;
1413 removeAddress_r(oldHost, addr, port);
1417 createHostAddrHashChain_r(index, addr, port, newHost);
1418 removeAddress_r(oldHost, addr, port);
1421 if ((!(oldHost->hostFlags & HOSTDELETED))
1422 && afs_uuid_equal(oldHostUuid, &(interf.uuid))) {
1423 removeAddress_r(newHost, addr, port);
1428 if (!(newHost->hostFlags & HOSTDELETED)) {
1429 removeAddress_r(newHost, addr, port);
1431 if (!(oldHost->hostFlags & HOSTDELETED)) {
1432 removeAddress_r(oldHost, addr, port);
1436 h_Release_r(newHost);
1437 h_Release_r(oldHost);
1438 rx_DestroyConnection(cb);
1442 /* inserts a new HashChain structure corresponding to this address */
1444 h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1447 struct h_AddrHashChain *chain;
1450 /* hash into proper bucket */
1451 index = h_HashIndex(addr);
1453 /* don't add the same address:port pair entry multiple times */
1454 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1455 if (chain->addr == addr && chain->port == port) {
1456 if (chain->hostPtr == host) {
1458 ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
1459 host, afs_inet_ntoa_r(chain->addr, hoststr),
1460 ntohs(chain->port)));
1463 if (!(chain->hostPtr->hostFlags & HOSTDELETED)) {
1464 /* attempt to resolve host address collision */
1465 reconcileHosts_r(addr, port, host, chain->hostPtr);
1470 createHostAddrHashChain_r(index, addr, port, host);
1474 * This is called with host locked and held.
1475 * It is called to either validate or add an additional interface
1476 * address/port on the specified host.
1478 * All addresses are in network byte order.
1481 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1485 struct Interface *interface;
1486 char hoststr[16], hoststr2[16];
1489 osi_Assert(host->interface);
1492 * Make sure this address is on the list of known addresses
1495 number = host->interface->numberOfInterfaces;
1496 for (i = 0; i < number; i++) {
1497 if (host->interface->interface[i].addr == addr &&
1498 host->interface->interface[i].port == port) {
1500 ("addInterfaceAddr : found host %" AFS_PTR_FMT " (%s:%d) adding %s:%d%s\n",
1501 host, afs_inet_ntoa_r(host->host, hoststr),
1502 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1503 ntohs(port), host->interface->interface[i].valid ? "" :
1506 if (host->interface->interface[i].valid == 0) {
1507 host->interface->interface[i].valid = 1;
1508 h_AddHostToAddrHashTable_r(addr, port, host);
1514 ViceLog(125, ("addInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) adding %s:%d\n",
1515 host, afs_inet_ntoa_r(host->host, hoststr),
1516 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1519 interface = (struct Interface *)
1520 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1522 ViceLogThenPanic(0, ("Failed malloc in addInterfaceAddr_r\n"));
1524 interface->numberOfInterfaces = number + 1;
1525 interface->uuid = host->interface->uuid;
1526 for (i = 0; i < number; i++)
1527 interface->interface[i] = host->interface->interface[i];
1529 /* Add the new valid interface */
1530 interface->interface[number].addr = addr;
1531 interface->interface[number].port = port;
1532 interface->interface[number].valid = 1;
1533 h_AddHostToAddrHashTable_r(addr, port, host);
1534 free(host->interface);
1535 host->interface = interface;
1542 * This is called with host locked and held.
1544 * All addresses are in network byte order.
1547 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1551 struct Interface *interface;
1552 char hoststr[16], hoststr2[16];
1555 osi_Assert(host->interface);
1557 ViceLog(125, ("removeInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1558 host, afs_inet_ntoa_r(host->host, hoststr),
1559 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1563 * Make sure this address is on the list of known addresses
1566 interface = host->interface;
1567 number = host->interface->numberOfInterfaces;
1568 for (i = 0; i < number; i++) {
1569 if (interface->interface[i].addr == addr &&
1570 interface->interface[i].port == port) {
1571 if (interface->interface[i].valid)
1572 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1574 for (; i < number; i++) {
1575 interface->interface[i] = interface->interface[i+1];
1577 interface->numberOfInterfaces = number;
1588 h_threadquota(int waiting)
1593 } else if (lwps > 32) {
1596 } else if (lwps > 16) {
1606 /* If found, host is returned with refCount incremented */
1608 h_GetHost_r(struct rx_connection *tcon)
1611 struct host *oldHost;
1613 struct interfaceAddr interf;
1614 int interfValid = 0;
1615 struct Identity *identP = NULL;
1618 char hoststr[16], hoststr2[16];
1620 struct rx_connection *cb_conn = NULL;
1621 struct rx_connection *cb_in = NULL;
1623 caps.Capabilities_val = NULL;
1625 haddr = rxr_HostOf(tcon);
1626 hport = rxr_PortOf(tcon);
1629 rx_DestroyConnection(cb_in);
1632 if (caps.Capabilities_val)
1633 free(caps.Capabilities_val);
1634 caps.Capabilities_val = NULL;
1635 caps.Capabilities_len = 0;
1638 if (h_Lookup_r(haddr, hport, &host))
1640 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1641 if (host && !identP && !(host->Console & 1)) {
1642 /* This is a new connection, and we already have a host
1643 * structure for this address. Verify that the identity
1644 * of the caller matches the identity in the host structure.
1646 if ((host->hostFlags & HWHO_INPROGRESS) &&
1647 h_threadquota(host->lock.num_waiting)) {
1653 if (!(host->hostFlags & ALTADDR) ||
1654 (host->hostFlags & HOSTDELETED)) {
1655 /* Another thread is doing initialization
1656 * or this host was deleted while we
1657 * waited for the lock. */
1660 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1661 host, afs_inet_ntoa_r(host->host, hoststr),
1662 ntohs(host->port)));
1666 host->hostFlags |= HWHO_INPROGRESS;
1667 host->hostFlags &= ~ALTADDR;
1669 /* We received a new connection from an IP address/port
1670 * that is associated with 'host' but the address/port of
1671 * the callback connection does not have to match it.
1672 * If there is a match, we can use the existing callback
1673 * connection to verify the UUID. If they do not match
1674 * we need to use a new callback connection to verify the
1675 * UUID of the incoming caller and perhaps use the old
1676 * callback connection to verify that the old address/port
1680 cb_conn = host->callback_rxcon;
1681 rx_GetConnection(cb_conn);
1683 if (haddr == host->host && hport == host->port) {
1684 /* The existing callback connection matches the
1685 * incoming connection so just use it.
1688 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1689 if (code == RXGEN_OPCODE)
1690 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1692 /* We do not have a match. Create a new connection
1693 * for the new addr/port and use multi_Rx to probe
1694 * both of them simultaneously.
1697 sc = rxnull_NewClientSecurityObject();
1698 cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1699 rx_SetConnDeadTime(cb_in, 50);
1700 rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1701 rx_SetConnSecondsUntilNatPing(cb_in, 20);
1704 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1705 if (code == RXGEN_OPCODE)
1706 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1708 rx_PutConnection(cb_conn);
1711 if ((code == RXGEN_OPCODE) ||
1712 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1713 identP = (struct Identity *)malloc(sizeof(struct Identity));
1715 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1718 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1719 if (cb_in == NULL) {
1720 /* The host on this connection was unable to respond to
1721 * the WhoAreYou. We will treat this as a new connection
1722 * from the existing host. The worst that can happen is
1723 * that we maintain some extra callback state information */
1724 if (host->interface) {
1726 ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1728 afs_inet_ntoa_r(host->host, hoststr),
1729 ntohs(host->port)));
1730 host->hostFlags |= HOSTDELETED;
1731 host->hostFlags &= ~HWHO_INPROGRESS;
1738 /* The incoming connection does not support WhoAreYou but
1739 * the original one might have. Use removeAddress_r() to
1740 * remove this addr/port from the host that was found.
1741 * If there are no more addresses left for the host it
1742 * will be deleted. Then we retry.
1744 removeAddress_r(host, haddr, hport);
1745 host->hostFlags &= ~HWHO_INPROGRESS;
1746 host->hostFlags |= ALTADDR;
1752 } else if (code == 0) {
1754 identP = (struct Identity *)malloc(sizeof(struct Identity));
1756 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1759 identP->uuid = interf.uuid;
1760 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1761 /* Check whether the UUID on this connection matches
1762 * the UUID in the host structure. If they don't match
1763 * then this is not the same host as before. */
1764 if (!host->interface
1765 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1768 ("Uuid doesn't match connection (%s:%d).\n",
1769 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1770 removeAddress_r(host, haddr, hport);
1773 ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1774 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1776 removeAddress_r(host, host->host, host->port);
1778 host->hostFlags &= ~HWHO_INPROGRESS;
1779 host->hostFlags |= ALTADDR;
1785 /* the UUID matched the client at the incoming addr/port
1786 * but this is not the address of the active callback
1787 * connection. Try that connection and see if the client
1788 * is still there and if the reported UUID is the same.
1791 afsUUID uuid = host->interface->uuid;
1792 cb_conn = host->callback_rxcon;
1793 rx_GetConnection(cb_conn);
1794 rx_SetConnDeadTime(cb_conn, 2);
1795 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1797 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1799 rx_SetConnDeadTime(cb_conn, 50);
1800 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1801 rx_PutConnection(cb_conn);
1804 /* The primary address is either not responding or
1805 * is not the client we are looking for. Need to
1806 * remove the primary address and add swap in the new
1807 * callback connection, and destroy the old one.
1809 struct rx_connection *rxconn;
1810 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1812 afs_inet_ntoa_r(host->host, hoststr),
1813 ntohs(host->port),code2));
1816 * make sure we add and then remove. otherwise, we
1817 * might end up with no valid interfaces after the
1818 * remove and the host will have been marked deleted.
1820 addInterfaceAddr_r(host, haddr, hport);
1821 removeInterfaceAddr_r(host, host->host, host->port);
1824 rxconn = host->callback_rxcon;
1825 host->callback_rxcon = cb_in;
1830 * If rx_DestroyConnection calls h_FreeConnection we
1831 * will deadlock on the host_glock_mutex. Work around
1832 * the problem by unhooking the client from the
1833 * connection before destroying the connection.
1835 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1836 rx_DestroyConnection(rxconn);
1842 /* A callback to the incoming connection address is failing.
1843 * Assume that the addr/port is no longer associated with the host
1844 * returned by h_Lookup_r.
1847 ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1848 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1849 removeAddress_r(host, haddr, hport);
1850 host->hostFlags &= ~HWHO_INPROGRESS;
1851 host->hostFlags |= ALTADDR;
1855 rx_DestroyConnection(cb_in);
1860 ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1861 host, afs_inet_ntoa_r(host->host, hoststr),
1862 ntohs(host->port), code));
1863 host->hostFlags |= VENUSDOWN;
1866 if (caps.Capabilities_val
1867 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1868 host->hostFlags |= HERRORTRANS;
1870 host->hostFlags &= ~(HERRORTRANS);
1871 host->hostFlags |= ALTADDR;
1872 host->hostFlags &= ~HWHO_INPROGRESS;
1875 if (!(host->hostFlags & ALTADDR)) {
1876 /* another thread is doing the initialisation */
1878 ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1879 host, afs_inet_ntoa_r(host->host, hoststr),
1880 ntohs(host->port)));
1884 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1885 host, afs_inet_ntoa_r(host->host, hoststr),
1886 ntohs(host->port)));
1890 /* We need to check whether the identity in the host structure
1891 * matches the identity on the connection. If they don't match
1892 * then treat this a new host. */
1893 if (!(host->Console & 1)
1894 && ((!identP->valid && host->interface)
1895 || (identP->valid && !host->interface)
1897 && !afs_uuid_equal(&identP->uuid,
1898 &host->interface->uuid)))) {
1899 char uuid1[128], uuid2[128];
1901 afsUUID_to_string(&identP->uuid, uuid1, 127);
1902 if (host->interface)
1903 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1905 ("CB: new identity for host %p (%s:%d), "
1906 "deleting(%x %p %s %s)\n",
1907 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1908 identP->valid, host->interface,
1909 identP->valid ? uuid1 : "no_uuid",
1910 host->interface ? uuid2 : "no_uuid"));
1912 /* The host in the cache is not the host for this connection */
1914 host->hostFlags |= HOSTDELETED;
1920 host = h_Alloc_r(tcon); /* returned held and locked */
1923 h_gethostcps_r(host, FT_ApproxTime());
1924 if (!(host->Console & 1)) {
1926 cb_conn = host->callback_rxcon;
1927 rx_GetConnection(cb_conn);
1928 host->hostFlags |= HWHO_INPROGRESS;
1931 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1932 if (code == RXGEN_OPCODE)
1933 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1934 rx_PutConnection(cb_conn);
1937 if ((code == RXGEN_OPCODE) ||
1938 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1941 (struct Identity *)malloc(sizeof(struct Identity));
1946 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1950 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1952 ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1953 host, afs_inet_ntoa_r(host->host, hoststr),
1954 ntohs(host->port)));
1956 } else if (code == 0) {
1959 (struct Identity *)malloc(sizeof(struct Identity));
1964 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1968 identP->uuid = interf.uuid;
1970 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1972 ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
1973 host, afs_inet_ntoa_r(host->host, hoststr),
1974 ntohs(host->port)));
1976 if (code == 0 && !identP->valid) {
1977 cb_conn = host->callback_rxcon;
1978 rx_GetConnection(cb_conn);
1980 code = RXAFSCB_InitCallBackState(cb_conn);
1981 rx_PutConnection(cb_conn);
1984 } else if (code == 0) {
1985 oldHost = h_LookupUuid_r(&identP->uuid);
1990 if (oldHost->hostFlags & HOSTDELETED) {
1991 h_Unlock_r(oldHost);
1992 h_Release_r(oldHost);
2000 oldHost->hostFlags |= HWHO_INPROGRESS;
2002 if (oldHost->interface) {
2004 afsUUID uuid = oldHost->interface->uuid;
2005 cb_conn = oldHost->callback_rxcon;
2006 rx_GetConnection(cb_conn);
2007 rx_SetConnDeadTime(cb_conn, 2);
2008 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2010 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2012 rx_SetConnDeadTime(cb_conn, 50);
2013 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2014 rx_PutConnection(cb_conn);
2017 /* The primary address is either not responding or
2018 * is not the client we are looking for.
2019 * MultiProbeAlternateAddress_r() will remove the
2020 * alternate interfaces that do not have the same
2022 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
2024 afs_inet_ntoa_r(oldHost->host, hoststr),
2025 ntohs(oldHost->port),code2));
2026 MultiProbeAlternateAddress_r(oldHost);
2033 /* This is a new address for an existing host. Update
2034 * the list of interfaces for the existing host and
2035 * delete the host structure we just allocated. */
2037 /* prevent warnings while manipulating interface lists */
2038 host->hostFlags |= HOSTDELETED;
2040 if (oldHost->host != haddr || oldHost->port != hport) {
2041 struct rx_connection *rxconn;
2044 ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
2046 afs_inet_ntoa_r(oldHost->host, hoststr2),
2047 ntohs(oldHost->port),
2048 afs_inet_ntoa_r(haddr, hoststr),
2051 * add then remove. otherwise the host may get marked
2052 * deleted if we removed the only valid address.
2054 addInterfaceAddr_r(oldHost, haddr, hport);
2055 if (probefail || oldHost->host == haddr) {
2057 * The probe failed which means that the old
2058 * address is either unreachable or is not the
2059 * same host we were just contacted by. We will
2060 * also remove addresses if only the port has
2061 * changed because that indicates the client
2064 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
2067 struct Interface *interface = oldHost->interface;
2068 int number = oldHost->interface->numberOfInterfaces;
2069 for (i = 0; i < number; i++) {
2070 if (interface->interface[i].addr == haddr &&
2071 interface->interface[i].port != hport) {
2073 * We have just been contacted by a client
2074 * that has been seen from behind a NAT
2075 * and at least one other address.
2077 removeInterfaceAddr_r(oldHost, haddr,
2078 interface->interface[i].port);
2083 h_AddHostToAddrHashTable_r(haddr, hport, oldHost);
2084 oldHost->host = haddr;
2085 oldHost->port = hport;
2086 rxconn = oldHost->callback_rxcon;
2087 oldHost->callback_rxcon = host->callback_rxcon;
2088 host->callback_rxcon = rxconn;
2090 /* don't destroy rxconn here; let h_TossStuff_r
2091 * take care of that via h_Release_r below */
2093 host->hostFlags &= ~HWHO_INPROGRESS;
2095 /* release host because it was allocated by h_Alloc_r */
2098 /* the new host is held and locked */
2100 /* This really is a new host */
2101 h_AddHostToUuidHashTable_r(&identP->uuid, host);
2102 cb_conn = host->callback_rxcon;
2103 rx_GetConnection(cb_conn);
2106 RXAFSCB_InitCallBackState3(cb_conn,
2108 rx_PutConnection(cb_conn);
2113 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2114 host, afs_inet_ntoa_r(host->host, hoststr),
2115 ntohs(host->port)));
2116 osi_Assert(interfValid == 1);
2117 initInterfaceAddr_r(host, &interf);
2123 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2124 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2125 host->hostFlags |= VENUSDOWN;
2128 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2129 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2130 host->hostFlags |= RESETDONE;
2133 if (caps.Capabilities_val
2134 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2135 host->hostFlags |= HERRORTRANS;
2137 host->hostFlags &= ~(HERRORTRANS);
2138 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2139 host->hostFlags &= ~HWHO_INPROGRESS;
2144 if (caps.Capabilities_val)
2145 free(caps.Capabilities_val);
2146 caps.Capabilities_val = NULL;
2147 caps.Capabilities_len = 0;
2149 rx_DestroyConnection(cb_in);
2157 static char localcellname[PR_MAXNAMELEN + 1];
2158 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
2159 int num_lrealms = -1;
2163 h_InitHostPackage(void)
2165 memset(&nulluuid, 0, sizeof(afsUUID));
2166 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
2167 if (num_lrealms == -1) {
2169 for (i=0; i<AFS_NUM_LREALMS; i++) {
2170 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
2176 ("afs_krb_get_lrealm failed, using %s.\n",
2178 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
2184 /* initialize the rest of the local realms to nullstring for debugging */
2185 for (; i<AFS_NUM_LREALMS; i++)
2186 local_realms[i][0] = '\0';
2188 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2189 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2190 MUTEX_INIT(&host_glock_mutex, "host glock", MUTEX_DEFAULT, 0);
2194 MapName_r(char *aname, char *acell, afs_int32 * aval)
2199 afs_int32 anamelen, cnamelen;
2203 anamelen = strlen(aname);
2204 if (anamelen >= PR_MAXNAMELEN)
2205 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
2207 lnames.namelist_len = 1;
2208 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
2209 lids.idlist_len = 0;
2210 lids.idlist_val = NULL;
2212 cnamelen = strlen(acell);
2214 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2216 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2217 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2218 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2220 ("MapName: Name too long, using AnonymousID for %s@%s\n",
2222 *aval = AnonymousID;
2225 foreign = 1; /* attempt cross-cell authentication */
2226 tname = (char *)malloc(PR_MAXNAMELEN);
2228 ViceLogThenPanic(0, ("Failed malloc in MapName_r\n"));
2230 strcpy(tname, aname);
2231 tname[anamelen] = '@';
2232 strcpy(tname + anamelen + 1, acell);
2233 lnames.namelist_val = (prname *) tname;
2238 code = hpr_NameToId(&lnames, &lids);
2241 if (lids.idlist_val) {
2242 *aval = lids.idlist_val[0];
2243 if (*aval == AnonymousID) {
2245 ("MapName: NameToId on %s returns anonymousID\n",
2246 lnames.namelist_val[0]));
2248 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2251 ("MapName: NameToId on '%s' is unknown\n",
2252 lnames.namelist_val[0]));
2258 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
2266 /* NOTE: this returns the client with a Write lock and a refCount */
2268 h_ID2Client(afs_int32 vid)
2270 struct client *client;
2275 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
2276 if (host->hostFlags & HOSTDELETED)
2278 for (client = host->FirstClient; client; client = client->next) {
2279 if (!client->deleted && client->ViceId == vid) {
2282 ObtainWriteLock(&client->lock);
2287 if (count != hostCount) {
2288 ViceLog(0, ("h_ID2Client found %d of %d hosts\n", count, hostCount));
2289 } else if (host != NULL) {
2290 ViceLog(0, ("h_ID2Client found more than %d hosts\n", hostCount));
2291 ShutDownAndCore(PANIC);
2299 * Called by the server main loop. Returns a h_Held client, which must be
2300 * released later the main loop. Allocates a client if the matching one
2301 * isn't around. The client is returned with its reference count incremented
2302 * by one. The caller must call h_ReleaseClient_r when finished with
2305 * The refCount on client->host is returned incremented. h_ReleaseClient_r
2306 * does not decrement the refCount on client->host.
2309 h_FindClient_r(struct rx_connection *tcon)
2311 struct client *client;
2312 struct host *host = NULL;
2313 struct client *oldClient;
2314 afs_int32 viceid = 0;
2318 #if (64-MAXKTCNAMELEN)
2319 ticket name length != 64
2323 char uname[PR_MAXNAMELEN];
2324 char tcell[MAXKTCREALMLEN];
2328 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2329 if (client && client->sid == rx_GetConnectionId(tcon)
2330 && client->VenusEpoch == rx_GetConnectionEpoch(tcon)
2331 && !(client->host->hostFlags & HOSTDELETED)
2332 && !client->deleted) {
2335 h_Hold_r(client->host);
2336 if (client->prfail != 2) {
2337 /* Could add shared lock on client here */
2338 /* note that we don't have to lock entry in this path to
2339 * ensure CPS is initialized, since we don't call rx_SetSpecific
2340 * until initialization is done, and we only get here if
2341 * rx_GetSpecific located the client structure.
2346 ObtainWriteLock(&client->lock); /* released at end */
2352 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2354 ("FindClient: authenticating connection: authClass=%d\n",
2356 if (authClass == 1) {
2357 /* A bcrypt tickets, no longer supported */
2358 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2359 viceid = AnonymousID;
2360 expTime = 0x7fffffff;
2361 } else if (authClass == 2) {
2364 /* kerberos ticket */
2365 code = rxkad_GetServerInfo(tcon, /*level */ 0, (afs_uint32 *)&expTime,
2366 tname, tinst, tcell, &kvno);
2368 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2369 viceid = AnonymousID;
2370 expTime = 0x7fffffff;
2372 int ilen = strlen(tinst);
2374 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2375 tname, tinst, tcell, expTime, kvno));
2376 strncpy(uname, tname, sizeof(uname));
2378 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2381 strcat(uname, tinst);
2383 /* translate the name to a vice id */
2384 code = MapName_r(uname, tcell, &viceid);
2388 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2391 viceid = AnonymousID;
2392 expTime = 0x7fffffff;
2396 viceid = AnonymousID; /* unknown security class */
2397 expTime = 0x7fffffff;
2400 if (!client) { /* loop */
2401 host = h_GetHost_r(tcon); /* Returns with incremented refCount */
2407 /* First try to find the client structure */
2408 for (client = host->FirstClient; client; client = client->next) {
2409 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2410 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2413 ObtainWriteLock(&client->lock);
2419 /* Still no client structure - get one */
2422 if (host->hostFlags & HOSTDELETED) {
2427 /* Retry to find the client structure */
2428 for (client = host->FirstClient; client; client = client->next) {
2429 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2430 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2432 goto retryfirstclient;
2437 ObtainWriteLock(&client->lock);
2438 client->refCount = 1;
2439 client->host = host;
2440 client->InSameNetwork = host->InSameNetwork;
2441 client->ViceId = viceid;
2442 client->expTime = expTime; /* rx only */
2443 client->authClass = authClass; /* rx only */
2444 client->sid = rx_GetConnectionId(tcon);
2445 client->VenusEpoch = rx_GetConnectionEpoch(tcon);
2446 client->CPS.prlist_val = NULL;
2447 client->CPS.prlist_len = 0;
2451 client->prfail = fail;
2453 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2454 client->CPS.prlist_len = 0;
2455 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2456 free(client->CPS.prlist_val);
2457 client->CPS.prlist_val = NULL;
2458 client->ViceId = viceid;
2459 client->expTime = expTime;
2461 if (viceid == ANONYMOUSID) {
2462 client->CPS.prlist_len = AnonCPS.prlist_len;
2463 client->CPS.prlist_val = AnonCPS.prlist_val;
2466 code = hpr_GetCPS(viceid, &client->CPS);
2471 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2472 code, viceid, client->host,
2473 afs_inet_ntoa_r(client->host->host,hoststr),
2474 ntohs(client->host->port)));
2476 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2477 * all protection servers and reevaluates things if no
2478 * sync server or quorum is found we could still end up
2479 * with one of these errors. In such case we would like to
2480 * reevaluate the rpc call to find if there's cps for this
2481 * guy. We treat other errors (except network failures
2482 * ones - i.e. code < 0) as an indication that there is no
2483 * CPS for this host. Ideally we could like to deal this
2484 * problem the other way around (i.e. if code == NOCPS
2485 * ignore else retry next time) but the problem is that
2486 * there're other errors (i.e. EPERM) for which we don't
2487 * want to retry and we don't know the whole code list!
2489 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2493 /* the disabling of system:administrators is so iffy and has so many
2494 * possible failure modes that we will disable it again */
2495 /* Turn off System:Administrator for safety
2496 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2497 * osi_Assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2500 /* Now, tcon may already be set to a rock, since we blocked with no host
2501 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2502 * required). So, before setting the RPC's rock, we should disconnect
2503 * the RPC from the other client structure's rock.
2505 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2506 if (oldClient && oldClient != client
2507 && oldClient->sid == rx_GetConnectionId(tcon)
2508 && oldClient->VenusEpoch == rx_GetConnectionEpoch(tcon)
2509 && !(oldClient->host->hostFlags & HOSTDELETED)) {
2511 if (!oldClient->deleted) {
2512 /* if we didn't create it, it's not ours to put back */
2514 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2515 "conn %p (host %s:%d) had client %p(%x)\n",
2516 client, client->sid, tcon,
2517 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2518 ntohs(rxr_PortOf(tcon)),
2519 oldClient, oldClient->sid));
2520 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2521 free(client->CPS.prlist_val);
2522 client->CPS.prlist_val = NULL;
2523 client->CPS.prlist_len = 0;
2525 /* We should perhaps check for 0 here */
2527 ReleaseWriteLock(&client->lock);
2532 oldClient->refCount++;
2534 h_Hold_r(oldClient->host);
2535 h_Release_r(client->host);
2538 ObtainWriteLock(&oldClient->lock);
2541 host = oldClient->host;
2543 ViceLog(0, ("FindClient: deleted client %p(%x ref %d host %p href "
2544 "%d) already had conn %p (host %s:%d, cid %x), stolen "
2545 "by client %p(%x, ref %d host %p href %d)\n",
2546 oldClient, oldClient->sid, oldClient->refCount,
2547 oldClient->host, oldClient->host->refCount, tcon,
2548 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2549 ntohs(rxr_PortOf(tcon)), rx_GetConnectionId(tcon),
2550 client, client->sid, client->refCount,
2551 client->host, client->host->refCount));
2552 /* rx_SetSpecific will be done immediately below */
2555 /* Avoid chaining in more than once. */
2559 if (host->hostFlags & HOSTDELETED) {
2564 client->host = NULL;
2566 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2567 free(client->CPS.prlist_val);
2568 client->CPS.prlist_val = NULL;
2569 client->CPS.prlist_len = 0;
2572 ReleaseWriteLock(&client->lock);
2577 client->next = host->FirstClient;
2578 host->FirstClient = client;
2580 CurrentConnections++; /* increment number of connections */
2582 rx_SetSpecific(tcon, rxcon_client_key, client);
2583 ReleaseWriteLock(&client->lock);
2587 } /*h_FindClient_r */
2590 h_ReleaseClient_r(struct client *client)
2592 osi_Assert(client->refCount > 0);
2599 * Sigh: this one is used to get the client AGAIN within the individual
2600 * server routines. This does not bother h_Holding the host, since
2601 * this is assumed already have been done by the server main loop.
2602 * It does check tokens, since only the server routines can return the
2603 * VICETOKENDEAD error code
2606 GetClient(struct rx_connection *tcon, struct client **cp)
2608 struct client *client;
2613 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2614 if (client == NULL) {
2616 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2617 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2618 ntohs(rxr_PortOf(tcon))));
2622 if (rx_GetConnectionId(tcon) != client->sid
2623 || rx_GetConnectionEpoch(tcon) != client->VenusEpoch) {
2625 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2626 tcon, rx_GetConnectionId(tcon), client->sid));
2630 if (client && client->LastCall > client->expTime && client->expTime) {
2632 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2633 afs_inet_ntoa_r(client->host->host, hoststr),
2634 ntohs(client->host->port), client->expTime));
2636 return VICETOKENDEAD;
2638 if (client->deleted) {
2639 ViceLog(0, ("GetClient: got deleted client, connection will appear "
2640 "anonymous; tcon %p cid %x client %p ref %d host %p "
2641 "(%s:%d) href %d ViceId %d\n",
2642 tcon, rx_GetConnectionId(tcon), client, client->refCount,
2644 afs_inet_ntoa_r(client->host->host, hoststr),
2645 (int)ntohs(client->host->port), client->host->refCount,
2646 (int)client->ViceId));
2656 PutClient(struct client **cp)
2662 h_ReleaseClient_r(*cp);
2669 /* Client user name for short term use. Note that this is NOT inexpensive */
2671 h_UserName(struct client *client)
2673 static char User[PR_MAXNAMELEN + 1];
2677 lids.idlist_len = 1;
2678 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2679 if (!lids.idlist_val) {
2680 ViceLogThenPanic(0, ("Failed malloc in h_UserName\n"));
2682 lnames.namelist_len = 0;
2683 lnames.namelist_val = (prname *) 0;
2684 lids.idlist_val[0] = client->ViceId;
2685 if (hpr_IdToName(&lids, &lnames)) {
2686 /* We need to free id we alloced above! */
2687 free(lids.idlist_val);
2688 return "*UNKNOWN USER NAME*";
2690 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2691 free(lids.idlist_val);
2692 free(lnames.namelist_val);
2701 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2702 CEs, CEBlocks, HTs, HTBlocks));
2708 h_PrintClient(struct host *host, void *rock)
2710 StreamHandle_t *file = (StreamHandle_t *)rock;
2711 struct client *client;
2716 time_t LastCall, expTime;
2720 LastCall = host->LastCall;
2721 if (host->hostFlags & HOSTDELETED) {
2725 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2726 localtime_r(&LastCall, &tm));
2727 snprintf(tmpStr, sizeof tmpStr, "Host %s:%d down = %d, LastCall %s\n",
2728 afs_inet_ntoa_r(host->host, hoststr),
2729 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2731 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2732 for (client = host->FirstClient; client; client = client->next) {
2733 if (!client->deleted) {
2734 expTime = client->expTime;
2735 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2736 localtime_r(&expTime, &tm));
2737 snprintf(tmpStr, sizeof tmpStr,
2738 " user id=%d, name=%s, sl=%s till %s\n",
2739 client->ViceId, h_UserName(client),
2740 client->authClass ? "Authenticated"
2741 : "Not authenticated",
2742 client->authClass ? tbuffer : "No Limit");
2743 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2744 snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2745 client->CPS.prlist_len);
2746 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2747 if (client->CPS.prlist_val) {
2748 for (i = 0; i < client->CPS.prlist_len; i++) {
2749 snprintf(tmpStr, sizeof tmpStr, " %d",
2750 client->CPS.prlist_val[i]);
2751 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2754 sprintf(tmpStr, "]\n");
2755 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2761 } /*h_PrintClient */
2766 * Print a list of clients, with last security level and token value seen,
2770 h_PrintClients(void)
2777 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2781 ("Couldn't create client dump file %s\n",
2782 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2785 now = FT_ApproxTime();
2786 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2787 localtime_r(&now, &tm));
2788 snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n\n",
2790 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2791 h_Enumerate(h_PrintClient, (char *)file);
2792 STREAM_REALLYCLOSE(file);
2793 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2800 h_DumpHost(struct host *host, void *rock)
2802 StreamHandle_t *file = (StreamHandle_t *)rock;
2809 snprintf(tmpStr, sizeof tmpStr,
2810 "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u "
2811 "down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u "
2813 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
2814 host->index, host->cblist, CheckLock(&host->lock),
2815 host->LastCall, host->ActiveCall, (host->hostFlags & VENUSDOWN),
2816 host->hostFlags & HOSTDELETED, host->Console,
2817 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2819 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2820 if (host->hcps.prlist_val)
2821 for (i = 0; i < host->hcps.prlist_len; i++) {
2822 snprintf(tmpStr, sizeof tmpStr, " %d", host->hcps.prlist_val[i]);
2823 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2825 sprintf(tmpStr, "] [");
2826 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2827 if (host->interface)
2828 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2830 sprintf(tmpStr, " %s:%d",
2831 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2832 ntohs(host->interface->interface[i].port));
2833 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2835 sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2836 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2848 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2855 ("Couldn't create host dump file %s\n",
2856 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2859 now = FT_ApproxTime();
2860 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2861 localtime_r(&now, &tm));
2862 snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n\n", tbuffer);
2863 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2864 h_Enumerate(h_DumpHost, (char *)file);
2865 STREAM_REALLYCLOSE(file);
2866 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2870 #ifdef AFS_DEMAND_ATTACH_FS
2873 * host state serialization
2875 static int h_stateFillHeader(struct host_state_header * hdr);
2876 static int h_stateCheckHeader(struct host_state_header * hdr);
2877 static int h_stateAllocMap(struct fs_dump_state * state);
2878 static int h_stateSaveHost(struct host * host, void *rock);
2879 static int h_stateRestoreHost(struct fs_dump_state * state);
2880 static int h_stateRestoreIndex(struct host * h, void *rock);
2881 static int h_stateVerifyHost(struct host * h, void *rock);
2882 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
2883 afs_uint32 addr, afs_uint16 port, int valid);
2884 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2885 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2886 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2889 * Is this host busy?
2891 * This is just a hint and should not be trusted; this should probably only be
2892 * used by the host state serialization code when trying to detect if a host
2893 * can be sanely serialized to disk or not. If this function returns 1, the
2894 * host may be in an invalid state and thus should not be saved to disk.
2897 h_isBusy_r(struct host *host)
2899 struct Lock *hostLock = &host->lock;
2902 LOCK_LOCK(hostLock);
2903 if (hostLock->excl_locked || hostLock->readers_reading) {
2906 LOCK_UNLOCK(hostLock);
2912 if ((host->hostFlags & HWHO_INPROGRESS) || !(host->hostFlags & ALTADDR)) {
2913 /* We shouldn't hit this if the host wasn't locked, but just in case... */
2920 /* this procedure saves all host state to disk for fast startup */
2922 h_stateSave(struct fs_dump_state * state)
2924 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2927 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2929 /* invalidate host state header */
2930 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2932 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2933 sizeof(struct host_state_header))) {
2938 fs_stateIncEOF(state, sizeof(struct host_state_header));
2940 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2945 h_stateFillHeader(state->h_hdr);
2947 /* write the real header to disk */
2948 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2949 sizeof(struct host_state_header));
2956 * host state serialization
2958 * this procedure restores all host state from a disk for fast startup
2961 h_stateRestore(struct fs_dump_state * state)
2965 /* seek to the right position and read in the host state header */
2966 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2967 sizeof(struct host_state_header))) {
2972 /* check the validity of the header */
2973 if (h_stateCheckHeader(state->h_hdr)) {
2978 records = state->h_hdr->records;
2980 if (h_stateAllocMap(state)) {
2985 /* iterate over records restoring host state */
2986 for (i=0; i < records; i++) {
2987 if (h_stateRestoreHost(state) != 0) {
2998 h_stateRestoreIndices(struct fs_dump_state * state)
3000 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
3005 h_stateRestoreIndex(struct host * h, void *rock)
3007 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3008 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
3009 return H_ENUMERATE_BAIL(0);
3015 h_stateVerify(struct fs_dump_state * state)
3017 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
3022 h_stateVerifyHost(struct host * h, void* rock)
3024 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3028 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3029 return H_ENUMERATE_BAIL(0);
3033 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
3034 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
3035 h->interface->interface[i].port,
3036 h->interface->interface[i].valid)) {
3040 if (h_stateVerifyUuidHash(state, h)) {
3043 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
3047 if (cb_stateVerifyHCBList(state, h)) {
3055 * verify a host is either in, or absent from, the addr hash table.
3057 * @param[in] state fs dump state
3058 * @param[in] h host we're dealing with
3059 * @param[in] addr addr to look for (NBO)
3060 * @param[in] port port to look for (NBO)
3061 * @param[in] valid 1 if we're verifying that the specified addr and port
3062 * in the hash table point to the specified host. 0 if we're
3063 * verifying that the specified addr and port do NOT point
3064 * to the specified host
3066 * @return operation status
3067 * @retval 1 failed to verify, bail out
3068 * @retval 0 verified successfully, all is well
3071 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3072 afs_uint32 addr, afs_uint16 port, int valid)
3074 int ret = 0, found = 0;
3075 struct host *host = NULL;
3076 struct h_AddrHashChain *chain;
3077 int index = h_HashIndex(addr);
3081 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3082 host = chain->hostPtr;
3084 afs_inet_ntoa_r(addr, tmp);
3085 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3089 if ((chain->addr == addr) && (chain->port == port)) {
3092 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3093 "points to different host struct (%d, %d)\n",
3094 h->index, host->index));
3095 state->flags.warnings_generated = 1;
3099 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3100 "marked invalid, but points to the containing "
3101 "host\n", afs_inet_ntoa_r(addr, tmp),
3102 (unsigned)htons(port)));
3110 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3111 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3112 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3119 if (!found && valid) {
3120 afs_inet_ntoa_r(addr, tmp);
3121 if (state->mode == FS_STATE_LOAD_MODE) {
3122 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3123 tmp, (unsigned)htons(port)));
3127 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3128 tmp, (unsigned)htons(port)));
3129 state->flags.warnings_generated = 1;
3138 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3140 int ret = 0, found = 0;
3141 struct host *host = NULL;
3142 struct h_UuidHashChain *chain;
3143 afsUUID * uuidp = &h->interface->uuid;
3144 int index = h_UuidHashIndex(uuidp);
3148 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3149 host = chain->hostPtr;
3151 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3152 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3156 if (host->interface &&
3157 afs_uuid_equal(&host->interface->uuid, uuidp)) {
3159 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3160 h->index, host->index));
3161 state->flags.warnings_generated = 1;
3166 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3167 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3168 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3176 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3177 if (state->mode == FS_STATE_LOAD_MODE) {
3178 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3182 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3183 state->flags.warnings_generated = 1;
3191 /* create the host state header structure */
3193 h_stateFillHeader(struct host_state_header * hdr)
3195 hdr->stamp.magic = HOST_STATE_MAGIC;
3196 hdr->stamp.version = HOST_STATE_VERSION;
3200 /* check the contents of the host state header structure */
3202 h_stateCheckHeader(struct host_state_header * hdr)
3206 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3207 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3210 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3211 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3217 /* allocate the host id mapping table */
3219 h_stateAllocMap(struct fs_dump_state * state)
3221 state->h_map.len = state->h_hdr->index_max + 1;
3222 state->h_map.entries = (struct idx_map_entry_t *)
3223 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3224 return (state->h_map.entries != NULL) ? 0 : 1;
3227 /* function called by h_Enumerate to save a host to disk */
3229 h_stateSaveHost(struct host * host, void* rock)
3231 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3232 int if_len=0, hcps_len=0;
3233 struct hostDiskEntry hdsk;
3234 struct host_state_entry_header hdr;
3235 struct Interface * ifp = NULL;
3236 afs_int32 * hcps = NULL;
3237 struct iovec iov[4];
3240 if (h_isBusy_r(host)) {
3242 ViceLog(1, ("Not saving host %s:%d to disk; host appears busy\n",
3243 afs_inet_ntoa_r(host->host, hoststr), (int)ntohs(host->port)));
3244 /* Make sure we don't try to save callbacks to disk for this host, or
3245 * we'll get confused on restore */
3246 DeleteAllCallBacks_r(host, 1);
3250 memset(&hdr, 0, sizeof(hdr));
3252 if (state->h_hdr->index_max < host->index) {
3253 state->h_hdr->index_max = host->index;
3256 h_hostToDiskEntry_r(host, &hdsk);
3257 if (host->interface) {
3258 if_len = sizeof(struct Interface) +
3259 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3260 ifp = (struct Interface *) malloc(if_len);
3261 osi_Assert(ifp != NULL);
3262 memcpy(ifp, host->interface, if_len);
3263 hdr.interfaces = host->interface->numberOfInterfaces;
3264 iov[iovcnt].iov_base = (char *) ifp;
3265 iov[iovcnt].iov_len = if_len;
3268 if (host->hcps.prlist_val) {
3269 hdr.hcps = host->hcps.prlist_len;
3270 hcps_len = hdr.hcps * sizeof(afs_int32);
3271 hcps = (afs_int32 *) malloc(hcps_len);
3272 osi_Assert(hcps != NULL);
3273 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3274 iov[iovcnt].iov_base = (char *) hcps;
3275 iov[iovcnt].iov_len = hcps_len;
3279 if (hdsk.index > state->h_hdr->index_max)
3280 state->h_hdr->index_max = hdsk.index;
3282 hdr.len = sizeof(struct host_state_entry_header) +
3283 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3284 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3286 iov[0].iov_base = (char *) &hdr;
3287 iov[0].iov_len = sizeof(hdr);
3288 iov[1].iov_base = (char *) &hdsk;
3289 iov[1].iov_len = sizeof(struct hostDiskEntry);
3291 if (fs_stateWriteV(state, iov, iovcnt)) {
3292 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3296 fs_stateIncEOF(state, hdr.len);
3298 state->h_hdr->records++;
3305 return H_ENUMERATE_BAIL(0);
3310 /* restores a host from disk */
3312 h_stateRestoreHost(struct fs_dump_state * state)
3314 int ifp_len=0, hcps_len=0, bail=0;
3315 struct host_state_entry_header hdr;
3316 struct hostDiskEntry hdsk;
3317 struct host *host = NULL;
3318 struct Interface *ifp = NULL;
3319 afs_int32 * hcps = NULL;
3320 struct iovec iov[3];
3323 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3324 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3330 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3331 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3337 iov[0].iov_base = (char *) &hdsk;
3338 iov[0].iov_len = sizeof(struct hostDiskEntry);
3340 if (hdr.interfaces) {
3341 ifp_len = sizeof(struct Interface) +
3342 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3343 ifp = (struct Interface *) malloc(ifp_len);
3344 osi_Assert(ifp != NULL);
3345 iov[iovcnt].iov_base = (char *) ifp;
3346 iov[iovcnt].iov_len = ifp_len;
3350 hcps_len = hdr.hcps * sizeof(afs_int32);
3351 hcps = (afs_int32 *) malloc(hcps_len);
3352 osi_Assert(hcps != NULL);
3353 iov[iovcnt].iov_base = (char *) hcps;
3354 iov[iovcnt].iov_len = hcps_len;
3358 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3359 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3364 if (fs_stateReadV(state, iov, iovcnt)) {
3365 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3370 if (!hdr.hcps && hdsk.hcps_valid) {
3371 /* valid, zero-length host cps ; does this ever happen? */
3372 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3373 osi_Assert(hcps != NULL);
3376 if ((hdsk.hostFlags & HWHO_INPROGRESS) || !(hdsk.hostFlags & ALTADDR)) {
3378 ViceLog(0, ("h_stateRestoreHost: skipping host %s:%d due to invalid flags 0x%x\n",
3379 afs_inet_ntoa_r(hdsk.host, hoststr), (int)ntohs(hdsk.port),
3380 (unsigned)hdsk.hostFlags));
3382 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_SKIPPED;
3386 /* for restoring state, we better be able to get a host! */
3388 osi_Assert(host != NULL);
3391 host->interface = ifp;
3394 host->hcps.prlist_val = hcps;
3395 host->hcps.prlist_len = hdr.hcps;
3398 h_diskEntryToHost_r(&hdsk, host);
3399 h_SetupCallbackConn_r(host);
3401 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3404 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3405 if (ifp->interface[i].valid &&
3406 !(ifp->interface[i].addr == host->host &&
3407 ifp->interface[i].port == host->port)) {
3408 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3409 ifp->interface[i].port,
3413 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3415 h_InsertList_r(host);
3417 /* setup host id map entry */
3418 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_VALID;
3419 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3420 state->h_map.entries[hdsk.index].new_idx = host->index;
3432 /* serialize a host structure to disk */
3434 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3436 out->host = in->host;
3437 out->port = in->port;
3438 out->hostFlags = in->hostFlags;
3439 out->Console = in->Console;
3440 out->hcpsfailed = in->hcpsfailed;
3441 out->LastCall = in->LastCall;
3442 out->ActiveCall = in->ActiveCall;
3443 out->cpsCall = in->cpsCall;
3444 out->cblist = in->cblist;
3445 out->InSameNetwork = in->InSameNetwork;
3447 /* special fields we save, but are not memcpy'd back on restore */
3448 out->index = in->index;
3449 out->hcps_len = in->hcps.prlist_len;
3450 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3453 /* restore a host structure from disk */
3455 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3457 out->host = in->host;
3458 out->port = in->port;
3459 out->hostFlags = in->hostFlags;
3460 out->Console = in->Console;
3461 out->hcpsfailed = in->hcpsfailed;
3462 out->LastCall = in->LastCall;
3463 out->ActiveCall = in->ActiveCall;
3464 out->cpsCall = in->cpsCall;
3465 out->cblist = in->cblist;
3466 out->InSameNetwork = in->InSameNetwork;
3469 /* index translation routines */
3471 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3475 /* hosts use a zero-based index, so old==0 is valid */
3477 if (old >= state->h_map.len) {
3478 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3480 } else if (state->h_map.entries[old].valid != FS_STATE_IDX_VALID ||
3481 state->h_map.entries[old].old_idx != old) { /* sanity check */
3482 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3485 *new = state->h_map.entries[old].new_idx;
3490 #endif /* AFS_DEMAND_ATTACH_FS */
3494 * This counts the number of workstations, the number of active workstations,
3495 * and the number of workstations declared "down" (i.e. not heard from
3496 * recently). An active workstation has received a call since the cutoff
3497 * time argument passed.
3500 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3503 int num = 0, active = 0, del = 0;
3507 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3508 if (!(host->hostFlags & HOSTDELETED)) {
3510 if (host->ActiveCall > cutofftime)
3512 if (host->hostFlags & VENUSDOWN)
3516 if (count != hostCount) {
3517 ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3518 } else if (host != NULL) {
3519 ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3520 ShutDownAndCore(PANIC);
3530 } /*h_GetWorkStats */
3533 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp,
3534 afs_int32 cutofftime)
3536 int num, active, del;
3537 h_GetWorkStats(&num, &active, &del, cutofftime);
3546 /*------------------------------------------------------------------------
3547 * PRIVATE h_ClassifyAddress
3550 * Given a target IP address and a candidate IP address (both
3551 * in host byte order), classify the candidate into one of three
3552 * buckets in relation to the target by bumping the counters passed
3556 * a_targetAddr : Target address.
3557 * a_candAddr : Candidate address.
3558 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3559 * addresses are either in the same network
3560 * or the same subnet.
3561 * a_diffSubnetP : ...when the candidate is in a different
3563 * a_diffNetworkP : ...when the candidate is in a different
3570 * The target and candidate addresses are both in host byte
3571 * order, NOT network byte order, when passed in.
3575 *------------------------------------------------------------------------*/
3578 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3579 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3580 afs_int32 * a_diffNetworkP)
3581 { /*h_ClassifyAddress */
3583 afs_uint32 targetNet;
3584 afs_uint32 targetSubnet;
3586 afs_uint32 candSubnet;
3589 * Put bad values into the subnet info to start with.
3591 targetSubnet = (afs_uint32) 0;
3592 candSubnet = (afs_uint32) 0;
3595 * Pull out the network and subnetwork numbers from the target
3596 * and candidate addresses. We can short-circuit this whole
3597 * affair if the target and candidate addresses are not of the
3600 if (IN_CLASSA(a_targetAddr)) {
3601 if (!(IN_CLASSA(a_candAddr))) {
3602 (*a_diffNetworkP)++;
3605 targetNet = a_targetAddr & IN_CLASSA_NET;
3606 candNet = a_candAddr & IN_CLASSA_NET;
3607 if (IN_SUBNETA(a_targetAddr))
3608 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3609 if (IN_SUBNETA(a_candAddr))
3610 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3611 } else if (IN_CLASSB(a_targetAddr)) {
3612 if (!(IN_CLASSB(a_candAddr))) {
3613 (*a_diffNetworkP)++;
3616 targetNet = a_targetAddr & IN_CLASSB_NET;
3617 candNet = a_candAddr & IN_CLASSB_NET;
3618 if (IN_SUBNETB(a_targetAddr))
3619 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3620 if (IN_SUBNETB(a_candAddr))
3621 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3622 } /*Class B target */
3623 else if (IN_CLASSC(a_targetAddr)) {
3624 if (!(IN_CLASSC(a_candAddr))) {
3625 (*a_diffNetworkP)++;
3628 targetNet = a_targetAddr & IN_CLASSC_NET;
3629 candNet = a_candAddr & IN_CLASSC_NET;
3632 * Note that class C addresses can't have subnets,
3633 * so we leave the defaults untouched.
3635 } /*Class C target */
3637 targetNet = a_targetAddr;
3638 candNet = a_candAddr;
3639 } /*Class D address */
3642 * Now, simply compare the extracted net and subnet values for
3643 * the two addresses (which at this point are known to be of the
3646 if (targetNet == candNet) {
3647 if (targetSubnet == candSubnet)
3648 (*a_sameNetOrSubnetP)++;
3652 (*a_diffNetworkP)++;
3654 } /*h_ClassifyAddress */
3657 /*------------------------------------------------------------------------
3658 * EXPORTED h_GetHostNetStats
3661 * Iterate through the host table, and classify each (non-deleted)
3662 * host entry into ``proximity'' categories (same net or subnet,
3663 * different subnet, different network).
3666 * a_numHostsP : Set to total number of (non-deleted) hosts.
3667 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3668 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3669 * a_diffNetworkP : Set to # hosts on diff network as server.
3675 * We only count non-deleted hosts. The storage pointed to by our
3676 * parameters is zeroed upon entry.
3680 *------------------------------------------------------------------------*/
3683 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3684 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3685 { /*h_GetHostNetStats */
3687 struct host *hostP; /*Ptr to current host entry */
3688 afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3692 * Clear out the storage pointed to by our parameters.
3694 *a_numHostsP = (afs_int32) 0;
3695 *a_sameNetOrSubnetP = (afs_int32) 0;
3696 *a_diffSubnetP = (afs_int32) 0;
3697 *a_diffNetworkP = (afs_int32) 0;
3700 for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3701 if (!(hostP->hostFlags & HOSTDELETED)) {
3703 * Bump the number of undeleted host entries found.
3704 * In classifying the current entry's address, make
3705 * sure to first convert to host byte order.
3708 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3709 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3710 a_sameNetOrSubnetP, a_diffSubnetP,
3712 } /*Only look at non-deleted hosts */
3713 } /*For each host record hashed to this index */
3714 if (count != hostCount) {
3715 ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3716 } else if (hostP != NULL) {
3717 ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3718 ShutDownAndCore(PANIC);
3721 } /*h_GetHostNetStats */
3723 static afs_uint32 checktime;
3724 static afs_uint32 clientdeletetime;
3725 static struct AFSFid zerofid;
3729 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3730 * Since it can serialize them, and pile up, it should be a separate LWP
3731 * from other events.
3735 CheckHost(struct host *host, int flags, void *rock)
3737 struct client *client;
3738 struct rx_connection *cb_conn = NULL;
3741 #ifdef AFS_DEMAND_ATTACH_FS
3742 /* kill the checkhost lwp ASAP during shutdown */
3744 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3746 return H_ENUMERATE_BAIL(flags);
3751 /* Host is held by h_Enumerate */
3753 for (client = host->FirstClient; client; client = client->next) {
3754 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3755 client->deleted = 1;
3756 host->hostFlags |= CLIENTDELETED;
3759 if (host->LastCall < checktime) {
3761 if (!(host->hostFlags & HOSTDELETED)) {
3762 host->hostFlags |= HWHO_INPROGRESS;
3763 cb_conn = host->callback_rxcon;
3764 rx_GetConnection(cb_conn);
3765 if (host->LastCall < clientdeletetime) {
3766 host->hostFlags |= HOSTDELETED;
3767 if (!(host->hostFlags & VENUSDOWN)) {
3768 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3769 if (host->interface) {
3772 RXAFSCB_InitCallBackState3(cb_conn,
3778 RXAFSCB_InitCallBackState(cb_conn);
3781 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3784 (void)afs_inet_ntoa_r(host->host, hoststr);
3786 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3787 hoststr, ntohs(host->port)));
3788 host->hostFlags |= VENUSDOWN;
3790 /* Note: it's safe to delete hosts even if they have call
3791 * back state, because break delayed callbacks (called when a
3792 * message is received from the workstation) will always send a
3793 * break all call backs to the workstation if there is no
3798 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3800 (void)afs_inet_ntoa_r(host->host, hoststr);
3801 if (host->interface) {
3802 afsUUID uuid = host->interface->uuid;
3804 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3807 if (MultiProbeAlternateAddress_r(host)) {
3808 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3809 hoststr, ntohs(host->port), code));
3810 host->hostFlags |= VENUSDOWN;
3815 code = RXAFSCB_Probe(cb_conn);
3819 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3820 hoststr, ntohs(host->port), code));
3821 host->hostFlags |= VENUSDOWN;
3827 rx_PutConnection(cb_conn);
3830 host->hostFlags &= ~HWHO_INPROGRESS;
3841 CheckHost_r(struct host *host, void *dummy)
3843 struct client *client;
3844 struct rx_connection *cb_conn = NULL;
3847 #ifdef AFS_DEMAND_ATTACH_FS
3848 /* kill the checkhost lwp ASAP during shutdown */
3850 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3852 return H_ENUMERATE_BAIL(0);
3857 /* Host is held by h_Enumerate_r */
3858 for (client = host->FirstClient; client; client = client->next) {
3859 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3860 client->deleted = 1;
3861 host->hostFlags |= CLIENTDELETED;
3864 if (host->LastCall < checktime) {
3866 if (!(host->hostFlags & HOSTDELETED)) {
3867 host->hostFlags |= HWHO_INPROGRESS;
3868 cb_conn = host->callback_rxcon;
3869 rx_GetConnection(cb_conn);
3870 if (host->LastCall < clientdeletetime) {
3871 host->hostFlags |= HOSTDELETED;
3872 if (!(host->hostFlags & VENUSDOWN)) {
3873 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3874 if (host->interface) {
3877 RXAFSCB_InitCallBackState3(cb_conn,
3883 RXAFSCB_InitCallBackState(cb_conn);
3886 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3889 (void)afs_inet_ntoa_r(host->host, hoststr);
3891 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3892 hoststr, ntohs(host->port)));
3893 host->hostFlags |= VENUSDOWN;
3895 /* Note: it's safe to delete hosts even if they have call
3896 * back state, because break delayed callbacks (called when a
3897 * message is received from the workstation) will always send a
3898 * break all call backs to the workstation if there is no
3903 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3905 (void)afs_inet_ntoa_r(host->host, hoststr);
3906 if (host->interface) {
3907 afsUUID uuid = host->interface->uuid;
3909 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3912 if (MultiProbeAlternateAddress_r(host)) {
3913 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3914 hoststr, ntohs(host->port), code));
3915 host->hostFlags |= VENUSDOWN;
3920 code = RXAFSCB_Probe(cb_conn);
3924 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3925 hoststr, ntohs(host->port), code));
3926 host->hostFlags |= VENUSDOWN;
3932 rx_PutConnection(cb_conn);
3935 host->hostFlags &= ~HWHO_INPROGRESS;
3945 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3946 * don't respond to a probe. Note that VenusDown can only be cleared if
3947 * a message is received from the host (see ServerLWP in file.c).
3948 * Delete hosts that have not had any calls in 1 hour, clients that
3949 * have not had any calls in 15 minutes.
3951 * This routine is called roughly every 5 minutes.
3956 afs_uint32 now = FT_ApproxTime();
3958 memset(&zerofid, 0, sizeof(zerofid));
3960 * Send a probe to the workstation if it hasn't been heard from in
3963 checktime = now - 15 * 60;
3964 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3967 h_Enumerate_r(CheckHost_r, hostList, NULL);
3972 * This is called with host locked and held. At this point, the
3973 * hostAddrHashTable has an entry for the primary addr/port inserted
3974 * by h_Alloc_r(). No other interfaces should be considered valid.
3976 * The addresses in the interfaceAddr list are in host byte order.
3979 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3986 struct Interface *interface;
3989 afs_uint16 port7001 = htons(7001);
3994 number = interf->numberOfInterfaces;
3995 myAddr = host->host; /* current interface address */
3996 myPort = host->port; /* current port */
3999 ("initInterfaceAddr : host %s:%d numAddr %d\n",
4000 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
4002 /* validation checks */
4003 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
4005 ("Invalid number of alternate addresses is %d\n", number));
4010 * The client's notion of its own IP addresses is not reliable.
4012 * 1. The client list might contain private address ranges which
4013 * are likely to be re-used by many clients allocated addresses
4016 * 2. The client list will not include any public addresses that
4017 * are hidden by a NAT.
4019 * 3. Private address ranges that are exposed to the server will
4020 * be obtained from the rx connections that use them.
4022 * 4. Lists provided by the client are not necessarily truthful.
4023 * Many existing clients (UNIX) do not refresh the IP address
4024 * list as the actual assigned addresses change. The end result
4025 * is that they report the initial address list for the lifetime
4026 * of the process. In other words, a client can report addresses
4027 * that they are in fact not using. Adding these addresses to
4028 * the host interface list without verification is not only
4029 * pointless, it is downright dangerous.
4031 * We therefore do not add alternate addresses to the addr hash table.
4032 * We only use them for multi-rx callback breaks.
4036 * Convert IP addresses to network byte order, and remove
4037 * duplicate IP addresses from the interface list, and
4038 * determine whether or not the incoming addr/port is
4039 * listed. Note that if the address matches it is not
4040 * truly a match because the port number for the entries
4041 * in the interface list are port 7001 and the port number
4042 * for this connection might not be 7001.
4044 for (i = 0, count = 0, found = 0; i < number; i++) {
4045 interf->addr_in[i] = htonl(interf->addr_in[i]);
4046 for (j = 0; j < count; j++) {
4047 if (interf->addr_in[j] == interf->addr_in[i])
4051 interf->addr_in[count] = interf->addr_in[i];
4052 if (interf->addr_in[count] == myAddr &&
4060 * Allocate and initialize an interface structure for this host.
4063 interface = (struct Interface *)
4064 malloc(sizeof(struct Interface) +
4065 (sizeof(struct AddrPort) * (count - 1)));
4067 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
4069 interface->numberOfInterfaces = count;
4071 interface = (struct Interface *)
4072 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
4074 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4076 interface->numberOfInterfaces = count + 1;
4077 interface->interface[count].addr = myAddr;
4078 interface->interface[count].port = myPort;
4079 interface->interface[count].valid = 1;
4082 for (i = 0; i < count; i++) {
4084 interface->interface[i].addr = interf->addr_in[i];
4085 /* We store the port as 7001 because the addresses reported by
4086 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4087 * are coming from fully connected hosts (no NAT/PATs)
4089 interface->interface[i].port = port7001;
4090 interface->interface[i].valid =
4091 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4094 interface->uuid = interf->uuid;
4096 osi_Assert(!host->interface);
4097 host->interface = interface;
4099 if (LogLevel >= 125) {
4100 afsUUID_to_string(&interface->uuid, uuidstr, 127);
4102 ViceLog(125, ("--- uuid %s\n", uuidstr));
4103 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
4104 ViceLog(125, ("--- alt address %s:%d\n",
4105 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4106 ntohs(host->interface->interface[i].port)));
4113 /* deleted a HashChain structure for this address and host */
4114 /* returns 1 on success */
4116 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4120 struct h_AddrHashChain **hp, *th;
4122 if (addr == 0 && port == 0)
4125 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4127 osi_Assert(th->hostPtr);
4128 if (th->hostPtr == host && th->addr == addr && th->port == port) {
4129 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4130 host, afs_inet_ntoa_r(host->host, hoststr),
4131 ntohs(host->port)));
4138 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4139 host, afs_inet_ntoa_r(host->host, hoststr),
4140 ntohs(host->port)));
4146 ** prints out all alternate interface address for the host. The 'level'
4147 ** parameter indicates what level of debugging sets this output
4150 printInterfaceAddr(struct host *host, int level)
4155 if (host->interface) {
4156 /* check alternate addresses */
4157 number = host->interface->numberOfInterfaces;
4159 ViceLog(level, ("no-addresses "));
4161 for (i = 0; i < number; i++)
4162 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4163 ntohs(host->interface->interface[i].port)));
4166 ViceLog(level, ("\n"));