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>
20 #ifdef HAVE_SYS_FILE_H
24 #include <afs/afsint.h>
25 #define FSINT_COMMON_XG
26 #include <afs/afscbint.h>
27 #include <afs/rxgen_consts.h>
29 #include <afs/errors.h>
30 #include <afs/ihandle.h>
32 #include <afs/ptclient.h>
33 #include <afs/ptuser.h>
34 #include <afs/prs_fs.h>
36 #include <afs/afsutil.h>
37 #include <afs/com_err.h>
39 #include <afs/cellconfig.h>
40 #include "viced_prototypes.h"
44 #ifdef AFS_DEMAND_ATTACH_FS
45 #include "../util/afsutil_prototypes.h"
46 #include "serialize_state.h"
47 #endif /* AFS_DEMAND_ATTACH_FS */
49 pthread_mutex_t host_glock_mutex;
52 extern int CurrentConnections;
54 extern int AnonymousID;
55 extern prlist AnonCPS;
57 extern struct afsconf_dir *confDir; /* config dir object */
58 extern int lwps; /* the max number of server threads */
59 extern afsUUID FS_HostUUID;
60 extern char *FS_configPath;
63 int CEs = 0; /* active clients */
64 int CEBlocks = 0; /* number of blocks of CEs */
65 struct client *CEFree = 0; /* first free client */
66 struct host *hostList = 0; /* linked list of all hosts */
67 int hostCount = 0; /* number of hosts in hostList */
71 static struct rx_securityClass *sc = NULL;
72 static int h_quota_limit;
74 /* arguments for PerHost_EnumerateClient enumeration */
75 struct enumclient_args {
77 int (*proc)(struct client *client, void *rock);
81 static void h_SetupCallbackConn_r(struct host * host);
82 static int h_threadquota(int);
83 static int initInterfaceAddr_r(struct host *, struct interfaceAddr *);
85 #define CESPERBLOCK 73
86 struct CEBlock { /* block of CESPERBLOCK file entries */
87 struct client entry[CESPERBLOCK];
90 void h_TossStuff_r(struct host *host);
93 * Make sure the subnet macros have been defined.
96 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
99 #ifndef IN_CLASSA_SUBNET
100 #define IN_CLASSA_SUBNET 0xffff0000
104 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
107 #ifndef IN_CLASSB_SUBNET
108 #define IN_CLASSB_SUBNET 0xffffff00
112 /* get a new block of CEs and chain it on CEFree */
116 struct CEBlock *block;
119 block = malloc(sizeof(struct CEBlock));
121 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
122 ShutDownAndCore(PANIC);
125 for (i = 0; i < (CESPERBLOCK - 1); i++) {
126 Lock_Init(&block->entry[i].lock);
127 block->entry[i].next = &(block->entry[i + 1]);
129 block->entry[CESPERBLOCK - 1].next = 0;
130 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
131 CEFree = (struct client *)block;
137 /* get the next available CE */
138 static struct client *
141 struct client *entry;
146 ViceLog(0, ("CEFree NULL in GetCE\n"));
147 ShutDownAndCore(PANIC);
151 CEFree = entry->next;
153 memset(entry, 0, CLIENT_TO_ZERO(entry));
159 /* return an entry to the free list */
161 FreeCE(struct client *entry)
163 entry->VenusEpoch = 0;
165 entry->next = CEFree;
172 * The HTs and HTBlocks variables were formerly static, but they are
173 * now referenced elsewhere in the FileServer.
175 int HTs = 0; /* active file entries */
176 int HTBlocks = 0; /* number of blocks of HTs */
177 static struct host *HTFree = 0; /* first free file entry */
180 * Hash tables of host pointers. We need two tables, one
181 * to map IP addresses onto host pointers, and another
182 * to map host UUIDs onto host pointers.
184 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
185 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
186 #define h_HashIndex(hostip) (ntohl(hostip) & (h_HASHENTRIES-1))
187 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
189 struct HTBlock { /* block of HTSPERBLOCK file entries */
190 struct host entry[h_HTSPERBLOCK];
194 /* get a new block of HTs and chain it on HTFree */
198 struct HTBlock *block;
200 static int index = 0;
202 if (HTBlocks == h_MAXHOSTTABLES) {
203 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
207 block = malloc(sizeof(struct HTBlock));
209 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
210 ShutDownAndCore(PANIC);
212 for (i = 0; i < (h_HTSPERBLOCK); i++)
213 opr_cv_init(&block->entry[i].cond);
214 for (i = 0; i < (h_HTSPERBLOCK); i++)
215 Lock_Init(&block->entry[i].lock);
216 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
217 block->entry[i].next = &(block->entry[i + 1]);
218 for (i = 0; i < (h_HTSPERBLOCK); i++)
219 block->entry[i].index = index++;
220 block->entry[h_HTSPERBLOCK - 1].next = 0;
221 HTFree = (struct host *)block;
222 hosttableptrs[HTBlocks++] = block->entry;
227 /* get the next available HT */
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(FS_configPath);
271 ("hpr_Initialize: Could not open configuration directory: %s",
276 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
278 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
283 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
285 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s",
286 cellstr, tdir->name, AFSDIR_CELLSERVDB_FILE));
293 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
298 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
299 * to force use of the KeyFile. secLevel == 0 implies -noauth was
301 code = afsconf_ClientAuthSecure(tdir, &sc, &scIndex);
303 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s "
304 "(so trying noauth)", code, afs_error_message(code)));
305 scIndex = RX_SECIDX_NULL;
306 sc = rxnull_NewClientSecurityObject();
309 if (scIndex == RX_SECIDX_NULL)
310 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, "
311 "running unauthenticated. [%d]", code));
313 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
314 for (i = 0; i < info.numServers; i++) {
316 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
317 info.hostAddr[i].sin_port, PRSRV,
321 code = ubik_ClientInit(serverconns, uclient);
323 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
326 code = rxs_Release(sc);
331 hpr_End(struct ubik_client *uclient)
336 code = ubik_ClientDestroy(uclient);
342 getThreadClient(struct ubik_client **client)
346 *client = pthread_getspecific(viced_uclient_key);
350 code = hpr_Initialize(client);
354 opr_Verify(pthread_setspecific(viced_uclient_key, *client) == 0);
360 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
364 struct ubik_client *uclient;
366 code = getThreadClient(&uclient);
371 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
372 if (code != PRSUCCESS)
375 /* do something about this, probably make a new call */
376 /* don't forget there's a hard limit in the interface */
378 "membership list for host id %d exceeds display limit\n",
385 hpr_NameToId(namelist *names, idlist *ids)
389 struct ubik_client *uclient;
391 code = getThreadClient(&uclient);
395 for (i = 0; i < names->namelist_len; i++)
396 stolower(names->namelist_val[i]);
397 code = ubik_PR_NameToID(uclient, 0, names, ids);
402 hpr_IdToName(idlist *ids, namelist *names)
405 struct ubik_client *uclient;
407 code = getThreadClient(&uclient);
411 code = ubik_PR_IDToName(uclient, 0, ids, names);
416 hpr_GetCPS(afs_int32 id, prlist *CPS)
420 struct ubik_client *uclient;
422 code = getThreadClient(&uclient);
427 code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
428 if (code != PRSUCCESS)
431 /* do something about this, probably make a new call */
432 /* don't forget there's a hard limit in the interface */
433 fprintf(stderr, "membership list for id %d exceeds display limit\n",
439 static short consolePort = 0;
442 h_Lock_r(struct host *host)
452 * returns 1 if already locked
453 * else returns locks and returns 0
457 h_NBLock_r(struct host *host)
459 struct Lock *hostLock = &host->lock;
464 if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
465 hostLock->excl_locked = WRITE_LOCK;
469 LOCK_UNLOCK(hostLock);
478 /*------------------------------------------------------------------------
479 * PRIVATE h_AddrInSameNetwork
482 * Given a target IP address and a candidate IP address (both
483 * in host byte order), return a non-zero value (1) if the
484 * candidate address is in a different network from the target
488 * a_targetAddr : Target address.
489 * a_candAddr : Candidate address.
492 * 1 if the candidate address is in the same net as the target,
496 * The target and candidate addresses are both in host byte
497 * order, NOT network byte order, when passed in. We return
498 * our value as a character, since that's the type of field in
499 * the host structure, where this info will be stored.
503 *------------------------------------------------------------------------*/
506 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
507 { /*h_AddrInSameNetwork */
509 afs_uint32 targetNet;
513 * Pull out the network and subnetwork numbers from the target
514 * and candidate addresses. We can short-circuit this whole
515 * affair if the target and candidate addresses are not of the
518 if (IN_CLASSA(a_targetAddr)) {
519 if (!(IN_CLASSA(a_candAddr))) {
522 targetNet = a_targetAddr & IN_CLASSA_NET;
523 candNet = a_candAddr & IN_CLASSA_NET;
524 } else if (IN_CLASSB(a_targetAddr)) {
525 if (!(IN_CLASSB(a_candAddr))) {
528 targetNet = a_targetAddr & IN_CLASSB_NET;
529 candNet = a_candAddr & IN_CLASSB_NET;
530 } /*Class B target */
531 else if (IN_CLASSC(a_targetAddr)) {
532 if (!(IN_CLASSC(a_candAddr))) {
535 targetNet = a_targetAddr & IN_CLASSC_NET;
536 candNet = a_candAddr & IN_CLASSC_NET;
537 } /*Class C target */
539 targetNet = a_targetAddr;
540 candNet = a_candAddr;
541 } /*Class D address */
544 * Now, simply compare the extracted net values for the two addresses
545 * (which at this point are known to be of the same class)
547 if (targetNet == candNet)
552 } /*h_AddrInSameNetwork */
555 /* Assumptions: called with held host */
557 h_gethostcps_r(struct host *host, afs_int32 now)
562 /* wait if somebody else is already doing the getCPS call */
563 while (host->hostFlags & HCPS_INPROGRESS) {
564 slept = 1; /* I did sleep */
565 host->hostFlags |= HCPS_WAITING; /* I am sleeping now */
566 opr_cv_wait(&host->cond, &host_glock_mutex);
570 host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
571 if (host->hcps.prlist_val)
572 free(host->hcps.prlist_val); /* this is for hostaclRefresh */
573 host->hcps.prlist_val = NULL;
574 host->hcps.prlist_len = 0;
575 host->cpsCall = slept ? time(NULL) : (now);
578 code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
583 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
584 * and reevaluates things if no sync server or quorum is found we could still end up
585 * with one of these errors. In such case we would like to reevaluate the rpc call to
586 * find if there's cps for this guy. We treat other errors (except network failures
587 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
588 * we could like to deal this problem the other way around (i.e. if code == NOCPS
589 * ignore else retry next time) but the problem is that there're other errors (i.e.
590 * EPERM) for which we don't want to retry and we don't know the whole code list!
592 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
594 * We would have preferred to use a while loop and try again since ops in protected
595 * acls for this host will fail now but they'll be reevaluated on any subsequent
596 * call. The attempt to wait for a quorum/sync site or network error won't work
597 * since this problems really should only occurs during a complete fileserver
598 * restart. Since the fileserver will start before the ptservers (and thus before
599 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
601 host->hcpsfailed = 1;
603 ("Warning: GetHostCPS failed (%d) for %p (%s:%d); will retry\n",
604 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
606 host->hcpsfailed = 0;
608 ("gethost: GetHostCPS failed (%d) for %p (%s:%d); ignored\n",
609 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
611 if (host->hcps.prlist_val)
612 free(host->hcps.prlist_val);
613 host->hcps.prlist_val = NULL;
614 host->hcps.prlist_len = 0; /* Make sure it's zero */
616 host->hcpsfailed = 0;
618 host->hostFlags &= ~HCPS_INPROGRESS;
619 /* signal all who are waiting */
620 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
621 host->hostFlags &= ~HCPS_WAITING;
622 opr_cv_broadcast(&host->cond);
626 /* args in net byte order */
628 h_flushhostcps(afs_uint32 hostaddr, afs_uint16 hport)
633 h_Lookup_r(hostaddr, hport, &host);
635 host->hcpsfailed = 1;
644 * Allocate a host. It will be identified by the peer (ip,port) info in the
645 * rx connection provided. The host is returned held and locked
647 #define DEF_ROPCONS 2115
650 h_Alloc_r(struct rx_connection *r_con)
652 struct servent *serverentry;
654 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
661 /* acquire the host lock withot dropping H_LOCK. we can do this here
662 * because we know we will not block; we just created this host and
663 * nobody else knows about it. */
664 ObtainWriteLock(&host->lock);
666 host->host = rxr_HostOf(r_con);
667 host->port = rxr_PortOf(r_con);
669 h_AddHostToAddrHashTable_r(host->host, host->port, host);
671 if (consolePort == 0) { /* find the portal number for console */
672 #if defined(AFS_OSF_ENV)
673 serverentry = getservbyname("ropcons", "");
675 serverentry = getservbyname("ropcons", 0);
678 consolePort = serverentry->s_port;
680 consolePort = htons(DEF_ROPCONS); /* Use a default */
682 if (host->port == consolePort)
684 /* Make a callback channel even for the console, on the off chance that it
685 * makes a request that causes a break call back. It shouldn't. */
686 h_SetupCallbackConn_r(host);
687 host->LastCall = host->cpsCall = host->ActiveCall = time(NULL);
689 host->hcps.prlist_val = NULL;
690 host->hcps.prlist_len = 0;
691 host->interface = NULL;
693 host->hcpsfailed = 0; /* save cycles */
694 h_gethostcps(host); /* do this under host hold/lock */
696 host->FirstClient = NULL;
697 h_InsertList_r(host); /* update global host List */
699 * Compare the new host's IP address (in host byte order) with ours
700 * (the File Server's), remembering if they are in the same network.
702 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
703 host->InSameNetwork =
704 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
711 /* Make a callback channel even for the console, on the off chance that it
712 * makes a request that causes a break call back. It shouldn't. */
714 h_SetupCallbackConn_r(struct host * host)
717 sc = rxnull_NewClientSecurityObject();
718 host->callback_rxcon =
719 rx_NewConnection(host->host, host->port, 1, sc, 0);
720 rx_SetConnDeadTime(host->callback_rxcon, 50);
721 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
722 rx_SetConnSecondsUntilNatPing(host->callback_rxcon, 20);
726 * Lookup a host given an IP address and UDP port number.
727 * hostaddr and hport are in network order
728 * hostaddr and hport are in network order
729 * On return, refCount is incremented.
732 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, struct host **hostp)
735 struct host *host = NULL;
736 struct h_AddrHashChain *chain;
737 int index = h_HashIndex(haddr);
738 extern int hostaclRefresh;
741 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
742 host = chain->hostPtr;
744 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
745 && chain->port == hport) {
746 if ((host->hostFlags & HWHO_INPROGRESS) &&
747 h_threadquota(host->lock.num_waiting)) {
753 if (host->hostFlags & HOSTDELETED) {
760 now = time(NULL); /* always evaluate "now" */
761 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
763 * Every hostaclRefresh period (def 2 hrs) get the new
764 * membership list for the host. Note this could be the
765 * first time that the host is added to a group. Also
766 * here we also retry on previous legitimate hcps failures.
768 * If we get here refCount is elevated.
770 h_gethostcps_r(host, now);
780 /* Lookup a host given its UUID. */
782 h_LookupUuid_r(afsUUID * uuidp)
784 struct host *host = 0;
785 struct h_UuidHashChain *chain;
786 int index = h_UuidHashIndex(uuidp);
788 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
789 host = chain->hostPtr;
791 if (!(host->hostFlags & HOSTDELETED) && host->interface
792 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
800 /* h_TossStuff_r: Toss anything in the host structure (the host or
801 * clients marked for deletion. Called from h_Release_r ONLY.
802 * To be called, there must be no holds, and either host->deleted
803 * or host->clientDeleted must be set.
806 h_TossStuff_r(struct host *host)
808 struct client **cp, *client;
812 if ((host->hostFlags & HOSTDELETED)) {
816 /* make sure host doesn't go away over h_NBLock_r */
819 code = h_NBLock_r(host);
821 /* don't use h_Release_r, since that may call h_TossStuff_r again */
824 /* if somebody still has this host locked */
828 /* someone locked the host while HOSTDELETED was set; that is bad */
829 ViceLog(0, ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT
830 " (%s:%d flags 0x%x) was locked.\n",
831 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
832 (unsigned)host->hostFlags));
839 /* if somebody still has this host held */
840 /* we must check this _after_ h_NBLock_r, since h_NBLock_r can drop and
841 * reacquire H_LOCK */
842 if (host->refCount > 0) {
845 /* someone grabbed a ref while HOSTDELETED was set; that is bad */
846 ViceLog(0, ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT
847 " (%s:%d flags 0x%x) was held.\n",
848 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
849 (unsigned)host->hostFlags));
854 /* ASSUMPTION: rxi_FreeConnection() does not yield */
855 for (cp = &host->FirstClient; (client = *cp);) {
856 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
858 ObtainWriteLockNoBlock(&client->lock, code);
862 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
863 "client %p was locked.\n",
864 host, afs_inet_ntoa_r(host->host, hoststr),
865 ntohs(host->port), client));
869 if (client->refCount) {
872 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
873 "client %p refcount %d.\n",
874 host, afs_inet_ntoa_r(host->host, hoststr),
875 ntohs(host->port), client, client->refCount));
876 /* This is the same thing we do if the host is locked */
877 ReleaseWriteLock(&client->lock);
880 client->CPS.prlist_len = 0;
881 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
882 free(client->CPS.prlist_val);
883 client->CPS.prlist_val = NULL;
884 CurrentConnections--;
886 ReleaseWriteLock(&client->lock);
892 /* We've just cleaned out all the deleted clients; clear the flag */
893 host->hostFlags &= ~CLIENTDELETED;
895 if (host->hostFlags & HOSTDELETED) {
896 struct rx_connection *rxconn;
897 struct AddrPort hostAddrPort;
900 if (host->Console & 1)
902 if ((rxconn = host->callback_rxcon)) {
903 host->callback_rxcon = (struct rx_connection *)0;
904 rx_DestroyConnection(rxconn);
906 if (host->hcps.prlist_val)
907 free(host->hcps.prlist_val);
908 host->hcps.prlist_val = NULL;
909 host->hcps.prlist_len = 0;
910 DeleteAllCallBacks_r(host, 1);
911 host->hostFlags &= ~RESETDONE; /* just to be safe */
913 /* if alternate addresses do not exist */
914 if (!(host->interface)) {
915 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
917 h_DeleteHostFromUuidHashTable_r(host);
918 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
919 /* delete the hash entry for each valid alternate addresses */
920 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
921 hostAddrPort = host->interface->interface[i];
923 * if the interface addr/port is the primary, we already
924 * removed it. If the addr/port is not valid, its not
927 if (hostAddrPort.valid &&
928 (host->host != hostAddrPort.addr ||
929 host->port != hostAddrPort.port))
930 h_DeleteHostFromAddrHashTable_r(hostAddrPort.addr, hostAddrPort.port, host);
932 free(host->interface);
933 host->interface = NULL;
934 } /* if alternate address exists */
936 h_DeleteList_r(host); /* remove host from global host List */
943 /* h_Enumerate: Calls (*proc)(host, param) for at least each host in the
944 * system at the start of the enumeration (perhaps more). Hosts may be deleted
945 * (have delete flag set); ditto for clients. refCount is always incremented
946 * before (*proc) is called.
948 * The return value of the proc is a set of flags. The proc should set
949 * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
952 h_Enumerate(int (*proc) (struct host*, void *), void *param)
954 struct host *host, **list;
959 if (hostCount == 0) {
963 list = malloc(hostCount * sizeof(struct host *));
965 ViceLogThenPanic(0, ("Failed malloc in h_Enumerate (list)\n"));
967 for (totalCount = count = 0, host = hostList;
968 host && totalCount < hostCount;
969 host = host->next, totalCount++) {
971 if (!(host->hostFlags & HOSTDELETED)) {
977 if (totalCount != hostCount) {
978 ViceLog(0, ("h_Enumerate found %d of %d hosts\n", totalCount, hostCount));
979 } else if (host != NULL) {
980 ViceLog(0, ("h_Enumerate found more than %d hosts\n", hostCount));
981 ShutDownAndCore(PANIC);
984 for (i = 0; i < count; i++) {
986 flags = (*proc) (list[i], param);
988 h_Release_r(list[i]);
990 /* bail out of the enumeration early */
991 if (H_ENUMERATE_ISSET_BAIL(flags)) {
994 ViceLog(0, ("h_Enumerate got back invalid return value %d\n", flags));
995 ShutDownAndCore(PANIC);
999 /* we bailed out of enumerating hosts early; we still have holds on
1000 * some of the hosts in 'list', so release them */
1003 for ( ; i < count; i++) {
1004 h_Release_r(list[i]);
1012 /* h_Enumerate_r (revised):
1013 * Calls (*proc)(host, param) for each host in hostList, starting
1014 * at enumstart. Called only under H_LOCK. Hosts may be deleted (have
1015 * delete flag set); ditto for clients. refCount is always incremented
1016 * before (*proc) is called.
1018 * @note Assumes that hostList is only prepended to, that a host is never
1019 * inserted into the middle. Otherwise this would not be guaranteed to
1022 * The return value of the proc is a set of flags. The proc should set
1023 * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
1026 h_Enumerate_r(int (*proc) (struct host *, void *),
1027 struct host *enumstart, void *param)
1029 struct host *host, *next;
1033 if (hostCount == 0) {
1040 /* find the first non-deleted host, so we know where to actually start
1042 for (count = 0; host && count < hostCount; count++) {
1043 if (!(host->hostFlags & HOSTDELETED)) {
1050 /* we didn't find a non-deleted host... */
1052 if (host && count >= hostCount) {
1053 /* ...because we found a loop */
1054 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", hostCount));
1055 ShutDownAndCore(PANIC);
1058 /* ...because the hostList is full of deleted hosts */
1062 h_Hold_r(enumstart);
1064 /* remember hostCount, lest it change over the potential H_LOCK drop in
1066 origHostCount = hostCount;
1068 for (count = 0, host = enumstart; host && count < origHostCount; host = next, count++) {
1071 /* find the next non-deleted host */
1072 while (next && (next->hostFlags & HOSTDELETED)) {
1074 /* inc count for the skipped-over host */
1075 if (++count > origHostCount) {
1076 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1077 ShutDownAndCore(PANIC);
1083 if (!(host->hostFlags & HOSTDELETED)) {
1085 flags = (*proc) (host, param);
1086 if (H_ENUMERATE_ISSET_BAIL(flags)) {
1087 h_Release_r(host); /* this might free up the host */
1093 ViceLog(0, ("h_Enumerate_r got back invalid return value %d\n", flags));
1094 ShutDownAndCore(PANIC);
1097 h_Release_r(host); /* this might free up the host */
1099 if (host != NULL && count >= origHostCount) {
1100 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1101 ShutDownAndCore(PANIC);
1103 } /*h_Enumerate_r */
1106 /* inserts a new HashChain structure corresponding to this UUID */
1108 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1111 struct h_UuidHashChain *chain;
1112 char uuid1[128], uuid2[128];
1115 /* hash into proper bucket */
1116 index = h_UuidHashIndex(uuid);
1118 /* don't add the same entry multiple times */
1119 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1120 if (!chain->hostPtr)
1123 if (chain->hostPtr->interface &&
1124 afs_uuid_equal(&chain->hostPtr->interface->uuid, uuid)) {
1125 if (LogLevel >= 125) {
1126 afsUUID_to_string(&chain->hostPtr->interface->uuid, uuid1,
1128 afsUUID_to_string(uuid, uuid2, 127);
1129 ViceLog(125, ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s) exists as %s:%d (uuid %s)\n",
1131 afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1132 ntohs(chain->hostPtr->port), uuid2));
1138 /* insert into beginning of list for this bucket */
1139 chain = malloc(sizeof(struct h_UuidHashChain));
1141 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1143 chain->hostPtr = host;
1144 chain->next = hostUuidHashTable[index];
1145 hostUuidHashTable[index] = chain;
1148 afsUUID_to_string(uuid, uuid2, 127);
1150 ("h_AddHostToUuidHashTable_r: host %p (%s:%d) added as uuid %s\n",
1151 host, afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1152 ntohs(chain->hostPtr->port), uuid2));
1155 /* deletes a HashChain structure corresponding to this host */
1157 h_DeleteHostFromUuidHashTable_r(struct host *host)
1160 struct h_UuidHashChain **uhp, *uth;
1164 if (!host->interface)
1167 /* hash into proper bucket */
1168 index = h_UuidHashIndex(&host->interface->uuid);
1170 if (LogLevel >= 125)
1171 afsUUID_to_string(&host->interface->uuid, uuid1, 127);
1172 for (uhp = &hostUuidHashTable[index]; (uth = *uhp); uhp = &uth->next) {
1173 opr_Assert(uth->hostPtr);
1174 if (uth->hostPtr == host) {
1176 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d)\n",
1177 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1178 ntohs(host->port)));
1185 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d) not found\n",
1186 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1187 ntohs(host->port)));
1192 * This is called with host locked and held.
1194 * All addresses are in network byte order.
1197 invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1201 struct Interface *interface;
1202 char hoststr[16], hoststr2[16];
1205 opr_Assert(host->interface);
1207 ViceLog(125, ("invalidateInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1208 host, afs_inet_ntoa_r(host->host, hoststr),
1209 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1213 * Make sure this address is on the list of known addresses
1216 interface = host->interface;
1217 number = host->interface->numberOfInterfaces;
1218 for (i = 0; i < number; i++) {
1219 if (interface->interface[i].addr == addr &&
1220 interface->interface[i].port == port) {
1221 if (interface->interface[i].valid) {
1222 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1223 interface->interface[i].valid = 0;
1234 * This is called with host locked and held. This function differs
1235 * from removeInterfaceAddr_r in that it is called when the address
1236 * is being removed from the host regardless of whether or not there
1237 * is an interface list for the host. This function will delete the
1238 * host if there are no addresses left on it.
1240 * All addresses are in network byte order.
1243 removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1246 char hoststr[16], hoststr2[16];
1247 struct rx_connection *rxconn;
1249 if (!host->interface || host->interface->numberOfInterfaces == 1) {
1250 if (host->host == addr && host->port == port) {
1252 ("Removing only address for host %" AFS_PTR_FMT " (%s:%d), deleting host.\n",
1253 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1254 host->hostFlags |= HOSTDELETED;
1256 * Do not remove the primary addr/port from the hash table.
1257 * It will be ignored due to the HOSTDELETED flag and will
1258 * be removed when h_TossStuff_r() cleans up the HOSTDELETED
1259 * host. Removing it here will only result in a search for
1260 * the host/addr/port in the hash chain which will fail.
1264 ("Removing address that does not belong to host %" AFS_PTR_FMT " (%s:%d).\n",
1265 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1268 if (host->host == addr && host->port == port) {
1269 removeInterfaceAddr_r(host, addr, port);
1271 for (i=0; i < host->interface->numberOfInterfaces; i++) {
1272 if (host->interface->interface[i].valid) {
1274 ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
1275 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1276 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
1277 ntohs(host->interface->interface[i].port)));
1278 host->host = host->interface->interface[i].addr;
1279 host->port = host->interface->interface[i].port;
1280 h_AddHostToAddrHashTable_r(host->host, host->port, host);
1285 if (i == host->interface->numberOfInterfaces) {
1287 ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
1288 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1289 host->hostFlags |= HOSTDELETED;
1290 /* addr/port was removed from the hash table */
1294 rxconn = host->callback_rxcon;
1295 host->callback_rxcon = NULL;
1298 rx_DestroyConnection(rxconn);
1302 h_SetupCallbackConn_r(host);
1305 /* not the primary addr/port, just invalidate it */
1306 invalidateInterfaceAddr_r(host, addr, port);
1314 createHostAddrHashChain_r(int index, afs_uint32 addr, afs_uint16 port, struct host *host)
1316 struct h_AddrHashChain *chain;
1319 /* insert into beginning of list for this bucket */
1320 chain = malloc(sizeof(struct h_AddrHashChain));
1322 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToAddrHashTable_r\n"));
1324 chain->hostPtr = host;
1325 chain->next = hostAddrHashTable[index];
1328 hostAddrHashTable[index] = chain;
1329 ViceLog(125, ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " added as %s:%d\n",
1330 host, afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1334 * Resolve host address conflicts when hashing by address.
1336 * @param[in] addr an ip address of the interface
1337 * @param[in] port the port of the interface
1338 * @param[in] newHost the host being added with this address
1339 * @param[in] oldHost the host previously added with this address
1342 reconcileHosts_r(afs_uint32 addr, afs_uint16 port, struct host *newHost,
1343 struct host *oldHost)
1345 struct rx_connection *cb = NULL;
1347 struct interfaceAddr interf;
1349 afsUUID *newHostUuid = &nulluuid;
1350 afsUUID *oldHostUuid = &nulluuid;
1354 ("reconcileHosts_r: addr %s:%d newHost %" AFS_PTR_FMT " oldHost %"
1355 AFS_PTR_FMT, afs_inet_ntoa_r(addr, hoststr), ntohs(port),
1358 opr_Assert(oldHost != newHost);
1359 caps.Capabilities_val = NULL;
1362 sc = rxnull_NewClientSecurityObject();
1365 cb = rx_NewConnection(addr, port, 1, sc, 0);
1366 rx_SetConnDeadTime(cb, 50);
1367 rx_SetConnHardDeadTime(cb, AFS_HARDDEADTIME);
1372 code = RXAFSCB_TellMeAboutYourself(cb, &interf, &caps);
1373 if (code == RXGEN_OPCODE) {
1374 code = RXAFSCB_WhoAreYou(cb, &interf);
1378 if (code == RXGEN_OPCODE ||
1379 (code == 0 && afs_uuid_equal(&interf.uuid, &nulluuid))) {
1381 ("reconcileHosts_r: WhoAreYou not supported for connection (%s:%d), error %d\n",
1382 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1387 ("reconcileHosts_r: WhoAreYou failed for connection (%s:%d), error %d\n",
1388 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1392 /* Since lock was dropped, the hosts may have been deleted during the rpcs. */
1393 if ((newHost->hostFlags & HOSTDELETED)
1394 && (oldHost->hostFlags & HOSTDELETED)) {
1396 ("reconcileHosts_r: new and old hosts were deleted during probe.\n"));
1400 /* A check can be done if at least one of the hosts has a uuid. It
1401 * is an error if the hosts have the same (not null) uuid. */
1402 if ((!(newHost->hostFlags & HOSTDELETED)) && newHost->interface) {
1403 newHostUuid = &(newHost->interface->uuid);
1405 if ((!(oldHost->hostFlags & HOSTDELETED)) && oldHost->interface) {
1406 oldHostUuid = &(oldHost->interface->uuid);
1408 if (afs_uuid_equal(newHostUuid, &nulluuid) &&
1409 afs_uuid_equal(oldHostUuid, &nulluuid)) {
1411 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), no uuids\n",
1412 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1415 if (afs_uuid_equal(newHostUuid, oldHostUuid)) {
1417 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), same uuids\n",
1418 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1422 /* Determine which host should be hashed */
1423 if ((!(newHost->hostFlags & HOSTDELETED))
1424 && afs_uuid_equal(newHostUuid, &(interf.uuid))) {
1425 /* Install the new host into the hash before removing the stale
1426 * addresses. Walk the hash chain again since the hash table may have
1427 * been changed when the host lock was dropped to get the uuid. */
1428 struct h_AddrHashChain *chain;
1429 int index = h_HashIndex(addr);
1430 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1431 if (chain->addr == addr && chain->port == port) {
1432 chain->hostPtr = newHost;
1433 removeAddress_r(oldHost, addr, port);
1437 createHostAddrHashChain_r(index, addr, port, newHost);
1438 removeAddress_r(oldHost, addr, port);
1441 if ((!(oldHost->hostFlags & HOSTDELETED))
1442 && afs_uuid_equal(oldHostUuid, &(interf.uuid))) {
1443 removeAddress_r(newHost, addr, port);
1448 if (!(newHost->hostFlags & HOSTDELETED)) {
1449 removeAddress_r(newHost, addr, port);
1451 if (!(oldHost->hostFlags & HOSTDELETED)) {
1452 removeAddress_r(oldHost, addr, port);
1456 h_Release_r(newHost);
1457 h_Release_r(oldHost);
1458 rx_DestroyConnection(cb);
1462 /* inserts a new HashChain structure corresponding to this address */
1464 h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1467 struct h_AddrHashChain *chain;
1470 /* hash into proper bucket */
1471 index = h_HashIndex(addr);
1473 /* don't add the same address:port pair entry multiple times */
1474 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1475 if (chain->addr == addr && chain->port == port) {
1476 if (chain->hostPtr == host) {
1478 ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
1479 host, afs_inet_ntoa_r(chain->addr, hoststr),
1480 ntohs(chain->port)));
1483 if (!(chain->hostPtr->hostFlags & HOSTDELETED)) {
1484 /* attempt to resolve host address collision */
1485 reconcileHosts_r(addr, port, host, chain->hostPtr);
1490 createHostAddrHashChain_r(index, addr, port, host);
1494 * This is called with host locked and held.
1495 * It is called to either validate or add an additional interface
1496 * address/port on the specified host.
1498 * All addresses are in network byte order.
1501 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1505 struct Interface *interface;
1506 char hoststr[16], hoststr2[16];
1509 opr_Assert(host->interface);
1512 * Make sure this address is on the list of known addresses
1515 number = host->interface->numberOfInterfaces;
1516 for (i = 0; i < number; i++) {
1517 if (host->interface->interface[i].addr == addr &&
1518 host->interface->interface[i].port == port) {
1520 ("addInterfaceAddr : found host %" AFS_PTR_FMT " (%s:%d) adding %s:%d%s\n",
1521 host, afs_inet_ntoa_r(host->host, hoststr),
1522 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1523 ntohs(port), host->interface->interface[i].valid ? "" :
1526 if (host->interface->interface[i].valid == 0) {
1527 host->interface->interface[i].valid = 1;
1528 h_AddHostToAddrHashTable_r(addr, port, host);
1534 ViceLog(125, ("addInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) adding %s:%d\n",
1535 host, afs_inet_ntoa_r(host->host, hoststr),
1536 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1539 interface = malloc(sizeof(struct Interface)
1540 + (sizeof(struct AddrPort) * number));
1542 ViceLogThenPanic(0, ("Failed malloc in addInterfaceAddr_r\n"));
1544 interface->numberOfInterfaces = number + 1;
1545 interface->uuid = host->interface->uuid;
1546 for (i = 0; i < number; i++)
1547 interface->interface[i] = host->interface->interface[i];
1549 /* Add the new valid interface */
1550 interface->interface[number].addr = addr;
1551 interface->interface[number].port = port;
1552 interface->interface[number].valid = 1;
1553 h_AddHostToAddrHashTable_r(addr, port, host);
1554 free(host->interface);
1555 host->interface = interface;
1562 * This is called with host locked and held.
1564 * All addresses are in network byte order.
1567 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1571 struct Interface *interface;
1572 char hoststr[16], hoststr2[16];
1575 opr_Assert(host->interface);
1577 ViceLog(125, ("removeInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1578 host, afs_inet_ntoa_r(host->host, hoststr),
1579 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1583 * Make sure this address is on the list of known addresses
1586 interface = host->interface;
1587 number = host->interface->numberOfInterfaces;
1588 for (i = 0; i < number; i++) {
1589 if (interface->interface[i].addr == addr &&
1590 interface->interface[i].port == port) {
1591 if (interface->interface[i].valid)
1592 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1594 for (; i < number; i++) {
1595 interface->interface[i] = interface->interface[i+1];
1597 interface->numberOfInterfaces = number;
1608 h_threadquota(int waiting)
1610 if (waiting > h_quota_limit) {
1616 /* If found, host is returned with refCount incremented */
1618 h_GetHost_r(struct rx_connection *tcon)
1621 struct host *oldHost;
1623 struct interfaceAddr interf;
1624 int interfValid = 0;
1625 struct Identity *identP = NULL;
1628 char hoststr[16], hoststr2[16];
1630 struct rx_connection *cb_conn = NULL;
1631 struct rx_connection *cb_in = NULL;
1633 caps.Capabilities_val = NULL;
1635 haddr = rxr_HostOf(tcon);
1636 hport = rxr_PortOf(tcon);
1639 rx_DestroyConnection(cb_in);
1642 if (caps.Capabilities_val)
1643 free(caps.Capabilities_val);
1644 caps.Capabilities_val = NULL;
1645 caps.Capabilities_len = 0;
1648 if (h_Lookup_r(haddr, hport, &host))
1650 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1651 if (host && !identP && !(host->Console & 1)) {
1652 /* This is a new connection, and we already have a host
1653 * structure for this address. Verify that the identity
1654 * of the caller matches the identity in the host structure.
1656 if ((host->hostFlags & HWHO_INPROGRESS) &&
1657 h_threadquota(host->lock.num_waiting)) {
1663 if (!(host->hostFlags & ALTADDR) ||
1664 (host->hostFlags & HOSTDELETED)) {
1665 /* Another thread is doing initialization
1666 * or this host was deleted while we
1667 * waited for the lock. */
1670 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1671 host, afs_inet_ntoa_r(host->host, hoststr),
1672 ntohs(host->port)));
1676 host->hostFlags |= HWHO_INPROGRESS;
1677 host->hostFlags &= ~ALTADDR;
1679 /* We received a new connection from an IP address/port
1680 * that is associated with 'host' but the address/port of
1681 * the callback connection does not have to match it.
1682 * If there is a match, we can use the existing callback
1683 * connection to verify the UUID. If they do not match
1684 * we need to use a new callback connection to verify the
1685 * UUID of the incoming caller and perhaps use the old
1686 * callback connection to verify that the old address/port
1690 cb_conn = host->callback_rxcon;
1691 rx_GetConnection(cb_conn);
1693 if (haddr == host->host && hport == host->port) {
1694 /* The existing callback connection matches the
1695 * incoming connection so just use it.
1698 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1699 if (code == RXGEN_OPCODE)
1700 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1702 /* We do not have a match. Create a new connection
1703 * for the new addr/port and use multi_Rx to probe
1704 * both of them simultaneously.
1707 sc = rxnull_NewClientSecurityObject();
1708 cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1709 rx_SetConnDeadTime(cb_in, 50);
1710 rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1711 rx_SetConnSecondsUntilNatPing(cb_in, 20);
1714 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1715 if (code == RXGEN_OPCODE)
1716 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1718 rx_PutConnection(cb_conn);
1721 if ((code == RXGEN_OPCODE) ||
1722 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1723 identP = malloc(sizeof(struct Identity));
1725 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1728 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1729 if (cb_in == NULL) {
1730 /* The host on this connection was unable to respond to
1731 * the WhoAreYou. We will treat this as a new connection
1732 * from the existing host. The worst that can happen is
1733 * that we maintain some extra callback state information */
1734 if (host->interface) {
1736 ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1738 afs_inet_ntoa_r(host->host, hoststr),
1739 ntohs(host->port)));
1740 host->hostFlags |= HOSTDELETED;
1741 host->hostFlags &= ~HWHO_INPROGRESS;
1748 /* The incoming connection does not support WhoAreYou but
1749 * the original one might have. Use removeAddress_r() to
1750 * remove this addr/port from the host that was found.
1751 * If there are no more addresses left for the host it
1752 * will be deleted. Then we retry.
1754 removeAddress_r(host, haddr, hport);
1755 host->hostFlags &= ~HWHO_INPROGRESS;
1756 host->hostFlags |= ALTADDR;
1762 } else if (code == 0) {
1764 identP = malloc(sizeof(struct Identity));
1766 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1769 identP->uuid = interf.uuid;
1770 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1771 /* Check whether the UUID on this connection matches
1772 * the UUID in the host structure. If they don't match
1773 * then this is not the same host as before. */
1774 if (!host->interface
1775 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1778 ("Uuid doesn't match connection (%s:%d).\n",
1779 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1780 removeAddress_r(host, haddr, hport);
1783 ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1784 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1786 removeAddress_r(host, host->host, host->port);
1788 host->hostFlags &= ~HWHO_INPROGRESS;
1789 host->hostFlags |= ALTADDR;
1795 /* the UUID matched the client at the incoming addr/port
1796 * but this is not the address of the active callback
1797 * connection. Try that connection and see if the client
1798 * is still there and if the reported UUID is the same.
1801 afsUUID uuid = host->interface->uuid;
1802 cb_conn = host->callback_rxcon;
1803 rx_GetConnection(cb_conn);
1804 rx_SetConnDeadTime(cb_conn, 2);
1805 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1807 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1809 rx_SetConnDeadTime(cb_conn, 50);
1810 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1811 rx_PutConnection(cb_conn);
1814 /* The primary address is either not responding or
1815 * is not the client we are looking for. Need to
1816 * remove the primary address and add swap in the new
1817 * callback connection, and destroy the old one.
1819 struct rx_connection *rxconn;
1820 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1822 afs_inet_ntoa_r(host->host, hoststr),
1823 ntohs(host->port),code2));
1826 * make sure we add and then remove. otherwise, we
1827 * might end up with no valid interfaces after the
1828 * remove and the host will have been marked deleted.
1830 addInterfaceAddr_r(host, haddr, hport);
1831 removeInterfaceAddr_r(host, host->host, host->port);
1834 rxconn = host->callback_rxcon;
1835 host->callback_rxcon = cb_in;
1840 * If rx_DestroyConnection calls h_FreeConnection we
1841 * will deadlock on the host_glock_mutex. Work around
1842 * the problem by unhooking the client from the
1843 * connection before destroying the connection.
1845 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1846 rx_DestroyConnection(rxconn);
1852 /* A callback to the incoming connection address is failing.
1853 * Assume that the addr/port is no longer associated with the host
1854 * returned by h_Lookup_r.
1857 ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1858 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1859 removeAddress_r(host, haddr, hport);
1860 host->hostFlags &= ~HWHO_INPROGRESS;
1861 host->hostFlags |= ALTADDR;
1865 rx_DestroyConnection(cb_in);
1870 ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1871 host, afs_inet_ntoa_r(host->host, hoststr),
1872 ntohs(host->port), code));
1873 host->hostFlags |= VENUSDOWN;
1876 if (caps.Capabilities_val
1877 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1878 host->hostFlags |= HERRORTRANS;
1880 host->hostFlags &= ~(HERRORTRANS);
1881 host->hostFlags |= ALTADDR;
1882 host->hostFlags &= ~HWHO_INPROGRESS;
1885 if (!(host->hostFlags & ALTADDR)) {
1886 /* another thread is doing the initialisation */
1888 ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1889 host, afs_inet_ntoa_r(host->host, hoststr),
1890 ntohs(host->port)));
1894 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1895 host, afs_inet_ntoa_r(host->host, hoststr),
1896 ntohs(host->port)));
1900 /* We need to check whether the identity in the host structure
1901 * matches the identity on the connection. If they don't match
1902 * then treat this a new host. */
1903 if (!(host->Console & 1)
1904 && ((!identP->valid && host->interface)
1905 || (identP->valid && !host->interface)
1907 && !afs_uuid_equal(&identP->uuid,
1908 &host->interface->uuid)))) {
1909 char uuid1[128], uuid2[128];
1911 afsUUID_to_string(&identP->uuid, uuid1, 127);
1912 if (host->interface)
1913 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1915 ("CB: new identity for host %p (%s:%d), "
1916 "deleting(%x %p %s %s)\n",
1917 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1918 identP->valid, host->interface,
1919 identP->valid ? uuid1 : "no_uuid",
1920 host->interface ? uuid2 : "no_uuid"));
1922 /* The host in the cache is not the host for this connection */
1924 host->hostFlags |= HOSTDELETED;
1930 host = h_Alloc_r(tcon); /* returned held and locked */
1933 h_gethostcps_r(host, time(NULL));
1934 if (!(host->Console & 1)) {
1936 cb_conn = host->callback_rxcon;
1937 rx_GetConnection(cb_conn);
1938 host->hostFlags |= HWHO_INPROGRESS;
1941 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1942 if (code == RXGEN_OPCODE)
1943 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1944 rx_PutConnection(cb_conn);
1947 if ((code == RXGEN_OPCODE) ||
1948 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1950 identP = malloc(sizeof(struct Identity));
1955 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1959 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1961 ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1962 host, afs_inet_ntoa_r(host->host, hoststr),
1963 ntohs(host->port)));
1965 } else if (code == 0) {
1967 identP = malloc(sizeof(struct Identity));
1972 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1976 identP->uuid = interf.uuid;
1978 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1980 ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
1981 host, afs_inet_ntoa_r(host->host, hoststr),
1982 ntohs(host->port)));
1984 if (code == 0 && !identP->valid) {
1985 cb_conn = host->callback_rxcon;
1986 rx_GetConnection(cb_conn);
1988 code = RXAFSCB_InitCallBackState(cb_conn);
1989 rx_PutConnection(cb_conn);
1992 } else if (code == 0) {
1993 oldHost = h_LookupUuid_r(&identP->uuid);
1998 if (oldHost->hostFlags & HOSTDELETED) {
1999 h_Unlock_r(oldHost);
2000 h_Release_r(oldHost);
2008 /* This is a new address for an existing host. Update
2009 * the list of interfaces for the existing host and
2010 * delete the host structure we just allocated. */
2012 /* mark the duplicate host as deleted before we do
2013 * anything. The probing code below may try to change
2014 * "oldHost" to the same IP address as "host" currently
2015 * has, and we do not want a pseudo-"collision" to be
2017 host->hostFlags |= HOSTDELETED;
2019 oldHost->hostFlags |= HWHO_INPROGRESS;
2021 if (oldHost->interface) {
2023 afsUUID uuid = oldHost->interface->uuid;
2024 cb_conn = oldHost->callback_rxcon;
2025 rx_GetConnection(cb_conn);
2026 rx_SetConnDeadTime(cb_conn, 2);
2027 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2029 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2031 rx_SetConnDeadTime(cb_conn, 50);
2032 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2033 rx_PutConnection(cb_conn);
2036 /* The primary address is either not responding or
2037 * is not the client we are looking for.
2038 * MultiProbeAlternateAddress_r() will remove the
2039 * alternate interfaces that do not have the same
2041 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
2043 afs_inet_ntoa_r(oldHost->host, hoststr),
2044 ntohs(oldHost->port),code2));
2046 if (MultiProbeAlternateAddress_r(oldHost)) {
2047 /* If MultiProbeAlternateAddress_r succeeded,
2048 * it updated oldHost->host and oldHost->port
2049 * to an address that responded successfully to
2050 * a ProbeUuid, so it is as if the ProbeUuid
2051 * call above returned success. So, only set
2052 * 'probefail' if MultiProbeAlternateAddress_r
2061 if (oldHost->host != haddr || oldHost->port != hport) {
2062 struct rx_connection *rxconn;
2065 ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
2067 afs_inet_ntoa_r(oldHost->host, hoststr2),
2068 ntohs(oldHost->port),
2069 afs_inet_ntoa_r(haddr, hoststr),
2072 * add then remove. otherwise the host may get marked
2073 * deleted if we removed the only valid address.
2075 addInterfaceAddr_r(oldHost, haddr, hport);
2076 if (probefail || oldHost->host == haddr) {
2078 * The probe failed which means that the old
2079 * address is either unreachable or is not the
2080 * same host we were just contacted by. We will
2081 * also remove addresses if only the port has
2082 * changed because that indicates the client
2085 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
2088 struct Interface *interface = oldHost->interface;
2089 int number = oldHost->interface->numberOfInterfaces;
2090 for (i = 0; i < number; i++) {
2091 if (interface->interface[i].addr == haddr &&
2092 interface->interface[i].port != hport) {
2094 * We have just been contacted by a client
2095 * that has been seen from behind a NAT
2096 * and at least one other address.
2098 removeInterfaceAddr_r(oldHost, haddr,
2099 interface->interface[i].port);
2104 oldHost->host = haddr;
2105 oldHost->port = hport;
2106 rxconn = oldHost->callback_rxcon;
2107 oldHost->callback_rxcon = host->callback_rxcon;
2108 host->callback_rxcon = rxconn;
2110 /* don't destroy rxconn here; let h_TossStuff_r
2111 * take care of that via h_Release_r below */
2113 host->hostFlags &= ~HWHO_INPROGRESS;
2115 /* release host because it was allocated by h_Alloc_r */
2118 /* the new host is held and locked */
2120 /* This really is a new host */
2121 opr_Assert(interfValid == 1);
2122 initInterfaceAddr_r(host, &interf);
2124 cb_conn = host->callback_rxcon;
2125 rx_GetConnection(cb_conn);
2128 RXAFSCB_InitCallBackState3(cb_conn,
2130 rx_PutConnection(cb_conn);
2135 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2136 host, afs_inet_ntoa_r(host->host, hoststr),
2137 ntohs(host->port)));
2143 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2144 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2145 host->hostFlags |= VENUSDOWN;
2148 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2149 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2150 host->hostFlags |= RESETDONE;
2153 if (caps.Capabilities_val
2154 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2155 host->hostFlags |= HERRORTRANS;
2157 host->hostFlags &= ~(HERRORTRANS);
2158 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2159 host->hostFlags &= ~HWHO_INPROGRESS;
2164 if (caps.Capabilities_val)
2165 free(caps.Capabilities_val);
2166 caps.Capabilities_val = NULL;
2167 caps.Capabilities_len = 0;
2169 rx_DestroyConnection(cb_in);
2179 h_InitHostPackage(int hquota)
2181 opr_Assert(hquota > 0);
2182 h_quota_limit = hquota;
2184 memset(&nulluuid, 0, sizeof(afsUUID));
2185 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2186 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2187 opr_mutex_init(&host_glock_mutex);
2191 MapName_r(char *uname, afs_int32 * aval)
2197 lnames.namelist_len = 1;
2198 lnames.namelist_val = (prname *) uname;
2199 lids.idlist_len = 0;
2200 lids.idlist_val = NULL;
2203 code = hpr_NameToId(&lnames, &lids);
2206 if (lids.idlist_val) {
2207 *aval = lids.idlist_val[0];
2208 if (*aval == AnonymousID) {
2210 ("MapName: NameToId on %s returns anonymousID\n",
2211 lnames.namelist_val[0]));
2213 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2216 ("MapName: NameToId on '%s' is unknown\n",
2217 lnames.namelist_val[0]));
2228 PerHost_EnumerateClient(struct host *host, void *arock)
2230 struct enumclient_args *args = arock;
2231 struct client *client;
2234 for (client = host->FirstClient; client; client = client->next) {
2235 if (!client->deleted && client->ViceId == args->vid) {
2240 code = (*args->proc)(client, args->rock);
2243 h_ReleaseClient_r(client);
2246 return H_ENUMERATE_BAIL(0);
2255 h_EnumerateClients(VolumeId vid,
2256 int (*proc)(struct client *client, void *rock),
2259 struct enumclient_args args;
2265 h_Enumerate_r(PerHost_EnumerateClient, hostList, &args);
2270 format_vname(char *vname, int usize, const char *tname, const char *tinst,
2271 const char *tcell, afs_int32 islocal)
2275 len = strlcpy(vname, tname, usize);
2279 len = strlcat(vname, ".", usize);
2282 len = strlcat(vname, tinst, usize);
2286 if (tcell[0] && !islocal) {
2287 len = strlcat(vname, "@", usize);
2290 len = strlcat(vname, tcell, usize);
2298 getPeerDetails(struct rx_connection *conn,
2299 afs_int32 *viceid, afs_int32 *expTime, int authClass)
2302 #if (64-MAXKTCNAMELEN)
2303 ticket name length != 64
2307 char tcell[MAXKTCREALMLEN];
2308 char uname[PR_MAXNAMELEN];
2310 *viceid = AnonymousID;
2311 *expTime = 0x7fffffff;
2314 ("FindClient: authenticating connection: authClass=%d\n",
2316 if (authClass == 1) {
2317 /* A bcrypt tickets, no longer supported */
2318 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2322 if (authClass == 2) {
2323 /* an rxkad ticket */
2327 /* kerberos ticket */
2328 code = rxkad_GetServerInfo(conn, /*level */ 0, (afs_uint32 *)expTime,
2329 tname, tinst, tcell, &kvno);
2331 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2336 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2337 tname, tinst, tcell, *expTime, kvno));
2338 code = afsconf_IsLocalRealmMatch(confDir, &islocal, tname, tinst, tcell);
2341 ViceLog(0, ("FindClient: local realm check failed; code=%d", code));
2345 code = format_vname(uname, sizeof(uname), tname, tinst, tcell, islocal);
2347 ViceLog(0, ("FindClient: uname truncated."));
2351 /* translate the name to a vice id */
2352 code = MapName_r(uname, viceid);
2354 ViceLog(1, ("failed to map name=%s -> code=%d\n", uname,
2356 return code; /* Actually flag this is a failure */
2366 * Called by the server main loop. Returns a h_Held client, which must be
2367 * released later the main loop. Allocates a client if the matching one
2368 * isn't around. The client is returned with its reference count incremented
2369 * by one. The caller must call h_ReleaseClient_r when finished with
2372 * The refCount on client->host is returned incremented. h_ReleaseClient_r
2373 * does not decrement the refCount on client->host.
2375 * *a_viceid is set to the user's ViceId, even if we don't return a client
2379 h_FindClient_r(struct rx_connection *tcon, afs_int32 *a_viceid)
2381 struct client *client;
2382 struct host *host = NULL;
2383 struct client *oldClient;
2384 afs_int32 viceid = 0;
2392 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2393 if (client && client->sid == rx_GetConnectionId(tcon)
2394 && client->VenusEpoch == rx_GetConnectionEpoch(tcon)
2395 && !(client->host->hostFlags & HOSTDELETED)
2396 && !client->deleted) {
2399 *a_viceid = client->ViceId;
2402 h_Hold_r(client->host);
2403 if (client->prfail != 2) {
2404 /* Could add shared lock on client here */
2405 /* note that we don't have to lock entry in this path to
2406 * ensure CPS is initialized, since we don't call rx_SetSpecific
2407 * until initialization is done, and we only get here if
2408 * rx_GetSpecific located the client structure.
2413 ObtainWriteLock(&client->lock); /* released at end */
2419 authClass = rx_SecurityClassOf(tcon);
2421 code = getPeerDetails(tcon, &viceid, &expTime, authClass);
2429 if (!client) { /* loop */
2430 host = h_GetHost_r(tcon); /* Returns with incremented refCount */
2436 /* First try to find the client structure */
2437 for (client = host->FirstClient; client; client = client->next) {
2438 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2439 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2442 ObtainWriteLock(&client->lock);
2448 /* Still no client structure - get one */
2451 if (host->hostFlags & HOSTDELETED) {
2456 /* Retry to find the client structure */
2457 for (client = host->FirstClient; client; client = client->next) {
2458 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2459 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2461 goto retryfirstclient;
2466 ObtainWriteLock(&client->lock);
2467 client->refCount = 1;
2468 client->host = host;
2469 client->InSameNetwork = host->InSameNetwork;
2470 client->ViceId = viceid;
2471 client->expTime = expTime; /* rx only */
2472 client->authClass = authClass; /* rx only */
2473 client->sid = rx_GetConnectionId(tcon);
2474 client->VenusEpoch = rx_GetConnectionEpoch(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
2536 && oldClient->sid == rx_GetConnectionId(tcon)
2537 && oldClient->VenusEpoch == rx_GetConnectionEpoch(tcon)
2538 && !(oldClient->host->hostFlags & HOSTDELETED)) {
2540 if (!oldClient->deleted) {
2541 /* if we didn't create it, it's not ours to put back */
2543 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2544 "conn %p (host %s:%d) had client %p(%x)\n",
2545 client, client->sid, tcon,
2546 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2547 ntohs(rxr_PortOf(tcon)),
2548 oldClient, oldClient->sid));
2549 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2550 free(client->CPS.prlist_val);
2551 client->CPS.prlist_val = NULL;
2552 client->CPS.prlist_len = 0;
2554 /* We should perhaps check for 0 here */
2556 ReleaseWriteLock(&client->lock);
2561 oldClient->refCount++;
2563 h_Hold_r(oldClient->host);
2564 h_Release_r(client->host);
2567 ObtainWriteLock(&oldClient->lock);
2570 host = oldClient->host;
2572 ViceLog(0, ("FindClient: deleted client %p(%x ref %d host %p href "
2573 "%d) already had conn %p (host %s:%d, cid %x), stolen "
2574 "by client %p(%x, ref %d host %p href %d)\n",
2575 oldClient, oldClient->sid, oldClient->refCount,
2576 oldClient->host, oldClient->host->refCount, tcon,
2577 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2578 ntohs(rxr_PortOf(tcon)), rx_GetConnectionId(tcon),
2579 client, client->sid, client->refCount,
2580 client->host, client->host->refCount));
2581 /* rx_SetSpecific will be done immediately below */
2584 /* Avoid chaining in more than once. */
2588 if (host->hostFlags & HOSTDELETED) {
2593 client->host = NULL;
2595 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2596 free(client->CPS.prlist_val);
2597 client->CPS.prlist_val = NULL;
2598 client->CPS.prlist_len = 0;
2601 ReleaseWriteLock(&client->lock);
2606 client->next = host->FirstClient;
2607 host->FirstClient = client;
2609 CurrentConnections++; /* increment number of connections */
2611 rx_SetSpecific(tcon, rxcon_client_key, client);
2612 ReleaseWriteLock(&client->lock);
2616 } /*h_FindClient_r */
2619 h_ReleaseClient_r(struct client *client)
2621 opr_Assert(client->refCount > 0);
2628 * Sigh: this one is used to get the client AGAIN within the individual
2629 * server routines. This does not bother h_Holding the host, since
2630 * this is assumed already have been done by the server main loop.
2631 * It does check tokens, since only the server routines can return the
2632 * VICETOKENDEAD error code
2635 GetClient(struct rx_connection *tcon, struct client **cp)
2637 struct client *client;
2642 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2643 if (client == NULL) {
2645 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2646 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2647 ntohs(rxr_PortOf(tcon))));
2651 if (rx_GetConnectionId(tcon) != client->sid
2652 || rx_GetConnectionEpoch(tcon) != client->VenusEpoch) {
2654 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2655 tcon, rx_GetConnectionId(tcon), client->sid));
2659 if (client && client->LastCall > client->expTime && client->expTime) {
2661 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2662 afs_inet_ntoa_r(client->host->host, hoststr),
2663 ntohs(client->host->port), client->expTime));
2665 return VICETOKENDEAD;
2667 if (client->deleted) {
2668 ViceLog(0, ("GetClient: got deleted client, connection will appear "
2669 "anonymous; tcon %p cid %x client %p ref %d host %p "
2670 "(%s:%d) href %d ViceId %d\n",
2671 tcon, rx_GetConnectionId(tcon), client, client->refCount,
2673 afs_inet_ntoa_r(client->host->host, hoststr),
2674 (int)ntohs(client->host->port), client->host->refCount,
2675 (int)client->ViceId));
2685 PutClient(struct client **cp)
2691 h_ReleaseClient_r(*cp);
2698 /* Client user name for short term use. Note that this is NOT inexpensive */
2700 h_UserName(struct client *client)
2702 static char User[PR_MAXNAMELEN + 1];
2706 lids.idlist_len = 1;
2707 lids.idlist_val = malloc(1 * sizeof(afs_int32));
2708 if (!lids.idlist_val) {
2709 ViceLogThenPanic(0, ("Failed malloc in h_UserName\n"));
2711 lnames.namelist_len = 0;
2712 lnames.namelist_val = (prname *) 0;
2713 lids.idlist_val[0] = client->ViceId;
2714 if (hpr_IdToName(&lids, &lnames)) {
2715 /* We need to free id we alloced above! */
2716 free(lids.idlist_val);
2717 return "*UNKNOWN USER NAME*";
2719 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2720 free(lids.idlist_val);
2721 free(lnames.namelist_val);
2730 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2731 CEs, CEBlocks, HTs, HTBlocks));
2737 h_PrintClient(struct host *host, void *rock)
2739 StreamHandle_t *file = (StreamHandle_t *)rock;
2740 struct client *client;
2745 time_t LastCall, expTime;
2749 LastCall = host->LastCall;
2750 if (host->hostFlags & HOSTDELETED) {
2754 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2755 localtime_r(&LastCall, &tm));
2756 snprintf(tmpStr, sizeof tmpStr, "Host %s:%d down = %d, LastCall %s\n",
2757 afs_inet_ntoa_r(host->host, hoststr),
2758 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2760 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2761 for (client = host->FirstClient; client; client = client->next) {
2762 if (!client->deleted) {
2763 expTime = client->expTime;
2764 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2765 localtime_r(&expTime, &tm));
2766 snprintf(tmpStr, sizeof tmpStr,
2767 " user id=%d, name=%s, sl=%s till %s\n",
2768 client->ViceId, h_UserName(client),
2769 client->authClass ? "Authenticated"
2770 : "Not authenticated",
2771 client->authClass ? tbuffer : "No Limit");
2772 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2773 snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2774 client->CPS.prlist_len);
2775 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2776 if (client->CPS.prlist_val) {
2777 for (i = 0; i < client->CPS.prlist_len; i++) {
2778 snprintf(tmpStr, sizeof tmpStr, " %d",
2779 client->CPS.prlist_val[i]);
2780 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2783 sprintf(tmpStr, "]\n");
2784 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2790 } /*h_PrintClient */
2795 * Print a list of clients, with last security level and token value seen,
2799 h_PrintClients(void)
2806 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2810 ("Couldn't create client dump file %s\n",
2811 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2815 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2816 localtime_r(&now, &tm));
2817 snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n\n",
2819 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2820 h_Enumerate(h_PrintClient, (char *)file);
2821 STREAM_REALLYCLOSE(file);
2822 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2829 h_DumpHost(struct host *host, void *rock)
2831 StreamHandle_t *file = (StreamHandle_t *)rock;
2838 snprintf(tmpStr, sizeof tmpStr,
2839 "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u "
2840 "down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u "
2842 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
2843 host->index, host->cblist, CheckLock(&host->lock),
2844 host->LastCall, host->ActiveCall, (host->hostFlags & VENUSDOWN),
2845 host->hostFlags & HOSTDELETED, host->Console,
2846 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2848 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2849 if (host->hcps.prlist_val)
2850 for (i = 0; i < host->hcps.prlist_len; i++) {
2851 snprintf(tmpStr, sizeof tmpStr, " %d", host->hcps.prlist_val[i]);
2852 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2854 sprintf(tmpStr, "] [");
2855 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2856 if (host->interface)
2857 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2859 sprintf(tmpStr, " %s:%d",
2860 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2861 ntohs(host->interface->interface[i].port));
2862 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2864 sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2865 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2877 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2884 ("Couldn't create host dump file %s\n",
2885 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2889 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2890 localtime_r(&now, &tm));
2891 snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n\n", tbuffer);
2892 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2893 h_Enumerate(h_DumpHost, (char *)file);
2894 STREAM_REALLYCLOSE(file);
2895 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2899 #ifdef AFS_DEMAND_ATTACH_FS
2902 * host state serialization
2904 static int h_stateFillHeader(struct host_state_header * hdr);
2905 static int h_stateCheckHeader(struct host_state_header * hdr);
2906 static int h_stateAllocMap(struct fs_dump_state * state);
2907 static int h_stateSaveHost(struct host * host, void *rock);
2908 static int h_stateRestoreHost(struct fs_dump_state * state);
2909 static int h_stateRestoreIndex(struct host * h, void *rock);
2910 static int h_stateVerifyHost(struct host * h, void *rock);
2911 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
2912 afs_uint32 addr, afs_uint16 port, int valid);
2913 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2914 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2915 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2918 * Is this host busy?
2920 * This is just a hint and should not be trusted; this should probably only be
2921 * used by the host state serialization code when trying to detect if a host
2922 * can be sanely serialized to disk or not. If this function returns 1, the
2923 * host may be in an invalid state and thus should not be saved to disk.
2926 h_isBusy_r(struct host *host)
2928 struct Lock *hostLock = &host->lock;
2931 LOCK_LOCK(hostLock);
2932 if (hostLock->excl_locked || hostLock->readers_reading) {
2935 LOCK_UNLOCK(hostLock);
2941 if ((host->hostFlags & HWHO_INPROGRESS) || !(host->hostFlags & ALTADDR)) {
2942 /* We shouldn't hit this if the host wasn't locked, but just in case... */
2949 /* this procedure saves all host state to disk for fast startup */
2951 h_stateSave(struct fs_dump_state * state)
2953 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2956 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2958 /* invalidate host state header */
2959 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2961 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2962 sizeof(struct host_state_header))) {
2967 fs_stateIncEOF(state, sizeof(struct host_state_header));
2969 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2974 h_stateFillHeader(state->h_hdr);
2976 /* write the real header to disk */
2977 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2978 sizeof(struct host_state_header));
2985 * host state serialization
2987 * this procedure restores all host state from a disk for fast startup
2990 h_stateRestore(struct fs_dump_state * state)
2994 /* seek to the right position and read in the host state header */
2995 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2996 sizeof(struct host_state_header))) {
3001 /* check the validity of the header */
3002 if (h_stateCheckHeader(state->h_hdr)) {
3007 records = state->h_hdr->records;
3009 if (h_stateAllocMap(state)) {
3014 /* iterate over records restoring host state */
3015 for (i=0; i < records; i++) {
3016 if (h_stateRestoreHost(state) != 0) {
3027 h_stateRestoreIndices(struct fs_dump_state * state)
3029 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
3034 h_stateRestoreIndex(struct host * h, void *rock)
3036 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3037 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
3038 return H_ENUMERATE_BAIL(0);
3044 h_stateVerify(struct fs_dump_state * state)
3046 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
3051 h_stateVerifyHost(struct host * h, void* rock)
3053 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3057 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3058 return H_ENUMERATE_BAIL(0);
3062 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
3063 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
3064 h->interface->interface[i].port,
3065 h->interface->interface[i].valid)) {
3069 if (h_stateVerifyUuidHash(state, h)) {
3072 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
3076 if (cb_stateVerifyHCBList(state, h)) {
3084 * verify a host is either in, or absent from, the addr hash table.
3086 * @param[in] state fs dump state
3087 * @param[in] h host we're dealing with
3088 * @param[in] addr addr to look for (NBO)
3089 * @param[in] port port to look for (NBO)
3090 * @param[in] valid 1 if we're verifying that the specified addr and port
3091 * in the hash table point to the specified host. 0 if we're
3092 * verifying that the specified addr and port do NOT point
3093 * to the specified host
3095 * @return operation status
3096 * @retval 1 failed to verify, bail out
3097 * @retval 0 verified successfully, all is well
3100 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3101 afs_uint32 addr, afs_uint16 port, int valid)
3103 int ret = 0, found = 0;
3104 struct host *host = NULL;
3105 struct h_AddrHashChain *chain;
3106 int index = h_HashIndex(addr);
3110 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3111 host = chain->hostPtr;
3113 afs_inet_ntoa_r(addr, tmp);
3114 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3118 if ((chain->addr == addr) && (chain->port == port)) {
3121 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3122 "points to different host struct (%d, %d)\n",
3123 h->index, host->index));
3124 state->flags.warnings_generated = 1;
3128 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3129 "marked invalid, but points to the containing "
3130 "host\n", afs_inet_ntoa_r(addr, tmp),
3131 (unsigned)htons(port)));
3139 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3140 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3141 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3148 if (!found && valid) {
3149 afs_inet_ntoa_r(addr, tmp);
3150 if (state->mode == FS_STATE_LOAD_MODE) {
3151 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3152 tmp, (unsigned)htons(port)));
3156 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3157 tmp, (unsigned)htons(port)));
3158 state->flags.warnings_generated = 1;
3167 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3170 struct host *host = NULL;
3171 struct h_UuidHashChain *chain;
3172 afsUUID * uuidp = &h->interface->uuid;
3173 int index = h_UuidHashIndex(uuidp);
3177 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3178 host = chain->hostPtr;
3180 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3181 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3185 if (host->interface &&
3186 afs_uuid_equal(&host->interface->uuid, uuidp)) {
3188 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3189 h->index, host->index));
3190 state->flags.warnings_generated = 1;
3194 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3195 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3196 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3203 /* Fall through, so host not found */
3205 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3206 if (state->mode == FS_STATE_LOAD_MODE) {
3207 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3211 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3212 state->flags.warnings_generated = 1;
3219 /* create the host state header structure */
3221 h_stateFillHeader(struct host_state_header * hdr)
3223 hdr->stamp.magic = HOST_STATE_MAGIC;
3224 hdr->stamp.version = HOST_STATE_VERSION;
3228 /* check the contents of the host state header structure */
3230 h_stateCheckHeader(struct host_state_header * hdr)
3234 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3235 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3238 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3239 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3245 /* allocate the host id mapping table */
3247 h_stateAllocMap(struct fs_dump_state * state)
3249 state->h_map.len = state->h_hdr->index_max + 1;
3250 state->h_map.entries = (struct idx_map_entry_t *)
3251 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3252 return (state->h_map.entries != NULL) ? 0 : 1;
3255 /* function called by h_Enumerate to save a host to disk */
3257 h_stateSaveHost(struct host * host, void* rock)
3259 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3260 int if_len=0, hcps_len=0;
3261 struct hostDiskEntry hdsk;
3262 struct host_state_entry_header hdr;
3263 struct Interface * ifp = NULL;
3264 afs_int32 * hcps = NULL;
3265 struct iovec iov[4];
3268 if (h_isBusy_r(host)) {
3270 ViceLog(1, ("Not saving host %s:%d to disk; host appears busy\n",
3271 afs_inet_ntoa_r(host->host, hoststr), (int)ntohs(host->port)));
3272 /* Make sure we don't try to save callbacks to disk for this host, or
3273 * we'll get confused on restore */
3274 DeleteAllCallBacks_r(host, 1);
3278 memset(&hdr, 0, sizeof(hdr));
3280 if (state->h_hdr->index_max < host->index) {
3281 state->h_hdr->index_max = host->index;
3284 h_hostToDiskEntry_r(host, &hdsk);
3285 if (host->interface) {
3286 if_len = sizeof(struct Interface) +
3287 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3288 ifp = malloc(if_len);
3289 opr_Assert(ifp != NULL);
3290 memcpy(ifp, host->interface, if_len);
3291 hdr.interfaces = host->interface->numberOfInterfaces;
3292 iov[iovcnt].iov_base = (char *) ifp;
3293 iov[iovcnt].iov_len = if_len;
3296 if (host->hcps.prlist_val) {
3297 hdr.hcps = host->hcps.prlist_len;
3298 hcps_len = hdr.hcps * sizeof(afs_int32);
3299 hcps = malloc(hcps_len);
3300 opr_Assert(hcps != NULL);
3301 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3302 iov[iovcnt].iov_base = (char *) hcps;
3303 iov[iovcnt].iov_len = hcps_len;
3307 if (hdsk.index > state->h_hdr->index_max)
3308 state->h_hdr->index_max = hdsk.index;
3310 hdr.len = sizeof(struct host_state_entry_header) +
3311 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3312 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3314 iov[0].iov_base = (char *) &hdr;
3315 iov[0].iov_len = sizeof(hdr);
3316 iov[1].iov_base = (char *) &hdsk;
3317 iov[1].iov_len = sizeof(struct hostDiskEntry);
3319 if (fs_stateWriteV(state, iov, iovcnt)) {
3320 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3324 fs_stateIncEOF(state, hdr.len);
3326 state->h_hdr->records++;
3333 return H_ENUMERATE_BAIL(0);
3338 /* restores a host from disk */
3340 h_stateRestoreHost(struct fs_dump_state * state)
3342 int ifp_len=0, hcps_len=0, bail=0;
3343 struct host_state_entry_header hdr;
3344 struct hostDiskEntry hdsk;
3345 struct host *host = NULL;
3346 struct Interface *ifp = NULL;
3347 afs_int32 * hcps = NULL;
3348 struct iovec iov[3];
3351 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3352 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3358 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3359 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3365 iov[0].iov_base = (char *) &hdsk;
3366 iov[0].iov_len = sizeof(struct hostDiskEntry);
3368 if (hdr.interfaces) {
3369 ifp_len = sizeof(struct Interface) +
3370 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3371 ifp = malloc(ifp_len);
3372 opr_Assert(ifp != NULL);
3373 iov[iovcnt].iov_base = (char *) ifp;
3374 iov[iovcnt].iov_len = ifp_len;
3378 hcps_len = hdr.hcps * sizeof(afs_int32);
3379 hcps = malloc(hcps_len);
3380 opr_Assert(hcps != NULL);
3381 iov[iovcnt].iov_base = (char *) hcps;
3382 iov[iovcnt].iov_len = hcps_len;
3386 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3387 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3392 if (fs_stateReadV(state, iov, iovcnt)) {
3393 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3398 if (!hdr.hcps && hdsk.hcps_valid) {
3399 /* valid, zero-length host cps ; does this ever happen? */
3400 hcps = malloc(sizeof(afs_int32));
3401 opr_Assert(hcps != NULL);
3404 if ((hdsk.hostFlags & HWHO_INPROGRESS) || !(hdsk.hostFlags & ALTADDR)) {
3406 ViceLog(0, ("h_stateRestoreHost: skipping host %s:%d due to invalid flags 0x%x\n",
3407 afs_inet_ntoa_r(hdsk.host, hoststr), (int)ntohs(hdsk.port),
3408 (unsigned)hdsk.hostFlags));
3410 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_SKIPPED;
3414 /* for restoring state, we better be able to get a host! */
3416 opr_Assert(host != NULL);
3419 host->interface = ifp;
3422 host->hcps.prlist_val = hcps;
3423 host->hcps.prlist_len = hdr.hcps;
3426 h_diskEntryToHost_r(&hdsk, host);
3427 h_SetupCallbackConn_r(host);
3429 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3432 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3433 if (ifp->interface[i].valid &&
3434 !(ifp->interface[i].addr == host->host &&
3435 ifp->interface[i].port == host->port)) {
3436 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3437 ifp->interface[i].port,
3441 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3443 h_InsertList_r(host);
3445 /* setup host id map entry */
3446 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_VALID;
3447 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3448 state->h_map.entries[hdsk.index].new_idx = host->index;
3460 /* serialize a host structure to disk */
3462 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3464 out->host = in->host;
3465 out->port = in->port;
3466 out->hostFlags = in->hostFlags;
3467 out->Console = in->Console;
3468 out->hcpsfailed = in->hcpsfailed;
3469 out->LastCall = in->LastCall;
3470 out->ActiveCall = in->ActiveCall;
3471 out->cpsCall = in->cpsCall;
3472 out->cblist = in->cblist;
3473 out->InSameNetwork = in->InSameNetwork;
3475 /* special fields we save, but are not memcpy'd back on restore */
3476 out->index = in->index;
3477 out->hcps_len = in->hcps.prlist_len;
3478 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3481 /* restore a host structure from disk */
3483 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3485 out->host = in->host;
3486 out->port = in->port;
3487 out->hostFlags = in->hostFlags;
3488 out->Console = in->Console;
3489 out->hcpsfailed = in->hcpsfailed;
3490 out->LastCall = in->LastCall;
3491 out->ActiveCall = in->ActiveCall;
3492 out->cpsCall = in->cpsCall;
3493 out->cblist = in->cblist;
3494 out->InSameNetwork = in->InSameNetwork;
3497 /* index translation routines */
3499 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3503 /* hosts use a zero-based index, so old==0 is valid */
3505 if (old >= state->h_map.len) {
3506 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3508 } else if (state->h_map.entries[old].valid != FS_STATE_IDX_VALID ||
3509 state->h_map.entries[old].old_idx != old) { /* sanity check */
3510 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3513 *new = state->h_map.entries[old].new_idx;
3518 #endif /* AFS_DEMAND_ATTACH_FS */
3522 * This counts the number of workstations, the number of active workstations,
3523 * and the number of workstations declared "down" (i.e. not heard from
3524 * recently). An active workstation has received a call since the cutoff
3525 * time argument passed.
3528 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3531 int num = 0, active = 0, del = 0;
3535 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3536 if (!(host->hostFlags & HOSTDELETED)) {
3538 if (host->ActiveCall > cutofftime)
3540 if (host->hostFlags & VENUSDOWN)
3544 if (count != hostCount) {
3545 ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3546 } else if (host != NULL) {
3547 ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3548 ShutDownAndCore(PANIC);
3558 } /*h_GetWorkStats */
3561 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp,
3562 afs_int32 cutofftime)
3564 int num, active, del;
3565 h_GetWorkStats(&num, &active, &del, cutofftime);
3574 /*------------------------------------------------------------------------
3575 * PRIVATE h_ClassifyAddress
3578 * Given a target IP address and a candidate IP address (both
3579 * in host byte order), classify the candidate into one of three
3580 * buckets in relation to the target by bumping the counters passed
3584 * a_targetAddr : Target address.
3585 * a_candAddr : Candidate address.
3586 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3587 * addresses are either in the same network
3588 * or the same subnet.
3589 * a_diffSubnetP : ...when the candidate is in a different
3591 * a_diffNetworkP : ...when the candidate is in a different
3598 * The target and candidate addresses are both in host byte
3599 * order, NOT network byte order, when passed in.
3603 *------------------------------------------------------------------------*/
3606 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3607 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3608 afs_int32 * a_diffNetworkP)
3609 { /*h_ClassifyAddress */
3611 afs_uint32 targetNet;
3612 afs_uint32 targetSubnet;
3614 afs_uint32 candSubnet;
3617 * Put bad values into the subnet info to start with.
3619 targetSubnet = (afs_uint32) 0;
3620 candSubnet = (afs_uint32) 0;
3623 * Pull out the network and subnetwork numbers from the target
3624 * and candidate addresses. We can short-circuit this whole
3625 * affair if the target and candidate addresses are not of the
3628 if (IN_CLASSA(a_targetAddr)) {
3629 if (!(IN_CLASSA(a_candAddr))) {
3630 (*a_diffNetworkP)++;
3633 targetNet = a_targetAddr & IN_CLASSA_NET;
3634 candNet = a_candAddr & IN_CLASSA_NET;
3635 if (IN_SUBNETA(a_targetAddr))
3636 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3637 if (IN_SUBNETA(a_candAddr))
3638 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3639 } else if (IN_CLASSB(a_targetAddr)) {
3640 if (!(IN_CLASSB(a_candAddr))) {
3641 (*a_diffNetworkP)++;
3644 targetNet = a_targetAddr & IN_CLASSB_NET;
3645 candNet = a_candAddr & IN_CLASSB_NET;
3646 if (IN_SUBNETB(a_targetAddr))
3647 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3648 if (IN_SUBNETB(a_candAddr))
3649 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3650 } /*Class B target */
3651 else if (IN_CLASSC(a_targetAddr)) {
3652 if (!(IN_CLASSC(a_candAddr))) {
3653 (*a_diffNetworkP)++;
3656 targetNet = a_targetAddr & IN_CLASSC_NET;
3657 candNet = a_candAddr & IN_CLASSC_NET;
3660 * Note that class C addresses can't have subnets,
3661 * so we leave the defaults untouched.
3663 } /*Class C target */
3665 targetNet = a_targetAddr;
3666 candNet = a_candAddr;
3667 } /*Class D address */
3670 * Now, simply compare the extracted net and subnet values for
3671 * the two addresses (which at this point are known to be of the
3674 if (targetNet == candNet) {
3675 if (targetSubnet == candSubnet)
3676 (*a_sameNetOrSubnetP)++;
3680 (*a_diffNetworkP)++;
3682 } /*h_ClassifyAddress */
3685 /*------------------------------------------------------------------------
3686 * EXPORTED h_GetHostNetStats
3689 * Iterate through the host table, and classify each (non-deleted)
3690 * host entry into ``proximity'' categories (same net or subnet,
3691 * different subnet, different network).
3694 * a_numHostsP : Set to total number of (non-deleted) hosts.
3695 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3696 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3697 * a_diffNetworkP : Set to # hosts on diff network as server.
3703 * We only count non-deleted hosts. The storage pointed to by our
3704 * parameters is zeroed upon entry.
3708 *------------------------------------------------------------------------*/
3711 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3712 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3713 { /*h_GetHostNetStats */
3715 struct host *hostP; /*Ptr to current host entry */
3716 afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3720 * Clear out the storage pointed to by our parameters.
3722 *a_numHostsP = (afs_int32) 0;
3723 *a_sameNetOrSubnetP = (afs_int32) 0;
3724 *a_diffSubnetP = (afs_int32) 0;
3725 *a_diffNetworkP = (afs_int32) 0;
3728 for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3729 if (!(hostP->hostFlags & HOSTDELETED)) {
3731 * Bump the number of undeleted host entries found.
3732 * In classifying the current entry's address, make
3733 * sure to first convert to host byte order.
3736 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3737 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3738 a_sameNetOrSubnetP, a_diffSubnetP,
3740 } /*Only look at non-deleted hosts */
3741 } /*For each host record hashed to this index */
3742 if (count != hostCount) {
3743 ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3744 } else if (hostP != NULL) {
3745 ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3746 ShutDownAndCore(PANIC);
3749 } /*h_GetHostNetStats */
3751 static afs_uint32 checktime;
3752 static afs_uint32 clientdeletetime;
3753 static struct AFSFid zerofid;
3757 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3758 * Since it can serialize them, and pile up, it should be a separate LWP
3759 * from other events.
3763 CheckHost_r(struct host *host, void *dummy)
3765 struct client *client;
3766 struct rx_connection *cb_conn = NULL;
3769 #ifdef AFS_DEMAND_ATTACH_FS
3770 /* kill the checkhost lwp ASAP during shutdown */
3772 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3774 return H_ENUMERATE_BAIL(0);
3779 /* Host is held by h_Enumerate_r */
3780 for (client = host->FirstClient; client; client = client->next) {
3781 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3782 client->deleted = 1;
3783 host->hostFlags |= CLIENTDELETED;
3786 if (host->LastCall < checktime) {
3788 if (!(host->hostFlags & HOSTDELETED)) {
3789 host->hostFlags |= HWHO_INPROGRESS;
3790 cb_conn = host->callback_rxcon;
3791 rx_GetConnection(cb_conn);
3792 if (host->LastCall < clientdeletetime) {
3793 host->hostFlags |= HOSTDELETED;
3794 if (!(host->hostFlags & VENUSDOWN)) {
3795 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3796 if (host->interface) {
3799 RXAFSCB_InitCallBackState3(cb_conn,
3805 RXAFSCB_InitCallBackState(cb_conn);
3808 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3811 (void)afs_inet_ntoa_r(host->host, hoststr);
3813 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3814 hoststr, ntohs(host->port)));
3815 host->hostFlags |= VENUSDOWN;
3817 /* Note: it's safe to delete hosts even if they have call
3818 * back state, because break delayed callbacks (called when a
3819 * message is received from the workstation) will always send a
3820 * break all call backs to the workstation if there is no
3825 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3827 (void)afs_inet_ntoa_r(host->host, hoststr);
3828 if (host->interface) {
3829 afsUUID uuid = host->interface->uuid;
3831 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3834 if (MultiProbeAlternateAddress_r(host)) {
3835 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3836 hoststr, ntohs(host->port), code));
3837 host->hostFlags |= VENUSDOWN;
3842 code = RXAFSCB_Probe(cb_conn);
3846 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3847 hoststr, ntohs(host->port), code));
3848 host->hostFlags |= VENUSDOWN;
3854 rx_PutConnection(cb_conn);
3857 host->hostFlags &= ~HWHO_INPROGRESS;
3867 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3868 * don't respond to a probe. Note that VenusDown can only be cleared if
3869 * a message is received from the host (see ServerLWP in file.c).
3870 * Delete hosts that have not had any calls in 1 hour, clients that
3871 * have not had any calls in 15 minutes.
3873 * This routine is called roughly every 5 minutes.
3878 afs_uint32 now = time(NULL);
3880 memset(&zerofid, 0, sizeof(zerofid));
3882 * Send a probe to the workstation if it hasn't been heard from in
3885 checktime = now - 15 * 60;
3886 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3889 h_Enumerate_r(CheckHost_r, hostList, NULL);
3894 * This is called with host locked and held. At this point, the
3895 * hostAddrHashTable has an entry for the primary addr/port inserted
3896 * by h_Alloc_r(). No other interfaces should be considered valid.
3898 * The addresses in the interfaceAddr list are in host byte order.
3901 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3908 struct Interface *interface;
3911 afs_uint16 port7001 = htons(7001);
3916 number = interf->numberOfInterfaces;
3917 myAddr = host->host; /* current interface address */
3918 myPort = host->port; /* current port */
3921 ("initInterfaceAddr : host %s:%d numAddr %d\n",
3922 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3924 /* validation checks */
3925 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3927 ("Invalid number of alternate addresses is %d\n", number));
3932 * The client's notion of its own IP addresses is not reliable.
3934 * 1. The client list might contain private address ranges which
3935 * are likely to be re-used by many clients allocated addresses
3938 * 2. The client list will not include any public addresses that
3939 * are hidden by a NAT.
3941 * 3. Private address ranges that are exposed to the server will
3942 * be obtained from the rx connections that use them.
3944 * 4. Lists provided by the client are not necessarily truthful.
3945 * Many existing clients (UNIX) do not refresh the IP address
3946 * list as the actual assigned addresses change. The end result
3947 * is that they report the initial address list for the lifetime
3948 * of the process. In other words, a client can report addresses
3949 * that they are in fact not using. Adding these addresses to
3950 * the host interface list without verification is not only
3951 * pointless, it is downright dangerous.
3953 * We therefore do not add alternate addresses to the addr hash table.
3954 * We only use them for multi-rx callback breaks.
3958 * Convert IP addresses to network byte order, and remove
3959 * duplicate and loopback IP addresses from the interface list, and
3960 * determine whether or not the incoming addr/port is
3961 * listed. Note that if the address matches it is not
3962 * truly a match because the port number for the entries
3963 * in the interface list are port 7001 and the port number
3964 * for this connection might not be 7001.
3966 for (i = 0, count = 0, found = 0; i < number; i++) {
3967 if (rx_IsLoopbackAddr(interf->addr_in[i])) {
3970 interf->addr_in[i] = htonl(interf->addr_in[i]);
3971 for (j = 0; j < count; j++) {
3972 if (interf->addr_in[j] == interf->addr_in[i])
3976 interf->addr_in[count] = interf->addr_in[i];
3977 if (interf->addr_in[count] == myAddr &&
3985 * Allocate and initialize an interface structure for this host.
3988 interface = malloc(sizeof(struct Interface) +
3989 (sizeof(struct AddrPort) * (count - 1)));
3991 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
3993 interface->numberOfInterfaces = count;
3995 interface = malloc(sizeof(struct Interface) +
3996 (sizeof(struct AddrPort) * count));
3998 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4000 interface->numberOfInterfaces = count + 1;
4001 interface->interface[count].addr = myAddr;
4002 interface->interface[count].port = myPort;
4003 interface->interface[count].valid = 1;
4006 for (i = 0; i < count; i++) {
4008 interface->interface[i].addr = interf->addr_in[i];
4009 /* We store the port as 7001 because the addresses reported by
4010 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4011 * are coming from fully connected hosts (no NAT/PATs)
4013 interface->interface[i].port = port7001;
4014 interface->interface[i].valid =
4015 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4018 interface->uuid = interf->uuid;
4020 opr_Assert(!host->interface);
4021 host->interface = interface;
4023 h_AddHostToUuidHashTable_r(&interface->uuid, host);
4025 if (LogLevel >= 125) {
4026 afsUUID_to_string(&interface->uuid, uuidstr, 127);
4028 ViceLog(125, ("--- uuid %s\n", uuidstr));
4029 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
4030 ViceLog(125, ("--- alt address %s:%d\n",
4031 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4032 ntohs(host->interface->interface[i].port)));
4039 /* deleted a HashChain structure for this address and host */
4040 /* returns 1 on success */
4042 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4046 struct h_AddrHashChain **hp, *th;
4048 if (addr == 0 && port == 0)
4051 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4053 opr_Assert(th->hostPtr);
4054 if (th->hostPtr == host && th->addr == addr && th->port == port) {
4055 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4056 host, afs_inet_ntoa_r(host->host, hoststr),
4057 ntohs(host->port)));
4064 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4065 host, afs_inet_ntoa_r(host->host, hoststr),
4066 ntohs(host->port)));
4072 ** prints out all alternate interface address for the host. The 'level'
4073 ** parameter indicates what level of debugging sets this output
4076 printInterfaceAddr(struct host *host, int level)
4081 if (host->interface) {
4082 /* check alternate addresses */
4083 number = host->interface->numberOfInterfaces;
4085 ViceLog(level, ("no-addresses "));
4087 for (i = 0; i < number; i++)
4088 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4089 ntohs(host->interface->interface[i].port)));
4092 ViceLog(level, ("\n"));