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>
18 #ifdef HAVE_SYS_FILE_H
23 #include <afs/afs_assert.h>
26 #include <afs/afsint.h>
27 #define FSINT_COMMON_XG
28 #include <afs/afscbint.h>
29 #include <afs/rxgen_consts.h>
31 #include <afs/errors.h>
32 #include <afs/ihandle.h>
33 #include <afs/vnode.h>
34 #include <afs/volume.h>
35 #ifdef AFS_ATHENA_STDENV
39 #include <afs/ptclient.h>
40 #include <afs/ptuser.h>
41 #include <afs/prs_fs.h>
43 #include <afs/afsutil.h>
44 #include <afs/com_err.h>
46 #include <afs/cellconfig.h>
47 #include "viced_prototypes.h"
51 #ifdef AFS_DEMAND_ATTACH_FS
52 #include "../util/afsutil_prototypes.h"
53 #include "../tviced/serialize_state.h"
54 #endif /* AFS_DEMAND_ATTACH_FS */
56 #ifdef AFS_PTHREAD_ENV
57 pthread_mutex_t host_glock_mutex;
58 #endif /* AFS_PTHREAD_ENV */
61 extern int CurrentConnections;
63 extern int AnonymousID;
64 extern prlist AnonCPS;
66 extern struct afsconf_dir *confDir; /* config dir object */
67 extern int lwps; /* the max number of server threads */
68 extern afsUUID FS_HostUUID;
71 int CEs = 0; /* active clients */
72 int CEBlocks = 0; /* number of blocks of CEs */
73 struct client *CEFree = 0; /* first free client */
74 struct host *hostList = 0; /* linked list of all hosts */
75 int hostCount = 0; /* number of hosts in hostList */
79 static struct rx_securityClass *sc = NULL;
81 static void h_SetupCallbackConn_r(struct host * host);
82 static int h_threadquota(int);
84 #define CESPERBLOCK 73
85 struct CEBlock { /* block of CESPERBLOCK file entries */
86 struct client entry[CESPERBLOCK];
89 void h_TossStuff_r(struct host *host);
92 * Make sure the subnet macros have been defined.
95 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
98 #ifndef IN_CLASSA_SUBNET
99 #define IN_CLASSA_SUBNET 0xffff0000
103 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
106 #ifndef IN_CLASSB_SUBNET
107 #define IN_CLASSB_SUBNET 0xffffff00
111 /* get a new block of CEs and chain it on CEFree */
115 struct CEBlock *block;
118 block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
120 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
121 ShutDownAndCore(PANIC);
124 for (i = 0; i < (CESPERBLOCK - 1); i++) {
125 Lock_Init(&block->entry[i].lock);
126 block->entry[i].next = &(block->entry[i + 1]);
128 block->entry[CESPERBLOCK - 1].next = 0;
129 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
130 CEFree = (struct client *)block;
136 /* get the next available CE */
137 static struct client *
140 struct client *entry;
145 ViceLog(0, ("CEFree NULL in GetCE\n"));
146 ShutDownAndCore(PANIC);
150 CEFree = entry->next;
152 memset(entry, 0, CLIENT_TO_ZERO(entry));
158 /* return an entry to the free list */
160 FreeCE(struct client *entry)
162 entry->VenusEpoch = 0;
164 entry->next = CEFree;
171 * The HTs and HTBlocks variables were formerly static, but they are
172 * now referenced elsewhere in the FileServer.
174 int HTs = 0; /* active file entries */
175 int HTBlocks = 0; /* number of blocks of HTs */
176 static struct host *HTFree = 0; /* first free file entry */
179 * Hash tables of host pointers. We need two tables, one
180 * to map IP addresses onto host pointers, and another
181 * to map host UUIDs onto host pointers.
183 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
184 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
185 #define h_HashIndex(hostip) (ntohl(hostip) & (h_HASHENTRIES-1))
186 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
188 struct HTBlock { /* block of HTSPERBLOCK file entries */
189 struct host entry[h_HTSPERBLOCK];
193 /* get a new block of HTs and chain it on HTFree */
197 struct HTBlock *block;
199 static int index = 0;
201 if (HTBlocks == h_MAXHOSTTABLES) {
202 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
203 ShutDownAndCore(PANIC);
206 block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
208 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
209 ShutDownAndCore(PANIC);
211 #ifdef AFS_PTHREAD_ENV
212 for (i = 0; i < (h_HTSPERBLOCK); i++)
213 CV_INIT(&block->entry[i].cond, "block entry", CV_DEFAULT, 0);
214 #endif /* AFS_PTHREAD_ENV */
215 for (i = 0; i < (h_HTSPERBLOCK); i++)
216 Lock_Init(&block->entry[i].lock);
217 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
218 block->entry[i].next = &(block->entry[i + 1]);
219 for (i = 0; i < (h_HTSPERBLOCK); i++)
220 block->entry[i].index = index++;
221 block->entry[h_HTSPERBLOCK - 1].next = 0;
222 HTFree = (struct host *)block;
223 hosttableptrs[HTBlocks++] = block->entry;
228 /* get the next available HT */
236 osi_Assert(HTFree != NULL);
238 HTFree = entry->next;
240 memset(entry, 0, HOST_TO_ZERO(entry));
246 /* return an entry to the free list */
248 FreeHT(struct host *entry)
250 entry->next = HTFree;
257 hpr_Initialize(struct ubik_client **uclient)
260 struct rx_connection *serverconns[MAXSERVERS];
261 struct rx_securityClass *sc;
262 struct afsconf_dir *tdir;
264 struct afsconf_cell info;
268 tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
270 ViceLog(0, ("hpr_Initialize: Could not open configuration directory: %s", AFSDIR_SERVER_ETC_DIRPATH));
274 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
276 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
281 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
283 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s",
284 cellstr, confDir->name, AFSDIR_CELLSERVDB_FILE));
291 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
296 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
297 * to force use of the KeyFile. secLevel == 0 implies -noauth was
299 code = afsconf_ClientAuthSecure(tdir, &sc, &scIndex);
301 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s "
302 "(so trying noauth)", code, afs_error_message(code)));
303 scIndex = RX_SECIDX_NULL;
304 sc = rxnull_NewClientSecurityObject();
307 if (scIndex == RX_SECIDX_NULL)
308 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, "
309 "running unauthenticated. [%d]", code));
311 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
312 for (i = 0; i < info.numServers; i++) {
314 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
315 info.hostAddr[i].sin_port, PRSRV,
319 code = ubik_ClientInit(serverconns, uclient);
321 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
324 code = rxs_Release(sc);
329 hpr_End(struct ubik_client *uclient)
334 code = ubik_ClientDestroy(uclient);
340 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
342 #ifdef AFS_PTHREAD_ENV
345 struct ubik_client *uclient =
346 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
349 code = hpr_Initialize(&uclient);
351 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
357 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
358 if (code != PRSUCCESS)
361 /* do something about this, probably make a new call */
362 /* don't forget there's a hard limit in the interface */
364 "membership list for host id %d exceeds display limit\n",
369 return pr_GetHostCPS(host, CPS);
374 hpr_NameToId(namelist *names, idlist *ids)
376 #ifdef AFS_PTHREAD_ENV
379 struct ubik_client *uclient =
380 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
383 code = hpr_Initialize(&uclient);
385 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
390 for (i = 0; i < names->namelist_len; i++)
391 stolower(names->namelist_val[i]);
392 code = ubik_PR_NameToID(uclient, 0, names, ids);
395 return pr_NameToId(names, ids);
400 hpr_IdToName(idlist *ids, namelist *names)
402 #ifdef AFS_PTHREAD_ENV
404 struct ubik_client *uclient =
405 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
408 code = hpr_Initialize(&uclient);
410 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
415 code = ubik_PR_IDToName(uclient, 0, ids, names);
418 return pr_IdToName(ids, names);
423 hpr_GetCPS(afs_int32 id, prlist *CPS)
425 #ifdef AFS_PTHREAD_ENV
428 struct ubik_client *uclient =
429 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
432 code = hpr_Initialize(&uclient);
434 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
440 code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
441 if (code != PRSUCCESS)
444 /* do something about this, probably make a new call */
445 /* don't forget there's a hard limit in the interface */
446 fprintf(stderr, "membership list for id %d exceeds display limit\n",
451 return pr_GetCPS(id, CPS);
455 static short consolePort = 0;
458 h_Lock_r(struct host *host)
468 * returns 1 if already locked
469 * else returns locks and returns 0
473 h_NBLock_r(struct host *host)
475 struct Lock *hostLock = &host->lock;
480 if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
481 hostLock->excl_locked = WRITE_LOCK;
485 LOCK_UNLOCK(hostLock);
494 #if FS_STATS_DETAILED
495 /*------------------------------------------------------------------------
496 * PRIVATE h_AddrInSameNetwork
499 * Given a target IP address and a candidate IP address (both
500 * in host byte order), return a non-zero value (1) if the
501 * candidate address is in a different network from the target
505 * a_targetAddr : Target address.
506 * a_candAddr : Candidate address.
509 * 1 if the candidate address is in the same net as the target,
513 * The target and candidate addresses are both in host byte
514 * order, NOT network byte order, when passed in. We return
515 * our value as a character, since that's the type of field in
516 * the host structure, where this info will be stored.
520 *------------------------------------------------------------------------*/
523 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
524 { /*h_AddrInSameNetwork */
526 afs_uint32 targetNet;
530 * Pull out the network and subnetwork numbers from the target
531 * and candidate addresses. We can short-circuit this whole
532 * affair if the target and candidate addresses are not of the
535 if (IN_CLASSA(a_targetAddr)) {
536 if (!(IN_CLASSA(a_candAddr))) {
539 targetNet = a_targetAddr & IN_CLASSA_NET;
540 candNet = a_candAddr & IN_CLASSA_NET;
541 } else if (IN_CLASSB(a_targetAddr)) {
542 if (!(IN_CLASSB(a_candAddr))) {
545 targetNet = a_targetAddr & IN_CLASSB_NET;
546 candNet = a_candAddr & IN_CLASSB_NET;
547 } /*Class B target */
548 else if (IN_CLASSC(a_targetAddr)) {
549 if (!(IN_CLASSC(a_candAddr))) {
552 targetNet = a_targetAddr & IN_CLASSC_NET;
553 candNet = a_candAddr & IN_CLASSC_NET;
554 } /*Class C target */
556 targetNet = a_targetAddr;
557 candNet = a_candAddr;
558 } /*Class D address */
561 * Now, simply compare the extracted net values for the two addresses
562 * (which at this point are known to be of the same class)
564 if (targetNet == candNet)
569 } /*h_AddrInSameNetwork */
570 #endif /* FS_STATS_DETAILED */
573 /* Assumptions: called with held host */
575 h_gethostcps_r(struct host *host, afs_int32 now)
580 /* wait if somebody else is already doing the getCPS call */
581 while (host->hostFlags & HCPS_INPROGRESS) {
582 slept = 1; /* I did sleep */
583 host->hostFlags |= HCPS_WAITING; /* I am sleeping now */
584 #ifdef AFS_PTHREAD_ENV
585 CV_WAIT(&host->cond, &host_glock_mutex);
586 #else /* AFS_PTHREAD_ENV */
587 if ((code = LWP_WaitProcess(&(host->hostFlags))) != LWP_SUCCESS)
588 ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
589 #endif /* AFS_PTHREAD_ENV */
593 host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
594 if (host->hcps.prlist_val)
595 free(host->hcps.prlist_val); /* this is for hostaclRefresh */
596 host->hcps.prlist_val = NULL;
597 host->hcps.prlist_len = 0;
598 host->cpsCall = slept ? (FT_ApproxTime()) : (now);
601 code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
606 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
607 * and reevaluates things if no sync server or quorum is found we could still end up
608 * with one of these errors. In such case we would like to reevaluate the rpc call to
609 * find if there's cps for this guy. We treat other errors (except network failures
610 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
611 * we could like to deal this problem the other way around (i.e. if code == NOCPS
612 * ignore else retry next time) but the problem is that there're other errors (i.e.
613 * EPERM) for which we don't want to retry and we don't know the whole code list!
615 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
617 * We would have preferred to use a while loop and try again since ops in protected
618 * acls for this host will fail now but they'll be reevaluated on any subsequent
619 * call. The attempt to wait for a quorum/sync site or network error won't work
620 * since this problems really should only occurs during a complete fileserver
621 * restart. Since the fileserver will start before the ptservers (and thus before
622 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
624 host->hcpsfailed = 1;
626 ("Warning: GetHostCPS failed (%d) for %p (%s:%d); will retry\n",
627 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
629 host->hcpsfailed = 0;
631 ("gethost: GetHostCPS failed (%d) for %p (%s:%d); ignored\n",
632 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
634 if (host->hcps.prlist_val)
635 free(host->hcps.prlist_val);
636 host->hcps.prlist_val = NULL;
637 host->hcps.prlist_len = 0; /* Make sure it's zero */
639 host->hcpsfailed = 0;
641 host->hostFlags &= ~HCPS_INPROGRESS;
642 /* signal all who are waiting */
643 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
644 host->hostFlags &= ~HCPS_WAITING;
645 #ifdef AFS_PTHREAD_ENV
646 CV_BROADCAST(&host->cond);
647 #else /* AFS_PTHREAD_ENV */
648 if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
649 ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
650 #endif /* AFS_PTHREAD_ENV */
654 /* args in net byte order */
656 h_flushhostcps(afs_uint32 hostaddr, afs_uint16 hport)
661 h_Lookup_r(hostaddr, hport, &host);
663 host->hcpsfailed = 1;
672 * Allocate a host. It will be identified by the peer (ip,port) info in the
673 * rx connection provided. The host is returned held and locked
675 #define DEF_ROPCONS 2115
678 h_Alloc_r(struct rx_connection *r_con)
680 struct servent *serverentry;
682 #if FS_STATS_DETAILED
683 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
684 #endif /* FS_STATS_DETAILED */
688 host->host = rxr_HostOf(r_con);
689 host->port = rxr_PortOf(r_con);
691 h_AddHostToAddrHashTable_r(host->host, host->port, host);
693 if (consolePort == 0) { /* find the portal number for console */
694 #if defined(AFS_OSF_ENV)
695 serverentry = getservbyname("ropcons", "");
697 serverentry = getservbyname("ropcons", 0);
700 consolePort = serverentry->s_port;
702 consolePort = htons(DEF_ROPCONS); /* Use a default */
704 if (host->port == consolePort)
706 /* Make a callback channel even for the console, on the off chance that it
707 * makes a request that causes a break call back. It shouldn't. */
708 h_SetupCallbackConn_r(host);
709 host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
711 host->hcps.prlist_val = NULL;
712 host->hcps.prlist_len = 0;
713 host->interface = NULL;
715 host->hcpsfailed = 0; /* save cycles */
716 h_gethostcps(host); /* do this under host hold/lock */
718 host->FirstClient = NULL;
721 h_InsertList_r(host); /* update global host List */
722 #if FS_STATS_DETAILED
724 * Compare the new host's IP address (in host byte order) with ours
725 * (the File Server's), remembering if they are in the same network.
727 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
728 host->InSameNetwork =
729 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
730 #endif /* FS_STATS_DETAILED */
737 /* Make a callback channel even for the console, on the off chance that it
738 * makes a request that causes a break call back. It shouldn't. */
740 h_SetupCallbackConn_r(struct host * host)
743 sc = rxnull_NewClientSecurityObject();
744 host->callback_rxcon =
745 rx_NewConnection(host->host, host->port, 1, sc, 0);
746 rx_SetConnDeadTime(host->callback_rxcon, 50);
747 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
751 * Lookup a host given an IP address and UDP port number.
752 * hostaddr and hport are in network order
753 * hostaddr and hport are in network order
754 * On return, refCount is incremented.
757 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, struct host **hostp)
760 struct host *host = NULL;
761 struct h_AddrHashChain *chain;
762 int index = h_HashIndex(haddr);
763 extern int hostaclRefresh;
766 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
767 host = chain->hostPtr;
769 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
770 && chain->port == hport) {
771 if ((host->hostFlags & HWHO_INPROGRESS) &&
772 h_threadquota(host->lock.num_waiting)) {
778 if (host->hostFlags & HOSTDELETED) {
785 now = FT_ApproxTime(); /* always evaluate "now" */
786 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
788 * Every hostaclRefresh period (def 2 hrs) get the new
789 * membership list for the host. Note this could be the
790 * first time that the host is added to a group. Also
791 * here we also retry on previous legitimate hcps failures.
793 * If we get here refCount is elevated.
795 h_gethostcps_r(host, now);
805 /* Lookup a host given its UUID. */
807 h_LookupUuid_r(afsUUID * uuidp)
809 struct host *host = 0;
810 struct h_UuidHashChain *chain;
811 int index = h_UuidHashIndex(uuidp);
813 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
814 host = chain->hostPtr;
816 if (!(host->hostFlags & HOSTDELETED) && host->interface
817 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
825 /* h_TossStuff_r: Toss anything in the host structure (the host or
826 * clients marked for deletion. Called from h_Release_r ONLY.
827 * To be called, there must be no holds, and either host->deleted
828 * or host->clientDeleted must be set.
831 h_TossStuff_r(struct host *host)
833 struct client **cp, *client;
836 /* make sure host doesn't go away over h_NBLock_r */
839 code = h_NBLock_r(host);
841 /* don't use h_Release_r, since that may call h_TossStuff_r again */
844 /* if somebody still has this host locked */
848 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was locked.\n",
849 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
855 /* if somebody still has this host held */
856 /* we must check this _after_ h_NBLock_r, since h_NBLock_r can drop and
857 * reacquire H_LOCK */
858 if (host->refCount > 0) {
861 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was held.\n",
862 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
866 /* ASSUMPTION: rxi_FreeConnection() does not yield */
867 for (cp = &host->FirstClient; (client = *cp);) {
868 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
870 ObtainWriteLockNoBlock(&client->lock, code);
874 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
875 "client %p was locked.\n",
876 host, afs_inet_ntoa_r(host->host, hoststr),
877 ntohs(host->port), client));
881 if (client->refCount) {
884 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
885 "client %p refcount %d.\n",
886 host, afs_inet_ntoa_r(host->host, hoststr),
887 ntohs(host->port), client, client->refCount));
888 /* This is the same thing we do if the host is locked */
889 ReleaseWriteLock(&client->lock);
892 client->CPS.prlist_len = 0;
893 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
894 free(client->CPS.prlist_val);
895 client->CPS.prlist_val = NULL;
896 CurrentConnections--;
898 ReleaseWriteLock(&client->lock);
904 /* We've just cleaned out all the deleted clients; clear the flag */
905 host->hostFlags &= ~CLIENTDELETED;
907 if (host->hostFlags & HOSTDELETED) {
908 struct rx_connection *rxconn;
909 struct AddrPort hostAddrPort;
912 if (host->Console & 1)
914 if ((rxconn = host->callback_rxcon)) {
915 host->callback_rxcon = (struct rx_connection *)0;
916 rx_DestroyConnection(rxconn);
918 if (host->hcps.prlist_val)
919 free(host->hcps.prlist_val);
920 host->hcps.prlist_val = NULL;
921 host->hcps.prlist_len = 0;
922 DeleteAllCallBacks_r(host, 1);
923 host->hostFlags &= ~RESETDONE; /* just to be safe */
925 /* if alternate addresses do not exist */
926 if (!(host->interface)) {
927 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
929 h_DeleteHostFromUuidHashTable_r(host);
930 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
931 /* delete the hash entry for each valid alternate addresses */
932 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
933 hostAddrPort = host->interface->interface[i];
935 * if the interface addr/port is the primary, we already
936 * removed it. If the addr/port is not valid, its not
939 if (hostAddrPort.valid &&
940 (host->host != hostAddrPort.addr ||
941 host->port != hostAddrPort.port))
942 h_DeleteHostFromAddrHashTable_r(hostAddrPort.addr, hostAddrPort.port, host);
944 free(host->interface);
945 host->interface = NULL;
946 } /* if alternate address exists */
948 h_DeleteList_r(host); /* remove host from global host List */
955 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
956 * system at the start of the enumeration (perhaps more). Hosts may be deleted
957 * (have delete flag set); ditto for clients. refCount is always incremented
958 * before (*proc) is called. The param flags is passed to (*proc) as the
959 * param flags, permitting (*proc) to stop the enumeration (BAIL).
961 * Needed? Why not always h_Hold_r and h_Release_r in (*proc), or even -never-
962 * h_Hold_r or h_Release_r in (*proc)?
964 * **The proc should return 0 if the host should be released, 1 if it should
965 * be held after enumeration.
968 h_Enumerate(int (*proc) (struct host*, int, void *), void *param)
970 struct host *host, **list;
976 if (hostCount == 0) {
980 list = (struct host **)malloc(hostCount * sizeof(struct host *));
982 ViceLogThenPanic(0, ("Failed malloc in h_Enumerate (list)\n"));
984 flags = (int *)malloc(hostCount * sizeof(int));
986 ViceLogThenPanic(0, ("Failed malloc in h_Enumerate (flags)\n"));
988 for (totalCount = count = 0, host = hostList;
989 host && totalCount < hostCount;
990 host = host->next, totalCount++) {
992 if (!(host->hostFlags & HOSTDELETED)) {
998 if (totalCount != hostCount) {
999 ViceLog(0, ("h_Enumerate found %d of %d hosts\n", totalCount, hostCount));
1000 } else if (host != NULL) {
1001 ViceLog(0, ("h_Enumerate found more than %d hosts\n", hostCount));
1002 ShutDownAndCore(PANIC);
1005 for (i = 0; i < count; i++) {
1006 flags[i] = (*proc) (list[i], flags[i], param);
1008 h_Release_r(list[i]);
1010 /* bail out of the enumeration early */
1011 if (H_ENUMERATE_ISSET_BAIL(flags[i]))
1015 free((void *)flags);
1019 /* h_Enumerate_r (revised):
1020 * Calls (*proc)(host, flags, param) for each host in hostList, starting
1021 * at enumstart. Called only under H_LOCK. Hosts may be deleted (have
1022 * delete flag set); ditto for clients. refCount is always incremented
1023 * before (*proc) is called. The param flags is passed to (*proc) as the
1024 * param flags, permitting (*proc) to stop the enumeration (BAIL).
1026 * Needed? Why not always h_Hold_r and h_Release_r in (*proc), or even -never-
1027 * h_Hold_r or h_Release_r in (*proc)?
1029 * @note Assumes that hostList is only prepended to, that a host is never
1030 * inserted into the middle. Otherwise this would not be guaranteed to
1033 * **The proc should return 0 if the host should be released, 1 if it should
1034 * be held after enumeration.
1037 h_Enumerate_r(int (*proc) (struct host *, int, void *),
1038 struct host *enumstart, void *param)
1040 struct host *host, *next;
1046 if (hostCount == 0) {
1053 /* find the first non-deleted host, so we know where to actually start
1055 for (count = 0; host && count < hostCount; count++) {
1056 if (!(host->hostFlags & HOSTDELETED)) {
1063 /* we didn't find a non-deleted host... */
1065 if (host && count >= hostCount) {
1066 /* ...because we found a loop */
1067 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", hostCount));
1068 ShutDownAndCore(PANIC);
1071 /* ...because the hostList is full of deleted hosts */
1075 h_Hold_r(enumstart);
1077 /* remember hostCount, lest it change over the potential H_LOCK drop in
1079 origHostCount = hostCount;
1081 for (count = 0, host = enumstart; host && count < origHostCount; host = next, flags = nflags, count++) {
1084 /* find the next non-deleted host */
1085 while (next && (next->hostFlags & HOSTDELETED)) {
1087 /* inc count for the skipped-over host */
1088 if (++count > origHostCount) {
1089 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1090 ShutDownAndCore(PANIC);
1093 if (next && !H_ENUMERATE_ISSET_BAIL(flags))
1096 if (!(host->hostFlags & HOSTDELETED)) {
1097 flags = (*proc) (host, flags, param);
1098 if (H_ENUMERATE_ISSET_BAIL(flags)) {
1099 h_Release_r(host); /* this might free up the host */
1103 h_Release_r(host); /* this might free up the host */
1105 if (host != NULL && count >= origHostCount) {
1106 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1107 ShutDownAndCore(PANIC);
1109 } /*h_Enumerate_r */
1112 /* inserts a new HashChain structure corresponding to this UUID */
1114 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1117 struct h_UuidHashChain *chain;
1118 char uuid1[128], uuid2[128];
1121 /* hash into proper bucket */
1122 index = h_UuidHashIndex(uuid);
1124 /* don't add the same entry multiple times */
1125 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1126 if (!chain->hostPtr)
1129 if (chain->hostPtr->interface &&
1130 afs_uuid_equal(&chain->hostPtr->interface->uuid, uuid)) {
1131 if (LogLevel >= 125) {
1132 afsUUID_to_string(&chain->hostPtr->interface->uuid, uuid1,
1134 afsUUID_to_string(uuid, uuid2, 127);
1135 ViceLog(125, ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s) exists as %s:%d (uuid %s)\n",
1137 afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1138 ntohs(chain->hostPtr->port), uuid2));
1144 /* insert into beginning of list for this bucket */
1145 chain = (struct h_UuidHashChain *)malloc(sizeof(struct h_UuidHashChain));
1147 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1149 chain->hostPtr = host;
1150 chain->next = hostUuidHashTable[index];
1151 hostUuidHashTable[index] = chain;
1154 afsUUID_to_string(uuid, uuid2, 127);
1156 ("h_AddHostToUuidHashTable_r: host %p (%s:%d) added as uuid %s\n",
1157 host, afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1158 ntohs(chain->hostPtr->port), uuid2));
1161 /* deletes a HashChain structure corresponding to this host */
1163 h_DeleteHostFromUuidHashTable_r(struct host *host)
1166 struct h_UuidHashChain **uhp, *uth;
1170 if (!host->interface)
1173 /* hash into proper bucket */
1174 index = h_UuidHashIndex(&host->interface->uuid);
1176 if (LogLevel >= 125)
1177 afsUUID_to_string(&host->interface->uuid, uuid1, 127);
1178 for (uhp = &hostUuidHashTable[index]; (uth = *uhp); uhp = &uth->next) {
1179 osi_Assert(uth->hostPtr);
1180 if (uth->hostPtr == host) {
1182 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d)\n",
1183 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1184 ntohs(host->port)));
1191 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d) not found\n",
1192 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1193 ntohs(host->port)));
1198 * This is called with host locked and held.
1200 * All addresses are in network byte order.
1203 invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1207 struct Interface *interface;
1208 char hoststr[16], hoststr2[16];
1211 osi_Assert(host->interface);
1213 ViceLog(125, ("invalidateInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1214 host, afs_inet_ntoa_r(host->host, hoststr),
1215 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1219 * Make sure this address is on the list of known addresses
1222 interface = host->interface;
1223 number = host->interface->numberOfInterfaces;
1224 for (i = 0; i < number; i++) {
1225 if (interface->interface[i].addr == addr &&
1226 interface->interface[i].port == port) {
1227 if (interface->interface[i].valid) {
1228 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1229 interface->interface[i].valid = 0;
1240 * This is called with host locked and held. This function differs
1241 * from removeInterfaceAddr_r in that it is called when the address
1242 * is being removed from the host regardless of whether or not there
1243 * is an interface list for the host. This function will delete the
1244 * host if there are no addresses left on it.
1246 * All addresses are in network byte order.
1249 removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1252 char hoststr[16], hoststr2[16];
1253 struct rx_connection *rxconn;
1255 if (!host->interface || host->interface->numberOfInterfaces == 1) {
1256 if (host->host == addr && host->port == port) {
1258 ("Removing only address for host %" AFS_PTR_FMT " (%s:%d), deleting host.\n",
1259 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1260 host->hostFlags |= HOSTDELETED;
1262 * Do not remove the primary addr/port from the hash table.
1263 * It will be ignored due to the HOSTDELETED flag and will
1264 * be removed when h_TossStuff_r() cleans up the HOSTDELETED
1265 * host. Removing it here will only result in a search for
1266 * the host/addr/port in the hash chain which will fail.
1270 ("Removing address that does not belong to host %" AFS_PTR_FMT " (%s:%d).\n",
1271 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1274 if (host->host == addr && host->port == port) {
1275 removeInterfaceAddr_r(host, addr, port);
1277 for (i=0; i < host->interface->numberOfInterfaces; i++) {
1278 if (host->interface->interface[i].valid) {
1280 ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
1281 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1282 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
1283 ntohs(host->interface->interface[i].port)));
1284 host->host = host->interface->interface[i].addr;
1285 host->port = host->interface->interface[i].port;
1286 h_AddHostToAddrHashTable_r(host->host, host->port, host);
1291 if (i == host->interface->numberOfInterfaces) {
1293 ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
1294 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1295 host->hostFlags |= HOSTDELETED;
1296 /* addr/port was removed from the hash table */
1300 rxconn = host->callback_rxcon;
1301 host->callback_rxcon = NULL;
1304 rx_DestroyConnection(rxconn);
1309 sc = rxnull_NewClientSecurityObject();
1310 host->callback_rxcon =
1311 rx_NewConnection(host->host, host->port, 1, sc, 0);
1312 rx_SetConnDeadTime(host->callback_rxcon, 50);
1313 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
1316 /* not the primary addr/port, just invalidate it */
1317 invalidateInterfaceAddr_r(host, addr, port);
1325 createHostAddrHashChain_r(int index, afs_uint32 addr, afs_uint16 port, struct host *host)
1327 struct h_AddrHashChain *chain;
1330 /* insert into beginning of list for this bucket */
1331 chain = (struct h_AddrHashChain *)malloc(sizeof(struct h_AddrHashChain));
1333 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToAddrHashTable_r\n"));
1335 chain->hostPtr = host;
1336 chain->next = hostAddrHashTable[index];
1339 hostAddrHashTable[index] = chain;
1340 ViceLog(125, ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " added as %s:%d\n",
1341 host, afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1345 * Resolve host address conflicts when hashing by address.
1347 * @param[in] addr an ip address of the interface
1348 * @param[in] port the port of the interface
1349 * @param[in] newHost the host being added with this address
1350 * @param[in] oldHost the host previously added with this address
1353 reconcileHosts_r(afs_uint32 addr, afs_uint16 port, struct host *newHost,
1354 struct host *oldHost)
1356 struct rx_connection *cb = NULL;
1358 struct interfaceAddr interf;
1360 afsUUID *newHostUuid = &nulluuid;
1361 afsUUID *oldHostUuid = &nulluuid;
1365 ("reconcileHosts_r: addr %s:%d newHost %" AFS_PTR_FMT " oldHost %"
1366 AFS_PTR_FMT, afs_inet_ntoa_r(addr, hoststr), ntohs(port),
1369 osi_Assert(oldHost != newHost);
1370 caps.Capabilities_val = NULL;
1373 sc = rxnull_NewClientSecurityObject();
1376 cb = rx_NewConnection(addr, port, 1, sc, 0);
1377 rx_SetConnDeadTime(cb, 50);
1378 rx_SetConnHardDeadTime(cb, AFS_HARDDEADTIME);
1383 code = RXAFSCB_TellMeAboutYourself(cb, &interf, &caps);
1384 if (code == RXGEN_OPCODE) {
1385 code = RXAFSCB_WhoAreYou(cb, &interf);
1389 if (code == RXGEN_OPCODE ||
1390 (code == 0 && afs_uuid_equal(&interf.uuid, &nulluuid))) {
1392 ("reconcileHosts_r: WhoAreYou not supported for connection (%s:%d), error %d\n",
1393 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1398 ("reconcileHosts_r: WhoAreYou failed for connection (%s:%d), error %d\n",
1399 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1403 /* Since lock was dropped, the hosts may have been deleted during the rpcs. */
1404 if ((newHost->hostFlags & HOSTDELETED)
1405 && (oldHost->hostFlags & HOSTDELETED)) {
1407 ("reconcileHosts_r: new and old hosts were deleted during probe.\n"));
1411 /* A check can be done if at least one of the hosts has a uuid. It
1412 * is an error if the hosts have the same (not null) uuid. */
1413 if ((!(newHost->hostFlags & HOSTDELETED)) && newHost->interface) {
1414 newHostUuid = &(newHost->interface->uuid);
1416 if ((!(oldHost->hostFlags & HOSTDELETED)) && oldHost->interface) {
1417 oldHostUuid = &(oldHost->interface->uuid);
1419 if (afs_uuid_equal(newHostUuid, &nulluuid) &&
1420 afs_uuid_equal(oldHostUuid, &nulluuid)) {
1422 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), no uuids\n",
1423 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1426 if (afs_uuid_equal(newHostUuid, oldHostUuid)) {
1428 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), same uuids\n",
1429 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1433 /* Determine which host should be hashed */
1434 if ((!(newHost->hostFlags & HOSTDELETED))
1435 && afs_uuid_equal(newHostUuid, &(interf.uuid))) {
1436 /* Install the new host into the hash before removing the stale
1437 * addresses. Walk the hash chain again since the hash table may have
1438 * been changed when the host lock was dropped to get the uuid. */
1439 struct h_AddrHashChain *chain;
1440 int index = h_HashIndex(addr);
1441 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1442 if (chain->addr == addr && chain->port == port) {
1443 chain->hostPtr = newHost;
1444 removeAddress_r(oldHost, addr, port);
1448 createHostAddrHashChain_r(index, addr, port, newHost);
1449 removeAddress_r(oldHost, addr, port);
1452 if ((!(oldHost->hostFlags & HOSTDELETED))
1453 && afs_uuid_equal(oldHostUuid, &(interf.uuid))) {
1454 removeAddress_r(newHost, addr, port);
1459 if (!(newHost->hostFlags & HOSTDELETED)) {
1460 removeAddress_r(newHost, addr, port);
1462 if (!(oldHost->hostFlags & HOSTDELETED)) {
1463 removeAddress_r(oldHost, addr, port);
1467 h_Release_r(newHost);
1468 h_Release_r(oldHost);
1469 rx_DestroyConnection(cb);
1473 /* inserts a new HashChain structure corresponding to this address */
1475 h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1478 struct h_AddrHashChain *chain;
1481 /* hash into proper bucket */
1482 index = h_HashIndex(addr);
1484 /* don't add the same address:port pair entry multiple times */
1485 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1486 if (chain->addr == addr && chain->port == port) {
1487 if (chain->hostPtr == host) {
1489 ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
1490 host, afs_inet_ntoa_r(chain->addr, hoststr),
1491 ntohs(chain->port)));
1494 if (!(chain->hostPtr->hostFlags & HOSTDELETED)) {
1495 /* attempt to resolve host address collision */
1496 reconcileHosts_r(addr, port, host, chain->hostPtr);
1501 createHostAddrHashChain_r(index, addr, port, host);
1505 * This is called with host locked and held.
1506 * It is called to either validate or add an additional interface
1507 * address/port on the specified host.
1509 * All addresses are in network byte order.
1512 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1516 struct Interface *interface;
1517 char hoststr[16], hoststr2[16];
1520 osi_Assert(host->interface);
1523 * Make sure this address is on the list of known addresses
1526 number = host->interface->numberOfInterfaces;
1527 for (i = 0; i < number; i++) {
1528 if (host->interface->interface[i].addr == addr &&
1529 host->interface->interface[i].port == port) {
1531 ("addInterfaceAddr : found host %" AFS_PTR_FMT " (%s:%d) adding %s:%d%s\n",
1532 host, afs_inet_ntoa_r(host->host, hoststr),
1533 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1534 ntohs(port), host->interface->interface[i].valid ? "" :
1537 if (host->interface->interface[i].valid == 0) {
1538 host->interface->interface[i].valid = 1;
1539 h_AddHostToAddrHashTable_r(addr, port, host);
1545 ViceLog(125, ("addInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) adding %s:%d\n",
1546 host, afs_inet_ntoa_r(host->host, hoststr),
1547 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1550 interface = (struct Interface *)
1551 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1553 ViceLogThenPanic(0, ("Failed malloc in addInterfaceAddr_r\n"));
1555 interface->numberOfInterfaces = number + 1;
1556 interface->uuid = host->interface->uuid;
1557 for (i = 0; i < number; i++)
1558 interface->interface[i] = host->interface->interface[i];
1560 /* Add the new valid interface */
1561 interface->interface[number].addr = addr;
1562 interface->interface[number].port = port;
1563 interface->interface[number].valid = 1;
1564 h_AddHostToAddrHashTable_r(addr, port, host);
1565 free(host->interface);
1566 host->interface = interface;
1573 * This is called with host locked and held.
1575 * All addresses are in network byte order.
1578 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1582 struct Interface *interface;
1583 char hoststr[16], hoststr2[16];
1586 osi_Assert(host->interface);
1588 ViceLog(125, ("removeInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1589 host, afs_inet_ntoa_r(host->host, hoststr),
1590 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1594 * Make sure this address is on the list of known addresses
1597 interface = host->interface;
1598 number = host->interface->numberOfInterfaces;
1599 for (i = 0; i < number; i++) {
1600 if (interface->interface[i].addr == addr &&
1601 interface->interface[i].port == port) {
1602 if (interface->interface[i].valid)
1603 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1605 for (; i < number; i++) {
1606 interface->interface[i] = interface->interface[i+1];
1608 interface->numberOfInterfaces = number;
1619 h_threadquota(int waiting)
1624 } else if (lwps > 32) {
1627 } else if (lwps > 16) {
1637 /* If found, host is returned with refCount incremented */
1639 h_GetHost_r(struct rx_connection *tcon)
1642 struct host *oldHost;
1644 struct interfaceAddr interf;
1645 int interfValid = 0;
1646 struct Identity *identP = NULL;
1649 char hoststr[16], hoststr2[16];
1651 struct rx_connection *cb_conn = NULL;
1652 struct rx_connection *cb_in = NULL;
1654 caps.Capabilities_val = NULL;
1656 haddr = rxr_HostOf(tcon);
1657 hport = rxr_PortOf(tcon);
1660 rx_DestroyConnection(cb_in);
1663 if (caps.Capabilities_val)
1664 free(caps.Capabilities_val);
1665 caps.Capabilities_val = NULL;
1666 caps.Capabilities_len = 0;
1669 if (h_Lookup_r(haddr, hport, &host))
1671 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1672 if (host && !identP && !(host->Console & 1)) {
1673 /* This is a new connection, and we already have a host
1674 * structure for this address. Verify that the identity
1675 * of the caller matches the identity in the host structure.
1677 if ((host->hostFlags & HWHO_INPROGRESS) &&
1678 h_threadquota(host->lock.num_waiting)) {
1684 if (!(host->hostFlags & ALTADDR) ||
1685 (host->hostFlags & HOSTDELETED)) {
1686 /* Another thread is doing initialization
1687 * or this host was deleted while we
1688 * waited for the lock. */
1691 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1692 host, afs_inet_ntoa_r(host->host, hoststr),
1693 ntohs(host->port)));
1697 host->hostFlags |= HWHO_INPROGRESS;
1698 host->hostFlags &= ~ALTADDR;
1700 /* We received a new connection from an IP address/port
1701 * that is associated with 'host' but the address/port of
1702 * the callback connection does not have to match it.
1703 * If there is a match, we can use the existing callback
1704 * connection to verify the UUID. If they do not match
1705 * we need to use a new callback connection to verify the
1706 * UUID of the incoming caller and perhaps use the old
1707 * callback connection to verify that the old address/port
1711 cb_conn = host->callback_rxcon;
1712 rx_GetConnection(cb_conn);
1714 if (haddr == host->host && hport == host->port) {
1715 /* The existing callback connection matches the
1716 * incoming connection so just use it.
1719 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1720 if (code == RXGEN_OPCODE)
1721 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1723 /* We do not have a match. Create a new connection
1724 * for the new addr/port and use multi_Rx to probe
1725 * both of them simultaneously.
1728 sc = rxnull_NewClientSecurityObject();
1729 cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1730 rx_SetConnDeadTime(cb_in, 50);
1731 rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1734 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1735 if (code == RXGEN_OPCODE)
1736 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1738 rx_PutConnection(cb_conn);
1741 if ((code == RXGEN_OPCODE) ||
1742 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1743 identP = (struct Identity *)malloc(sizeof(struct Identity));
1745 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1748 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1749 if (cb_in == NULL) {
1750 /* The host on this connection was unable to respond to
1751 * the WhoAreYou. We will treat this as a new connection
1752 * from the existing host. The worst that can happen is
1753 * that we maintain some extra callback state information */
1754 if (host->interface) {
1756 ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1758 afs_inet_ntoa_r(host->host, hoststr),
1759 ntohs(host->port)));
1760 host->hostFlags |= HOSTDELETED;
1761 host->hostFlags &= ~HWHO_INPROGRESS;
1768 /* The incoming connection does not support WhoAreYou but
1769 * the original one might have. Use removeAddress_r() to
1770 * remove this addr/port from the host that was found.
1771 * If there are no more addresses left for the host it
1772 * will be deleted. Then we retry.
1774 removeAddress_r(host, haddr, hport);
1775 host->hostFlags &= ~HWHO_INPROGRESS;
1776 host->hostFlags |= ALTADDR;
1782 } else if (code == 0) {
1784 identP = (struct Identity *)malloc(sizeof(struct Identity));
1786 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1789 identP->uuid = interf.uuid;
1790 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1791 /* Check whether the UUID on this connection matches
1792 * the UUID in the host structure. If they don't match
1793 * then this is not the same host as before. */
1794 if (!host->interface
1795 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1798 ("Uuid doesn't match connection (%s:%d).\n",
1799 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1800 removeAddress_r(host, haddr, hport);
1803 ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1804 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1806 removeAddress_r(host, host->host, host->port);
1808 host->hostFlags &= ~HWHO_INPROGRESS;
1809 host->hostFlags |= ALTADDR;
1815 /* the UUID matched the client at the incoming addr/port
1816 * but this is not the address of the active callback
1817 * connection. Try that connection and see if the client
1818 * is still there and if the reported UUID is the same.
1821 afsUUID uuid = host->interface->uuid;
1822 cb_conn = host->callback_rxcon;
1823 rx_GetConnection(cb_conn);
1824 rx_SetConnDeadTime(cb_conn, 2);
1825 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1827 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1829 rx_SetConnDeadTime(cb_conn, 50);
1830 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1831 rx_PutConnection(cb_conn);
1834 /* The primary address is either not responding or
1835 * is not the client we are looking for. Need to
1836 * remove the primary address and add swap in the new
1837 * callback connection, and destroy the old one.
1839 struct rx_connection *rxconn;
1840 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1842 afs_inet_ntoa_r(host->host, hoststr),
1843 ntohs(host->port),code2));
1846 * make sure we add and then remove. otherwise, we
1847 * might end up with no valid interfaces after the
1848 * remove and the host will have been marked deleted.
1850 addInterfaceAddr_r(host, haddr, hport);
1851 removeInterfaceAddr_r(host, host->host, host->port);
1854 rxconn = host->callback_rxcon;
1855 host->callback_rxcon = cb_in;
1860 * If rx_DestroyConnection calls h_FreeConnection we
1861 * will deadlock on the host_glock_mutex. Work around
1862 * the problem by unhooking the client from the
1863 * connection before destroying the connection.
1865 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1866 rx_DestroyConnection(rxconn);
1872 /* A callback to the incoming connection address is failing.
1873 * Assume that the addr/port is no longer associated with the host
1874 * returned by h_Lookup_r.
1877 ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1878 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1879 removeAddress_r(host, haddr, hport);
1880 host->hostFlags &= ~HWHO_INPROGRESS;
1881 host->hostFlags |= ALTADDR;
1885 rx_DestroyConnection(cb_in);
1890 ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1891 host, afs_inet_ntoa_r(host->host, hoststr),
1892 ntohs(host->port), code));
1893 host->hostFlags |= VENUSDOWN;
1896 if (caps.Capabilities_val
1897 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1898 host->hostFlags |= HERRORTRANS;
1900 host->hostFlags &= ~(HERRORTRANS);
1901 host->hostFlags |= ALTADDR;
1902 host->hostFlags &= ~HWHO_INPROGRESS;
1905 if (!(host->hostFlags & ALTADDR)) {
1906 /* another thread is doing the initialisation */
1908 ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1909 host, afs_inet_ntoa_r(host->host, hoststr),
1910 ntohs(host->port)));
1914 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1915 host, afs_inet_ntoa_r(host->host, hoststr),
1916 ntohs(host->port)));
1920 /* We need to check whether the identity in the host structure
1921 * matches the identity on the connection. If they don't match
1922 * then treat this a new host. */
1923 if (!(host->Console & 1)
1924 && ((!identP->valid && host->interface)
1925 || (identP->valid && !host->interface)
1927 && !afs_uuid_equal(&identP->uuid,
1928 &host->interface->uuid)))) {
1929 char uuid1[128], uuid2[128];
1931 afsUUID_to_string(&identP->uuid, uuid1, 127);
1932 if (host->interface)
1933 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1935 ("CB: new identity for host %p (%s:%d), "
1936 "deleting(%x %p %s %s)\n",
1937 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1938 identP->valid, host->interface,
1939 identP->valid ? uuid1 : "no_uuid",
1940 host->interface ? uuid2 : "no_uuid"));
1942 /* The host in the cache is not the host for this connection */
1944 host->hostFlags |= HOSTDELETED;
1950 host = h_Alloc_r(tcon); /* returned held and locked */
1951 h_gethostcps_r(host, FT_ApproxTime());
1952 if (!(host->Console & 1)) {
1954 cb_conn = host->callback_rxcon;
1955 rx_GetConnection(cb_conn);
1956 host->hostFlags |= HWHO_INPROGRESS;
1959 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1960 if (code == RXGEN_OPCODE)
1961 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1962 rx_PutConnection(cb_conn);
1965 if ((code == RXGEN_OPCODE) ||
1966 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1969 (struct Identity *)malloc(sizeof(struct Identity));
1974 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1978 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1980 ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1981 host, afs_inet_ntoa_r(host->host, hoststr),
1982 ntohs(host->port)));
1984 } else if (code == 0) {
1987 (struct Identity *)malloc(sizeof(struct Identity));
1992 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1996 identP->uuid = interf.uuid;
1998 rx_SetSpecific(tcon, rxcon_ident_key, identP);
2000 ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
2001 host, afs_inet_ntoa_r(host->host, hoststr),
2002 ntohs(host->port)));
2004 if (code == 0 && !identP->valid) {
2005 cb_conn = host->callback_rxcon;
2006 rx_GetConnection(cb_conn);
2008 code = RXAFSCB_InitCallBackState(cb_conn);
2009 rx_PutConnection(cb_conn);
2012 } else if (code == 0) {
2013 oldHost = h_LookupUuid_r(&identP->uuid);
2018 if (oldHost->hostFlags & HOSTDELETED) {
2019 h_Unlock_r(oldHost);
2020 h_Release_r(oldHost);
2028 oldHost->hostFlags |= HWHO_INPROGRESS;
2030 if (oldHost->interface) {
2032 afsUUID uuid = oldHost->interface->uuid;
2033 cb_conn = oldHost->callback_rxcon;
2034 rx_GetConnection(cb_conn);
2035 rx_SetConnDeadTime(cb_conn, 2);
2036 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2038 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2040 rx_SetConnDeadTime(cb_conn, 50);
2041 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2042 rx_PutConnection(cb_conn);
2045 /* The primary address is either not responding or
2046 * is not the client we are looking for.
2047 * MultiProbeAlternateAddress_r() will remove the
2048 * alternate interfaces that do not have the same
2050 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
2052 afs_inet_ntoa_r(oldHost->host, hoststr),
2053 ntohs(oldHost->port),code2));
2054 MultiProbeAlternateAddress_r(oldHost);
2061 /* This is a new address for an existing host. Update
2062 * the list of interfaces for the existing host and
2063 * delete the host structure we just allocated. */
2065 /* prevent warnings while manipulating interface lists */
2066 host->hostFlags |= HOSTDELETED;
2068 if (oldHost->host != haddr || oldHost->port != hport) {
2069 struct rx_connection *rxconn;
2072 ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
2074 afs_inet_ntoa_r(oldHost->host, hoststr2),
2075 ntohs(oldHost->port),
2076 afs_inet_ntoa_r(haddr, hoststr),
2079 * add then remove. otherwise the host may get marked
2080 * deleted if we removed the only valid address.
2082 addInterfaceAddr_r(oldHost, haddr, hport);
2083 if (probefail || oldHost->host == haddr) {
2085 * The probe failed which means that the old
2086 * address is either unreachable or is not the
2087 * same host we were just contacted by. We will
2088 * also remove addresses if only the port has
2089 * changed because that indicates the client
2092 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
2095 struct Interface *interface = oldHost->interface;
2096 int number = oldHost->interface->numberOfInterfaces;
2097 for (i = 0; i < number; i++) {
2098 if (interface->interface[i].addr == haddr &&
2099 interface->interface[i].port != hport) {
2101 * We have just been contacted by a client
2102 * that has been seen from behind a NAT
2103 * and at least one other address.
2105 removeInterfaceAddr_r(oldHost, haddr,
2106 interface->interface[i].port);
2111 h_AddHostToAddrHashTable_r(haddr, hport, oldHost);
2112 oldHost->host = haddr;
2113 oldHost->port = hport;
2114 rxconn = oldHost->callback_rxcon;
2115 oldHost->callback_rxcon = host->callback_rxcon;
2116 host->callback_rxcon = rxconn;
2118 /* don't destroy rxconn here; let h_TossStuff_r
2119 * take care of that via h_Release_r below */
2121 host->hostFlags &= ~HWHO_INPROGRESS;
2123 /* release host because it was allocated by h_Alloc_r */
2126 /* the new host is held and locked */
2128 /* This really is a new host */
2129 h_AddHostToUuidHashTable_r(&identP->uuid, host);
2130 cb_conn = host->callback_rxcon;
2131 rx_GetConnection(cb_conn);
2134 RXAFSCB_InitCallBackState3(cb_conn,
2136 rx_PutConnection(cb_conn);
2141 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2142 host, afs_inet_ntoa_r(host->host, hoststr),
2143 ntohs(host->port)));
2144 osi_Assert(interfValid == 1);
2145 initInterfaceAddr_r(host, &interf);
2151 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2152 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2153 host->hostFlags |= VENUSDOWN;
2156 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2157 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2158 host->hostFlags |= RESETDONE;
2161 if (caps.Capabilities_val
2162 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2163 host->hostFlags |= HERRORTRANS;
2165 host->hostFlags &= ~(HERRORTRANS);
2166 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2167 host->hostFlags &= ~HWHO_INPROGRESS;
2172 if (caps.Capabilities_val)
2173 free(caps.Capabilities_val);
2174 caps.Capabilities_val = NULL;
2175 caps.Capabilities_len = 0;
2177 rx_DestroyConnection(cb_in);
2185 static char localcellname[PR_MAXNAMELEN + 1];
2186 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
2187 int num_lrealms = -1;
2191 h_InitHostPackage(void)
2193 memset(&nulluuid, 0, sizeof(afsUUID));
2194 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
2195 if (num_lrealms == -1) {
2197 for (i=0; i<AFS_NUM_LREALMS; i++) {
2198 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
2204 ("afs_krb_get_lrealm failed, using %s.\n",
2206 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
2212 /* initialize the rest of the local realms to nullstring for debugging */
2213 for (; i<AFS_NUM_LREALMS; i++)
2214 local_realms[i][0] = '\0';
2216 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2217 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2218 MUTEX_INIT(&host_glock_mutex, "host glock", MUTEX_DEFAULT, 0);
2222 MapName_r(char *aname, char *acell, afs_int32 * aval)
2227 afs_int32 anamelen, cnamelen;
2231 anamelen = strlen(aname);
2232 if (anamelen >= PR_MAXNAMELEN)
2233 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
2235 lnames.namelist_len = 1;
2236 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
2237 lids.idlist_len = 0;
2238 lids.idlist_val = NULL;
2240 cnamelen = strlen(acell);
2242 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2244 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2245 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2246 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2248 ("MapName: Name too long, using AnonymousID for %s@%s\n",
2250 *aval = AnonymousID;
2253 foreign = 1; /* attempt cross-cell authentication */
2254 tname = (char *)malloc(PR_MAXNAMELEN);
2256 ViceLogThenPanic(0, ("Failed malloc in MapName_r\n"));
2258 strcpy(tname, aname);
2259 tname[anamelen] = '@';
2260 strcpy(tname + anamelen + 1, acell);
2261 lnames.namelist_val = (prname *) tname;
2266 code = hpr_NameToId(&lnames, &lids);
2269 if (lids.idlist_val) {
2270 *aval = lids.idlist_val[0];
2271 if (*aval == AnonymousID) {
2273 ("MapName: NameToId on %s returns anonymousID\n",
2274 lnames.namelist_val[0]));
2276 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2279 ("MapName: NameToId on '%s' is unknown\n",
2280 lnames.namelist_val[0]));
2286 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
2294 /* NOTE: this returns the client with a Write lock and a refCount */
2296 h_ID2Client(afs_int32 vid)
2298 struct client *client;
2303 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
2304 if (host->hostFlags & HOSTDELETED)
2306 for (client = host->FirstClient; client; client = client->next) {
2307 if (!client->deleted && client->ViceId == vid) {
2310 ObtainWriteLock(&client->lock);
2315 if (count != hostCount) {
2316 ViceLog(0, ("h_ID2Client found %d of %d hosts\n", count, hostCount));
2317 } else if (host != NULL) {
2318 ViceLog(0, ("h_ID2Client found more than %d hosts\n", hostCount));
2319 ShutDownAndCore(PANIC);
2327 * Called by the server main loop. Returns a h_Held client, which must be
2328 * released later the main loop. Allocates a client if the matching one
2329 * isn't around. The client is returned with its reference count incremented
2330 * by one. The caller must call h_ReleaseClient_r when finished with
2333 * The refCount on client->host is returned incremented. h_ReleaseClient_r
2334 * does not decrement the refCount on client->host.
2337 h_FindClient_r(struct rx_connection *tcon)
2339 struct client *client;
2340 struct host *host = NULL;
2341 struct client *oldClient;
2342 afs_int32 viceid = 0;
2346 #if (64-MAXKTCNAMELEN)
2347 ticket name length != 64
2351 char uname[PR_MAXNAMELEN];
2352 char tcell[MAXKTCREALMLEN];
2356 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2357 if (client && client->sid == rxr_CidOf(tcon)
2358 && client->VenusEpoch == rxr_GetEpoch(tcon)
2359 && !(client->host->hostFlags & HOSTDELETED)) {
2362 h_Hold_r(client->host);
2363 if (!client->deleted && client->prfail != 2) {
2364 /* Could add shared lock on client here */
2365 /* note that we don't have to lock entry in this path to
2366 * ensure CPS is initialized, since we don't call rx_SetSpecific
2367 * until initialization is done, and we only get here if
2368 * rx_GetSpecific located the client structure.
2373 ObtainWriteLock(&client->lock); /* released at end */
2379 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2381 ("FindClient: authenticating connection: authClass=%d\n",
2383 if (authClass == 1) {
2384 /* A bcrypt tickets, no longer supported */
2385 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2386 viceid = AnonymousID;
2387 expTime = 0x7fffffff;
2388 } else if (authClass == 2) {
2391 /* kerberos ticket */
2392 code = rxkad_GetServerInfo(tcon, /*level */ 0, (afs_uint32 *)&expTime,
2393 tname, tinst, tcell, &kvno);
2395 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2396 viceid = AnonymousID;
2397 expTime = 0x7fffffff;
2399 int ilen = strlen(tinst);
2401 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2402 tname, tinst, tcell, expTime, kvno));
2403 strncpy(uname, tname, sizeof(uname));
2405 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2408 strcat(uname, tinst);
2410 /* translate the name to a vice id */
2411 code = MapName_r(uname, tcell, &viceid);
2415 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2418 viceid = AnonymousID;
2419 expTime = 0x7fffffff;
2423 viceid = AnonymousID; /* unknown security class */
2424 expTime = 0x7fffffff;
2427 if (!client) { /* loop */
2428 host = h_GetHost_r(tcon); /* Returns with incremented refCount */
2434 /* First try to find the client structure */
2435 for (client = host->FirstClient; client; client = client->next) {
2436 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2437 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2440 ObtainWriteLock(&client->lock);
2446 /* Still no client structure - get one */
2449 if (host->hostFlags & HOSTDELETED) {
2454 /* Retry to find the client structure */
2455 for (client = host->FirstClient; client; client = client->next) {
2456 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2457 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2459 goto retryfirstclient;
2464 ObtainWriteLock(&client->lock);
2465 client->refCount = 1;
2466 client->host = host;
2467 #if FS_STATS_DETAILED
2468 client->InSameNetwork = host->InSameNetwork;
2469 #endif /* FS_STATS_DETAILED */
2470 client->ViceId = viceid;
2471 client->expTime = expTime; /* rx only */
2472 client->authClass = authClass; /* rx only */
2473 client->sid = rxr_CidOf(tcon);
2474 client->VenusEpoch = rxr_GetEpoch(tcon);
2475 client->CPS.prlist_val = NULL;
2476 client->CPS.prlist_len = 0;
2480 client->prfail = fail;
2482 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2483 client->CPS.prlist_len = 0;
2484 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2485 free(client->CPS.prlist_val);
2486 client->CPS.prlist_val = NULL;
2487 client->ViceId = viceid;
2488 client->expTime = expTime;
2490 if (viceid == ANONYMOUSID) {
2491 client->CPS.prlist_len = AnonCPS.prlist_len;
2492 client->CPS.prlist_val = AnonCPS.prlist_val;
2495 code = hpr_GetCPS(viceid, &client->CPS);
2500 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2501 code, viceid, client->host,
2502 afs_inet_ntoa_r(client->host->host,hoststr),
2503 ntohs(client->host->port)));
2505 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2506 * all protection servers and reevaluates things if no
2507 * sync server or quorum is found we could still end up
2508 * with one of these errors. In such case we would like to
2509 * reevaluate the rpc call to find if there's cps for this
2510 * guy. We treat other errors (except network failures
2511 * ones - i.e. code < 0) as an indication that there is no
2512 * CPS for this host. Ideally we could like to deal this
2513 * problem the other way around (i.e. if code == NOCPS
2514 * ignore else retry next time) but the problem is that
2515 * there're other errors (i.e. EPERM) for which we don't
2516 * want to retry and we don't know the whole code list!
2518 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2522 /* the disabling of system:administrators is so iffy and has so many
2523 * possible failure modes that we will disable it again */
2524 /* Turn off System:Administrator for safety
2525 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2526 * osi_Assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2529 /* Now, tcon may already be set to a rock, since we blocked with no host
2530 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2531 * required). So, before setting the RPC's rock, we should disconnect
2532 * the RPC from the other client structure's rock.
2534 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2535 if (oldClient && oldClient != client && oldClient->sid == rxr_CidOf(tcon)
2536 && oldClient->VenusEpoch == rxr_GetEpoch(tcon)) {
2538 if (!oldClient->deleted) {
2539 /* if we didn't create it, it's not ours to put back */
2541 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2542 "conn %p (host %s:%d) had client %p(%x)\n",
2543 client, client->sid, tcon,
2544 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2545 ntohs(rxr_PortOf(tcon)),
2546 oldClient, oldClient->sid));
2547 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2548 free(client->CPS.prlist_val);
2549 client->CPS.prlist_val = NULL;
2550 client->CPS.prlist_len = 0;
2552 /* We should perhaps check for 0 here */
2554 ReleaseWriteLock(&client->lock);
2559 oldClient->refCount++;
2561 ObtainWriteLock(&oldClient->lock);
2565 ViceLog(0, ("FindClient: deleted client %p(%x) already had "
2566 "conn %p (host %s:%d), stolen by client %p(%x)\n",
2567 oldClient, oldClient->sid, tcon,
2568 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2569 ntohs(rxr_PortOf(tcon)),
2570 client, client->sid));
2571 /* rx_SetSpecific will be done immediately below */
2574 /* Avoid chaining in more than once. */
2578 if (host->hostFlags & HOSTDELETED) {
2583 client->host = NULL;
2585 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2586 free(client->CPS.prlist_val);
2587 client->CPS.prlist_val = NULL;
2588 client->CPS.prlist_len = 0;
2591 ReleaseWriteLock(&client->lock);
2596 client->next = host->FirstClient;
2597 host->FirstClient = client;
2599 CurrentConnections++; /* increment number of connections */
2601 rx_SetSpecific(tcon, rxcon_client_key, client);
2602 ReleaseWriteLock(&client->lock);
2606 } /*h_FindClient_r */
2609 h_ReleaseClient_r(struct client *client)
2611 osi_Assert(client->refCount > 0);
2618 * Sigh: this one is used to get the client AGAIN within the individual
2619 * server routines. This does not bother h_Holding the host, since
2620 * this is assumed already have been done by the server main loop.
2621 * It does check tokens, since only the server routines can return the
2622 * VICETOKENDEAD error code
2625 GetClient(struct rx_connection *tcon, struct client **cp)
2627 struct client *client;
2632 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2633 if (client == NULL) {
2635 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2636 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2637 ntohs(rxr_PortOf(tcon))));
2641 if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2643 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2644 tcon, rxr_CidOf(tcon), client->sid));
2648 if (client && client->LastCall > client->expTime && client->expTime) {
2650 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2651 afs_inet_ntoa_r(client->host->host, hoststr),
2652 ntohs(client->host->port), client->expTime));
2654 return VICETOKENDEAD;
2664 PutClient(struct client **cp)
2670 h_ReleaseClient_r(*cp);
2677 /* Client user name for short term use. Note that this is NOT inexpensive */
2679 h_UserName(struct client *client)
2681 static char User[PR_MAXNAMELEN + 1];
2685 lids.idlist_len = 1;
2686 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2687 if (!lids.idlist_val) {
2688 ViceLogThenPanic(0, ("Failed malloc in h_UserName\n"));
2690 lnames.namelist_len = 0;
2691 lnames.namelist_val = (prname *) 0;
2692 lids.idlist_val[0] = client->ViceId;
2693 if (hpr_IdToName(&lids, &lnames)) {
2694 /* We need to free id we alloced above! */
2695 free(lids.idlist_val);
2696 return "*UNKNOWN USER NAME*";
2698 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2699 free(lids.idlist_val);
2700 free(lnames.namelist_val);
2709 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2710 CEs, CEBlocks, HTs, HTBlocks));
2716 h_PrintClient(struct host *host, int flags, void *rock)
2718 StreamHandle_t *file = (StreamHandle_t *)rock;
2719 struct client *client;
2724 time_t LastCall, expTime;
2728 LastCall = host->LastCall;
2729 if (host->hostFlags & HOSTDELETED) {
2733 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %T %Y",
2734 localtime_r(&LastCall, &tm));
2735 snprintf(tmpStr, sizeof tmpStr, "Host %s:%d down = %d, LastCall %s\n",
2736 afs_inet_ntoa_r(host->host, hoststr),
2737 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2739 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2740 for (client = host->FirstClient; client; client = client->next) {
2741 if (!client->deleted) {
2742 expTime = client->expTime;
2743 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %T %Y",
2744 localtime_r(&expTime, &tm));
2745 snprintf(tmpStr, sizeof tmpStr,
2746 " user id=%d, name=%s, sl=%s till %s\n",
2747 client->ViceId, h_UserName(client),
2748 client->authClass ? "Authenticated"
2749 : "Not authenticated",
2750 client->authClass ? tbuffer : "No Limit");
2751 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2752 snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2753 client->CPS.prlist_len);
2754 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2755 if (client->CPS.prlist_val) {
2756 for (i = 0; i < client->CPS.prlist_len; i++) {
2757 snprintf(tmpStr, sizeof tmpStr, " %d",
2758 client->CPS.prlist_val[i]);
2759 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2762 sprintf(tmpStr, "]\n");
2763 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2769 } /*h_PrintClient */
2774 * Print a list of clients, with last security level and token value seen,
2778 h_PrintClients(void)
2785 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2789 ("Couldn't create client dump file %s\n",
2790 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2793 now = FT_ApproxTime();
2794 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %T %Y",
2795 localtime_r(&now, &tm));
2796 snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n\n",
2798 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2799 h_Enumerate(h_PrintClient, (char *)file);
2800 STREAM_REALLYCLOSE(file);
2801 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2808 h_DumpHost(struct host *host, int flags, void *rock)
2810 StreamHandle_t *file = (StreamHandle_t *)rock;
2817 snprintf(tmpStr, sizeof tmpStr,
2818 "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u "
2819 "down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u "
2821 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
2822 host->index, host->cblist, CheckLock(&host->lock),
2823 host->LastCall, host->ActiveCall, (host->hostFlags & VENUSDOWN),
2824 host->hostFlags & HOSTDELETED, host->Console,
2825 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2827 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2828 if (host->hcps.prlist_val)
2829 for (i = 0; i < host->hcps.prlist_len; i++) {
2830 snprintf(tmpStr, sizeof tmpStr, " %d", host->hcps.prlist_val[i]);
2831 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2833 sprintf(tmpStr, "] [");
2834 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2835 if (host->interface)
2836 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2838 sprintf(tmpStr, " %s:%d",
2839 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2840 ntohs(host->interface->interface[i].port));
2841 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2843 sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2844 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2856 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2863 ("Couldn't create host dump file %s\n",
2864 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2867 now = FT_ApproxTime();
2868 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %T %Y",
2869 localtime_r(&now, &tm));
2870 snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n\n", tbuffer);
2871 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2872 h_Enumerate(h_DumpHost, (char *)file);
2873 STREAM_REALLYCLOSE(file);
2874 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2878 #ifdef AFS_DEMAND_ATTACH_FS
2881 * host state serialization
2883 static int h_stateFillHeader(struct host_state_header * hdr);
2884 static int h_stateCheckHeader(struct host_state_header * hdr);
2885 static int h_stateAllocMap(struct fs_dump_state * state);
2886 static int h_stateSaveHost(struct host * host, int flags, void *rock);
2887 static int h_stateRestoreHost(struct fs_dump_state * state);
2888 static int h_stateRestoreIndex(struct host * h, int flags, void *rock);
2889 static int h_stateVerifyHost(struct host * h, int flags, void *rock);
2890 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
2891 afs_uint32 addr, afs_uint16 port, int valid);
2892 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2893 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2894 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2897 /* this procedure saves all host state to disk for fast startup */
2899 h_stateSave(struct fs_dump_state * state)
2901 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2904 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2906 /* invalidate host state header */
2907 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2909 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2910 sizeof(struct host_state_header))) {
2915 fs_stateIncEOF(state, sizeof(struct host_state_header));
2917 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2922 h_stateFillHeader(state->h_hdr);
2924 /* write the real header to disk */
2925 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2926 sizeof(struct host_state_header));
2933 * host state serialization
2935 * this procedure restores all host state from a disk for fast startup
2938 h_stateRestore(struct fs_dump_state * state)
2942 /* seek to the right position and read in the host state header */
2943 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2944 sizeof(struct host_state_header))) {
2949 /* check the validity of the header */
2950 if (h_stateCheckHeader(state->h_hdr)) {
2955 records = state->h_hdr->records;
2957 if (h_stateAllocMap(state)) {
2962 /* iterate over records restoring host state */
2963 for (i=0; i < records; i++) {
2964 if (h_stateRestoreHost(state) != 0) {
2975 h_stateRestoreIndices(struct fs_dump_state * state)
2977 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
2982 h_stateRestoreIndex(struct host * h, int flags, void *rock)
2984 struct fs_dump_state *state = (struct fs_dump_state *)rock;
2985 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
2986 return H_ENUMERATE_BAIL(flags);
2992 h_stateVerify(struct fs_dump_state * state)
2994 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
2999 h_stateVerifyHost(struct host * h, int flags, void* rock)
3001 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3005 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3006 return H_ENUMERATE_BAIL(flags);
3010 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
3011 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
3012 h->interface->interface[i].port,
3013 h->interface->interface[i].valid)) {
3017 if (h_stateVerifyUuidHash(state, h)) {
3020 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
3024 if (cb_stateVerifyHCBList(state, h)) {
3032 * verify a host is either in, or absent from, the addr hash table.
3034 * @param[in] state fs dump state
3035 * @param[in] h host we're dealing with
3036 * @param[in] addr addr to look for (NBO)
3037 * @param[in] port port to look for (NBO)
3038 * @param[in] valid 1 if we're verifying that the specified addr and port
3039 * in the hash table point to the specified host. 0 if we're
3040 * verifying that the specified addr and port do NOT point
3041 * to the specified host
3043 * @return operation status
3044 * @retval 1 failed to verify, bail out
3045 * @retval 0 verified successfully, all is well
3048 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3049 afs_uint32 addr, afs_uint16 port, int valid)
3051 int ret = 0, found = 0;
3052 struct host *host = NULL;
3053 struct h_AddrHashChain *chain;
3054 int index = h_HashIndex(addr);
3058 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3059 host = chain->hostPtr;
3061 afs_inet_ntoa_r(addr, tmp);
3062 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3066 if ((chain->addr == addr) && (chain->port == port)) {
3069 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3070 "points to different host struct (%d, %d)\n",
3071 h->index, host->index));
3072 state->flags.warnings_generated = 1;
3076 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3077 "marked invalid, but points to the containing "
3078 "host\n", afs_inet_ntoa_r(addr, tmp),
3079 (unsigned)htons(port)));
3087 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3088 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3089 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3096 if (!found && valid) {
3097 afs_inet_ntoa_r(addr, tmp);
3098 if (state->mode == FS_STATE_LOAD_MODE) {
3099 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3100 tmp, (unsigned)htons(port)));
3104 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3105 tmp, (unsigned)htons(port)));
3106 state->flags.warnings_generated = 1;
3115 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3117 int ret = 0, found = 0;
3118 struct host *host = NULL;
3119 struct h_UuidHashChain *chain;
3120 afsUUID * uuidp = &h->interface->uuid;
3121 int index = h_UuidHashIndex(uuidp);
3125 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3126 host = chain->hostPtr;
3128 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3129 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3133 if (host->interface &&
3134 afs_uuid_equal(&host->interface->uuid, uuidp)) {
3136 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3137 h->index, host->index));
3138 state->flags.warnings_generated = 1;
3143 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3144 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3145 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3153 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3154 if (state->mode == FS_STATE_LOAD_MODE) {
3155 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3159 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3160 state->flags.warnings_generated = 1;
3168 /* create the host state header structure */
3170 h_stateFillHeader(struct host_state_header * hdr)
3172 hdr->stamp.magic = HOST_STATE_MAGIC;
3173 hdr->stamp.version = HOST_STATE_VERSION;
3177 /* check the contents of the host state header structure */
3179 h_stateCheckHeader(struct host_state_header * hdr)
3183 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3184 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3187 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3188 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3194 /* allocate the host id mapping table */
3196 h_stateAllocMap(struct fs_dump_state * state)
3198 state->h_map.len = state->h_hdr->index_max + 1;
3199 state->h_map.entries = (struct idx_map_entry_t *)
3200 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3201 return (state->h_map.entries != NULL) ? 0 : 1;
3204 /* function called by h_Enumerate to save a host to disk */
3206 h_stateSaveHost(struct host * host, int flags, void* rock)
3208 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3209 int if_len=0, hcps_len=0;
3210 struct hostDiskEntry hdsk;
3211 struct host_state_entry_header hdr;
3212 struct Interface * ifp = NULL;
3213 afs_int32 * hcps = NULL;
3214 struct iovec iov[4];
3217 memset(&hdr, 0, sizeof(hdr));
3219 if (state->h_hdr->index_max < host->index) {
3220 state->h_hdr->index_max = host->index;
3223 h_hostToDiskEntry_r(host, &hdsk);
3224 if (host->interface) {
3225 if_len = sizeof(struct Interface) +
3226 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3227 ifp = (struct Interface *) malloc(if_len);
3228 osi_Assert(ifp != NULL);
3229 memcpy(ifp, host->interface, if_len);
3230 hdr.interfaces = host->interface->numberOfInterfaces;
3231 iov[iovcnt].iov_base = (char *) ifp;
3232 iov[iovcnt].iov_len = if_len;
3235 if (host->hcps.prlist_val) {
3236 hdr.hcps = host->hcps.prlist_len;
3237 hcps_len = hdr.hcps * sizeof(afs_int32);
3238 hcps = (afs_int32 *) malloc(hcps_len);
3239 osi_Assert(hcps != NULL);
3240 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3241 iov[iovcnt].iov_base = (char *) hcps;
3242 iov[iovcnt].iov_len = hcps_len;
3246 if (hdsk.index > state->h_hdr->index_max)
3247 state->h_hdr->index_max = hdsk.index;
3249 hdr.len = sizeof(struct host_state_entry_header) +
3250 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3251 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3253 iov[0].iov_base = (char *) &hdr;
3254 iov[0].iov_len = sizeof(hdr);
3255 iov[1].iov_base = (char *) &hdsk;
3256 iov[1].iov_len = sizeof(struct hostDiskEntry);
3258 if (fs_stateWriteV(state, iov, iovcnt)) {
3259 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3263 fs_stateIncEOF(state, hdr.len);
3265 state->h_hdr->records++;
3272 return H_ENUMERATE_BAIL(flags);
3277 /* restores a host from disk */
3279 h_stateRestoreHost(struct fs_dump_state * state)
3281 int ifp_len=0, hcps_len=0, bail=0;
3282 struct host_state_entry_header hdr;
3283 struct hostDiskEntry hdsk;
3284 struct host *host = NULL;
3285 struct Interface *ifp = NULL;
3286 afs_int32 * hcps = NULL;
3287 struct iovec iov[3];
3290 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3291 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3297 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3298 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3304 iov[0].iov_base = (char *) &hdsk;
3305 iov[0].iov_len = sizeof(struct hostDiskEntry);
3307 if (hdr.interfaces) {
3308 ifp_len = sizeof(struct Interface) +
3309 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3310 ifp = (struct Interface *) malloc(ifp_len);
3311 osi_Assert(ifp != NULL);
3312 iov[iovcnt].iov_base = (char *) ifp;
3313 iov[iovcnt].iov_len = ifp_len;
3317 hcps_len = hdr.hcps * sizeof(afs_int32);
3318 hcps = (afs_int32 *) malloc(hcps_len);
3319 osi_Assert(hcps != NULL);
3320 iov[iovcnt].iov_base = (char *) hcps;
3321 iov[iovcnt].iov_len = hcps_len;
3325 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3326 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3331 if (fs_stateReadV(state, iov, iovcnt)) {
3332 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3337 if (!hdr.hcps && hdsk.hcps_valid) {
3338 /* valid, zero-length host cps ; does this ever happen? */
3339 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3340 osi_Assert(hcps != NULL);
3344 osi_Assert(host != NULL);
3347 host->interface = ifp;
3350 host->hcps.prlist_val = hcps;
3351 host->hcps.prlist_len = hdr.hcps;
3354 h_diskEntryToHost_r(&hdsk, host);
3355 h_SetupCallbackConn_r(host);
3357 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3360 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3361 if (ifp->interface[i].valid &&
3362 !(ifp->interface[i].addr == host->host &&
3363 ifp->interface[i].port == host->port)) {
3364 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3365 ifp->interface[i].port,
3369 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3371 h_InsertList_r(host);
3373 /* setup host id map entry */
3374 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3375 state->h_map.entries[hdsk.index].new_idx = host->index;
3387 /* serialize a host structure to disk */
3389 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3391 out->host = in->host;
3392 out->port = in->port;
3393 out->hostFlags = in->hostFlags;
3394 out->Console = in->Console;
3395 out->hcpsfailed = in->hcpsfailed;
3396 out->LastCall = in->LastCall;
3397 out->ActiveCall = in->ActiveCall;
3398 out->cpsCall = in->cpsCall;
3399 out->cblist = in->cblist;
3400 #ifdef FS_STATS_DETAILED
3401 out->InSameNetwork = in->InSameNetwork;
3404 /* special fields we save, but are not memcpy'd back on restore */
3405 out->index = in->index;
3406 out->hcps_len = in->hcps.prlist_len;
3407 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3410 /* restore a host structure from disk */
3412 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3414 out->host = in->host;
3415 out->port = in->port;
3416 out->hostFlags = in->hostFlags;
3417 out->Console = in->Console;
3418 out->hcpsfailed = in->hcpsfailed;
3419 out->LastCall = in->LastCall;
3420 out->ActiveCall = in->ActiveCall;
3421 out->cpsCall = in->cpsCall;
3422 out->cblist = in->cblist;
3423 #ifdef FS_STATS_DETAILED
3424 out->InSameNetwork = in->InSameNetwork;
3428 /* index translation routines */
3430 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3434 /* hosts use a zero-based index, so old==0 is valid */
3436 if (old >= state->h_map.len) {
3437 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3439 } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
3440 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3443 *new = state->h_map.entries[old].new_idx;
3448 #endif /* AFS_DEMAND_ATTACH_FS */
3452 * This counts the number of workstations, the number of active workstations,
3453 * and the number of workstations declared "down" (i.e. not heard from
3454 * recently). An active workstation has received a call since the cutoff
3455 * time argument passed.
3458 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3461 int num = 0, active = 0, del = 0;
3465 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3466 if (!(host->hostFlags & HOSTDELETED)) {
3468 if (host->ActiveCall > cutofftime)
3470 if (host->hostFlags & VENUSDOWN)
3474 if (count != hostCount) {
3475 ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3476 } else if (host != NULL) {
3477 ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3478 ShutDownAndCore(PANIC);
3488 } /*h_GetWorkStats */
3491 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp,
3492 afs_int32 cutofftime)
3494 int num, active, del;
3495 h_GetWorkStats(&num, &active, &del, cutofftime);
3504 /*------------------------------------------------------------------------
3505 * PRIVATE h_ClassifyAddress
3508 * Given a target IP address and a candidate IP address (both
3509 * in host byte order), classify the candidate into one of three
3510 * buckets in relation to the target by bumping the counters passed
3514 * a_targetAddr : Target address.
3515 * a_candAddr : Candidate address.
3516 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3517 * addresses are either in the same network
3518 * or the same subnet.
3519 * a_diffSubnetP : ...when the candidate is in a different
3521 * a_diffNetworkP : ...when the candidate is in a different
3528 * The target and candidate addresses are both in host byte
3529 * order, NOT network byte order, when passed in.
3533 *------------------------------------------------------------------------*/
3536 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3537 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3538 afs_int32 * a_diffNetworkP)
3539 { /*h_ClassifyAddress */
3541 afs_uint32 targetNet;
3542 afs_uint32 targetSubnet;
3544 afs_uint32 candSubnet;
3547 * Put bad values into the subnet info to start with.
3549 targetSubnet = (afs_uint32) 0;
3550 candSubnet = (afs_uint32) 0;
3553 * Pull out the network and subnetwork numbers from the target
3554 * and candidate addresses. We can short-circuit this whole
3555 * affair if the target and candidate addresses are not of the
3558 if (IN_CLASSA(a_targetAddr)) {
3559 if (!(IN_CLASSA(a_candAddr))) {
3560 (*a_diffNetworkP)++;
3563 targetNet = a_targetAddr & IN_CLASSA_NET;
3564 candNet = a_candAddr & IN_CLASSA_NET;
3565 if (IN_SUBNETA(a_targetAddr))
3566 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3567 if (IN_SUBNETA(a_candAddr))
3568 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3569 } else if (IN_CLASSB(a_targetAddr)) {
3570 if (!(IN_CLASSB(a_candAddr))) {
3571 (*a_diffNetworkP)++;
3574 targetNet = a_targetAddr & IN_CLASSB_NET;
3575 candNet = a_candAddr & IN_CLASSB_NET;
3576 if (IN_SUBNETB(a_targetAddr))
3577 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3578 if (IN_SUBNETB(a_candAddr))
3579 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3580 } /*Class B target */
3581 else if (IN_CLASSC(a_targetAddr)) {
3582 if (!(IN_CLASSC(a_candAddr))) {
3583 (*a_diffNetworkP)++;
3586 targetNet = a_targetAddr & IN_CLASSC_NET;
3587 candNet = a_candAddr & IN_CLASSC_NET;
3590 * Note that class C addresses can't have subnets,
3591 * so we leave the defaults untouched.
3593 } /*Class C target */
3595 targetNet = a_targetAddr;
3596 candNet = a_candAddr;
3597 } /*Class D address */
3600 * Now, simply compare the extracted net and subnet values for
3601 * the two addresses (which at this point are known to be of the
3604 if (targetNet == candNet) {
3605 if (targetSubnet == candSubnet)
3606 (*a_sameNetOrSubnetP)++;
3610 (*a_diffNetworkP)++;
3612 } /*h_ClassifyAddress */
3615 /*------------------------------------------------------------------------
3616 * EXPORTED h_GetHostNetStats
3619 * Iterate through the host table, and classify each (non-deleted)
3620 * host entry into ``proximity'' categories (same net or subnet,
3621 * different subnet, different network).
3624 * a_numHostsP : Set to total number of (non-deleted) hosts.
3625 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3626 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3627 * a_diffNetworkP : Set to # hosts on diff network as server.
3633 * We only count non-deleted hosts. The storage pointed to by our
3634 * parameters is zeroed upon entry.
3638 *------------------------------------------------------------------------*/
3641 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3642 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3643 { /*h_GetHostNetStats */
3645 struct host *hostP; /*Ptr to current host entry */
3646 afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3650 * Clear out the storage pointed to by our parameters.
3652 *a_numHostsP = (afs_int32) 0;
3653 *a_sameNetOrSubnetP = (afs_int32) 0;
3654 *a_diffSubnetP = (afs_int32) 0;
3655 *a_diffNetworkP = (afs_int32) 0;
3658 for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3659 if (!(hostP->hostFlags & HOSTDELETED)) {
3661 * Bump the number of undeleted host entries found.
3662 * In classifying the current entry's address, make
3663 * sure to first convert to host byte order.
3666 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3667 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3668 a_sameNetOrSubnetP, a_diffSubnetP,
3670 } /*Only look at non-deleted hosts */
3671 } /*For each host record hashed to this index */
3672 if (count != hostCount) {
3673 ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3674 } else if (hostP != NULL) {
3675 ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3676 ShutDownAndCore(PANIC);
3679 } /*h_GetHostNetStats */
3681 static afs_uint32 checktime;
3682 static afs_uint32 clientdeletetime;
3683 static struct AFSFid zerofid;
3687 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3688 * Since it can serialize them, and pile up, it should be a separate LWP
3689 * from other events.
3693 CheckHost(struct host *host, int flags, void *rock)
3695 struct client *client;
3696 struct rx_connection *cb_conn = NULL;
3699 #ifdef AFS_DEMAND_ATTACH_FS
3700 /* kill the checkhost lwp ASAP during shutdown */
3702 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3704 return H_ENUMERATE_BAIL(flags);
3709 /* Host is held by h_Enumerate */
3711 for (client = host->FirstClient; client; client = client->next) {
3712 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3713 client->deleted = 1;
3714 host->hostFlags |= CLIENTDELETED;
3717 if (host->LastCall < checktime) {
3719 if (!(host->hostFlags & HOSTDELETED)) {
3720 host->hostFlags |= HWHO_INPROGRESS;
3721 cb_conn = host->callback_rxcon;
3722 rx_GetConnection(cb_conn);
3723 if (host->LastCall < clientdeletetime) {
3724 host->hostFlags |= HOSTDELETED;
3725 if (!(host->hostFlags & VENUSDOWN)) {
3726 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3727 if (host->interface) {
3730 RXAFSCB_InitCallBackState3(cb_conn,
3736 RXAFSCB_InitCallBackState(cb_conn);
3739 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3742 (void)afs_inet_ntoa_r(host->host, hoststr);
3744 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3745 hoststr, ntohs(host->port)));
3746 host->hostFlags |= VENUSDOWN;
3748 /* Note: it's safe to delete hosts even if they have call
3749 * back state, because break delayed callbacks (called when a
3750 * message is received from the workstation) will always send a
3751 * break all call backs to the workstation if there is no
3756 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3758 (void)afs_inet_ntoa_r(host->host, hoststr);
3759 if (host->interface) {
3760 afsUUID uuid = host->interface->uuid;
3762 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3765 if (MultiProbeAlternateAddress_r(host)) {
3766 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3767 hoststr, ntohs(host->port), code));
3768 host->hostFlags |= VENUSDOWN;
3773 code = RXAFSCB_Probe(cb_conn);
3777 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3778 hoststr, ntohs(host->port), code));
3779 host->hostFlags |= VENUSDOWN;
3785 rx_PutConnection(cb_conn);
3788 host->hostFlags &= ~HWHO_INPROGRESS;
3799 CheckHost_r(struct host *host, int flags, void *dummy)
3801 struct client *client;
3802 struct rx_connection *cb_conn = NULL;
3805 #ifdef AFS_DEMAND_ATTACH_FS
3806 /* kill the checkhost lwp ASAP during shutdown */
3808 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3810 return H_ENUMERATE_BAIL(flags);
3815 /* Host is held by h_Enumerate_r */
3816 for (client = host->FirstClient; client; client = client->next) {
3817 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3818 client->deleted = 1;
3819 host->hostFlags |= CLIENTDELETED;
3822 if (host->LastCall < checktime) {
3824 if (!(host->hostFlags & HOSTDELETED)) {
3825 host->hostFlags |= HWHO_INPROGRESS;
3826 cb_conn = host->callback_rxcon;
3827 rx_GetConnection(cb_conn);
3828 if (host->LastCall < clientdeletetime) {
3829 host->hostFlags |= HOSTDELETED;
3830 if (!(host->hostFlags & VENUSDOWN)) {
3831 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3832 if (host->interface) {
3835 RXAFSCB_InitCallBackState3(cb_conn,
3841 RXAFSCB_InitCallBackState(cb_conn);
3844 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3847 (void)afs_inet_ntoa_r(host->host, hoststr);
3849 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3850 hoststr, ntohs(host->port)));
3851 host->hostFlags |= VENUSDOWN;
3853 /* Note: it's safe to delete hosts even if they have call
3854 * back state, because break delayed callbacks (called when a
3855 * message is received from the workstation) will always send a
3856 * break all call backs to the workstation if there is no
3861 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3863 (void)afs_inet_ntoa_r(host->host, hoststr);
3864 if (host->interface) {
3865 afsUUID uuid = host->interface->uuid;
3867 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3870 if (MultiProbeAlternateAddress_r(host)) {
3871 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3872 hoststr, ntohs(host->port), code));
3873 host->hostFlags |= VENUSDOWN;
3878 code = RXAFSCB_Probe(cb_conn);
3882 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3883 hoststr, ntohs(host->port), code));
3884 host->hostFlags |= VENUSDOWN;
3890 rx_PutConnection(cb_conn);
3893 host->hostFlags &= ~HWHO_INPROGRESS;
3903 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3904 * don't respond to a probe. Note that VenusDown can only be cleared if
3905 * a message is received from the host (see ServerLWP in file.c).
3906 * Delete hosts that have not had any calls in 1 hour, clients that
3907 * have not had any calls in 15 minutes.
3909 * This routine is called roughly every 5 minutes.
3914 afs_uint32 now = FT_ApproxTime();
3916 memset(&zerofid, 0, sizeof(zerofid));
3918 * Send a probe to the workstation if it hasn't been heard from in
3921 checktime = now - 15 * 60;
3922 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3925 h_Enumerate_r(CheckHost_r, hostList, NULL);
3930 * This is called with host locked and held. At this point, the
3931 * hostAddrHashTable has an entry for the primary addr/port inserted
3932 * by h_Alloc_r(). No other interfaces should be considered valid.
3934 * The addresses in the interfaceAddr list are in host byte order.
3937 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3944 struct Interface *interface;
3947 afs_uint16 port7001 = htons(7001);
3952 number = interf->numberOfInterfaces;
3953 myAddr = host->host; /* current interface address */
3954 myPort = host->port; /* current port */
3957 ("initInterfaceAddr : host %s:%d numAddr %d\n",
3958 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3960 /* validation checks */
3961 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3963 ("Invalid number of alternate addresses is %d\n", number));
3968 * The client's notion of its own IP addresses is not reliable.
3970 * 1. The client list might contain private address ranges which
3971 * are likely to be re-used by many clients allocated addresses
3974 * 2. The client list will not include any public addresses that
3975 * are hidden by a NAT.
3977 * 3. Private address ranges that are exposed to the server will
3978 * be obtained from the rx connections that use them.
3980 * 4. Lists provided by the client are not necessarily truthful.
3981 * Many existing clients (UNIX) do not refresh the IP address
3982 * list as the actual assigned addresses change. The end result
3983 * is that they report the initial address list for the lifetime
3984 * of the process. In other words, a client can report addresses
3985 * that they are in fact not using. Adding these addresses to
3986 * the host interface list without verification is not only
3987 * pointless, it is downright dangerous.
3989 * We therefore do not add alternate addresses to the addr hash table.
3990 * We only use them for multi-rx callback breaks.
3994 * Convert IP addresses to network byte order, and remove
3995 * duplicate IP addresses from the interface list, and
3996 * determine whether or not the incoming addr/port is
3997 * listed. Note that if the address matches it is not
3998 * truly a match because the port number for the entries
3999 * in the interface list are port 7001 and the port number
4000 * for this connection might not be 7001.
4002 for (i = 0, count = 0, found = 0; i < number; i++) {
4003 interf->addr_in[i] = htonl(interf->addr_in[i]);
4004 for (j = 0; j < count; j++) {
4005 if (interf->addr_in[j] == interf->addr_in[i])
4009 interf->addr_in[count] = interf->addr_in[i];
4010 if (interf->addr_in[count] == myAddr &&
4018 * Allocate and initialize an interface structure for this host.
4021 interface = (struct Interface *)
4022 malloc(sizeof(struct Interface) +
4023 (sizeof(struct AddrPort) * (count - 1)));
4025 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
4027 interface->numberOfInterfaces = count;
4029 interface = (struct Interface *)
4030 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
4032 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4034 interface->numberOfInterfaces = count + 1;
4035 interface->interface[count].addr = myAddr;
4036 interface->interface[count].port = myPort;
4037 interface->interface[count].valid = 1;
4040 for (i = 0; i < count; i++) {
4042 interface->interface[i].addr = interf->addr_in[i];
4043 /* We store the port as 7001 because the addresses reported by
4044 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4045 * are coming from fully connected hosts (no NAT/PATs)
4047 interface->interface[i].port = port7001;
4048 interface->interface[i].valid =
4049 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4052 interface->uuid = interf->uuid;
4054 osi_Assert(!host->interface);
4055 host->interface = interface;
4057 if (LogLevel >= 125) {
4058 afsUUID_to_string(&interface->uuid, uuidstr, 127);
4060 ViceLog(125, ("--- uuid %s\n", uuidstr));
4061 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
4062 ViceLog(125, ("--- alt address %s:%d\n",
4063 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4064 ntohs(host->interface->interface[i].port)));
4071 /* deleted a HashChain structure for this address and host */
4072 /* returns 1 on success */
4074 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4078 struct h_AddrHashChain **hp, *th;
4080 if (addr == 0 && port == 0)
4083 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4085 osi_Assert(th->hostPtr);
4086 if (th->hostPtr == host && th->addr == addr && th->port == port) {
4087 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4088 host, afs_inet_ntoa_r(host->host, hoststr),
4089 ntohs(host->port)));
4096 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4097 host, afs_inet_ntoa_r(host->host, hoststr),
4098 ntohs(host->port)));
4104 ** prints out all alternate interface address for the host. The 'level'
4105 ** parameter indicates what level of debugging sets this output
4108 printInterfaceAddr(struct host *host, int level)
4113 if (host->interface) {
4114 /* check alternate addresses */
4115 number = host->interface->numberOfInterfaces;
4117 ViceLog(level, ("no-addresses "));
4119 for (i = 0; i < number; i++)
4120 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4121 ntohs(host->interface->interface[i].port)));
4124 ViceLog(level, ("\n"));