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>
26 #include <netinet/in.h>
31 #include <afs/afs_assert.h>
34 #include <afs/afsint.h>
35 #define FSINT_COMMON_XG
36 #include <afs/afscbint.h>
37 #include <afs/rxgen_consts.h>
39 #include <afs/errors.h>
40 #include <afs/ihandle.h>
41 #include <afs/vnode.h>
42 #include <afs/volume.h>
43 #ifdef AFS_ATHENA_STDENV
47 #include <afs/ptclient.h>
48 #include <afs/ptuser.h>
49 #include <afs/prs_fs.h>
51 #include <afs/afsutil.h>
52 #include <afs/com_err.h>
54 #include <afs/cellconfig.h>
56 #include "viced_prototypes.h"
60 #ifdef AFS_DEMAND_ATTACH_FS
61 #include "../util/afsutil_prototypes.h"
62 #include "../tviced/serialize_state.h"
63 #endif /* AFS_DEMAND_ATTACH_FS */
65 #ifdef AFS_PTHREAD_ENV
66 pthread_mutex_t host_glock_mutex;
67 #endif /* AFS_PTHREAD_ENV */
70 extern int CurrentConnections;
72 extern int AnonymousID;
73 extern prlist AnonCPS;
75 extern struct afsconf_dir *confDir; /* config dir object */
76 extern int lwps; /* the max number of server threads */
77 extern afsUUID FS_HostUUID;
80 int CEs = 0; /* active clients */
81 int CEBlocks = 0; /* number of blocks of CEs */
82 struct client *CEFree = 0; /* first free client */
83 struct host *hostList = 0; /* linked list of all hosts */
84 int hostCount = 0; /* number of hosts in hostList */
88 static struct rx_securityClass *sc = NULL;
90 static void h_SetupCallbackConn_r(struct host * host);
91 static int h_threadquota(int);
93 #define CESPERBLOCK 73
94 struct CEBlock { /* block of CESPERBLOCK file entries */
95 struct client entry[CESPERBLOCK];
98 void h_TossStuff_r(struct host *host);
101 * Make sure the subnet macros have been defined.
104 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
107 #ifndef IN_CLASSA_SUBNET
108 #define IN_CLASSA_SUBNET 0xffff0000
112 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
115 #ifndef IN_CLASSB_SUBNET
116 #define IN_CLASSB_SUBNET 0xffffff00
120 /* get a new block of CEs and chain it on CEFree */
124 struct CEBlock *block;
127 block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
129 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
130 ShutDownAndCore(PANIC);
133 for (i = 0; i < (CESPERBLOCK - 1); i++) {
134 Lock_Init(&block->entry[i].lock);
135 block->entry[i].next = &(block->entry[i + 1]);
137 block->entry[CESPERBLOCK - 1].next = 0;
138 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
139 CEFree = (struct client *)block;
145 /* get the next available CE */
146 static struct client *
149 struct client *entry;
154 ViceLog(0, ("CEFree NULL in GetCE\n"));
155 ShutDownAndCore(PANIC);
159 CEFree = entry->next;
161 memset(entry, 0, CLIENT_TO_ZERO(entry));
167 /* return an entry to the free list */
169 FreeCE(struct client *entry)
171 entry->VenusEpoch = 0;
173 entry->next = CEFree;
180 * The HTs and HTBlocks variables were formerly static, but they are
181 * now referenced elsewhere in the FileServer.
183 int HTs = 0; /* active file entries */
184 int HTBlocks = 0; /* number of blocks of HTs */
185 static struct host *HTFree = 0; /* first free file entry */
188 * Hash tables of host pointers. We need two tables, one
189 * to map IP addresses onto host pointers, and another
190 * to map host UUIDs onto host pointers.
192 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
193 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
194 #define h_HashIndex(hostip) (ntohl(hostip) & (h_HASHENTRIES-1))
195 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
197 struct HTBlock { /* block of HTSPERBLOCK file entries */
198 struct host entry[h_HTSPERBLOCK];
202 /* get a new block of HTs and chain it on HTFree */
206 struct HTBlock *block;
208 static int index = 0;
210 if (HTBlocks == h_MAXHOSTTABLES) {
211 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
212 ShutDownAndCore(PANIC);
215 block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
217 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
218 ShutDownAndCore(PANIC);
220 #ifdef AFS_PTHREAD_ENV
221 for (i = 0; i < (h_HTSPERBLOCK); i++)
222 CV_INIT(&block->entry[i].cond, "block entry", CV_DEFAULT, 0);
223 #endif /* AFS_PTHREAD_ENV */
224 for (i = 0; i < (h_HTSPERBLOCK); i++)
225 Lock_Init(&block->entry[i].lock);
226 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
227 block->entry[i].next = &(block->entry[i + 1]);
228 for (i = 0; i < (h_HTSPERBLOCK); i++)
229 block->entry[i].index = index++;
230 block->entry[h_HTSPERBLOCK - 1].next = 0;
231 HTFree = (struct host *)block;
232 hosttableptrs[HTBlocks++] = block->entry;
237 /* get the next available HT */
245 osi_Assert(HTFree != NULL);
247 HTFree = entry->next;
249 memset(entry, 0, HOST_TO_ZERO(entry));
255 /* return an entry to the free list */
257 FreeHT(struct host *entry)
259 entry->next = HTFree;
266 hpr_Initialize(struct ubik_client **uclient)
269 struct rx_connection *serverconns[MAXSERVERS];
270 struct rx_securityClass *sc;
271 struct afsconf_dir *tdir;
273 struct afsconf_cell info;
277 tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
279 ViceLog(0, ("hpr_Initialize: Could not open configuration directory: %s", AFSDIR_SERVER_ETC_DIRPATH));
283 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
285 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
290 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
292 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s",
293 cellstr, confDir->name, AFSDIR_CELLSERVDB_FILE));
300 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
305 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
306 * to force use of the KeyFile. secLevel == 0 implies -noauth was
308 code = afsconf_ClientAuthSecure(tdir, &sc, &scIndex);
310 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s "
311 "(so trying noauth)", code, afs_error_message(code)));
312 scIndex = RX_SECIDX_NULL;
313 sc = rxnull_NewClientSecurityObject();
316 if (scIndex == RX_SECIDX_NULL)
317 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, "
318 "running unauthenticated. [%d]", code));
320 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
321 for (i = 0; i < info.numServers; i++) {
323 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
324 info.hostAddr[i].sin_port, PRSRV,
328 code = ubik_ClientInit(serverconns, uclient);
330 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
333 code = rxs_Release(sc);
338 hpr_End(struct ubik_client *uclient)
343 code = ubik_ClientDestroy(uclient);
349 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
351 #ifdef AFS_PTHREAD_ENV
354 struct ubik_client *uclient =
355 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
358 code = hpr_Initialize(&uclient);
360 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
366 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
367 if (code != PRSUCCESS)
370 /* do something about this, probably make a new call */
371 /* don't forget there's a hard limit in the interface */
373 "membership list for host id %d exceeds display limit\n",
378 return pr_GetHostCPS(host, CPS);
383 hpr_NameToId(namelist *names, idlist *ids)
385 #ifdef AFS_PTHREAD_ENV
388 struct ubik_client *uclient =
389 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
392 code = hpr_Initialize(&uclient);
394 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
399 for (i = 0; i < names->namelist_len; i++)
400 stolower(names->namelist_val[i]);
401 code = ubik_PR_NameToID(uclient, 0, names, ids);
404 return pr_NameToId(names, ids);
409 hpr_IdToName(idlist *ids, namelist *names)
411 #ifdef AFS_PTHREAD_ENV
413 struct ubik_client *uclient =
414 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
417 code = hpr_Initialize(&uclient);
419 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
424 code = ubik_PR_IDToName(uclient, 0, ids, names);
427 return pr_IdToName(ids, names);
432 hpr_GetCPS(afs_int32 id, prlist *CPS)
434 #ifdef AFS_PTHREAD_ENV
437 struct ubik_client *uclient =
438 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
441 code = hpr_Initialize(&uclient);
443 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
449 code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
450 if (code != PRSUCCESS)
453 /* do something about this, probably make a new call */
454 /* don't forget there's a hard limit in the interface */
455 fprintf(stderr, "membership list for id %d exceeds display limit\n",
460 return pr_GetCPS(id, CPS);
464 static short consolePort = 0;
467 h_Lock_r(struct host *host)
477 * returns 1 if already locked
478 * else returns locks and returns 0
482 h_NBLock_r(struct host *host)
484 struct Lock *hostLock = &host->lock;
489 if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
490 hostLock->excl_locked = WRITE_LOCK;
494 LOCK_UNLOCK(hostLock);
503 #if FS_STATS_DETAILED
504 /*------------------------------------------------------------------------
505 * PRIVATE h_AddrInSameNetwork
508 * Given a target IP address and a candidate IP address (both
509 * in host byte order), return a non-zero value (1) if the
510 * candidate address is in a different network from the target
514 * a_targetAddr : Target address.
515 * a_candAddr : Candidate address.
518 * 1 if the candidate address is in the same net as the target,
522 * The target and candidate addresses are both in host byte
523 * order, NOT network byte order, when passed in. We return
524 * our value as a character, since that's the type of field in
525 * the host structure, where this info will be stored.
529 *------------------------------------------------------------------------*/
532 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
533 { /*h_AddrInSameNetwork */
535 afs_uint32 targetNet;
539 * Pull out the network and subnetwork numbers from the target
540 * and candidate addresses. We can short-circuit this whole
541 * affair if the target and candidate addresses are not of the
544 if (IN_CLASSA(a_targetAddr)) {
545 if (!(IN_CLASSA(a_candAddr))) {
548 targetNet = a_targetAddr & IN_CLASSA_NET;
549 candNet = a_candAddr & IN_CLASSA_NET;
550 } else if (IN_CLASSB(a_targetAddr)) {
551 if (!(IN_CLASSB(a_candAddr))) {
554 targetNet = a_targetAddr & IN_CLASSB_NET;
555 candNet = a_candAddr & IN_CLASSB_NET;
556 } /*Class B target */
557 else if (IN_CLASSC(a_targetAddr)) {
558 if (!(IN_CLASSC(a_candAddr))) {
561 targetNet = a_targetAddr & IN_CLASSC_NET;
562 candNet = a_candAddr & IN_CLASSC_NET;
563 } /*Class C target */
565 targetNet = a_targetAddr;
566 candNet = a_candAddr;
567 } /*Class D address */
570 * Now, simply compare the extracted net values for the two addresses
571 * (which at this point are known to be of the same class)
573 if (targetNet == candNet)
578 } /*h_AddrInSameNetwork */
579 #endif /* FS_STATS_DETAILED */
582 /* Assumptions: called with held host */
584 h_gethostcps_r(struct host *host, afs_int32 now)
589 /* wait if somebody else is already doing the getCPS call */
590 while (host->hostFlags & HCPS_INPROGRESS) {
591 slept = 1; /* I did sleep */
592 host->hostFlags |= HCPS_WAITING; /* I am sleeping now */
593 #ifdef AFS_PTHREAD_ENV
594 CV_WAIT(&host->cond, &host_glock_mutex);
595 #else /* AFS_PTHREAD_ENV */
596 if ((code = LWP_WaitProcess(&(host->hostFlags))) != LWP_SUCCESS)
597 ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
598 #endif /* AFS_PTHREAD_ENV */
602 host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
603 if (host->hcps.prlist_val)
604 free(host->hcps.prlist_val); /* this is for hostaclRefresh */
605 host->hcps.prlist_val = NULL;
606 host->hcps.prlist_len = 0;
607 host->cpsCall = slept ? (FT_ApproxTime()) : (now);
610 code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
615 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
616 * and reevaluates things if no sync server or quorum is found we could still end up
617 * with one of these errors. In such case we would like to reevaluate the rpc call to
618 * find if there's cps for this guy. We treat other errors (except network failures
619 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
620 * we could like to deal this problem the other way around (i.e. if code == NOCPS
621 * ignore else retry next time) but the problem is that there're other errors (i.e.
622 * EPERM) for which we don't want to retry and we don't know the whole code list!
624 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
626 * We would have preferred to use a while loop and try again since ops in protected
627 * acls for this host will fail now but they'll be reevaluated on any subsequent
628 * call. The attempt to wait for a quorum/sync site or network error won't work
629 * since this problems really should only occurs during a complete fileserver
630 * restart. Since the fileserver will start before the ptservers (and thus before
631 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
633 host->hcpsfailed = 1;
635 ("Warning: GetHostCPS failed (%d) for %p (%s:%d); will retry\n",
636 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
638 host->hcpsfailed = 0;
640 ("gethost: GetHostCPS failed (%d) for %p (%s:%d); ignored\n",
641 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
643 if (host->hcps.prlist_val)
644 free(host->hcps.prlist_val);
645 host->hcps.prlist_val = NULL;
646 host->hcps.prlist_len = 0; /* Make sure it's zero */
648 host->hcpsfailed = 0;
650 host->hostFlags &= ~HCPS_INPROGRESS;
651 /* signal all who are waiting */
652 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
653 host->hostFlags &= ~HCPS_WAITING;
654 #ifdef AFS_PTHREAD_ENV
655 CV_BROADCAST(&host->cond);
656 #else /* AFS_PTHREAD_ENV */
657 if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
658 ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
659 #endif /* AFS_PTHREAD_ENV */
663 /* args in net byte order */
665 h_flushhostcps(afs_uint32 hostaddr, afs_uint16 hport)
670 h_Lookup_r(hostaddr, hport, &host);
672 host->hcpsfailed = 1;
681 * Allocate a host. It will be identified by the peer (ip,port) info in the
682 * rx connection provided. The host is returned held and locked
684 #define DEF_ROPCONS 2115
687 h_Alloc_r(struct rx_connection *r_con)
689 struct servent *serverentry;
691 #if FS_STATS_DETAILED
692 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
693 #endif /* FS_STATS_DETAILED */
697 host->host = rxr_HostOf(r_con);
698 host->port = rxr_PortOf(r_con);
700 h_AddHostToAddrHashTable_r(host->host, host->port, host);
702 if (consolePort == 0) { /* find the portal number for console */
703 #if defined(AFS_OSF_ENV)
704 serverentry = getservbyname("ropcons", "");
706 serverentry = getservbyname("ropcons", 0);
709 consolePort = serverentry->s_port;
711 consolePort = htons(DEF_ROPCONS); /* Use a default */
713 if (host->port == consolePort)
715 /* Make a callback channel even for the console, on the off chance that it
716 * makes a request that causes a break call back. It shouldn't. */
717 h_SetupCallbackConn_r(host);
718 host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
720 host->hcps.prlist_val = NULL;
721 host->hcps.prlist_len = 0;
722 host->interface = NULL;
724 host->hcpsfailed = 0; /* save cycles */
725 h_gethostcps(host); /* do this under host hold/lock */
727 host->FirstClient = NULL;
730 h_InsertList_r(host); /* update global host List */
731 #if FS_STATS_DETAILED
733 * Compare the new host's IP address (in host byte order) with ours
734 * (the File Server's), remembering if they are in the same network.
736 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
737 host->InSameNetwork =
738 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
739 #endif /* FS_STATS_DETAILED */
746 /* Make a callback channel even for the console, on the off chance that it
747 * makes a request that causes a break call back. It shouldn't. */
749 h_SetupCallbackConn_r(struct host * host)
752 sc = rxnull_NewClientSecurityObject();
753 host->callback_rxcon =
754 rx_NewConnection(host->host, host->port, 1, sc, 0);
755 rx_SetConnDeadTime(host->callback_rxcon, 50);
756 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
760 * Lookup a host given an IP address and UDP port number.
761 * hostaddr and hport are in network order
762 * hostaddr and hport are in network order
763 * On return, refCount is incremented.
766 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, struct host **hostp)
769 struct host *host = NULL;
770 struct h_AddrHashChain *chain;
771 int index = h_HashIndex(haddr);
772 extern int hostaclRefresh;
775 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
776 host = chain->hostPtr;
778 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
779 && chain->port == hport) {
780 if ((host->hostFlags & HWHO_INPROGRESS) &&
781 h_threadquota(host->lock.num_waiting)) {
787 if (host->hostFlags & HOSTDELETED) {
794 now = FT_ApproxTime(); /* always evaluate "now" */
795 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
797 * Every hostaclRefresh period (def 2 hrs) get the new
798 * membership list for the host. Note this could be the
799 * first time that the host is added to a group. Also
800 * here we also retry on previous legitimate hcps failures.
802 * If we get here refCount is elevated.
804 h_gethostcps_r(host, now);
814 /* Lookup a host given its UUID. */
816 h_LookupUuid_r(afsUUID * uuidp)
818 struct host *host = 0;
819 struct h_UuidHashChain *chain;
820 int index = h_UuidHashIndex(uuidp);
822 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
823 host = chain->hostPtr;
825 if (!(host->hostFlags & HOSTDELETED) && host->interface
826 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
834 /* h_TossStuff_r: Toss anything in the host structure (the host or
835 * clients marked for deletion. Called from h_Release_r ONLY.
836 * To be called, there must be no holds, and either host->deleted
837 * or host->clientDeleted must be set.
840 h_TossStuff_r(struct host *host)
842 struct client **cp, *client;
845 /* make sure host doesn't go away over h_NBLock_r */
848 code = h_NBLock_r(host);
850 /* don't use h_Release_r, since that may call h_TossStuff_r again */
853 /* if somebody still has this host locked */
857 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was locked.\n",
858 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
864 /* if somebody still has this host held */
865 /* we must check this _after_ h_NBLock_r, since h_NBLock_r can drop and
866 * reacquire H_LOCK */
867 if (host->refCount > 0) {
870 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was held.\n",
871 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
875 /* ASSUMPTION: rxi_FreeConnection() does not yield */
876 for (cp = &host->FirstClient; (client = *cp);) {
877 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
879 ObtainWriteLockNoBlock(&client->lock, code);
883 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
884 "client %p was locked.\n",
885 host, afs_inet_ntoa_r(host->host, hoststr),
886 ntohs(host->port), client));
890 if (client->refCount) {
893 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
894 "client %p refcount %d.\n",
895 host, afs_inet_ntoa_r(host->host, hoststr),
896 ntohs(host->port), client, client->refCount));
897 /* This is the same thing we do if the host is locked */
898 ReleaseWriteLock(&client->lock);
901 client->CPS.prlist_len = 0;
902 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
903 free(client->CPS.prlist_val);
904 client->CPS.prlist_val = NULL;
905 CurrentConnections--;
907 ReleaseWriteLock(&client->lock);
913 /* We've just cleaned out all the deleted clients; clear the flag */
914 host->hostFlags &= ~CLIENTDELETED;
916 if (host->hostFlags & HOSTDELETED) {
917 struct rx_connection *rxconn;
918 struct AddrPort hostAddrPort;
921 if (host->Console & 1)
923 if ((rxconn = host->callback_rxcon)) {
924 host->callback_rxcon = (struct rx_connection *)0;
925 rx_DestroyConnection(rxconn);
927 if (host->hcps.prlist_val)
928 free(host->hcps.prlist_val);
929 host->hcps.prlist_val = NULL;
930 host->hcps.prlist_len = 0;
931 DeleteAllCallBacks_r(host, 1);
932 host->hostFlags &= ~RESETDONE; /* just to be safe */
934 /* if alternate addresses do not exist */
935 if (!(host->interface)) {
936 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
938 h_DeleteHostFromUuidHashTable_r(host);
939 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
940 /* delete the hash entry for each valid alternate addresses */
941 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
942 hostAddrPort = host->interface->interface[i];
944 * if the interface addr/port is the primary, we already
945 * removed it. If the addr/port is not valid, its not
948 if (hostAddrPort.valid &&
949 (host->host != hostAddrPort.addr ||
950 host->port != hostAddrPort.port))
951 h_DeleteHostFromAddrHashTable_r(hostAddrPort.addr, hostAddrPort.port, host);
953 free(host->interface);
954 host->interface = NULL;
955 } /* if alternate address exists */
957 h_DeleteList_r(host); /* remove host from global host List */
964 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
965 * system at the start of the enumeration (perhaps more). Hosts may be deleted
966 * (have delete flag set); ditto for clients. refCount is always incremented
967 * before (*proc) is called. The param flags is passed to (*proc) as the
968 * param flags, permitting (*proc) to stop the enumeration (BAIL).
970 * Needed? Why not always h_Hold_r and h_Release_r in (*proc), or even -never-
971 * h_Hold_r or h_Release_r in (*proc)?
973 * **The proc should return 0 if the host should be released, 1 if it should
974 * be held after enumeration.
977 h_Enumerate(int (*proc) (struct host*, int, void *), void *param)
979 struct host *host, **list;
985 if (hostCount == 0) {
989 list = (struct host **)malloc(hostCount * sizeof(struct host *));
991 ViceLog(0, ("Failed malloc in h_Enumerate (list)\n"));
992 osi_Panic("Failed malloc in h_Enumerate (list)\n");
994 flags = (int *)malloc(hostCount * sizeof(int));
996 ViceLog(0, ("Failed malloc in h_Enumerate (flags)\n"));
997 osi_Panic("Failed malloc in h_Enumerate (flags)\n");
999 for (totalCount = count = 0, host = hostList;
1000 host && totalCount < hostCount;
1001 host = host->next, totalCount++) {
1003 if (!(host->hostFlags & HOSTDELETED)) {
1009 if (totalCount != hostCount) {
1010 ViceLog(0, ("h_Enumerate found %d of %d hosts\n", totalCount, hostCount));
1011 } else if (host != NULL) {
1012 ViceLog(0, ("h_Enumerate found more than %d hosts\n", hostCount));
1013 ShutDownAndCore(PANIC);
1016 for (i = 0; i < count; i++) {
1017 flags[i] = (*proc) (list[i], flags[i], param);
1019 h_Release_r(list[i]);
1021 /* bail out of the enumeration early */
1022 if (H_ENUMERATE_ISSET_BAIL(flags[i]))
1026 free((void *)flags);
1030 /* h_Enumerate_r (revised):
1031 * Calls (*proc)(host, flags, param) for each host in hostList, starting
1032 * at enumstart. Called only under H_LOCK. Hosts may be deleted (have
1033 * delete flag set); ditto for clients. refCount is always incremented
1034 * before (*proc) is called. The param flags is passed to (*proc) as the
1035 * param flags, permitting (*proc) to stop the enumeration (BAIL).
1037 * Needed? Why not always h_Hold_r and h_Release_r in (*proc), or even -never-
1038 * h_Hold_r or h_Release_r in (*proc)?
1040 * @note Assumes that hostList is only prepended to, that a host is never
1041 * inserted into the middle. Otherwise this would not be guaranteed to
1044 * **The proc should return 0 if the host should be released, 1 if it should
1045 * be held after enumeration.
1048 h_Enumerate_r(int (*proc) (struct host *, int, void *),
1049 struct host *enumstart, void *param)
1051 struct host *host, *next;
1057 if (hostCount == 0) {
1064 /* find the first non-deleted host, so we know where to actually start
1066 for (count = 0; host && count < hostCount; count++) {
1067 if (!(host->hostFlags & HOSTDELETED)) {
1074 /* we didn't find a non-deleted host... */
1076 if (host && count >= hostCount) {
1077 /* ...because we found a loop */
1078 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", hostCount));
1079 ShutDownAndCore(PANIC);
1082 /* ...because the hostList is full of deleted hosts */
1086 h_Hold_r(enumstart);
1088 /* remember hostCount, lest it change over the potential H_LOCK drop in
1090 origHostCount = hostCount;
1092 for (count = 0, host = enumstart; host && count < origHostCount; host = next, flags = nflags, count++) {
1095 /* find the next non-deleted host */
1096 while (next && (next->hostFlags & HOSTDELETED)) {
1098 /* inc count for the skipped-over host */
1099 if (++count > origHostCount) {
1100 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1101 ShutDownAndCore(PANIC);
1104 if (next && !H_ENUMERATE_ISSET_BAIL(flags))
1107 if (!(host->hostFlags & HOSTDELETED)) {
1108 flags = (*proc) (host, flags, param);
1109 if (H_ENUMERATE_ISSET_BAIL(flags)) {
1110 h_Release_r(host); /* this might free up the host */
1114 h_Release_r(host); /* this might free up the host */
1116 if (host != NULL && count >= origHostCount) {
1117 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1118 ShutDownAndCore(PANIC);
1120 } /*h_Enumerate_r */
1123 /* inserts a new HashChain structure corresponding to this UUID */
1125 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1128 struct h_UuidHashChain *chain;
1129 char uuid1[128], uuid2[128];
1132 /* hash into proper bucket */
1133 index = h_UuidHashIndex(uuid);
1135 /* don't add the same entry multiple times */
1136 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1137 if (!chain->hostPtr)
1140 if (chain->hostPtr->interface &&
1141 afs_uuid_equal(&chain->hostPtr->interface->uuid, uuid)) {
1142 if (LogLevel >= 125) {
1143 afsUUID_to_string(&chain->hostPtr->interface->uuid, uuid1,
1145 afsUUID_to_string(uuid, uuid2, 127);
1146 ViceLog(125, ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s) exists as %s:%d (uuid %s)\n",
1148 afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1149 ntohs(chain->hostPtr->port), uuid2));
1155 /* insert into beginning of list for this bucket */
1156 chain = (struct h_UuidHashChain *)malloc(sizeof(struct h_UuidHashChain));
1158 ViceLog(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1159 osi_Panic("Failed malloc in h_AddHostToUuidHashTable_r\n");
1161 chain->hostPtr = host;
1162 chain->next = hostUuidHashTable[index];
1163 hostUuidHashTable[index] = chain;
1166 afsUUID_to_string(uuid, uuid2, 127);
1168 ("h_AddHostToUuidHashTable_r: host %p (%s:%d) added as uuid %s\n",
1169 host, afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1170 ntohs(chain->hostPtr->port), uuid2));
1173 /* deletes a HashChain structure corresponding to this host */
1175 h_DeleteHostFromUuidHashTable_r(struct host *host)
1178 struct h_UuidHashChain **uhp, *uth;
1182 if (!host->interface)
1185 /* hash into proper bucket */
1186 index = h_UuidHashIndex(&host->interface->uuid);
1188 if (LogLevel >= 125)
1189 afsUUID_to_string(&host->interface->uuid, uuid1, 127);
1190 for (uhp = &hostUuidHashTable[index]; (uth = *uhp); uhp = &uth->next) {
1191 osi_Assert(uth->hostPtr);
1192 if (uth->hostPtr == host) {
1194 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d)\n",
1195 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1196 ntohs(host->port)));
1203 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d) not found\n",
1204 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1205 ntohs(host->port)));
1210 * This is called with host locked and held.
1212 * All addresses are in network byte order.
1215 invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1219 struct Interface *interface;
1220 char hoststr[16], hoststr2[16];
1223 osi_Assert(host->interface);
1225 ViceLog(125, ("invalidateInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1226 host, afs_inet_ntoa_r(host->host, hoststr),
1227 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1231 * Make sure this address is on the list of known addresses
1234 interface = host->interface;
1235 number = host->interface->numberOfInterfaces;
1236 for (i = 0; i < number; i++) {
1237 if (interface->interface[i].addr == addr &&
1238 interface->interface[i].port == port) {
1239 if (interface->interface[i].valid) {
1240 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1241 interface->interface[i].valid = 0;
1252 * This is called with host locked and held. This function differs
1253 * from removeInterfaceAddr_r in that it is called when the address
1254 * is being removed from the host regardless of whether or not there
1255 * is an interface list for the host. This function will delete the
1256 * host if there are no addresses left on it.
1258 * All addresses are in network byte order.
1261 removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1264 char hoststr[16], hoststr2[16];
1265 struct rx_connection *rxconn;
1267 if (!host->interface || host->interface->numberOfInterfaces == 1) {
1268 if (host->host == addr && host->port == port) {
1270 ("Removing only address for host %" AFS_PTR_FMT " (%s:%d), deleting host.\n",
1271 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1272 host->hostFlags |= HOSTDELETED;
1274 * Do not remove the primary addr/port from the hash table.
1275 * It will be ignored due to the HOSTDELETED flag and will
1276 * be removed when h_TossStuff_r() cleans up the HOSTDELETED
1277 * host. Removing it here will only result in a search for
1278 * the host/addr/port in the hash chain which will fail.
1282 ("Removing address that does not belong to host %" AFS_PTR_FMT " (%s:%d).\n",
1283 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1286 if (host->host == addr && host->port == port) {
1287 removeInterfaceAddr_r(host, addr, port);
1289 for (i=0; i < host->interface->numberOfInterfaces; i++) {
1290 if (host->interface->interface[i].valid) {
1292 ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
1293 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1294 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
1295 ntohs(host->interface->interface[i].port)));
1296 host->host = host->interface->interface[i].addr;
1297 host->port = host->interface->interface[i].port;
1298 h_AddHostToAddrHashTable_r(host->host, host->port, host);
1303 if (i == host->interface->numberOfInterfaces) {
1305 ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
1306 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1307 host->hostFlags |= HOSTDELETED;
1308 /* addr/port was removed from the hash table */
1312 rxconn = host->callback_rxcon;
1313 host->callback_rxcon = NULL;
1316 rx_DestroyConnection(rxconn);
1321 sc = rxnull_NewClientSecurityObject();
1322 host->callback_rxcon =
1323 rx_NewConnection(host->host, host->port, 1, sc, 0);
1324 rx_SetConnDeadTime(host->callback_rxcon, 50);
1325 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
1328 /* not the primary addr/port, just invalidate it */
1329 invalidateInterfaceAddr_r(host, addr, port);
1337 createHostAddrHashChain_r(int index, afs_uint32 addr, afs_uint16 port, struct host *host)
1339 struct h_AddrHashChain *chain;
1342 /* insert into beginning of list for this bucket */
1343 chain = (struct h_AddrHashChain *)malloc(sizeof(struct h_AddrHashChain));
1345 ViceLog(0, ("Failed malloc in h_AddHostToAddrHashTable_r\n"));
1346 osi_Panic("Failed malloc in h_AddHostToAddrHashTable_r\n");
1348 chain->hostPtr = host;
1349 chain->next = hostAddrHashTable[index];
1352 hostAddrHashTable[index] = chain;
1353 ViceLog(125, ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " added as %s:%d\n",
1354 host, afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1358 * Resolve host address conflicts when hashing by address.
1360 * @param[in] addr an ip address of the interface
1361 * @param[in] port the port of the interface
1362 * @param[in] newHost the host being added with this address
1363 * @param[in] oldHost the host previously added with this address
1366 reconcileHosts_r(afs_uint32 addr, afs_uint16 port, struct host *newHost,
1367 struct host *oldHost)
1369 struct rx_connection *cb = NULL;
1371 struct interfaceAddr interf;
1373 afsUUID *newHostUuid = &nulluuid;
1374 afsUUID *oldHostUuid = &nulluuid;
1378 ("reconcileHosts_r: addr %s:%d newHost %" AFS_PTR_FMT " oldHost %"
1379 AFS_PTR_FMT, afs_inet_ntoa_r(addr, hoststr), ntohs(port),
1382 osi_Assert(oldHost != newHost);
1383 caps.Capabilities_val = NULL;
1386 sc = rxnull_NewClientSecurityObject();
1389 cb = rx_NewConnection(addr, port, 1, sc, 0);
1390 rx_SetConnDeadTime(cb, 50);
1391 rx_SetConnHardDeadTime(cb, AFS_HARDDEADTIME);
1396 code = RXAFSCB_TellMeAboutYourself(cb, &interf, &caps);
1397 if (code == RXGEN_OPCODE) {
1398 code = RXAFSCB_WhoAreYou(cb, &interf);
1402 if (code == RXGEN_OPCODE ||
1403 (code == 0 && afs_uuid_equal(&interf.uuid, &nulluuid))) {
1405 ("reconcileHosts_r: WhoAreYou not supported for connection (%s:%d), error %d\n",
1406 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1411 ("reconcileHosts_r: WhoAreYou failed for connection (%s:%d), error %d\n",
1412 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1416 /* Since lock was dropped, the hosts may have been deleted during the rpcs. */
1417 if ((newHost->hostFlags & HOSTDELETED)
1418 && (oldHost->hostFlags & HOSTDELETED)) {
1420 ("reconcileHosts_r: new and old hosts were deleted during probe.\n"));
1424 /* A check can be done if at least one of the hosts has a uuid. It
1425 * is an error if the hosts have the same (not null) uuid. */
1426 if ((!(newHost->hostFlags & HOSTDELETED)) && newHost->interface) {
1427 newHostUuid = &(newHost->interface->uuid);
1429 if ((!(oldHost->hostFlags & HOSTDELETED)) && oldHost->interface) {
1430 oldHostUuid = &(oldHost->interface->uuid);
1432 if (afs_uuid_equal(newHostUuid, &nulluuid) &&
1433 afs_uuid_equal(oldHostUuid, &nulluuid)) {
1435 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), no uuids\n",
1436 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1439 if (afs_uuid_equal(newHostUuid, oldHostUuid)) {
1441 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), same uuids\n",
1442 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1446 /* Determine which host should be hashed */
1447 if ((!(newHost->hostFlags & HOSTDELETED))
1448 && afs_uuid_equal(newHostUuid, &(interf.uuid))) {
1449 /* Install the new host into the hash before removing the stale
1450 * addresses. Walk the hash chain again since the hash table may have
1451 * been changed when the host lock was dropped to get the uuid. */
1452 struct h_AddrHashChain *chain;
1453 int index = h_HashIndex(addr);
1454 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1455 if (chain->addr == addr && chain->port == port) {
1456 chain->hostPtr = newHost;
1457 removeAddress_r(oldHost, addr, port);
1461 createHostAddrHashChain_r(index, addr, port, newHost);
1462 removeAddress_r(oldHost, addr, port);
1465 if ((!(oldHost->hostFlags & HOSTDELETED))
1466 && afs_uuid_equal(oldHostUuid, &(interf.uuid))) {
1467 removeAddress_r(newHost, addr, port);
1472 if (!(newHost->hostFlags & HOSTDELETED)) {
1473 removeAddress_r(newHost, addr, port);
1475 if (!(oldHost->hostFlags & HOSTDELETED)) {
1476 removeAddress_r(oldHost, addr, port);
1480 h_Release_r(newHost);
1481 h_Release_r(oldHost);
1482 rx_DestroyConnection(cb);
1486 /* inserts a new HashChain structure corresponding to this address */
1488 h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1491 struct h_AddrHashChain *chain;
1494 /* hash into proper bucket */
1495 index = h_HashIndex(addr);
1497 /* don't add the same address:port pair entry multiple times */
1498 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1499 if (chain->addr == addr && chain->port == port) {
1500 if (chain->hostPtr == host) {
1502 ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
1503 host, afs_inet_ntoa_r(chain->addr, hoststr),
1504 ntohs(chain->port)));
1507 if (!(chain->hostPtr->hostFlags & HOSTDELETED)) {
1508 /* attempt to resolve host address collision */
1509 reconcileHosts_r(addr, port, host, chain->hostPtr);
1514 createHostAddrHashChain_r(index, addr, port, host);
1518 * This is called with host locked and held.
1519 * It is called to either validate or add an additional interface
1520 * address/port on the specified host.
1522 * All addresses are in network byte order.
1525 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1529 struct Interface *interface;
1530 char hoststr[16], hoststr2[16];
1533 osi_Assert(host->interface);
1536 * Make sure this address is on the list of known addresses
1539 number = host->interface->numberOfInterfaces;
1540 for (i = 0; i < number; i++) {
1541 if (host->interface->interface[i].addr == addr &&
1542 host->interface->interface[i].port == port) {
1544 ("addInterfaceAddr : found host %" AFS_PTR_FMT " (%s:%d) adding %s:%d%s\n",
1545 host, afs_inet_ntoa_r(host->host, hoststr),
1546 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1547 ntohs(port), host->interface->interface[i].valid ? "" :
1550 if (host->interface->interface[i].valid == 0) {
1551 host->interface->interface[i].valid = 1;
1552 h_AddHostToAddrHashTable_r(addr, port, host);
1558 ViceLog(125, ("addInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) adding %s:%d\n",
1559 host, afs_inet_ntoa_r(host->host, hoststr),
1560 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1563 interface = (struct Interface *)
1564 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1566 ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
1567 osi_Panic("Failed malloc in addInterfaceAddr_r\n");
1569 interface->numberOfInterfaces = number + 1;
1570 interface->uuid = host->interface->uuid;
1571 for (i = 0; i < number; i++)
1572 interface->interface[i] = host->interface->interface[i];
1574 /* Add the new valid interface */
1575 interface->interface[number].addr = addr;
1576 interface->interface[number].port = port;
1577 interface->interface[number].valid = 1;
1578 h_AddHostToAddrHashTable_r(addr, port, host);
1579 free(host->interface);
1580 host->interface = interface;
1587 * This is called with host locked and held.
1589 * All addresses are in network byte order.
1592 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1596 struct Interface *interface;
1597 char hoststr[16], hoststr2[16];
1600 osi_Assert(host->interface);
1602 ViceLog(125, ("removeInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1603 host, afs_inet_ntoa_r(host->host, hoststr),
1604 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1608 * Make sure this address is on the list of known addresses
1611 interface = host->interface;
1612 number = host->interface->numberOfInterfaces;
1613 for (i = 0; i < number; i++) {
1614 if (interface->interface[i].addr == addr &&
1615 interface->interface[i].port == port) {
1616 if (interface->interface[i].valid)
1617 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1619 for (; i < number; i++) {
1620 interface->interface[i] = interface->interface[i+1];
1622 interface->numberOfInterfaces = number;
1633 h_threadquota(int waiting)
1638 } else if (lwps > 32) {
1641 } else if (lwps > 16) {
1651 /* If found, host is returned with refCount incremented */
1653 h_GetHost_r(struct rx_connection *tcon)
1656 struct host *oldHost;
1658 struct interfaceAddr interf;
1659 int interfValid = 0;
1660 struct Identity *identP = NULL;
1663 char hoststr[16], hoststr2[16];
1665 struct rx_connection *cb_conn = NULL;
1666 struct rx_connection *cb_in = NULL;
1668 caps.Capabilities_val = NULL;
1670 haddr = rxr_HostOf(tcon);
1671 hport = rxr_PortOf(tcon);
1674 rx_DestroyConnection(cb_in);
1677 if (caps.Capabilities_val)
1678 free(caps.Capabilities_val);
1679 caps.Capabilities_val = NULL;
1680 caps.Capabilities_len = 0;
1683 if (h_Lookup_r(haddr, hport, &host))
1685 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1686 if (host && !identP && !(host->Console & 1)) {
1687 /* This is a new connection, and we already have a host
1688 * structure for this address. Verify that the identity
1689 * of the caller matches the identity in the host structure.
1691 if ((host->hostFlags & HWHO_INPROGRESS) &&
1692 h_threadquota(host->lock.num_waiting)) {
1698 if (!(host->hostFlags & ALTADDR) ||
1699 (host->hostFlags & HOSTDELETED)) {
1700 /* Another thread is doing initialization
1701 * or this host was deleted while we
1702 * waited for the lock. */
1705 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1706 host, afs_inet_ntoa_r(host->host, hoststr),
1707 ntohs(host->port)));
1711 host->hostFlags |= HWHO_INPROGRESS;
1712 host->hostFlags &= ~ALTADDR;
1714 /* We received a new connection from an IP address/port
1715 * that is associated with 'host' but the address/port of
1716 * the callback connection does not have to match it.
1717 * If there is a match, we can use the existing callback
1718 * connection to verify the UUID. If they do not match
1719 * we need to use a new callback connection to verify the
1720 * UUID of the incoming caller and perhaps use the old
1721 * callback connection to verify that the old address/port
1725 cb_conn = host->callback_rxcon;
1726 rx_GetConnection(cb_conn);
1728 if (haddr == host->host && hport == host->port) {
1729 /* The existing callback connection matches the
1730 * incoming connection so just use it.
1733 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1734 if (code == RXGEN_OPCODE)
1735 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1737 /* We do not have a match. Create a new connection
1738 * for the new addr/port and use multi_Rx to probe
1739 * both of them simultaneously.
1742 sc = rxnull_NewClientSecurityObject();
1743 cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1744 rx_SetConnDeadTime(cb_in, 50);
1745 rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1748 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1749 if (code == RXGEN_OPCODE)
1750 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1752 rx_PutConnection(cb_conn);
1755 if ((code == RXGEN_OPCODE) ||
1756 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1757 identP = (struct Identity *)malloc(sizeof(struct Identity));
1759 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1760 osi_Panic("Failed malloc in h_GetHost_r\n");
1763 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1764 if (cb_in == NULL) {
1765 /* The host on this connection was unable to respond to
1766 * the WhoAreYou. We will treat this as a new connection
1767 * from the existing host. The worst that can happen is
1768 * that we maintain some extra callback state information */
1769 if (host->interface) {
1771 ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1773 afs_inet_ntoa_r(host->host, hoststr),
1774 ntohs(host->port)));
1775 host->hostFlags |= HOSTDELETED;
1776 host->hostFlags &= ~HWHO_INPROGRESS;
1783 /* The incoming connection does not support WhoAreYou but
1784 * the original one might have. Use removeAddress_r() to
1785 * remove this addr/port from the host that was found.
1786 * If there are no more addresses left for the host it
1787 * will be deleted. Then we retry.
1789 removeAddress_r(host, haddr, hport);
1790 host->hostFlags &= ~HWHO_INPROGRESS;
1791 host->hostFlags |= ALTADDR;
1797 } else if (code == 0) {
1799 identP = (struct Identity *)malloc(sizeof(struct Identity));
1801 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1802 osi_Panic("Failed malloc in h_GetHost_r\n");
1805 identP->uuid = interf.uuid;
1806 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1807 /* Check whether the UUID on this connection matches
1808 * the UUID in the host structure. If they don't match
1809 * then this is not the same host as before. */
1810 if (!host->interface
1811 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1814 ("Uuid doesn't match connection (%s:%d).\n",
1815 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1816 removeAddress_r(host, haddr, hport);
1819 ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1820 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1822 removeAddress_r(host, host->host, host->port);
1824 host->hostFlags &= ~HWHO_INPROGRESS;
1825 host->hostFlags |= ALTADDR;
1831 /* the UUID matched the client at the incoming addr/port
1832 * but this is not the address of the active callback
1833 * connection. Try that connection and see if the client
1834 * is still there and if the reported UUID is the same.
1837 afsUUID uuid = host->interface->uuid;
1838 cb_conn = host->callback_rxcon;
1839 rx_GetConnection(cb_conn);
1840 rx_SetConnDeadTime(cb_conn, 2);
1841 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1843 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1845 rx_SetConnDeadTime(cb_conn, 50);
1846 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1847 rx_PutConnection(cb_conn);
1850 /* The primary address is either not responding or
1851 * is not the client we are looking for. Need to
1852 * remove the primary address and add swap in the new
1853 * callback connection, and destroy the old one.
1855 struct rx_connection *rxconn;
1856 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1858 afs_inet_ntoa_r(host->host, hoststr),
1859 ntohs(host->port),code2));
1862 * make sure we add and then remove. otherwise, we
1863 * might end up with no valid interfaces after the
1864 * remove and the host will have been marked deleted.
1866 addInterfaceAddr_r(host, haddr, hport);
1867 removeInterfaceAddr_r(host, host->host, host->port);
1870 rxconn = host->callback_rxcon;
1871 host->callback_rxcon = cb_in;
1876 * If rx_DestroyConnection calls h_FreeConnection we
1877 * will deadlock on the host_glock_mutex. Work around
1878 * the problem by unhooking the client from the
1879 * connection before destroying the connection.
1881 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1882 rx_DestroyConnection(rxconn);
1888 /* A callback to the incoming connection address is failing.
1889 * Assume that the addr/port is no longer associated with the host
1890 * returned by h_Lookup_r.
1893 ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1894 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1895 removeAddress_r(host, haddr, hport);
1896 host->hostFlags &= ~HWHO_INPROGRESS;
1897 host->hostFlags |= ALTADDR;
1901 rx_DestroyConnection(cb_in);
1906 ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1907 host, afs_inet_ntoa_r(host->host, hoststr),
1908 ntohs(host->port), code));
1909 host->hostFlags |= VENUSDOWN;
1912 if (caps.Capabilities_val
1913 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1914 host->hostFlags |= HERRORTRANS;
1916 host->hostFlags &= ~(HERRORTRANS);
1917 host->hostFlags |= ALTADDR;
1918 host->hostFlags &= ~HWHO_INPROGRESS;
1921 if (!(host->hostFlags & ALTADDR)) {
1922 /* another thread is doing the initialisation */
1924 ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1925 host, afs_inet_ntoa_r(host->host, hoststr),
1926 ntohs(host->port)));
1930 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1931 host, afs_inet_ntoa_r(host->host, hoststr),
1932 ntohs(host->port)));
1936 /* We need to check whether the identity in the host structure
1937 * matches the identity on the connection. If they don't match
1938 * then treat this a new host. */
1939 if (!(host->Console & 1)
1940 && ((!identP->valid && host->interface)
1941 || (identP->valid && !host->interface)
1943 && !afs_uuid_equal(&identP->uuid,
1944 &host->interface->uuid)))) {
1945 char uuid1[128], uuid2[128];
1947 afsUUID_to_string(&identP->uuid, uuid1, 127);
1948 if (host->interface)
1949 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1951 ("CB: new identity for host %p (%s:%d), "
1952 "deleting(%x %p %s %s)\n",
1953 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1954 identP->valid, host->interface,
1955 identP->valid ? uuid1 : "no_uuid",
1956 host->interface ? uuid2 : "no_uuid"));
1958 /* The host in the cache is not the host for this connection */
1960 host->hostFlags |= HOSTDELETED;
1966 host = h_Alloc_r(tcon); /* returned held and locked */
1967 h_gethostcps_r(host, FT_ApproxTime());
1968 if (!(host->Console & 1)) {
1970 cb_conn = host->callback_rxcon;
1971 rx_GetConnection(cb_conn);
1972 host->hostFlags |= HWHO_INPROGRESS;
1975 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1976 if (code == RXGEN_OPCODE)
1977 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1978 rx_PutConnection(cb_conn);
1981 if ((code == RXGEN_OPCODE) ||
1982 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1985 (struct Identity *)malloc(sizeof(struct Identity));
1990 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1991 osi_Panic("Failed malloc in h_GetHost_r\n");
1995 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1997 ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1998 host, afs_inet_ntoa_r(host->host, hoststr),
1999 ntohs(host->port)));
2001 } else if (code == 0) {
2004 (struct Identity *)malloc(sizeof(struct Identity));
2009 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
2010 osi_Panic("Failed malloc in h_GetHost_r\n");
2014 identP->uuid = interf.uuid;
2016 rx_SetSpecific(tcon, rxcon_ident_key, identP);
2018 ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
2019 host, afs_inet_ntoa_r(host->host, hoststr),
2020 ntohs(host->port)));
2022 if (code == 0 && !identP->valid) {
2023 cb_conn = host->callback_rxcon;
2024 rx_GetConnection(cb_conn);
2026 code = RXAFSCB_InitCallBackState(cb_conn);
2027 rx_PutConnection(cb_conn);
2030 } else if (code == 0) {
2031 oldHost = h_LookupUuid_r(&identP->uuid);
2036 if (oldHost->hostFlags & HOSTDELETED) {
2037 h_Unlock_r(oldHost);
2038 h_Release_r(oldHost);
2046 oldHost->hostFlags |= HWHO_INPROGRESS;
2048 if (oldHost->interface) {
2050 afsUUID uuid = oldHost->interface->uuid;
2051 cb_conn = oldHost->callback_rxcon;
2052 rx_GetConnection(cb_conn);
2053 rx_SetConnDeadTime(cb_conn, 2);
2054 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2056 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2058 rx_SetConnDeadTime(cb_conn, 50);
2059 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2060 rx_PutConnection(cb_conn);
2063 /* The primary address is either not responding or
2064 * is not the client we are looking for.
2065 * MultiProbeAlternateAddress_r() will remove the
2066 * alternate interfaces that do not have the same
2068 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
2070 afs_inet_ntoa_r(oldHost->host, hoststr),
2071 ntohs(oldHost->port),code2));
2072 MultiProbeAlternateAddress_r(oldHost);
2079 /* This is a new address for an existing host. Update
2080 * the list of interfaces for the existing host and
2081 * delete the host structure we just allocated. */
2083 /* prevent warnings while manipulating interface lists */
2084 host->hostFlags |= HOSTDELETED;
2086 if (oldHost->host != haddr || oldHost->port != hport) {
2087 struct rx_connection *rxconn;
2090 ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
2092 afs_inet_ntoa_r(oldHost->host, hoststr2),
2093 ntohs(oldHost->port),
2094 afs_inet_ntoa_r(haddr, hoststr),
2097 * add then remove. otherwise the host may get marked
2098 * deleted if we removed the only valid address.
2100 addInterfaceAddr_r(oldHost, haddr, hport);
2101 if (probefail || oldHost->host == haddr) {
2103 * The probe failed which means that the old
2104 * address is either unreachable or is not the
2105 * same host we were just contacted by. We will
2106 * also remove addresses if only the port has
2107 * changed because that indicates the client
2110 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
2113 struct Interface *interface = oldHost->interface;
2114 int number = oldHost->interface->numberOfInterfaces;
2115 for (i = 0; i < number; i++) {
2116 if (interface->interface[i].addr == haddr &&
2117 interface->interface[i].port != hport) {
2119 * We have just been contacted by a client
2120 * that has been seen from behind a NAT
2121 * and at least one other address.
2123 removeInterfaceAddr_r(oldHost, haddr,
2124 interface->interface[i].port);
2129 h_AddHostToAddrHashTable_r(haddr, hport, oldHost);
2130 oldHost->host = haddr;
2131 oldHost->port = hport;
2132 rxconn = oldHost->callback_rxcon;
2133 oldHost->callback_rxcon = host->callback_rxcon;
2134 host->callback_rxcon = rxconn;
2136 /* don't destroy rxconn here; let h_TossStuff_r
2137 * take care of that via h_Release_r below */
2139 host->hostFlags &= ~HWHO_INPROGRESS;
2141 /* release host because it was allocated by h_Alloc_r */
2144 /* the new host is held and locked */
2146 /* This really is a new host */
2147 h_AddHostToUuidHashTable_r(&identP->uuid, host);
2148 cb_conn = host->callback_rxcon;
2149 rx_GetConnection(cb_conn);
2152 RXAFSCB_InitCallBackState3(cb_conn,
2154 rx_PutConnection(cb_conn);
2159 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2160 host, afs_inet_ntoa_r(host->host, hoststr),
2161 ntohs(host->port)));
2162 osi_Assert(interfValid == 1);
2163 initInterfaceAddr_r(host, &interf);
2169 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2170 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2171 host->hostFlags |= VENUSDOWN;
2174 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2175 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2176 host->hostFlags |= RESETDONE;
2179 if (caps.Capabilities_val
2180 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2181 host->hostFlags |= HERRORTRANS;
2183 host->hostFlags &= ~(HERRORTRANS);
2184 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2185 host->hostFlags &= ~HWHO_INPROGRESS;
2190 if (caps.Capabilities_val)
2191 free(caps.Capabilities_val);
2192 caps.Capabilities_val = NULL;
2193 caps.Capabilities_len = 0;
2195 rx_DestroyConnection(cb_in);
2203 static char localcellname[PR_MAXNAMELEN + 1];
2204 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
2205 int num_lrealms = -1;
2209 h_InitHostPackage(void)
2211 memset(&nulluuid, 0, sizeof(afsUUID));
2212 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
2213 if (num_lrealms == -1) {
2215 for (i=0; i<AFS_NUM_LREALMS; i++) {
2216 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
2222 ("afs_krb_get_lrealm failed, using %s.\n",
2224 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
2230 /* initialize the rest of the local realms to nullstring for debugging */
2231 for (; i<AFS_NUM_LREALMS; i++)
2232 local_realms[i][0] = '\0';
2234 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2235 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2236 MUTEX_INIT(&host_glock_mutex, "host glock", MUTEX_DEFAULT, 0);
2240 MapName_r(char *aname, char *acell, afs_int32 * aval)
2245 afs_int32 anamelen, cnamelen;
2249 anamelen = strlen(aname);
2250 if (anamelen >= PR_MAXNAMELEN)
2251 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
2253 lnames.namelist_len = 1;
2254 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
2255 lids.idlist_len = 0;
2256 lids.idlist_val = NULL;
2258 cnamelen = strlen(acell);
2260 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2262 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2263 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2264 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2266 ("MapName: Name too long, using AnonymousID for %s@%s\n",
2268 *aval = AnonymousID;
2271 foreign = 1; /* attempt cross-cell authentication */
2272 tname = (char *)malloc(PR_MAXNAMELEN);
2274 ViceLog(0, ("Failed malloc in MapName_r\n"));
2275 osi_Panic("Failed malloc in MapName_r\n");
2277 strcpy(tname, aname);
2278 tname[anamelen] = '@';
2279 strcpy(tname + anamelen + 1, acell);
2280 lnames.namelist_val = (prname *) tname;
2285 code = hpr_NameToId(&lnames, &lids);
2288 if (lids.idlist_val) {
2289 *aval = lids.idlist_val[0];
2290 if (*aval == AnonymousID) {
2292 ("MapName: NameToId on %s returns anonymousID\n",
2293 lnames.namelist_val[0]));
2295 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2298 ("MapName: NameToId on '%s' is unknown\n",
2299 lnames.namelist_val[0]));
2305 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
2313 /* NOTE: this returns the client with a Write lock and a refCount */
2315 h_ID2Client(afs_int32 vid)
2317 struct client *client;
2322 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
2323 if (host->hostFlags & HOSTDELETED)
2325 for (client = host->FirstClient; client; client = client->next) {
2326 if (!client->deleted && client->ViceId == vid) {
2329 ObtainWriteLock(&client->lock);
2334 if (count != hostCount) {
2335 ViceLog(0, ("h_ID2Client found %d of %d hosts\n", count, hostCount));
2336 } else if (host != NULL) {
2337 ViceLog(0, ("h_ID2Client found more than %d hosts\n", hostCount));
2338 ShutDownAndCore(PANIC);
2346 * Called by the server main loop. Returns a h_Held client, which must be
2347 * released later the main loop. Allocates a client if the matching one
2348 * isn't around. The client is returned with its reference count incremented
2349 * by one. The caller must call h_ReleaseClient_r when finished with
2352 * The refCount on client->host is returned incremented. h_ReleaseClient_r
2353 * does not decrement the refCount on client->host.
2356 h_FindClient_r(struct rx_connection *tcon)
2358 struct client *client;
2359 struct host *host = NULL;
2360 struct client *oldClient;
2361 afs_int32 viceid = 0;
2365 #if (64-MAXKTCNAMELEN)
2366 ticket name length != 64
2370 char uname[PR_MAXNAMELEN];
2371 char tcell[MAXKTCREALMLEN];
2375 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2376 if (client && client->sid == rxr_CidOf(tcon)
2377 && client->VenusEpoch == rxr_GetEpoch(tcon)
2378 && !(client->host->hostFlags & HOSTDELETED)) {
2381 h_Hold_r(client->host);
2382 if (!client->deleted && client->prfail != 2) {
2383 /* Could add shared lock on client here */
2384 /* note that we don't have to lock entry in this path to
2385 * ensure CPS is initialized, since we don't call rx_SetSpecific
2386 * until initialization is done, and we only get here if
2387 * rx_GetSpecific located the client structure.
2392 ObtainWriteLock(&client->lock); /* released at end */
2398 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2400 ("FindClient: authenticating connection: authClass=%d\n",
2402 if (authClass == 1) {
2403 /* A bcrypt tickets, no longer supported */
2404 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2405 viceid = AnonymousID;
2406 expTime = 0x7fffffff;
2407 } else if (authClass == 2) {
2410 /* kerberos ticket */
2411 code = rxkad_GetServerInfo(tcon, /*level */ 0, (afs_uint32 *)&expTime,
2412 tname, tinst, tcell, &kvno);
2414 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2415 viceid = AnonymousID;
2416 expTime = 0x7fffffff;
2418 int ilen = strlen(tinst);
2420 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2421 tname, tinst, tcell, expTime, kvno));
2422 strncpy(uname, tname, sizeof(uname));
2424 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2427 strcat(uname, tinst);
2429 /* translate the name to a vice id */
2430 code = MapName_r(uname, tcell, &viceid);
2434 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2437 viceid = AnonymousID;
2438 expTime = 0x7fffffff;
2442 viceid = AnonymousID; /* unknown security class */
2443 expTime = 0x7fffffff;
2446 if (!client) { /* loop */
2447 host = h_GetHost_r(tcon); /* Returns with incremented refCount */
2453 /* First try to find the client structure */
2454 for (client = host->FirstClient; client; client = client->next) {
2455 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2456 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2459 ObtainWriteLock(&client->lock);
2465 /* Still no client structure - get one */
2468 if (host->hostFlags & HOSTDELETED) {
2473 /* Retry to find the client structure */
2474 for (client = host->FirstClient; client; client = client->next) {
2475 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2476 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2478 goto retryfirstclient;
2483 ObtainWriteLock(&client->lock);
2484 client->refCount = 1;
2485 client->host = host;
2486 #if FS_STATS_DETAILED
2487 client->InSameNetwork = host->InSameNetwork;
2488 #endif /* FS_STATS_DETAILED */
2489 client->ViceId = viceid;
2490 client->expTime = expTime; /* rx only */
2491 client->authClass = authClass; /* rx only */
2492 client->sid = rxr_CidOf(tcon);
2493 client->VenusEpoch = rxr_GetEpoch(tcon);
2494 client->CPS.prlist_val = NULL;
2495 client->CPS.prlist_len = 0;
2499 client->prfail = fail;
2501 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2502 client->CPS.prlist_len = 0;
2503 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2504 free(client->CPS.prlist_val);
2505 client->CPS.prlist_val = NULL;
2506 client->ViceId = viceid;
2507 client->expTime = expTime;
2509 if (viceid == ANONYMOUSID) {
2510 client->CPS.prlist_len = AnonCPS.prlist_len;
2511 client->CPS.prlist_val = AnonCPS.prlist_val;
2514 code = hpr_GetCPS(viceid, &client->CPS);
2519 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2520 code, viceid, client->host,
2521 afs_inet_ntoa_r(client->host->host,hoststr),
2522 ntohs(client->host->port)));
2524 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2525 * all protection servers and reevaluates things if no
2526 * sync server or quorum is found we could still end up
2527 * with one of these errors. In such case we would like to
2528 * reevaluate the rpc call to find if there's cps for this
2529 * guy. We treat other errors (except network failures
2530 * ones - i.e. code < 0) as an indication that there is no
2531 * CPS for this host. Ideally we could like to deal this
2532 * problem the other way around (i.e. if code == NOCPS
2533 * ignore else retry next time) but the problem is that
2534 * there're other errors (i.e. EPERM) for which we don't
2535 * want to retry and we don't know the whole code list!
2537 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2541 /* the disabling of system:administrators is so iffy and has so many
2542 * possible failure modes that we will disable it again */
2543 /* Turn off System:Administrator for safety
2544 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2545 * osi_Assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2548 /* Now, tcon may already be set to a rock, since we blocked with no host
2549 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2550 * required). So, before setting the RPC's rock, we should disconnect
2551 * the RPC from the other client structure's rock.
2553 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2554 if (oldClient && oldClient != client && oldClient->sid == rxr_CidOf(tcon)
2555 && oldClient->VenusEpoch == rxr_GetEpoch(tcon)) {
2557 if (!oldClient->deleted) {
2558 /* if we didn't create it, it's not ours to put back */
2560 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2561 "conn %p (host %s:%d) had client %p(%x)\n",
2562 client, client->sid, tcon,
2563 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2564 ntohs(rxr_PortOf(tcon)),
2565 oldClient, oldClient->sid));
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;
2571 /* We should perhaps check for 0 here */
2573 ReleaseWriteLock(&client->lock);
2578 oldClient->refCount++;
2580 ObtainWriteLock(&oldClient->lock);
2584 ViceLog(0, ("FindClient: deleted client %p(%x) already had "
2585 "conn %p (host %s:%d), stolen by client %p(%x)\n",
2586 oldClient, oldClient->sid, tcon,
2587 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2588 ntohs(rxr_PortOf(tcon)),
2589 client, client->sid));
2590 /* rx_SetSpecific will be done immediately below */
2593 /* Avoid chaining in more than once. */
2597 if (host->hostFlags & HOSTDELETED) {
2602 client->host = NULL;
2604 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2605 free(client->CPS.prlist_val);
2606 client->CPS.prlist_val = NULL;
2607 client->CPS.prlist_len = 0;
2610 ReleaseWriteLock(&client->lock);
2615 client->next = host->FirstClient;
2616 host->FirstClient = client;
2618 CurrentConnections++; /* increment number of connections */
2620 rx_SetSpecific(tcon, rxcon_client_key, client);
2621 ReleaseWriteLock(&client->lock);
2625 } /*h_FindClient_r */
2628 h_ReleaseClient_r(struct client *client)
2630 osi_Assert(client->refCount > 0);
2637 * Sigh: this one is used to get the client AGAIN within the individual
2638 * server routines. This does not bother h_Holding the host, since
2639 * this is assumed already have been done by the server main loop.
2640 * It does check tokens, since only the server routines can return the
2641 * VICETOKENDEAD error code
2644 GetClient(struct rx_connection *tcon, struct client **cp)
2646 struct client *client;
2651 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2652 if (client == NULL) {
2654 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2655 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2656 ntohs(rxr_PortOf(tcon))));
2660 if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2662 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2663 tcon, rxr_CidOf(tcon), client->sid));
2667 if (client && client->LastCall > client->expTime && client->expTime) {
2669 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2670 afs_inet_ntoa_r(client->host->host, hoststr),
2671 ntohs(client->host->port), client->expTime));
2673 return VICETOKENDEAD;
2683 PutClient(struct client **cp)
2689 h_ReleaseClient_r(*cp);
2696 /* Client user name for short term use. Note that this is NOT inexpensive */
2698 h_UserName(struct client *client)
2700 static char User[PR_MAXNAMELEN + 1];
2704 lids.idlist_len = 1;
2705 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2706 if (!lids.idlist_val) {
2707 ViceLog(0, ("Failed malloc in h_UserName\n"));
2708 osi_Panic("Failed malloc in h_UserName\n");
2710 lnames.namelist_len = 0;
2711 lnames.namelist_val = (prname *) 0;
2712 lids.idlist_val[0] = client->ViceId;
2713 if (hpr_IdToName(&lids, &lnames)) {
2714 /* We need to free id we alloced above! */
2715 free(lids.idlist_val);
2716 return "*UNKNOWN USER NAME*";
2718 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2719 free(lids.idlist_val);
2720 free(lnames.namelist_val);
2729 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2730 CEs, CEBlocks, HTs, HTBlocks));
2736 h_PrintClient(struct host *host, int flags, void *rock)
2738 StreamHandle_t *file = (StreamHandle_t *)rock;
2739 struct client *client;
2744 time_t LastCall, expTime;
2747 LastCall = host->LastCall;
2748 if (host->hostFlags & HOSTDELETED) {
2752 snprintf(tmpStr, sizeof tmpStr, "Host %s:%d down = %d, LastCall %s",
2753 afs_inet_ntoa_r(host->host, hoststr),
2754 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2755 afs_ctime(&LastCall, tbuffer, sizeof(tbuffer)));
2756 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2757 for (client = host->FirstClient; client; client = client->next) {
2758 if (!client->deleted) {
2759 expTime = client->expTime;
2760 snprintf(tmpStr, sizeof tmpStr,
2761 " user id=%d, name=%s, sl=%s till %s",
2762 client->ViceId, h_UserName(client),
2763 client->authClass ? "Authenticated"
2764 : "Not authenticated",
2765 client->authClass ? afs_ctime(&expTime, tbuffer,
2768 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2769 snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2770 client->CPS.prlist_len);
2771 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2772 if (client->CPS.prlist_val) {
2773 for (i = 0; i < client->CPS.prlist_len; i++) {
2774 snprintf(tmpStr, sizeof tmpStr, " %d",
2775 client->CPS.prlist_val[i]);
2776 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2779 sprintf(tmpStr, "]\n");
2780 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2786 } /*h_PrintClient */
2791 * Print a list of clients, with last security level and token value seen,
2795 h_PrintClients(void)
2801 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2805 ("Couldn't create client dump file %s\n",
2806 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2809 now = FT_ApproxTime();
2810 snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
2811 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2812 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2813 h_Enumerate(h_PrintClient, (char *)file);
2814 STREAM_REALLYCLOSE(file);
2815 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2822 h_DumpHost(struct host *host, int flags, void *rock)
2824 StreamHandle_t *file = (StreamHandle_t *)rock;
2831 snprintf(tmpStr, sizeof tmpStr,
2832 "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u "
2833 "down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u "
2835 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
2836 host->index, host->cblist, CheckLock(&host->lock),
2837 host->LastCall, host->ActiveCall, (host->hostFlags & VENUSDOWN),
2838 host->hostFlags & HOSTDELETED, host->Console,
2839 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2841 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2842 if (host->hcps.prlist_val)
2843 for (i = 0; i < host->hcps.prlist_len; i++) {
2844 snprintf(tmpStr, sizeof tmpStr, " %d", host->hcps.prlist_val[i]);
2845 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2847 sprintf(tmpStr, "] [");
2848 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2849 if (host->interface)
2850 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2852 sprintf(tmpStr, " %s:%d",
2853 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2854 ntohs(host->interface->interface[i].port));
2855 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2857 sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2858 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2870 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2876 ("Couldn't create host dump file %s\n",
2877 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2880 now = FT_ApproxTime();
2881 snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
2882 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2883 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2884 h_Enumerate(h_DumpHost, (char *)file);
2885 STREAM_REALLYCLOSE(file);
2886 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2890 #ifdef AFS_DEMAND_ATTACH_FS
2893 * host state serialization
2895 static int h_stateFillHeader(struct host_state_header * hdr);
2896 static int h_stateCheckHeader(struct host_state_header * hdr);
2897 static int h_stateAllocMap(struct fs_dump_state * state);
2898 static int h_stateSaveHost(struct host * host, int flags, void *rock);
2899 static int h_stateRestoreHost(struct fs_dump_state * state);
2900 static int h_stateRestoreIndex(struct host * h, int flags, void *rock);
2901 static int h_stateVerifyHost(struct host * h, int flags, void *rock);
2902 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
2903 afs_uint32 addr, afs_uint16 port, int valid);
2904 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2905 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2906 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2909 /* this procedure saves all host state to disk for fast startup */
2911 h_stateSave(struct fs_dump_state * state)
2913 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2916 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2918 /* invalidate host state header */
2919 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2921 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2922 sizeof(struct host_state_header))) {
2927 fs_stateIncEOF(state, sizeof(struct host_state_header));
2929 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2934 h_stateFillHeader(state->h_hdr);
2936 /* write the real header to disk */
2937 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2938 sizeof(struct host_state_header));
2945 * host state serialization
2947 * this procedure restores all host state from a disk for fast startup
2950 h_stateRestore(struct fs_dump_state * state)
2954 /* seek to the right position and read in the host state header */
2955 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2956 sizeof(struct host_state_header))) {
2961 /* check the validity of the header */
2962 if (h_stateCheckHeader(state->h_hdr)) {
2967 records = state->h_hdr->records;
2969 if (h_stateAllocMap(state)) {
2974 /* iterate over records restoring host state */
2975 for (i=0; i < records; i++) {
2976 if (h_stateRestoreHost(state) != 0) {
2987 h_stateRestoreIndices(struct fs_dump_state * state)
2989 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
2994 h_stateRestoreIndex(struct host * h, int flags, void *rock)
2996 struct fs_dump_state *state = (struct fs_dump_state *)rock;
2997 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
2998 return H_ENUMERATE_BAIL(flags);
3004 h_stateVerify(struct fs_dump_state * state)
3006 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
3011 h_stateVerifyHost(struct host * h, int flags, void* rock)
3013 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3017 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3018 return H_ENUMERATE_BAIL(flags);
3022 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
3023 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
3024 h->interface->interface[i].port,
3025 h->interface->interface[i].valid)) {
3029 if (h_stateVerifyUuidHash(state, h)) {
3032 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
3036 if (cb_stateVerifyHCBList(state, h)) {
3044 * verify a host is either in, or absent from, the addr hash table.
3046 * @param[in] state fs dump state
3047 * @param[in] h host we're dealing with
3048 * @param[in] addr addr to look for (NBO)
3049 * @param[in] port port to look for (NBO)
3050 * @param[in] valid 1 if we're verifying that the specified addr and port
3051 * in the hash table point to the specified host. 0 if we're
3052 * verifying that the specified addr and port do NOT point
3053 * to the specified host
3055 * @return operation status
3056 * @retval 1 failed to verify, bail out
3057 * @retval 0 verified successfully, all is well
3060 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3061 afs_uint32 addr, afs_uint16 port, int valid)
3063 int ret = 0, found = 0;
3064 struct host *host = NULL;
3065 struct h_AddrHashChain *chain;
3066 int index = h_HashIndex(addr);
3070 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3071 host = chain->hostPtr;
3073 afs_inet_ntoa_r(addr, tmp);
3074 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3078 if ((chain->addr == addr) && (chain->port == port)) {
3081 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3082 "points to different host struct (%d, %d)\n",
3083 h->index, host->index));
3084 state->flags.warnings_generated = 1;
3088 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3089 "marked invalid, but points to the containing "
3090 "host\n", afs_inet_ntoa_r(addr, tmp),
3091 (unsigned)htons(port)));
3099 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3100 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3101 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3108 if (!found && valid) {
3109 afs_inet_ntoa_r(addr, tmp);
3110 if (state->mode == FS_STATE_LOAD_MODE) {
3111 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3112 tmp, (unsigned)htons(port)));
3116 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3117 tmp, (unsigned)htons(port)));
3118 state->flags.warnings_generated = 1;
3127 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3129 int ret = 0, found = 0;
3130 struct host *host = NULL;
3131 struct h_UuidHashChain *chain;
3132 afsUUID * uuidp = &h->interface->uuid;
3133 int index = h_UuidHashIndex(uuidp);
3137 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3138 host = chain->hostPtr;
3140 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3141 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3145 if (host->interface &&
3146 afs_uuid_equal(&host->interface->uuid, uuidp)) {
3148 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3149 h->index, host->index));
3150 state->flags.warnings_generated = 1;
3155 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3156 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3157 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3165 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3166 if (state->mode == FS_STATE_LOAD_MODE) {
3167 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3171 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3172 state->flags.warnings_generated = 1;
3180 /* create the host state header structure */
3182 h_stateFillHeader(struct host_state_header * hdr)
3184 hdr->stamp.magic = HOST_STATE_MAGIC;
3185 hdr->stamp.version = HOST_STATE_VERSION;
3189 /* check the contents of the host state header structure */
3191 h_stateCheckHeader(struct host_state_header * hdr)
3195 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3196 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3199 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3200 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3206 /* allocate the host id mapping table */
3208 h_stateAllocMap(struct fs_dump_state * state)
3210 state->h_map.len = state->h_hdr->index_max + 1;
3211 state->h_map.entries = (struct idx_map_entry_t *)
3212 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3213 return (state->h_map.entries != NULL) ? 0 : 1;
3216 /* function called by h_Enumerate to save a host to disk */
3218 h_stateSaveHost(struct host * host, int flags, void* rock)
3220 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3221 int if_len=0, hcps_len=0;
3222 struct hostDiskEntry hdsk;
3223 struct host_state_entry_header hdr;
3224 struct Interface * ifp = NULL;
3225 afs_int32 * hcps = NULL;
3226 struct iovec iov[4];
3229 memset(&hdr, 0, sizeof(hdr));
3231 if (state->h_hdr->index_max < host->index) {
3232 state->h_hdr->index_max = host->index;
3235 h_hostToDiskEntry_r(host, &hdsk);
3236 if (host->interface) {
3237 if_len = sizeof(struct Interface) +
3238 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3239 ifp = (struct Interface *) malloc(if_len);
3240 osi_Assert(ifp != NULL);
3241 memcpy(ifp, host->interface, if_len);
3242 hdr.interfaces = host->interface->numberOfInterfaces;
3243 iov[iovcnt].iov_base = (char *) ifp;
3244 iov[iovcnt].iov_len = if_len;
3247 if (host->hcps.prlist_val) {
3248 hdr.hcps = host->hcps.prlist_len;
3249 hcps_len = hdr.hcps * sizeof(afs_int32);
3250 hcps = (afs_int32 *) malloc(hcps_len);
3251 osi_Assert(hcps != NULL);
3252 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3253 iov[iovcnt].iov_base = (char *) hcps;
3254 iov[iovcnt].iov_len = hcps_len;
3258 if (hdsk.index > state->h_hdr->index_max)
3259 state->h_hdr->index_max = hdsk.index;
3261 hdr.len = sizeof(struct host_state_entry_header) +
3262 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3263 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3265 iov[0].iov_base = (char *) &hdr;
3266 iov[0].iov_len = sizeof(hdr);
3267 iov[1].iov_base = (char *) &hdsk;
3268 iov[1].iov_len = sizeof(struct hostDiskEntry);
3270 if (fs_stateWriteV(state, iov, iovcnt)) {
3271 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3275 fs_stateIncEOF(state, hdr.len);
3277 state->h_hdr->records++;
3284 return H_ENUMERATE_BAIL(flags);
3289 /* restores a host from disk */
3291 h_stateRestoreHost(struct fs_dump_state * state)
3293 int ifp_len=0, hcps_len=0, bail=0;
3294 struct host_state_entry_header hdr;
3295 struct hostDiskEntry hdsk;
3296 struct host *host = NULL;
3297 struct Interface *ifp = NULL;
3298 afs_int32 * hcps = NULL;
3299 struct iovec iov[3];
3302 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3303 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3309 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3310 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3316 iov[0].iov_base = (char *) &hdsk;
3317 iov[0].iov_len = sizeof(struct hostDiskEntry);
3319 if (hdr.interfaces) {
3320 ifp_len = sizeof(struct Interface) +
3321 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3322 ifp = (struct Interface *) malloc(ifp_len);
3323 osi_Assert(ifp != NULL);
3324 iov[iovcnt].iov_base = (char *) ifp;
3325 iov[iovcnt].iov_len = ifp_len;
3329 hcps_len = hdr.hcps * sizeof(afs_int32);
3330 hcps = (afs_int32 *) malloc(hcps_len);
3331 osi_Assert(hcps != NULL);
3332 iov[iovcnt].iov_base = (char *) hcps;
3333 iov[iovcnt].iov_len = hcps_len;
3337 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3338 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3343 if (fs_stateReadV(state, iov, iovcnt)) {
3344 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3349 if (!hdr.hcps && hdsk.hcps_valid) {
3350 /* valid, zero-length host cps ; does this ever happen? */
3351 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3352 osi_Assert(hcps != NULL);
3356 osi_Assert(host != NULL);
3359 host->interface = ifp;
3362 host->hcps.prlist_val = hcps;
3363 host->hcps.prlist_len = hdr.hcps;
3366 h_diskEntryToHost_r(&hdsk, host);
3367 h_SetupCallbackConn_r(host);
3369 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3372 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3373 if (ifp->interface[i].valid &&
3374 !(ifp->interface[i].addr == host->host &&
3375 ifp->interface[i].port == host->port)) {
3376 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3377 ifp->interface[i].port,
3381 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3383 h_InsertList_r(host);
3385 /* setup host id map entry */
3386 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3387 state->h_map.entries[hdsk.index].new_idx = host->index;
3399 /* serialize a host structure to disk */
3401 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3403 out->host = in->host;
3404 out->port = in->port;
3405 out->hostFlags = in->hostFlags;
3406 out->Console = in->Console;
3407 out->hcpsfailed = in->hcpsfailed;
3408 out->LastCall = in->LastCall;
3409 out->ActiveCall = in->ActiveCall;
3410 out->cpsCall = in->cpsCall;
3411 out->cblist = in->cblist;
3412 #ifdef FS_STATS_DETAILED
3413 out->InSameNetwork = in->InSameNetwork;
3416 /* special fields we save, but are not memcpy'd back on restore */
3417 out->index = in->index;
3418 out->hcps_len = in->hcps.prlist_len;
3419 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3422 /* restore a host structure from disk */
3424 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3426 out->host = in->host;
3427 out->port = in->port;
3428 out->hostFlags = in->hostFlags;
3429 out->Console = in->Console;
3430 out->hcpsfailed = in->hcpsfailed;
3431 out->LastCall = in->LastCall;
3432 out->ActiveCall = in->ActiveCall;
3433 out->cpsCall = in->cpsCall;
3434 out->cblist = in->cblist;
3435 #ifdef FS_STATS_DETAILED
3436 out->InSameNetwork = in->InSameNetwork;
3440 /* index translation routines */
3442 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3446 /* hosts use a zero-based index, so old==0 is valid */
3448 if (old >= state->h_map.len) {
3449 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3451 } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
3452 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3455 *new = state->h_map.entries[old].new_idx;
3460 #endif /* AFS_DEMAND_ATTACH_FS */
3464 * This counts the number of workstations, the number of active workstations,
3465 * and the number of workstations declared "down" (i.e. not heard from
3466 * recently). An active workstation has received a call since the cutoff
3467 * time argument passed.
3470 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3473 int num = 0, active = 0, del = 0;
3477 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3478 if (!(host->hostFlags & HOSTDELETED)) {
3480 if (host->ActiveCall > cutofftime)
3482 if (host->hostFlags & VENUSDOWN)
3486 if (count != hostCount) {
3487 ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3488 } else if (host != NULL) {
3489 ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3490 ShutDownAndCore(PANIC);
3500 } /*h_GetWorkStats */
3503 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp,
3504 afs_int32 cutofftime)
3506 int num, active, del;
3507 h_GetWorkStats(&num, &active, &del, cutofftime);
3516 /*------------------------------------------------------------------------
3517 * PRIVATE h_ClassifyAddress
3520 * Given a target IP address and a candidate IP address (both
3521 * in host byte order), classify the candidate into one of three
3522 * buckets in relation to the target by bumping the counters passed
3526 * a_targetAddr : Target address.
3527 * a_candAddr : Candidate address.
3528 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3529 * addresses are either in the same network
3530 * or the same subnet.
3531 * a_diffSubnetP : ...when the candidate is in a different
3533 * a_diffNetworkP : ...when the candidate is in a different
3540 * The target and candidate addresses are both in host byte
3541 * order, NOT network byte order, when passed in.
3545 *------------------------------------------------------------------------*/
3548 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3549 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3550 afs_int32 * a_diffNetworkP)
3551 { /*h_ClassifyAddress */
3553 afs_uint32 targetNet;
3554 afs_uint32 targetSubnet;
3556 afs_uint32 candSubnet;
3559 * Put bad values into the subnet info to start with.
3561 targetSubnet = (afs_uint32) 0;
3562 candSubnet = (afs_uint32) 0;
3565 * Pull out the network and subnetwork numbers from the target
3566 * and candidate addresses. We can short-circuit this whole
3567 * affair if the target and candidate addresses are not of the
3570 if (IN_CLASSA(a_targetAddr)) {
3571 if (!(IN_CLASSA(a_candAddr))) {
3572 (*a_diffNetworkP)++;
3575 targetNet = a_targetAddr & IN_CLASSA_NET;
3576 candNet = a_candAddr & IN_CLASSA_NET;
3577 if (IN_SUBNETA(a_targetAddr))
3578 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3579 if (IN_SUBNETA(a_candAddr))
3580 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3581 } else if (IN_CLASSB(a_targetAddr)) {
3582 if (!(IN_CLASSB(a_candAddr))) {
3583 (*a_diffNetworkP)++;
3586 targetNet = a_targetAddr & IN_CLASSB_NET;
3587 candNet = a_candAddr & IN_CLASSB_NET;
3588 if (IN_SUBNETB(a_targetAddr))
3589 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3590 if (IN_SUBNETB(a_candAddr))
3591 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3592 } /*Class B target */
3593 else if (IN_CLASSC(a_targetAddr)) {
3594 if (!(IN_CLASSC(a_candAddr))) {
3595 (*a_diffNetworkP)++;
3598 targetNet = a_targetAddr & IN_CLASSC_NET;
3599 candNet = a_candAddr & IN_CLASSC_NET;
3602 * Note that class C addresses can't have subnets,
3603 * so we leave the defaults untouched.
3605 } /*Class C target */
3607 targetNet = a_targetAddr;
3608 candNet = a_candAddr;
3609 } /*Class D address */
3612 * Now, simply compare the extracted net and subnet values for
3613 * the two addresses (which at this point are known to be of the
3616 if (targetNet == candNet) {
3617 if (targetSubnet == candSubnet)
3618 (*a_sameNetOrSubnetP)++;
3622 (*a_diffNetworkP)++;
3624 } /*h_ClassifyAddress */
3627 /*------------------------------------------------------------------------
3628 * EXPORTED h_GetHostNetStats
3631 * Iterate through the host table, and classify each (non-deleted)
3632 * host entry into ``proximity'' categories (same net or subnet,
3633 * different subnet, different network).
3636 * a_numHostsP : Set to total number of (non-deleted) hosts.
3637 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3638 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3639 * a_diffNetworkP : Set to # hosts on diff network as server.
3645 * We only count non-deleted hosts. The storage pointed to by our
3646 * parameters is zeroed upon entry.
3650 *------------------------------------------------------------------------*/
3653 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3654 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3655 { /*h_GetHostNetStats */
3657 struct host *hostP; /*Ptr to current host entry */
3658 afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3662 * Clear out the storage pointed to by our parameters.
3664 *a_numHostsP = (afs_int32) 0;
3665 *a_sameNetOrSubnetP = (afs_int32) 0;
3666 *a_diffSubnetP = (afs_int32) 0;
3667 *a_diffNetworkP = (afs_int32) 0;
3670 for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3671 if (!(hostP->hostFlags & HOSTDELETED)) {
3673 * Bump the number of undeleted host entries found.
3674 * In classifying the current entry's address, make
3675 * sure to first convert to host byte order.
3678 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3679 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3680 a_sameNetOrSubnetP, a_diffSubnetP,
3682 } /*Only look at non-deleted hosts */
3683 } /*For each host record hashed to this index */
3684 if (count != hostCount) {
3685 ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3686 } else if (hostP != NULL) {
3687 ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3688 ShutDownAndCore(PANIC);
3691 } /*h_GetHostNetStats */
3693 static afs_uint32 checktime;
3694 static afs_uint32 clientdeletetime;
3695 static struct AFSFid zerofid;
3699 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3700 * Since it can serialize them, and pile up, it should be a separate LWP
3701 * from other events.
3705 CheckHost(struct host *host, int flags, void *rock)
3707 struct client *client;
3708 struct rx_connection *cb_conn = NULL;
3711 #ifdef AFS_DEMAND_ATTACH_FS
3712 /* kill the checkhost lwp ASAP during shutdown */
3714 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3716 return H_ENUMERATE_BAIL(flags);
3721 /* Host is held by h_Enumerate */
3723 for (client = host->FirstClient; client; client = client->next) {
3724 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3725 client->deleted = 1;
3726 host->hostFlags |= CLIENTDELETED;
3729 if (host->LastCall < checktime) {
3731 if (!(host->hostFlags & HOSTDELETED)) {
3732 host->hostFlags |= HWHO_INPROGRESS;
3733 cb_conn = host->callback_rxcon;
3734 rx_GetConnection(cb_conn);
3735 if (host->LastCall < clientdeletetime) {
3736 host->hostFlags |= HOSTDELETED;
3737 if (!(host->hostFlags & VENUSDOWN)) {
3738 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3739 if (host->interface) {
3742 RXAFSCB_InitCallBackState3(cb_conn,
3748 RXAFSCB_InitCallBackState(cb_conn);
3751 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3754 (void)afs_inet_ntoa_r(host->host, hoststr);
3756 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3757 hoststr, ntohs(host->port)));
3758 host->hostFlags |= VENUSDOWN;
3760 /* Note: it's safe to delete hosts even if they have call
3761 * back state, because break delayed callbacks (called when a
3762 * message is received from the workstation) will always send a
3763 * break all call backs to the workstation if there is no
3768 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3770 (void)afs_inet_ntoa_r(host->host, hoststr);
3771 if (host->interface) {
3772 afsUUID uuid = host->interface->uuid;
3774 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3777 if (MultiProbeAlternateAddress_r(host)) {
3778 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3779 hoststr, ntohs(host->port), code));
3780 host->hostFlags |= VENUSDOWN;
3785 code = RXAFSCB_Probe(cb_conn);
3789 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3790 hoststr, ntohs(host->port), code));
3791 host->hostFlags |= VENUSDOWN;
3797 rx_PutConnection(cb_conn);
3800 host->hostFlags &= ~HWHO_INPROGRESS;
3811 CheckHost_r(struct host *host, int flags, void *dummy)
3813 struct client *client;
3814 struct rx_connection *cb_conn = NULL;
3817 #ifdef AFS_DEMAND_ATTACH_FS
3818 /* kill the checkhost lwp ASAP during shutdown */
3820 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3822 return H_ENUMERATE_BAIL(flags);
3827 /* Host is held by h_Enumerate_r */
3828 for (client = host->FirstClient; client; client = client->next) {
3829 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3830 client->deleted = 1;
3831 host->hostFlags |= CLIENTDELETED;
3834 if (host->LastCall < checktime) {
3836 if (!(host->hostFlags & HOSTDELETED)) {
3837 host->hostFlags |= HWHO_INPROGRESS;
3838 cb_conn = host->callback_rxcon;
3839 rx_GetConnection(cb_conn);
3840 if (host->LastCall < clientdeletetime) {
3841 host->hostFlags |= HOSTDELETED;
3842 if (!(host->hostFlags & VENUSDOWN)) {
3843 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3844 if (host->interface) {
3847 RXAFSCB_InitCallBackState3(cb_conn,
3853 RXAFSCB_InitCallBackState(cb_conn);
3856 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3859 (void)afs_inet_ntoa_r(host->host, hoststr);
3861 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3862 hoststr, ntohs(host->port)));
3863 host->hostFlags |= VENUSDOWN;
3865 /* Note: it's safe to delete hosts even if they have call
3866 * back state, because break delayed callbacks (called when a
3867 * message is received from the workstation) will always send a
3868 * break all call backs to the workstation if there is no
3873 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3875 (void)afs_inet_ntoa_r(host->host, hoststr);
3876 if (host->interface) {
3877 afsUUID uuid = host->interface->uuid;
3879 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3882 if (MultiProbeAlternateAddress_r(host)) {
3883 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3884 hoststr, ntohs(host->port), code));
3885 host->hostFlags |= VENUSDOWN;
3890 code = RXAFSCB_Probe(cb_conn);
3894 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3895 hoststr, ntohs(host->port), code));
3896 host->hostFlags |= VENUSDOWN;
3902 rx_PutConnection(cb_conn);
3905 host->hostFlags &= ~HWHO_INPROGRESS;
3915 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3916 * don't respond to a probe. Note that VenusDown can only be cleared if
3917 * a message is received from the host (see ServerLWP in file.c).
3918 * Delete hosts that have not had any calls in 1 hour, clients that
3919 * have not had any calls in 15 minutes.
3921 * This routine is called roughly every 5 minutes.
3926 afs_uint32 now = FT_ApproxTime();
3928 memset(&zerofid, 0, sizeof(zerofid));
3930 * Send a probe to the workstation if it hasn't been heard from in
3933 checktime = now - 15 * 60;
3934 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3937 h_Enumerate_r(CheckHost_r, hostList, NULL);
3942 * This is called with host locked and held. At this point, the
3943 * hostAddrHashTable has an entry for the primary addr/port inserted
3944 * by h_Alloc_r(). No other interfaces should be considered valid.
3946 * The addresses in the interfaceAddr list are in host byte order.
3949 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3956 struct Interface *interface;
3959 afs_uint16 port7001 = htons(7001);
3964 number = interf->numberOfInterfaces;
3965 myAddr = host->host; /* current interface address */
3966 myPort = host->port; /* current port */
3969 ("initInterfaceAddr : host %s:%d numAddr %d\n",
3970 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3972 /* validation checks */
3973 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3975 ("Invalid number of alternate addresses is %d\n", number));
3980 * The client's notion of its own IP addresses is not reliable.
3982 * 1. The client list might contain private address ranges which
3983 * are likely to be re-used by many clients allocated addresses
3986 * 2. The client list will not include any public addresses that
3987 * are hidden by a NAT.
3989 * 3. Private address ranges that are exposed to the server will
3990 * be obtained from the rx connections that use them.
3992 * 4. Lists provided by the client are not necessarily truthful.
3993 * Many existing clients (UNIX) do not refresh the IP address
3994 * list as the actual assigned addresses change. The end result
3995 * is that they report the initial address list for the lifetime
3996 * of the process. In other words, a client can report addresses
3997 * that they are in fact not using. Adding these addresses to
3998 * the host interface list without verification is not only
3999 * pointless, it is downright dangerous.
4001 * We therefore do not add alternate addresses to the addr hash table.
4002 * We only use them for multi-rx callback breaks.
4006 * Convert IP addresses to network byte order, and remove
4007 * duplicate IP addresses from the interface list, and
4008 * determine whether or not the incoming addr/port is
4009 * listed. Note that if the address matches it is not
4010 * truly a match because the port number for the entries
4011 * in the interface list are port 7001 and the port number
4012 * for this connection might not be 7001.
4014 for (i = 0, count = 0, found = 0; i < number; i++) {
4015 interf->addr_in[i] = htonl(interf->addr_in[i]);
4016 for (j = 0; j < count; j++) {
4017 if (interf->addr_in[j] == interf->addr_in[i])
4021 interf->addr_in[count] = interf->addr_in[i];
4022 if (interf->addr_in[count] == myAddr &&
4030 * Allocate and initialize an interface structure for this host.
4033 interface = (struct Interface *)
4034 malloc(sizeof(struct Interface) +
4035 (sizeof(struct AddrPort) * (count - 1)));
4037 ViceLog(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
4038 osi_Panic("Failed malloc in initInterfaceAddr_r 1\n");
4040 interface->numberOfInterfaces = count;
4042 interface = (struct Interface *)
4043 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
4045 ViceLog(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4046 osi_Panic("Failed malloc in initInterfaceAddr_r 2\n");
4048 interface->numberOfInterfaces = count + 1;
4049 interface->interface[count].addr = myAddr;
4050 interface->interface[count].port = myPort;
4051 interface->interface[count].valid = 1;
4054 for (i = 0; i < count; i++) {
4056 interface->interface[i].addr = interf->addr_in[i];
4057 /* We store the port as 7001 because the addresses reported by
4058 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4059 * are coming from fully connected hosts (no NAT/PATs)
4061 interface->interface[i].port = port7001;
4062 interface->interface[i].valid =
4063 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4066 interface->uuid = interf->uuid;
4068 osi_Assert(!host->interface);
4069 host->interface = interface;
4071 if (LogLevel >= 125) {
4072 afsUUID_to_string(&interface->uuid, uuidstr, 127);
4074 ViceLog(125, ("--- uuid %s\n", uuidstr));
4075 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
4076 ViceLog(125, ("--- alt address %s:%d\n",
4077 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4078 ntohs(host->interface->interface[i].port)));
4085 /* deleted a HashChain structure for this address and host */
4086 /* returns 1 on success */
4088 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4092 struct h_AddrHashChain **hp, *th;
4094 if (addr == 0 && port == 0)
4097 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4099 osi_Assert(th->hostPtr);
4100 if (th->hostPtr == host && th->addr == addr && th->port == port) {
4101 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4102 host, afs_inet_ntoa_r(host->host, hoststr),
4103 ntohs(host->port)));
4110 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4111 host, afs_inet_ntoa_r(host->host, hoststr),
4112 ntohs(host->port)));
4118 ** prints out all alternate interface address for the host. The 'level'
4119 ** parameter indicates what level of debugging sets this output
4122 printInterfaceAddr(struct host *host, int level)
4127 if (host->interface) {
4128 /* check alternate addresses */
4129 number = host->interface->numberOfInterfaces;
4131 ViceLog(level, ("no-addresses "));
4133 for (i = 0; i < number; i++)
4134 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4135 ntohs(host->interface->interface[i].port)));
4138 ViceLog(level, ("\n"));