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;
73 /* arguments for PerHost_EnumerateClient enumeration */
74 struct enumclient_args {
76 int (*proc)(struct client *client, void *rock);
80 static void h_SetupCallbackConn_r(struct host * host);
81 static int h_threadquota(int);
82 static int initInterfaceAddr_r(struct host *, struct interfaceAddr *);
84 #define CESPERBLOCK 73
85 struct CEBlock { /* block of CESPERBLOCK file entries */
86 struct client entry[CESPERBLOCK];
89 void h_TossStuff_r(struct host *host);
92 * Make sure the subnet macros have been defined.
95 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
98 #ifndef IN_CLASSA_SUBNET
99 #define IN_CLASSA_SUBNET 0xffff0000
103 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
106 #ifndef IN_CLASSB_SUBNET
107 #define IN_CLASSB_SUBNET 0xffffff00
111 /* get a new block of CEs and chain it on CEFree */
115 struct CEBlock *block;
118 block = malloc(sizeof(struct CEBlock));
120 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
121 ShutDownAndCore(PANIC);
124 for (i = 0; i < (CESPERBLOCK - 1); i++) {
125 Lock_Init(&block->entry[i].lock);
126 block->entry[i].next = &(block->entry[i + 1]);
128 block->entry[CESPERBLOCK - 1].next = 0;
129 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
130 CEFree = (struct client *)block;
136 /* get the next available CE */
137 static struct client *
140 struct client *entry;
145 ViceLog(0, ("CEFree NULL in GetCE\n"));
146 ShutDownAndCore(PANIC);
150 CEFree = entry->next;
152 memset(entry, 0, CLIENT_TO_ZERO(entry));
158 /* return an entry to the free list */
160 FreeCE(struct client *entry)
162 entry->VenusEpoch = 0;
164 entry->next = CEFree;
171 * The HTs and HTBlocks variables were formerly static, but they are
172 * now referenced elsewhere in the FileServer.
174 int HTs = 0; /* active file entries */
175 int HTBlocks = 0; /* number of blocks of HTs */
176 static struct host *HTFree = 0; /* first free file entry */
179 * Hash tables of host pointers. We need two tables, one
180 * to map IP addresses onto host pointers, and another
181 * to map host UUIDs onto host pointers.
183 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
184 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
185 #define h_HashIndex(hostip) (ntohl(hostip) & (h_HASHENTRIES-1))
186 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
188 struct HTBlock { /* block of HTSPERBLOCK file entries */
189 struct host entry[h_HTSPERBLOCK];
193 /* get a new block of HTs and chain it on HTFree */
197 struct HTBlock *block;
199 static int index = 0;
201 if (HTBlocks == h_MAXHOSTTABLES) {
202 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
206 block = malloc(sizeof(struct HTBlock));
208 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
209 ShutDownAndCore(PANIC);
211 for (i = 0; i < (h_HTSPERBLOCK); i++)
212 opr_cv_init(&block->entry[i].cond);
213 for (i = 0; i < (h_HTSPERBLOCK); i++)
214 Lock_Init(&block->entry[i].lock);
215 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
216 block->entry[i].next = &(block->entry[i + 1]);
217 for (i = 0; i < (h_HTSPERBLOCK); i++)
218 block->entry[i].index = index++;
219 block->entry[h_HTSPERBLOCK - 1].next = 0;
220 HTFree = (struct host *)block;
221 hosttableptrs[HTBlocks++] = block->entry;
226 /* get the next available HT */
237 HTFree = entry->next;
239 memset(entry, 0, HOST_TO_ZERO(entry));
245 /* return an entry to the free list */
247 FreeHT(struct host *entry)
249 entry->next = HTFree;
256 hpr_Initialize(struct ubik_client **uclient)
259 struct rx_connection *serverconns[MAXSERVERS];
260 struct rx_securityClass *sc;
261 struct afsconf_dir *tdir;
263 struct afsconf_cell info;
267 tdir = afsconf_Open(FS_configPath);
270 ("hpr_Initialize: Could not open configuration directory: %s",
275 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
277 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
282 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
284 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s",
285 cellstr, tdir->name, AFSDIR_CELLSERVDB_FILE));
292 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
297 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
298 * to force use of the KeyFile. secLevel == 0 implies -noauth was
300 code = afsconf_ClientAuthSecure(tdir, &sc, &scIndex);
302 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s "
303 "(so trying noauth)", code, afs_error_message(code)));
304 scIndex = RX_SECIDX_NULL;
305 sc = rxnull_NewClientSecurityObject();
308 if (scIndex == RX_SECIDX_NULL)
309 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, "
310 "running unauthenticated. [%d]", code));
312 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
313 for (i = 0; i < info.numServers; i++) {
315 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
316 info.hostAddr[i].sin_port, PRSRV,
320 code = ubik_ClientInit(serverconns, uclient);
322 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
325 code = rxs_Release(sc);
330 hpr_End(struct ubik_client *uclient)
335 code = ubik_ClientDestroy(uclient);
341 getThreadClient(struct ubik_client **client)
345 *client = pthread_getspecific(viced_uclient_key);
349 code = hpr_Initialize(client);
353 opr_Verify(pthread_setspecific(viced_uclient_key, *client) == 0);
359 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
363 struct ubik_client *uclient;
365 code = getThreadClient(&uclient);
370 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
371 if (code != PRSUCCESS)
374 /* do something about this, probably make a new call */
375 /* don't forget there's a hard limit in the interface */
377 "membership list for host id %d exceeds display limit\n",
384 hpr_NameToId(namelist *names, idlist *ids)
388 struct ubik_client *uclient;
390 code = getThreadClient(&uclient);
394 for (i = 0; i < names->namelist_len; i++)
395 stolower(names->namelist_val[i]);
396 code = ubik_PR_NameToID(uclient, 0, names, ids);
401 hpr_IdToName(idlist *ids, namelist *names)
404 struct ubik_client *uclient;
406 code = getThreadClient(&uclient);
410 code = ubik_PR_IDToName(uclient, 0, ids, names);
415 hpr_GetCPS(afs_int32 id, prlist *CPS)
419 struct ubik_client *uclient;
421 code = getThreadClient(&uclient);
426 code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
427 if (code != PRSUCCESS)
430 /* do something about this, probably make a new call */
431 /* don't forget there's a hard limit in the interface */
432 fprintf(stderr, "membership list for id %d exceeds display limit\n",
438 static short consolePort = 0;
441 h_Lock_r(struct host *host)
451 * returns 1 if already locked
452 * else returns locks and returns 0
456 h_NBLock_r(struct host *host)
458 struct Lock *hostLock = &host->lock;
463 if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
464 hostLock->excl_locked = WRITE_LOCK;
468 LOCK_UNLOCK(hostLock);
477 /*------------------------------------------------------------------------
478 * PRIVATE h_AddrInSameNetwork
481 * Given a target IP address and a candidate IP address (both
482 * in host byte order), return a non-zero value (1) if the
483 * candidate address is in a different network from the target
487 * a_targetAddr : Target address.
488 * a_candAddr : Candidate address.
491 * 1 if the candidate address is in the same net as the target,
495 * The target and candidate addresses are both in host byte
496 * order, NOT network byte order, when passed in. We return
497 * our value as a character, since that's the type of field in
498 * the host structure, where this info will be stored.
502 *------------------------------------------------------------------------*/
505 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
506 { /*h_AddrInSameNetwork */
508 afs_uint32 targetNet;
512 * Pull out the network and subnetwork numbers from the target
513 * and candidate addresses. We can short-circuit this whole
514 * affair if the target and candidate addresses are not of the
517 if (IN_CLASSA(a_targetAddr)) {
518 if (!(IN_CLASSA(a_candAddr))) {
521 targetNet = a_targetAddr & IN_CLASSA_NET;
522 candNet = a_candAddr & IN_CLASSA_NET;
523 } else if (IN_CLASSB(a_targetAddr)) {
524 if (!(IN_CLASSB(a_candAddr))) {
527 targetNet = a_targetAddr & IN_CLASSB_NET;
528 candNet = a_candAddr & IN_CLASSB_NET;
529 } /*Class B target */
530 else if (IN_CLASSC(a_targetAddr)) {
531 if (!(IN_CLASSC(a_candAddr))) {
534 targetNet = a_targetAddr & IN_CLASSC_NET;
535 candNet = a_candAddr & IN_CLASSC_NET;
536 } /*Class C target */
538 targetNet = a_targetAddr;
539 candNet = a_candAddr;
540 } /*Class D address */
543 * Now, simply compare the extracted net values for the two addresses
544 * (which at this point are known to be of the same class)
546 if (targetNet == candNet)
551 } /*h_AddrInSameNetwork */
554 /* Assumptions: called with held host */
556 h_gethostcps_r(struct host *host, afs_int32 now)
561 /* wait if somebody else is already doing the getCPS call */
562 while (host->hostFlags & HCPS_INPROGRESS) {
563 slept = 1; /* I did sleep */
564 host->hostFlags |= HCPS_WAITING; /* I am sleeping now */
565 opr_cv_wait(&host->cond, &host_glock_mutex);
569 host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
570 if (host->hcps.prlist_val)
571 free(host->hcps.prlist_val); /* this is for hostaclRefresh */
572 host->hcps.prlist_val = NULL;
573 host->hcps.prlist_len = 0;
574 host->cpsCall = slept ? time(NULL) : (now);
577 code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
582 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
583 * and reevaluates things if no sync server or quorum is found we could still end up
584 * with one of these errors. In such case we would like to reevaluate the rpc call to
585 * find if there's cps for this guy. We treat other errors (except network failures
586 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
587 * we could like to deal this problem the other way around (i.e. if code == NOCPS
588 * ignore else retry next time) but the problem is that there're other errors (i.e.
589 * EPERM) for which we don't want to retry and we don't know the whole code list!
591 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
593 * We would have preferred to use a while loop and try again since ops in protected
594 * acls for this host will fail now but they'll be reevaluated on any subsequent
595 * call. The attempt to wait for a quorum/sync site or network error won't work
596 * since this problems really should only occurs during a complete fileserver
597 * restart. Since the fileserver will start before the ptservers (and thus before
598 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
600 host->hcpsfailed = 1;
602 ("Warning: GetHostCPS failed (%d) for %p (%s:%d); will retry\n",
603 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
605 host->hcpsfailed = 0;
607 ("gethost: GetHostCPS failed (%d) for %p (%s:%d); ignored\n",
608 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
610 if (host->hcps.prlist_val)
611 free(host->hcps.prlist_val);
612 host->hcps.prlist_val = NULL;
613 host->hcps.prlist_len = 0; /* Make sure it's zero */
615 host->hcpsfailed = 0;
617 host->hostFlags &= ~HCPS_INPROGRESS;
618 /* signal all who are waiting */
619 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
620 host->hostFlags &= ~HCPS_WAITING;
621 opr_cv_broadcast(&host->cond);
625 /* args in net byte order */
627 h_flushhostcps(afs_uint32 hostaddr, afs_uint16 hport)
632 h_Lookup_r(hostaddr, hport, &host);
634 host->hcpsfailed = 1;
643 * Allocate a host. It will be identified by the peer (ip,port) info in the
644 * rx connection provided. The host is returned held and locked
646 #define DEF_ROPCONS 2115
649 h_Alloc_r(struct rx_connection *r_con)
651 struct servent *serverentry;
653 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
660 /* acquire the host lock withot dropping H_LOCK. we can do this here
661 * because we know we will not block; we just created this host and
662 * nobody else knows about it. */
663 ObtainWriteLock(&host->lock);
665 host->host = rxr_HostOf(r_con);
666 host->port = rxr_PortOf(r_con);
668 h_AddHostToAddrHashTable_r(host->host, host->port, host);
670 if (consolePort == 0) { /* find the portal number for console */
671 #if defined(AFS_OSF_ENV)
672 serverentry = getservbyname("ropcons", "");
674 serverentry = getservbyname("ropcons", 0);
677 consolePort = serverentry->s_port;
679 consolePort = htons(DEF_ROPCONS); /* Use a default */
681 if (host->port == consolePort)
683 /* Make a callback channel even for the console, on the off chance that it
684 * makes a request that causes a break call back. It shouldn't. */
685 h_SetupCallbackConn_r(host);
686 host->LastCall = host->cpsCall = host->ActiveCall = time(NULL);
688 host->hcps.prlist_val = NULL;
689 host->hcps.prlist_len = 0;
690 host->interface = NULL;
692 host->hcpsfailed = 0; /* save cycles */
693 h_gethostcps(host); /* do this under host hold/lock */
695 host->FirstClient = NULL;
696 h_InsertList_r(host); /* update global host List */
698 * Compare the new host's IP address (in host byte order) with ours
699 * (the File Server's), remembering if they are in the same network.
701 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
702 host->InSameNetwork =
703 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
710 /* Make a callback channel even for the console, on the off chance that it
711 * makes a request that causes a break call back. It shouldn't. */
713 h_SetupCallbackConn_r(struct host * host)
716 sc = rxnull_NewClientSecurityObject();
717 host->callback_rxcon =
718 rx_NewConnection(host->host, host->port, 1, sc, 0);
719 rx_SetConnDeadTime(host->callback_rxcon, 50);
720 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
721 rx_SetConnSecondsUntilNatPing(host->callback_rxcon, 20);
725 * Lookup a host given an IP address and UDP port number.
726 * hostaddr and hport are in network order
727 * hostaddr and hport are in network order
728 * On return, refCount is incremented.
731 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, struct host **hostp)
734 struct host *host = NULL;
735 struct h_AddrHashChain *chain;
736 int index = h_HashIndex(haddr);
737 extern int hostaclRefresh;
740 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
741 host = chain->hostPtr;
743 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
744 && chain->port == hport) {
745 if ((host->hostFlags & HWHO_INPROGRESS) &&
746 h_threadquota(host->lock.num_waiting)) {
752 if (host->hostFlags & HOSTDELETED) {
759 now = time(NULL); /* always evaluate "now" */
760 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
762 * Every hostaclRefresh period (def 2 hrs) get the new
763 * membership list for the host. Note this could be the
764 * first time that the host is added to a group. Also
765 * here we also retry on previous legitimate hcps failures.
767 * If we get here refCount is elevated.
769 h_gethostcps_r(host, now);
779 /* Lookup a host given its UUID. */
781 h_LookupUuid_r(afsUUID * uuidp)
783 struct host *host = 0;
784 struct h_UuidHashChain *chain;
785 int index = h_UuidHashIndex(uuidp);
787 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
788 host = chain->hostPtr;
790 if (!(host->hostFlags & HOSTDELETED) && host->interface
791 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
799 /* h_TossStuff_r: Toss anything in the host structure (the host or
800 * clients marked for deletion. Called from h_Release_r ONLY.
801 * To be called, there must be no holds, and either host->deleted
802 * or host->clientDeleted must be set.
805 h_TossStuff_r(struct host *host)
807 struct client **cp, *client;
811 if ((host->hostFlags & HOSTDELETED)) {
815 /* make sure host doesn't go away over h_NBLock_r */
818 code = h_NBLock_r(host);
820 /* don't use h_Release_r, since that may call h_TossStuff_r again */
823 /* if somebody still has this host locked */
827 /* someone locked the host while HOSTDELETED was set; that is bad */
828 ViceLog(0, ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT
829 " (%s:%d flags 0x%x) was locked.\n",
830 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
831 (unsigned)host->hostFlags));
838 /* if somebody still has this host held */
839 /* we must check this _after_ h_NBLock_r, since h_NBLock_r can drop and
840 * reacquire H_LOCK */
841 if (host->refCount > 0) {
844 /* someone grabbed a ref while HOSTDELETED was set; that is bad */
845 ViceLog(0, ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT
846 " (%s:%d flags 0x%x) was held.\n",
847 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
848 (unsigned)host->hostFlags));
853 /* ASSUMPTION: rxi_FreeConnection() does not yield */
854 for (cp = &host->FirstClient; (client = *cp);) {
855 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
857 ObtainWriteLockNoBlock(&client->lock, code);
861 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
862 "client %p was locked.\n",
863 host, afs_inet_ntoa_r(host->host, hoststr),
864 ntohs(host->port), client));
868 if (client->refCount) {
871 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
872 "client %p refcount %d.\n",
873 host, afs_inet_ntoa_r(host->host, hoststr),
874 ntohs(host->port), client, client->refCount));
875 /* This is the same thing we do if the host is locked */
876 ReleaseWriteLock(&client->lock);
879 client->CPS.prlist_len = 0;
880 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
881 free(client->CPS.prlist_val);
882 client->CPS.prlist_val = NULL;
883 CurrentConnections--;
885 ReleaseWriteLock(&client->lock);
891 /* We've just cleaned out all the deleted clients; clear the flag */
892 host->hostFlags &= ~CLIENTDELETED;
894 if (host->hostFlags & HOSTDELETED) {
895 struct rx_connection *rxconn;
896 struct AddrPort hostAddrPort;
899 if (host->Console & 1)
901 if ((rxconn = host->callback_rxcon)) {
902 host->callback_rxcon = (struct rx_connection *)0;
903 rx_DestroyConnection(rxconn);
905 if (host->hcps.prlist_val)
906 free(host->hcps.prlist_val);
907 host->hcps.prlist_val = NULL;
908 host->hcps.prlist_len = 0;
909 DeleteAllCallBacks_r(host, 1);
910 host->hostFlags &= ~RESETDONE; /* just to be safe */
912 /* if alternate addresses do not exist */
913 if (!(host->interface)) {
914 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
916 h_DeleteHostFromUuidHashTable_r(host);
917 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
918 /* delete the hash entry for each valid alternate addresses */
919 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
920 hostAddrPort = host->interface->interface[i];
922 * if the interface addr/port is the primary, we already
923 * removed it. If the addr/port is not valid, its not
926 if (hostAddrPort.valid &&
927 (host->host != hostAddrPort.addr ||
928 host->port != hostAddrPort.port))
929 h_DeleteHostFromAddrHashTable_r(hostAddrPort.addr, hostAddrPort.port, host);
931 free(host->interface);
932 host->interface = NULL;
933 } /* if alternate address exists */
935 h_DeleteList_r(host); /* remove host from global host List */
942 /* h_Enumerate: Calls (*proc)(host, param) for at least each host in the
943 * system at the start of the enumeration (perhaps more). Hosts may be deleted
944 * (have delete flag set); ditto for clients. refCount is always incremented
945 * before (*proc) is called.
947 * The return value of the proc is a set of flags. The proc should set
948 * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
951 h_Enumerate(int (*proc) (struct host*, void *), void *param)
953 struct host *host, **list;
958 if (hostCount == 0) {
962 list = malloc(hostCount * sizeof(struct host *));
964 ViceLogThenPanic(0, ("Failed malloc in h_Enumerate (list)\n"));
966 for (totalCount = count = 0, host = hostList;
967 host && totalCount < hostCount;
968 host = host->next, totalCount++) {
970 if (!(host->hostFlags & HOSTDELETED)) {
976 if (totalCount != hostCount) {
977 ViceLog(0, ("h_Enumerate found %d of %d hosts\n", totalCount, hostCount));
978 } else if (host != NULL) {
979 ViceLog(0, ("h_Enumerate found more than %d hosts\n", hostCount));
980 ShutDownAndCore(PANIC);
983 for (i = 0; i < count; i++) {
985 flags = (*proc) (list[i], param);
987 h_Release_r(list[i]);
989 /* bail out of the enumeration early */
990 if (H_ENUMERATE_ISSET_BAIL(flags)) {
993 ViceLog(0, ("h_Enumerate got back invalid return value %d\n", flags));
994 ShutDownAndCore(PANIC);
998 /* we bailed out of enumerating hosts early; we still have holds on
999 * some of the hosts in 'list', so release them */
1002 for ( ; i < count; i++) {
1003 h_Release_r(list[i]);
1011 /* h_Enumerate_r (revised):
1012 * Calls (*proc)(host, param) for each host in hostList, starting
1013 * at enumstart. Called only under H_LOCK. Hosts may be deleted (have
1014 * delete flag set); ditto for clients. refCount is always incremented
1015 * before (*proc) is called.
1017 * @note Assumes that hostList is only prepended to, that a host is never
1018 * inserted into the middle. Otherwise this would not be guaranteed to
1021 * The return value of the proc is a set of flags. The proc should set
1022 * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
1025 h_Enumerate_r(int (*proc) (struct host *, void *),
1026 struct host *enumstart, void *param)
1028 struct host *host, *next;
1032 if (hostCount == 0) {
1039 /* find the first non-deleted host, so we know where to actually start
1041 for (count = 0; host && count < hostCount; count++) {
1042 if (!(host->hostFlags & HOSTDELETED)) {
1049 /* we didn't find a non-deleted host... */
1051 if (host && count >= hostCount) {
1052 /* ...because we found a loop */
1053 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", hostCount));
1054 ShutDownAndCore(PANIC);
1057 /* ...because the hostList is full of deleted hosts */
1061 h_Hold_r(enumstart);
1063 /* remember hostCount, lest it change over the potential H_LOCK drop in
1065 origHostCount = hostCount;
1067 for (count = 0, host = enumstart; host && count < origHostCount; host = next, count++) {
1070 /* find the next non-deleted host */
1071 while (next && (next->hostFlags & HOSTDELETED)) {
1073 /* inc count for the skipped-over host */
1074 if (++count > origHostCount) {
1075 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1076 ShutDownAndCore(PANIC);
1082 if (!(host->hostFlags & HOSTDELETED)) {
1084 flags = (*proc) (host, param);
1085 if (H_ENUMERATE_ISSET_BAIL(flags)) {
1086 h_Release_r(host); /* this might free up the host */
1092 ViceLog(0, ("h_Enumerate_r got back invalid return value %d\n", flags));
1093 ShutDownAndCore(PANIC);
1096 h_Release_r(host); /* this might free up the host */
1098 if (host != NULL && count >= origHostCount) {
1099 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1100 ShutDownAndCore(PANIC);
1102 } /*h_Enumerate_r */
1105 /* inserts a new HashChain structure corresponding to this UUID */
1107 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1110 struct h_UuidHashChain *chain;
1111 char uuid1[128], uuid2[128];
1114 /* hash into proper bucket */
1115 index = h_UuidHashIndex(uuid);
1117 /* don't add the same entry multiple times */
1118 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1119 if (!chain->hostPtr)
1122 if (chain->hostPtr->interface &&
1123 afs_uuid_equal(&chain->hostPtr->interface->uuid, uuid)) {
1124 if (LogLevel >= 125) {
1125 afsUUID_to_string(&chain->hostPtr->interface->uuid, uuid1,
1127 afsUUID_to_string(uuid, uuid2, 127);
1128 ViceLog(125, ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s) exists as %s:%d (uuid %s)\n",
1130 afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1131 ntohs(chain->hostPtr->port), uuid2));
1137 /* insert into beginning of list for this bucket */
1138 chain = malloc(sizeof(struct h_UuidHashChain));
1140 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1142 chain->hostPtr = host;
1143 chain->next = hostUuidHashTable[index];
1144 hostUuidHashTable[index] = chain;
1147 afsUUID_to_string(uuid, uuid2, 127);
1149 ("h_AddHostToUuidHashTable_r: host %p (%s:%d) added as uuid %s\n",
1150 host, afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1151 ntohs(chain->hostPtr->port), uuid2));
1154 /* deletes a HashChain structure corresponding to this host */
1156 h_DeleteHostFromUuidHashTable_r(struct host *host)
1159 struct h_UuidHashChain **uhp, *uth;
1163 if (!host->interface)
1166 /* hash into proper bucket */
1167 index = h_UuidHashIndex(&host->interface->uuid);
1169 if (LogLevel >= 125)
1170 afsUUID_to_string(&host->interface->uuid, uuid1, 127);
1171 for (uhp = &hostUuidHashTable[index]; (uth = *uhp); uhp = &uth->next) {
1172 opr_Assert(uth->hostPtr);
1173 if (uth->hostPtr == host) {
1175 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d)\n",
1176 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1177 ntohs(host->port)));
1184 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d) not found\n",
1185 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1186 ntohs(host->port)));
1191 * This is called with host locked and held.
1193 * All addresses are in network byte order.
1196 invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1200 struct Interface *interface;
1201 char hoststr[16], hoststr2[16];
1204 opr_Assert(host->interface);
1206 ViceLog(125, ("invalidateInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1207 host, afs_inet_ntoa_r(host->host, hoststr),
1208 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1212 * Make sure this address is on the list of known addresses
1215 interface = host->interface;
1216 number = host->interface->numberOfInterfaces;
1217 for (i = 0; i < number; i++) {
1218 if (interface->interface[i].addr == addr &&
1219 interface->interface[i].port == port) {
1220 if (interface->interface[i].valid) {
1221 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1222 interface->interface[i].valid = 0;
1233 * This is called with host locked and held. This function differs
1234 * from removeInterfaceAddr_r in that it is called when the address
1235 * is being removed from the host regardless of whether or not there
1236 * is an interface list for the host. This function will delete the
1237 * host if there are no addresses left on it.
1239 * All addresses are in network byte order.
1242 removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1245 char hoststr[16], hoststr2[16];
1246 struct rx_connection *rxconn;
1248 if (!host->interface || host->interface->numberOfInterfaces == 1) {
1249 if (host->host == addr && host->port == port) {
1251 ("Removing only address for host %" AFS_PTR_FMT " (%s:%d), deleting host.\n",
1252 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1253 host->hostFlags |= HOSTDELETED;
1255 * Do not remove the primary addr/port from the hash table.
1256 * It will be ignored due to the HOSTDELETED flag and will
1257 * be removed when h_TossStuff_r() cleans up the HOSTDELETED
1258 * host. Removing it here will only result in a search for
1259 * the host/addr/port in the hash chain which will fail.
1263 ("Removing address that does not belong to host %" AFS_PTR_FMT " (%s:%d).\n",
1264 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1267 if (host->host == addr && host->port == port) {
1268 removeInterfaceAddr_r(host, addr, port);
1270 for (i=0; i < host->interface->numberOfInterfaces; i++) {
1271 if (host->interface->interface[i].valid) {
1273 ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
1274 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1275 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
1276 ntohs(host->interface->interface[i].port)));
1277 host->host = host->interface->interface[i].addr;
1278 host->port = host->interface->interface[i].port;
1279 h_AddHostToAddrHashTable_r(host->host, host->port, host);
1284 if (i == host->interface->numberOfInterfaces) {
1286 ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
1287 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1288 host->hostFlags |= HOSTDELETED;
1289 /* addr/port was removed from the hash table */
1293 rxconn = host->callback_rxcon;
1294 host->callback_rxcon = NULL;
1297 rx_DestroyConnection(rxconn);
1301 h_SetupCallbackConn_r(host);
1304 /* not the primary addr/port, just invalidate it */
1305 invalidateInterfaceAddr_r(host, addr, port);
1313 createHostAddrHashChain_r(int index, afs_uint32 addr, afs_uint16 port, struct host *host)
1315 struct h_AddrHashChain *chain;
1318 /* insert into beginning of list for this bucket */
1319 chain = malloc(sizeof(struct h_AddrHashChain));
1321 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToAddrHashTable_r\n"));
1323 chain->hostPtr = host;
1324 chain->next = hostAddrHashTable[index];
1327 hostAddrHashTable[index] = chain;
1328 ViceLog(125, ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " added as %s:%d\n",
1329 host, afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1333 * Resolve host address conflicts when hashing by address.
1335 * @param[in] addr an ip address of the interface
1336 * @param[in] port the port of the interface
1337 * @param[in] newHost the host being added with this address
1338 * @param[in] oldHost the host previously added with this address
1341 reconcileHosts_r(afs_uint32 addr, afs_uint16 port, struct host *newHost,
1342 struct host *oldHost)
1344 struct rx_connection *cb = NULL;
1346 struct interfaceAddr interf;
1348 afsUUID *newHostUuid = &nulluuid;
1349 afsUUID *oldHostUuid = &nulluuid;
1353 ("reconcileHosts_r: addr %s:%d newHost %" AFS_PTR_FMT " oldHost %"
1354 AFS_PTR_FMT, afs_inet_ntoa_r(addr, hoststr), ntohs(port),
1357 opr_Assert(oldHost != newHost);
1358 caps.Capabilities_val = NULL;
1361 sc = rxnull_NewClientSecurityObject();
1364 cb = rx_NewConnection(addr, port, 1, sc, 0);
1365 rx_SetConnDeadTime(cb, 50);
1366 rx_SetConnHardDeadTime(cb, AFS_HARDDEADTIME);
1371 code = RXAFSCB_TellMeAboutYourself(cb, &interf, &caps);
1372 if (code == RXGEN_OPCODE) {
1373 code = RXAFSCB_WhoAreYou(cb, &interf);
1377 if (code == RXGEN_OPCODE ||
1378 (code == 0 && afs_uuid_equal(&interf.uuid, &nulluuid))) {
1380 ("reconcileHosts_r: WhoAreYou not supported for connection (%s:%d), error %d\n",
1381 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1386 ("reconcileHosts_r: WhoAreYou failed for connection (%s:%d), error %d\n",
1387 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1391 /* Since lock was dropped, the hosts may have been deleted during the rpcs. */
1392 if ((newHost->hostFlags & HOSTDELETED)
1393 && (oldHost->hostFlags & HOSTDELETED)) {
1395 ("reconcileHosts_r: new and old hosts were deleted during probe.\n"));
1399 /* A check can be done if at least one of the hosts has a uuid. It
1400 * is an error if the hosts have the same (not null) uuid. */
1401 if ((!(newHost->hostFlags & HOSTDELETED)) && newHost->interface) {
1402 newHostUuid = &(newHost->interface->uuid);
1404 if ((!(oldHost->hostFlags & HOSTDELETED)) && oldHost->interface) {
1405 oldHostUuid = &(oldHost->interface->uuid);
1407 if (afs_uuid_equal(newHostUuid, &nulluuid) &&
1408 afs_uuid_equal(oldHostUuid, &nulluuid)) {
1410 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), no uuids\n",
1411 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1414 if (afs_uuid_equal(newHostUuid, oldHostUuid)) {
1416 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), same uuids\n",
1417 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1421 /* Determine which host should be hashed */
1422 if ((!(newHost->hostFlags & HOSTDELETED))
1423 && afs_uuid_equal(newHostUuid, &(interf.uuid))) {
1424 /* Install the new host into the hash before removing the stale
1425 * addresses. Walk the hash chain again since the hash table may have
1426 * been changed when the host lock was dropped to get the uuid. */
1427 struct h_AddrHashChain *chain;
1428 int index = h_HashIndex(addr);
1429 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1430 if (chain->addr == addr && chain->port == port) {
1431 chain->hostPtr = newHost;
1432 removeAddress_r(oldHost, addr, port);
1436 createHostAddrHashChain_r(index, addr, port, newHost);
1437 removeAddress_r(oldHost, addr, port);
1440 if ((!(oldHost->hostFlags & HOSTDELETED))
1441 && afs_uuid_equal(oldHostUuid, &(interf.uuid))) {
1442 removeAddress_r(newHost, addr, port);
1447 if (!(newHost->hostFlags & HOSTDELETED)) {
1448 removeAddress_r(newHost, addr, port);
1450 if (!(oldHost->hostFlags & HOSTDELETED)) {
1451 removeAddress_r(oldHost, addr, port);
1455 h_Release_r(newHost);
1456 h_Release_r(oldHost);
1457 rx_DestroyConnection(cb);
1461 /* inserts a new HashChain structure corresponding to this address */
1463 h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1466 struct h_AddrHashChain *chain;
1469 /* hash into proper bucket */
1470 index = h_HashIndex(addr);
1472 /* don't add the same address:port pair entry multiple times */
1473 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1474 if (chain->addr == addr && chain->port == port) {
1475 if (chain->hostPtr == host) {
1477 ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
1478 host, afs_inet_ntoa_r(chain->addr, hoststr),
1479 ntohs(chain->port)));
1482 if (!(chain->hostPtr->hostFlags & HOSTDELETED)) {
1483 /* attempt to resolve host address collision */
1484 reconcileHosts_r(addr, port, host, chain->hostPtr);
1489 createHostAddrHashChain_r(index, addr, port, host);
1493 * This is called with host locked and held.
1494 * It is called to either validate or add an additional interface
1495 * address/port on the specified host.
1497 * All addresses are in network byte order.
1500 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1504 struct Interface *interface;
1505 char hoststr[16], hoststr2[16];
1508 opr_Assert(host->interface);
1511 * Make sure this address is on the list of known addresses
1514 number = host->interface->numberOfInterfaces;
1515 for (i = 0; i < number; i++) {
1516 if (host->interface->interface[i].addr == addr &&
1517 host->interface->interface[i].port == port) {
1519 ("addInterfaceAddr : found host %" AFS_PTR_FMT " (%s:%d) adding %s:%d%s\n",
1520 host, afs_inet_ntoa_r(host->host, hoststr),
1521 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1522 ntohs(port), host->interface->interface[i].valid ? "" :
1525 if (host->interface->interface[i].valid == 0) {
1526 host->interface->interface[i].valid = 1;
1527 h_AddHostToAddrHashTable_r(addr, port, host);
1533 ViceLog(125, ("addInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) adding %s:%d\n",
1534 host, afs_inet_ntoa_r(host->host, hoststr),
1535 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1538 interface = malloc(sizeof(struct Interface)
1539 + (sizeof(struct AddrPort) * number));
1541 ViceLogThenPanic(0, ("Failed malloc in addInterfaceAddr_r\n"));
1543 interface->numberOfInterfaces = number + 1;
1544 interface->uuid = host->interface->uuid;
1545 for (i = 0; i < number; i++)
1546 interface->interface[i] = host->interface->interface[i];
1548 /* Add the new valid interface */
1549 interface->interface[number].addr = addr;
1550 interface->interface[number].port = port;
1551 interface->interface[number].valid = 1;
1552 h_AddHostToAddrHashTable_r(addr, port, host);
1553 free(host->interface);
1554 host->interface = interface;
1561 * This is called with host locked and held.
1563 * All addresses are in network byte order.
1566 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1570 struct Interface *interface;
1571 char hoststr[16], hoststr2[16];
1574 opr_Assert(host->interface);
1576 ViceLog(125, ("removeInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1577 host, afs_inet_ntoa_r(host->host, hoststr),
1578 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1582 * Make sure this address is on the list of known addresses
1585 interface = host->interface;
1586 number = host->interface->numberOfInterfaces;
1587 for (i = 0; i < number; i++) {
1588 if (interface->interface[i].addr == addr &&
1589 interface->interface[i].port == port) {
1590 if (interface->interface[i].valid)
1591 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1593 for (; i < number; i++) {
1594 interface->interface[i] = interface->interface[i+1];
1596 interface->numberOfInterfaces = number;
1607 h_threadquota(int waiting)
1612 } else if (lwps > 32) {
1615 } else if (lwps > 16) {
1625 /* If found, host is returned with refCount incremented */
1627 h_GetHost_r(struct rx_connection *tcon)
1630 struct host *oldHost;
1632 struct interfaceAddr interf;
1633 int interfValid = 0;
1634 struct Identity *identP = NULL;
1637 char hoststr[16], hoststr2[16];
1639 struct rx_connection *cb_conn = NULL;
1640 struct rx_connection *cb_in = NULL;
1642 caps.Capabilities_val = NULL;
1644 haddr = rxr_HostOf(tcon);
1645 hport = rxr_PortOf(tcon);
1648 rx_DestroyConnection(cb_in);
1651 if (caps.Capabilities_val)
1652 free(caps.Capabilities_val);
1653 caps.Capabilities_val = NULL;
1654 caps.Capabilities_len = 0;
1657 if (h_Lookup_r(haddr, hport, &host))
1659 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1660 if (host && !identP && !(host->Console & 1)) {
1661 /* This is a new connection, and we already have a host
1662 * structure for this address. Verify that the identity
1663 * of the caller matches the identity in the host structure.
1665 if ((host->hostFlags & HWHO_INPROGRESS) &&
1666 h_threadquota(host->lock.num_waiting)) {
1672 if (!(host->hostFlags & ALTADDR) ||
1673 (host->hostFlags & HOSTDELETED)) {
1674 /* Another thread is doing initialization
1675 * or this host was deleted while we
1676 * waited for the lock. */
1679 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1680 host, afs_inet_ntoa_r(host->host, hoststr),
1681 ntohs(host->port)));
1685 host->hostFlags |= HWHO_INPROGRESS;
1686 host->hostFlags &= ~ALTADDR;
1688 /* We received a new connection from an IP address/port
1689 * that is associated with 'host' but the address/port of
1690 * the callback connection does not have to match it.
1691 * If there is a match, we can use the existing callback
1692 * connection to verify the UUID. If they do not match
1693 * we need to use a new callback connection to verify the
1694 * UUID of the incoming caller and perhaps use the old
1695 * callback connection to verify that the old address/port
1699 cb_conn = host->callback_rxcon;
1700 rx_GetConnection(cb_conn);
1702 if (haddr == host->host && hport == host->port) {
1703 /* The existing callback connection matches the
1704 * incoming connection so just use it.
1707 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1708 if (code == RXGEN_OPCODE)
1709 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1711 /* We do not have a match. Create a new connection
1712 * for the new addr/port and use multi_Rx to probe
1713 * both of them simultaneously.
1716 sc = rxnull_NewClientSecurityObject();
1717 cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1718 rx_SetConnDeadTime(cb_in, 50);
1719 rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1720 rx_SetConnSecondsUntilNatPing(cb_in, 20);
1723 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1724 if (code == RXGEN_OPCODE)
1725 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1727 rx_PutConnection(cb_conn);
1730 if ((code == RXGEN_OPCODE) ||
1731 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1732 identP = malloc(sizeof(struct Identity));
1734 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1737 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1738 if (cb_in == NULL) {
1739 /* The host on this connection was unable to respond to
1740 * the WhoAreYou. We will treat this as a new connection
1741 * from the existing host. The worst that can happen is
1742 * that we maintain some extra callback state information */
1743 if (host->interface) {
1745 ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1747 afs_inet_ntoa_r(host->host, hoststr),
1748 ntohs(host->port)));
1749 host->hostFlags |= HOSTDELETED;
1750 host->hostFlags &= ~HWHO_INPROGRESS;
1757 /* The incoming connection does not support WhoAreYou but
1758 * the original one might have. Use removeAddress_r() to
1759 * remove this addr/port from the host that was found.
1760 * If there are no more addresses left for the host it
1761 * will be deleted. Then we retry.
1763 removeAddress_r(host, haddr, hport);
1764 host->hostFlags &= ~HWHO_INPROGRESS;
1765 host->hostFlags |= ALTADDR;
1771 } else if (code == 0) {
1773 identP = malloc(sizeof(struct Identity));
1775 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1778 identP->uuid = interf.uuid;
1779 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1780 /* Check whether the UUID on this connection matches
1781 * the UUID in the host structure. If they don't match
1782 * then this is not the same host as before. */
1783 if (!host->interface
1784 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1787 ("Uuid doesn't match connection (%s:%d).\n",
1788 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1789 removeAddress_r(host, haddr, hport);
1792 ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1793 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1795 removeAddress_r(host, host->host, host->port);
1797 host->hostFlags &= ~HWHO_INPROGRESS;
1798 host->hostFlags |= ALTADDR;
1804 /* the UUID matched the client at the incoming addr/port
1805 * but this is not the address of the active callback
1806 * connection. Try that connection and see if the client
1807 * is still there and if the reported UUID is the same.
1810 afsUUID uuid = host->interface->uuid;
1811 cb_conn = host->callback_rxcon;
1812 rx_GetConnection(cb_conn);
1813 rx_SetConnDeadTime(cb_conn, 2);
1814 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1816 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1818 rx_SetConnDeadTime(cb_conn, 50);
1819 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1820 rx_PutConnection(cb_conn);
1823 /* The primary address is either not responding or
1824 * is not the client we are looking for. Need to
1825 * remove the primary address and add swap in the new
1826 * callback connection, and destroy the old one.
1828 struct rx_connection *rxconn;
1829 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1831 afs_inet_ntoa_r(host->host, hoststr),
1832 ntohs(host->port),code2));
1835 * make sure we add and then remove. otherwise, we
1836 * might end up with no valid interfaces after the
1837 * remove and the host will have been marked deleted.
1839 addInterfaceAddr_r(host, haddr, hport);
1840 removeInterfaceAddr_r(host, host->host, host->port);
1843 rxconn = host->callback_rxcon;
1844 host->callback_rxcon = cb_in;
1849 * If rx_DestroyConnection calls h_FreeConnection we
1850 * will deadlock on the host_glock_mutex. Work around
1851 * the problem by unhooking the client from the
1852 * connection before destroying the connection.
1854 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1855 rx_DestroyConnection(rxconn);
1861 /* A callback to the incoming connection address is failing.
1862 * Assume that the addr/port is no longer associated with the host
1863 * returned by h_Lookup_r.
1866 ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1867 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1868 removeAddress_r(host, haddr, hport);
1869 host->hostFlags &= ~HWHO_INPROGRESS;
1870 host->hostFlags |= ALTADDR;
1874 rx_DestroyConnection(cb_in);
1879 ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1880 host, afs_inet_ntoa_r(host->host, hoststr),
1881 ntohs(host->port), code));
1882 host->hostFlags |= VENUSDOWN;
1885 if (caps.Capabilities_val
1886 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1887 host->hostFlags |= HERRORTRANS;
1889 host->hostFlags &= ~(HERRORTRANS);
1890 host->hostFlags |= ALTADDR;
1891 host->hostFlags &= ~HWHO_INPROGRESS;
1894 if (!(host->hostFlags & ALTADDR)) {
1895 /* another thread is doing the initialisation */
1897 ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1898 host, afs_inet_ntoa_r(host->host, hoststr),
1899 ntohs(host->port)));
1903 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1904 host, afs_inet_ntoa_r(host->host, hoststr),
1905 ntohs(host->port)));
1909 /* We need to check whether the identity in the host structure
1910 * matches the identity on the connection. If they don't match
1911 * then treat this a new host. */
1912 if (!(host->Console & 1)
1913 && ((!identP->valid && host->interface)
1914 || (identP->valid && !host->interface)
1916 && !afs_uuid_equal(&identP->uuid,
1917 &host->interface->uuid)))) {
1918 char uuid1[128], uuid2[128];
1920 afsUUID_to_string(&identP->uuid, uuid1, 127);
1921 if (host->interface)
1922 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1924 ("CB: new identity for host %p (%s:%d), "
1925 "deleting(%x %p %s %s)\n",
1926 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1927 identP->valid, host->interface,
1928 identP->valid ? uuid1 : "no_uuid",
1929 host->interface ? uuid2 : "no_uuid"));
1931 /* The host in the cache is not the host for this connection */
1933 host->hostFlags |= HOSTDELETED;
1939 host = h_Alloc_r(tcon); /* returned held and locked */
1942 h_gethostcps_r(host, time(NULL));
1943 if (!(host->Console & 1)) {
1945 cb_conn = host->callback_rxcon;
1946 rx_GetConnection(cb_conn);
1947 host->hostFlags |= HWHO_INPROGRESS;
1950 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1951 if (code == RXGEN_OPCODE)
1952 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1953 rx_PutConnection(cb_conn);
1956 if ((code == RXGEN_OPCODE) ||
1957 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1959 identP = malloc(sizeof(struct Identity));
1964 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1968 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1970 ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1971 host, afs_inet_ntoa_r(host->host, hoststr),
1972 ntohs(host->port)));
1974 } else if (code == 0) {
1976 identP = malloc(sizeof(struct Identity));
1981 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1985 identP->uuid = interf.uuid;
1987 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1989 ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
1990 host, afs_inet_ntoa_r(host->host, hoststr),
1991 ntohs(host->port)));
1993 if (code == 0 && !identP->valid) {
1994 cb_conn = host->callback_rxcon;
1995 rx_GetConnection(cb_conn);
1997 code = RXAFSCB_InitCallBackState(cb_conn);
1998 rx_PutConnection(cb_conn);
2001 } else if (code == 0) {
2002 oldHost = h_LookupUuid_r(&identP->uuid);
2007 if (oldHost->hostFlags & HOSTDELETED) {
2008 h_Unlock_r(oldHost);
2009 h_Release_r(oldHost);
2017 /* This is a new address for an existing host. Update
2018 * the list of interfaces for the existing host and
2019 * delete the host structure we just allocated. */
2021 /* mark the duplicate host as deleted before we do
2022 * anything. The probing code below may try to change
2023 * "oldHost" to the same IP address as "host" currently
2024 * has, and we do not want a pseudo-"collision" to be
2026 host->hostFlags |= HOSTDELETED;
2028 oldHost->hostFlags |= HWHO_INPROGRESS;
2030 if (oldHost->interface) {
2032 afsUUID uuid = oldHost->interface->uuid;
2033 cb_conn = oldHost->callback_rxcon;
2034 rx_GetConnection(cb_conn);
2035 rx_SetConnDeadTime(cb_conn, 2);
2036 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2038 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2040 rx_SetConnDeadTime(cb_conn, 50);
2041 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2042 rx_PutConnection(cb_conn);
2045 /* The primary address is either not responding or
2046 * is not the client we are looking for.
2047 * MultiProbeAlternateAddress_r() will remove the
2048 * alternate interfaces that do not have the same
2050 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
2052 afs_inet_ntoa_r(oldHost->host, hoststr),
2053 ntohs(oldHost->port),code2));
2055 if (MultiProbeAlternateAddress_r(oldHost)) {
2056 /* If MultiProbeAlternateAddress_r succeeded,
2057 * it updated oldHost->host and oldHost->port
2058 * to an address that responded successfully to
2059 * a ProbeUuid, so it is as if the ProbeUuid
2060 * call above returned success. So, only set
2061 * 'probefail' if MultiProbeAlternateAddress_r
2070 if (oldHost->host != haddr || oldHost->port != hport) {
2071 struct rx_connection *rxconn;
2074 ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
2076 afs_inet_ntoa_r(oldHost->host, hoststr2),
2077 ntohs(oldHost->port),
2078 afs_inet_ntoa_r(haddr, hoststr),
2081 * add then remove. otherwise the host may get marked
2082 * deleted if we removed the only valid address.
2084 addInterfaceAddr_r(oldHost, haddr, hport);
2085 if (probefail || oldHost->host == haddr) {
2087 * The probe failed which means that the old
2088 * address is either unreachable or is not the
2089 * same host we were just contacted by. We will
2090 * also remove addresses if only the port has
2091 * changed because that indicates the client
2094 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
2097 struct Interface *interface = oldHost->interface;
2098 int number = oldHost->interface->numberOfInterfaces;
2099 for (i = 0; i < number; i++) {
2100 if (interface->interface[i].addr == haddr &&
2101 interface->interface[i].port != hport) {
2103 * We have just been contacted by a client
2104 * that has been seen from behind a NAT
2105 * and at least one other address.
2107 removeInterfaceAddr_r(oldHost, haddr,
2108 interface->interface[i].port);
2113 oldHost->host = haddr;
2114 oldHost->port = hport;
2115 rxconn = oldHost->callback_rxcon;
2116 oldHost->callback_rxcon = host->callback_rxcon;
2117 host->callback_rxcon = rxconn;
2119 /* don't destroy rxconn here; let h_TossStuff_r
2120 * take care of that via h_Release_r below */
2122 host->hostFlags &= ~HWHO_INPROGRESS;
2124 /* release host because it was allocated by h_Alloc_r */
2127 /* the new host is held and locked */
2129 /* This really is a new host */
2130 opr_Assert(interfValid == 1);
2131 initInterfaceAddr_r(host, &interf);
2133 cb_conn = host->callback_rxcon;
2134 rx_GetConnection(cb_conn);
2137 RXAFSCB_InitCallBackState3(cb_conn,
2139 rx_PutConnection(cb_conn);
2144 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2145 host, afs_inet_ntoa_r(host->host, hoststr),
2146 ntohs(host->port)));
2152 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2153 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2154 host->hostFlags |= VENUSDOWN;
2157 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2158 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2159 host->hostFlags |= RESETDONE;
2162 if (caps.Capabilities_val
2163 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2164 host->hostFlags |= HERRORTRANS;
2166 host->hostFlags &= ~(HERRORTRANS);
2167 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2168 host->hostFlags &= ~HWHO_INPROGRESS;
2173 if (caps.Capabilities_val)
2174 free(caps.Capabilities_val);
2175 caps.Capabilities_val = NULL;
2176 caps.Capabilities_len = 0;
2178 rx_DestroyConnection(cb_in);
2188 h_InitHostPackage(void)
2190 memset(&nulluuid, 0, sizeof(afsUUID));
2191 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2192 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2193 opr_mutex_init(&host_glock_mutex);
2197 MapName_r(char *uname, afs_int32 * aval)
2203 lnames.namelist_len = 1;
2204 lnames.namelist_val = (prname *) uname;
2205 lids.idlist_len = 0;
2206 lids.idlist_val = NULL;
2209 code = hpr_NameToId(&lnames, &lids);
2212 if (lids.idlist_val) {
2213 *aval = lids.idlist_val[0];
2214 if (*aval == AnonymousID) {
2216 ("MapName: NameToId on %s returns anonymousID\n",
2217 lnames.namelist_val[0]));
2219 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2222 ("MapName: NameToId on '%s' is unknown\n",
2223 lnames.namelist_val[0]));
2234 PerHost_EnumerateClient(struct host *host, void *arock)
2236 struct enumclient_args *args = arock;
2237 struct client *client;
2240 for (client = host->FirstClient; client; client = client->next) {
2241 if (!client->deleted && client->ViceId == args->vid) {
2246 code = (*args->proc)(client, args->rock);
2249 h_ReleaseClient_r(client);
2252 return H_ENUMERATE_BAIL(0);
2261 h_EnumerateClients(VolumeId vid,
2262 int (*proc)(struct client *client, void *rock),
2265 struct enumclient_args args;
2271 h_Enumerate_r(PerHost_EnumerateClient, hostList, &args);
2276 format_vname(char *vname, int usize, const char *tname, const char *tinst,
2277 const char *tcell, afs_int32 islocal)
2281 len = strlcpy(vname, tname, usize);
2285 len = strlcat(vname, ".", usize);
2288 len = strlcat(vname, tinst, usize);
2292 if (tcell[0] && !islocal) {
2293 len = strlcat(vname, "@", usize);
2296 len = strlcat(vname, tcell, usize);
2304 getPeerDetails(struct rx_connection *conn,
2305 afs_int32 *viceid, afs_int32 *expTime, int authClass)
2308 #if (64-MAXKTCNAMELEN)
2309 ticket name length != 64
2313 char tcell[MAXKTCREALMLEN];
2314 char uname[PR_MAXNAMELEN];
2316 *viceid = AnonymousID;
2317 *expTime = 0x7fffffff;
2320 ("FindClient: authenticating connection: authClass=%d\n",
2322 if (authClass == 1) {
2323 /* A bcrypt tickets, no longer supported */
2324 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2328 if (authClass == 2) {
2329 /* an rxkad ticket */
2333 /* kerberos ticket */
2334 code = rxkad_GetServerInfo(conn, /*level */ 0, (afs_uint32 *)expTime,
2335 tname, tinst, tcell, &kvno);
2337 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2342 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2343 tname, tinst, tcell, *expTime, kvno));
2344 code = afsconf_IsLocalRealmMatch(confDir, &islocal, tname, tinst, tcell);
2347 ViceLog(0, ("FindClient: local realm check failed; code=%d", code));
2351 code = format_vname(uname, sizeof(uname), tname, tinst, tcell, islocal);
2353 ViceLog(0, ("FindClient: uname truncated."));
2357 /* translate the name to a vice id */
2358 code = MapName_r(uname, viceid);
2360 ViceLog(1, ("failed to map name=%s -> code=%d\n", uname,
2362 return code; /* Actually flag this is a failure */
2372 * Called by the server main loop. Returns a h_Held client, which must be
2373 * released later the main loop. Allocates a client if the matching one
2374 * isn't around. The client is returned with its reference count incremented
2375 * by one. The caller must call h_ReleaseClient_r when finished with
2378 * The refCount on client->host is returned incremented. h_ReleaseClient_r
2379 * does not decrement the refCount on client->host.
2381 * *a_viceid is set to the user's ViceId, even if we don't return a client
2385 h_FindClient_r(struct rx_connection *tcon, afs_int32 *a_viceid)
2387 struct client *client;
2388 struct host *host = NULL;
2389 struct client *oldClient;
2390 afs_int32 viceid = 0;
2398 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2399 if (client && client->sid == rx_GetConnectionId(tcon)
2400 && client->VenusEpoch == rx_GetConnectionEpoch(tcon)
2401 && !(client->host->hostFlags & HOSTDELETED)
2402 && !client->deleted) {
2405 *a_viceid = client->ViceId;
2408 h_Hold_r(client->host);
2409 if (client->prfail != 2) {
2410 /* Could add shared lock on client here */
2411 /* note that we don't have to lock entry in this path to
2412 * ensure CPS is initialized, since we don't call rx_SetSpecific
2413 * until initialization is done, and we only get here if
2414 * rx_GetSpecific located the client structure.
2419 ObtainWriteLock(&client->lock); /* released at end */
2425 authClass = rx_SecurityClassOf(tcon);
2427 code = getPeerDetails(tcon, &viceid, &expTime, authClass);
2435 if (!client) { /* loop */
2436 host = h_GetHost_r(tcon); /* Returns with incremented refCount */
2442 /* First try to find the client structure */
2443 for (client = host->FirstClient; client; client = client->next) {
2444 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2445 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2448 ObtainWriteLock(&client->lock);
2454 /* Still no client structure - get one */
2457 if (host->hostFlags & HOSTDELETED) {
2462 /* Retry to find the client structure */
2463 for (client = host->FirstClient; client; client = client->next) {
2464 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2465 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2467 goto retryfirstclient;
2472 ObtainWriteLock(&client->lock);
2473 client->refCount = 1;
2474 client->host = host;
2475 client->InSameNetwork = host->InSameNetwork;
2476 client->ViceId = viceid;
2477 client->expTime = expTime; /* rx only */
2478 client->authClass = authClass; /* rx only */
2479 client->sid = rx_GetConnectionId(tcon);
2480 client->VenusEpoch = rx_GetConnectionEpoch(tcon);
2481 client->CPS.prlist_val = NULL;
2482 client->CPS.prlist_len = 0;
2486 client->prfail = fail;
2488 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2489 client->CPS.prlist_len = 0;
2490 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2491 free(client->CPS.prlist_val);
2492 client->CPS.prlist_val = NULL;
2493 client->ViceId = viceid;
2494 client->expTime = expTime;
2496 if (viceid == ANONYMOUSID) {
2497 client->CPS.prlist_len = AnonCPS.prlist_len;
2498 client->CPS.prlist_val = AnonCPS.prlist_val;
2501 code = hpr_GetCPS(viceid, &client->CPS);
2506 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2507 code, viceid, client->host,
2508 afs_inet_ntoa_r(client->host->host,hoststr),
2509 ntohs(client->host->port)));
2511 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2512 * all protection servers and reevaluates things if no
2513 * sync server or quorum is found we could still end up
2514 * with one of these errors. In such case we would like to
2515 * reevaluate the rpc call to find if there's cps for this
2516 * guy. We treat other errors (except network failures
2517 * ones - i.e. code < 0) as an indication that there is no
2518 * CPS for this host. Ideally we could like to deal this
2519 * problem the other way around (i.e. if code == NOCPS
2520 * ignore else retry next time) but the problem is that
2521 * there're other errors (i.e. EPERM) for which we don't
2522 * want to retry and we don't know the whole code list!
2524 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2528 /* the disabling of system:administrators is so iffy and has so many
2529 * possible failure modes that we will disable it again */
2530 /* Turn off System:Administrator for safety
2531 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2532 * osi_Assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2535 /* Now, tcon may already be set to a rock, since we blocked with no host
2536 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2537 * required). So, before setting the RPC's rock, we should disconnect
2538 * the RPC from the other client structure's rock.
2540 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2541 if (oldClient && oldClient != client
2542 && oldClient->sid == rx_GetConnectionId(tcon)
2543 && oldClient->VenusEpoch == rx_GetConnectionEpoch(tcon)
2544 && !(oldClient->host->hostFlags & HOSTDELETED)) {
2546 if (!oldClient->deleted) {
2547 /* if we didn't create it, it's not ours to put back */
2549 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2550 "conn %p (host %s:%d) had client %p(%x)\n",
2551 client, client->sid, tcon,
2552 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2553 ntohs(rxr_PortOf(tcon)),
2554 oldClient, oldClient->sid));
2555 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2556 free(client->CPS.prlist_val);
2557 client->CPS.prlist_val = NULL;
2558 client->CPS.prlist_len = 0;
2560 /* We should perhaps check for 0 here */
2562 ReleaseWriteLock(&client->lock);
2567 oldClient->refCount++;
2569 h_Hold_r(oldClient->host);
2570 h_Release_r(client->host);
2573 ObtainWriteLock(&oldClient->lock);
2576 host = oldClient->host;
2578 ViceLog(0, ("FindClient: deleted client %p(%x ref %d host %p href "
2579 "%d) already had conn %p (host %s:%d, cid %x), stolen "
2580 "by client %p(%x, ref %d host %p href %d)\n",
2581 oldClient, oldClient->sid, oldClient->refCount,
2582 oldClient->host, oldClient->host->refCount, tcon,
2583 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2584 ntohs(rxr_PortOf(tcon)), rx_GetConnectionId(tcon),
2585 client, client->sid, client->refCount,
2586 client->host, client->host->refCount));
2587 /* rx_SetSpecific will be done immediately below */
2590 /* Avoid chaining in more than once. */
2594 if (host->hostFlags & HOSTDELETED) {
2599 client->host = NULL;
2601 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2602 free(client->CPS.prlist_val);
2603 client->CPS.prlist_val = NULL;
2604 client->CPS.prlist_len = 0;
2607 ReleaseWriteLock(&client->lock);
2612 client->next = host->FirstClient;
2613 host->FirstClient = client;
2615 CurrentConnections++; /* increment number of connections */
2617 rx_SetSpecific(tcon, rxcon_client_key, client);
2618 ReleaseWriteLock(&client->lock);
2622 } /*h_FindClient_r */
2625 h_ReleaseClient_r(struct client *client)
2627 opr_Assert(client->refCount > 0);
2634 * Sigh: this one is used to get the client AGAIN within the individual
2635 * server routines. This does not bother h_Holding the host, since
2636 * this is assumed already have been done by the server main loop.
2637 * It does check tokens, since only the server routines can return the
2638 * VICETOKENDEAD error code
2641 GetClient(struct rx_connection *tcon, struct client **cp)
2643 struct client *client;
2648 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2649 if (client == NULL) {
2651 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2652 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2653 ntohs(rxr_PortOf(tcon))));
2657 if (rx_GetConnectionId(tcon) != client->sid
2658 || rx_GetConnectionEpoch(tcon) != client->VenusEpoch) {
2660 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2661 tcon, rx_GetConnectionId(tcon), client->sid));
2665 if (client && client->LastCall > client->expTime && client->expTime) {
2667 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2668 afs_inet_ntoa_r(client->host->host, hoststr),
2669 ntohs(client->host->port), client->expTime));
2671 return VICETOKENDEAD;
2673 if (client->deleted) {
2674 ViceLog(0, ("GetClient: got deleted client, connection will appear "
2675 "anonymous; tcon %p cid %x client %p ref %d host %p "
2676 "(%s:%d) href %d ViceId %d\n",
2677 tcon, rx_GetConnectionId(tcon), client, client->refCount,
2679 afs_inet_ntoa_r(client->host->host, hoststr),
2680 (int)ntohs(client->host->port), client->host->refCount,
2681 (int)client->ViceId));
2691 PutClient(struct client **cp)
2697 h_ReleaseClient_r(*cp);
2704 /* Client user name for short term use. Note that this is NOT inexpensive */
2706 h_UserName(struct client *client)
2708 static char User[PR_MAXNAMELEN + 1];
2712 lids.idlist_len = 1;
2713 lids.idlist_val = malloc(1 * sizeof(afs_int32));
2714 if (!lids.idlist_val) {
2715 ViceLogThenPanic(0, ("Failed malloc in h_UserName\n"));
2717 lnames.namelist_len = 0;
2718 lnames.namelist_val = (prname *) 0;
2719 lids.idlist_val[0] = client->ViceId;
2720 if (hpr_IdToName(&lids, &lnames)) {
2721 /* We need to free id we alloced above! */
2722 free(lids.idlist_val);
2723 return "*UNKNOWN USER NAME*";
2725 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2726 free(lids.idlist_val);
2727 free(lnames.namelist_val);
2736 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2737 CEs, CEBlocks, HTs, HTBlocks));
2743 h_PrintClient(struct host *host, void *rock)
2745 StreamHandle_t *file = (StreamHandle_t *)rock;
2746 struct client *client;
2751 time_t LastCall, expTime;
2755 LastCall = host->LastCall;
2756 if (host->hostFlags & HOSTDELETED) {
2760 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2761 localtime_r(&LastCall, &tm));
2762 snprintf(tmpStr, sizeof tmpStr, "Host %s:%d down = %d, LastCall %s\n",
2763 afs_inet_ntoa_r(host->host, hoststr),
2764 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2766 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2767 for (client = host->FirstClient; client; client = client->next) {
2768 if (!client->deleted) {
2769 expTime = client->expTime;
2770 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2771 localtime_r(&expTime, &tm));
2772 snprintf(tmpStr, sizeof tmpStr,
2773 " user id=%d, name=%s, sl=%s till %s\n",
2774 client->ViceId, h_UserName(client),
2775 client->authClass ? "Authenticated"
2776 : "Not authenticated",
2777 client->authClass ? tbuffer : "No Limit");
2778 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2779 snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2780 client->CPS.prlist_len);
2781 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2782 if (client->CPS.prlist_val) {
2783 for (i = 0; i < client->CPS.prlist_len; i++) {
2784 snprintf(tmpStr, sizeof tmpStr, " %d",
2785 client->CPS.prlist_val[i]);
2786 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2789 sprintf(tmpStr, "]\n");
2790 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2796 } /*h_PrintClient */
2801 * Print a list of clients, with last security level and token value seen,
2805 h_PrintClients(void)
2812 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2816 ("Couldn't create client dump file %s\n",
2817 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2821 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2822 localtime_r(&now, &tm));
2823 snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n\n",
2825 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2826 h_Enumerate(h_PrintClient, (char *)file);
2827 STREAM_REALLYCLOSE(file);
2828 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2835 h_DumpHost(struct host *host, void *rock)
2837 StreamHandle_t *file = (StreamHandle_t *)rock;
2844 snprintf(tmpStr, sizeof tmpStr,
2845 "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u "
2846 "down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u "
2848 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
2849 host->index, host->cblist, CheckLock(&host->lock),
2850 host->LastCall, host->ActiveCall, (host->hostFlags & VENUSDOWN),
2851 host->hostFlags & HOSTDELETED, host->Console,
2852 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2854 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2855 if (host->hcps.prlist_val)
2856 for (i = 0; i < host->hcps.prlist_len; i++) {
2857 snprintf(tmpStr, sizeof tmpStr, " %d", host->hcps.prlist_val[i]);
2858 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2860 sprintf(tmpStr, "] [");
2861 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2862 if (host->interface)
2863 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2865 sprintf(tmpStr, " %s:%d",
2866 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2867 ntohs(host->interface->interface[i].port));
2868 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2870 sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2871 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2883 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2890 ("Couldn't create host dump file %s\n",
2891 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2895 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2896 localtime_r(&now, &tm));
2897 snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n\n", tbuffer);
2898 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2899 h_Enumerate(h_DumpHost, (char *)file);
2900 STREAM_REALLYCLOSE(file);
2901 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2905 #ifdef AFS_DEMAND_ATTACH_FS
2908 * host state serialization
2910 static int h_stateFillHeader(struct host_state_header * hdr);
2911 static int h_stateCheckHeader(struct host_state_header * hdr);
2912 static int h_stateAllocMap(struct fs_dump_state * state);
2913 static int h_stateSaveHost(struct host * host, void *rock);
2914 static int h_stateRestoreHost(struct fs_dump_state * state);
2915 static int h_stateRestoreIndex(struct host * h, void *rock);
2916 static int h_stateVerifyHost(struct host * h, void *rock);
2917 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
2918 afs_uint32 addr, afs_uint16 port, int valid);
2919 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2920 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2921 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2924 * Is this host busy?
2926 * This is just a hint and should not be trusted; this should probably only be
2927 * used by the host state serialization code when trying to detect if a host
2928 * can be sanely serialized to disk or not. If this function returns 1, the
2929 * host may be in an invalid state and thus should not be saved to disk.
2932 h_isBusy_r(struct host *host)
2934 struct Lock *hostLock = &host->lock;
2937 LOCK_LOCK(hostLock);
2938 if (hostLock->excl_locked || hostLock->readers_reading) {
2941 LOCK_UNLOCK(hostLock);
2947 if ((host->hostFlags & HWHO_INPROGRESS) || !(host->hostFlags & ALTADDR)) {
2948 /* We shouldn't hit this if the host wasn't locked, but just in case... */
2955 /* this procedure saves all host state to disk for fast startup */
2957 h_stateSave(struct fs_dump_state * state)
2959 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2962 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2964 /* invalidate host state header */
2965 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2967 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2968 sizeof(struct host_state_header))) {
2973 fs_stateIncEOF(state, sizeof(struct host_state_header));
2975 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2980 h_stateFillHeader(state->h_hdr);
2982 /* write the real header to disk */
2983 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2984 sizeof(struct host_state_header));
2991 * host state serialization
2993 * this procedure restores all host state from a disk for fast startup
2996 h_stateRestore(struct fs_dump_state * state)
3000 /* seek to the right position and read in the host state header */
3001 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
3002 sizeof(struct host_state_header))) {
3007 /* check the validity of the header */
3008 if (h_stateCheckHeader(state->h_hdr)) {
3013 records = state->h_hdr->records;
3015 if (h_stateAllocMap(state)) {
3020 /* iterate over records restoring host state */
3021 for (i=0; i < records; i++) {
3022 if (h_stateRestoreHost(state) != 0) {
3033 h_stateRestoreIndices(struct fs_dump_state * state)
3035 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
3040 h_stateRestoreIndex(struct host * h, void *rock)
3042 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3043 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
3044 return H_ENUMERATE_BAIL(0);
3050 h_stateVerify(struct fs_dump_state * state)
3052 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
3057 h_stateVerifyHost(struct host * h, void* rock)
3059 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3063 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3064 return H_ENUMERATE_BAIL(0);
3068 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
3069 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
3070 h->interface->interface[i].port,
3071 h->interface->interface[i].valid)) {
3075 if (h_stateVerifyUuidHash(state, h)) {
3078 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
3082 if (cb_stateVerifyHCBList(state, h)) {
3090 * verify a host is either in, or absent from, the addr hash table.
3092 * @param[in] state fs dump state
3093 * @param[in] h host we're dealing with
3094 * @param[in] addr addr to look for (NBO)
3095 * @param[in] port port to look for (NBO)
3096 * @param[in] valid 1 if we're verifying that the specified addr and port
3097 * in the hash table point to the specified host. 0 if we're
3098 * verifying that the specified addr and port do NOT point
3099 * to the specified host
3101 * @return operation status
3102 * @retval 1 failed to verify, bail out
3103 * @retval 0 verified successfully, all is well
3106 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3107 afs_uint32 addr, afs_uint16 port, int valid)
3109 int ret = 0, found = 0;
3110 struct host *host = NULL;
3111 struct h_AddrHashChain *chain;
3112 int index = h_HashIndex(addr);
3116 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3117 host = chain->hostPtr;
3119 afs_inet_ntoa_r(addr, tmp);
3120 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3124 if ((chain->addr == addr) && (chain->port == port)) {
3127 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3128 "points to different host struct (%d, %d)\n",
3129 h->index, host->index));
3130 state->flags.warnings_generated = 1;
3134 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3135 "marked invalid, but points to the containing "
3136 "host\n", afs_inet_ntoa_r(addr, tmp),
3137 (unsigned)htons(port)));
3145 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3146 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3147 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3154 if (!found && valid) {
3155 afs_inet_ntoa_r(addr, tmp);
3156 if (state->mode == FS_STATE_LOAD_MODE) {
3157 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3158 tmp, (unsigned)htons(port)));
3162 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3163 tmp, (unsigned)htons(port)));
3164 state->flags.warnings_generated = 1;
3173 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3176 struct host *host = NULL;
3177 struct h_UuidHashChain *chain;
3178 afsUUID * uuidp = &h->interface->uuid;
3179 int index = h_UuidHashIndex(uuidp);
3183 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3184 host = chain->hostPtr;
3186 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3187 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3191 if (host->interface &&
3192 afs_uuid_equal(&host->interface->uuid, uuidp)) {
3194 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3195 h->index, host->index));
3196 state->flags.warnings_generated = 1;
3200 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3201 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3202 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3209 /* Fall through, so host not found */
3211 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3212 if (state->mode == FS_STATE_LOAD_MODE) {
3213 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3217 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3218 state->flags.warnings_generated = 1;
3225 /* create the host state header structure */
3227 h_stateFillHeader(struct host_state_header * hdr)
3229 hdr->stamp.magic = HOST_STATE_MAGIC;
3230 hdr->stamp.version = HOST_STATE_VERSION;
3234 /* check the contents of the host state header structure */
3236 h_stateCheckHeader(struct host_state_header * hdr)
3240 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3241 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3244 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3245 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3251 /* allocate the host id mapping table */
3253 h_stateAllocMap(struct fs_dump_state * state)
3255 state->h_map.len = state->h_hdr->index_max + 1;
3256 state->h_map.entries = (struct idx_map_entry_t *)
3257 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3258 return (state->h_map.entries != NULL) ? 0 : 1;
3261 /* function called by h_Enumerate to save a host to disk */
3263 h_stateSaveHost(struct host * host, void* rock)
3265 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3266 int if_len=0, hcps_len=0;
3267 struct hostDiskEntry hdsk;
3268 struct host_state_entry_header hdr;
3269 struct Interface * ifp = NULL;
3270 afs_int32 * hcps = NULL;
3271 struct iovec iov[4];
3274 if (h_isBusy_r(host)) {
3276 ViceLog(1, ("Not saving host %s:%d to disk; host appears busy\n",
3277 afs_inet_ntoa_r(host->host, hoststr), (int)ntohs(host->port)));
3278 /* Make sure we don't try to save callbacks to disk for this host, or
3279 * we'll get confused on restore */
3280 DeleteAllCallBacks_r(host, 1);
3284 memset(&hdr, 0, sizeof(hdr));
3286 if (state->h_hdr->index_max < host->index) {
3287 state->h_hdr->index_max = host->index;
3290 h_hostToDiskEntry_r(host, &hdsk);
3291 if (host->interface) {
3292 if_len = sizeof(struct Interface) +
3293 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3294 ifp = malloc(if_len);
3295 opr_Assert(ifp != NULL);
3296 memcpy(ifp, host->interface, if_len);
3297 hdr.interfaces = host->interface->numberOfInterfaces;
3298 iov[iovcnt].iov_base = (char *) ifp;
3299 iov[iovcnt].iov_len = if_len;
3302 if (host->hcps.prlist_val) {
3303 hdr.hcps = host->hcps.prlist_len;
3304 hcps_len = hdr.hcps * sizeof(afs_int32);
3305 hcps = malloc(hcps_len);
3306 opr_Assert(hcps != NULL);
3307 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3308 iov[iovcnt].iov_base = (char *) hcps;
3309 iov[iovcnt].iov_len = hcps_len;
3313 if (hdsk.index > state->h_hdr->index_max)
3314 state->h_hdr->index_max = hdsk.index;
3316 hdr.len = sizeof(struct host_state_entry_header) +
3317 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3318 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3320 iov[0].iov_base = (char *) &hdr;
3321 iov[0].iov_len = sizeof(hdr);
3322 iov[1].iov_base = (char *) &hdsk;
3323 iov[1].iov_len = sizeof(struct hostDiskEntry);
3325 if (fs_stateWriteV(state, iov, iovcnt)) {
3326 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3330 fs_stateIncEOF(state, hdr.len);
3332 state->h_hdr->records++;
3339 return H_ENUMERATE_BAIL(0);
3344 /* restores a host from disk */
3346 h_stateRestoreHost(struct fs_dump_state * state)
3348 int ifp_len=0, hcps_len=0, bail=0;
3349 struct host_state_entry_header hdr;
3350 struct hostDiskEntry hdsk;
3351 struct host *host = NULL;
3352 struct Interface *ifp = NULL;
3353 afs_int32 * hcps = NULL;
3354 struct iovec iov[3];
3357 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3358 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3364 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3365 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3371 iov[0].iov_base = (char *) &hdsk;
3372 iov[0].iov_len = sizeof(struct hostDiskEntry);
3374 if (hdr.interfaces) {
3375 ifp_len = sizeof(struct Interface) +
3376 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3377 ifp = malloc(ifp_len);
3378 opr_Assert(ifp != NULL);
3379 iov[iovcnt].iov_base = (char *) ifp;
3380 iov[iovcnt].iov_len = ifp_len;
3384 hcps_len = hdr.hcps * sizeof(afs_int32);
3385 hcps = malloc(hcps_len);
3386 opr_Assert(hcps != NULL);
3387 iov[iovcnt].iov_base = (char *) hcps;
3388 iov[iovcnt].iov_len = hcps_len;
3392 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3393 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3398 if (fs_stateReadV(state, iov, iovcnt)) {
3399 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3404 if (!hdr.hcps && hdsk.hcps_valid) {
3405 /* valid, zero-length host cps ; does this ever happen? */
3406 hcps = malloc(sizeof(afs_int32));
3407 opr_Assert(hcps != NULL);
3410 if ((hdsk.hostFlags & HWHO_INPROGRESS) || !(hdsk.hostFlags & ALTADDR)) {
3412 ViceLog(0, ("h_stateRestoreHost: skipping host %s:%d due to invalid flags 0x%x\n",
3413 afs_inet_ntoa_r(hdsk.host, hoststr), (int)ntohs(hdsk.port),
3414 (unsigned)hdsk.hostFlags));
3416 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_SKIPPED;
3420 /* for restoring state, we better be able to get a host! */
3422 opr_Assert(host != NULL);
3425 host->interface = ifp;
3428 host->hcps.prlist_val = hcps;
3429 host->hcps.prlist_len = hdr.hcps;
3432 h_diskEntryToHost_r(&hdsk, host);
3433 h_SetupCallbackConn_r(host);
3435 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3438 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3439 if (ifp->interface[i].valid &&
3440 !(ifp->interface[i].addr == host->host &&
3441 ifp->interface[i].port == host->port)) {
3442 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3443 ifp->interface[i].port,
3447 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3449 h_InsertList_r(host);
3451 /* setup host id map entry */
3452 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_VALID;
3453 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3454 state->h_map.entries[hdsk.index].new_idx = host->index;
3466 /* serialize a host structure to disk */
3468 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3470 out->host = in->host;
3471 out->port = in->port;
3472 out->hostFlags = in->hostFlags;
3473 out->Console = in->Console;
3474 out->hcpsfailed = in->hcpsfailed;
3475 out->LastCall = in->LastCall;
3476 out->ActiveCall = in->ActiveCall;
3477 out->cpsCall = in->cpsCall;
3478 out->cblist = in->cblist;
3479 out->InSameNetwork = in->InSameNetwork;
3481 /* special fields we save, but are not memcpy'd back on restore */
3482 out->index = in->index;
3483 out->hcps_len = in->hcps.prlist_len;
3484 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3487 /* restore a host structure from disk */
3489 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3491 out->host = in->host;
3492 out->port = in->port;
3493 out->hostFlags = in->hostFlags;
3494 out->Console = in->Console;
3495 out->hcpsfailed = in->hcpsfailed;
3496 out->LastCall = in->LastCall;
3497 out->ActiveCall = in->ActiveCall;
3498 out->cpsCall = in->cpsCall;
3499 out->cblist = in->cblist;
3500 out->InSameNetwork = in->InSameNetwork;
3503 /* index translation routines */
3505 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3509 /* hosts use a zero-based index, so old==0 is valid */
3511 if (old >= state->h_map.len) {
3512 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3514 } else if (state->h_map.entries[old].valid != FS_STATE_IDX_VALID ||
3515 state->h_map.entries[old].old_idx != old) { /* sanity check */
3516 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3519 *new = state->h_map.entries[old].new_idx;
3524 #endif /* AFS_DEMAND_ATTACH_FS */
3528 * This counts the number of workstations, the number of active workstations,
3529 * and the number of workstations declared "down" (i.e. not heard from
3530 * recently). An active workstation has received a call since the cutoff
3531 * time argument passed.
3534 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3537 int num = 0, active = 0, del = 0;
3541 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3542 if (!(host->hostFlags & HOSTDELETED)) {
3544 if (host->ActiveCall > cutofftime)
3546 if (host->hostFlags & VENUSDOWN)
3550 if (count != hostCount) {
3551 ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3552 } else if (host != NULL) {
3553 ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3554 ShutDownAndCore(PANIC);
3564 } /*h_GetWorkStats */
3567 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp,
3568 afs_int32 cutofftime)
3570 int num, active, del;
3571 h_GetWorkStats(&num, &active, &del, cutofftime);
3580 /*------------------------------------------------------------------------
3581 * PRIVATE h_ClassifyAddress
3584 * Given a target IP address and a candidate IP address (both
3585 * in host byte order), classify the candidate into one of three
3586 * buckets in relation to the target by bumping the counters passed
3590 * a_targetAddr : Target address.
3591 * a_candAddr : Candidate address.
3592 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3593 * addresses are either in the same network
3594 * or the same subnet.
3595 * a_diffSubnetP : ...when the candidate is in a different
3597 * a_diffNetworkP : ...when the candidate is in a different
3604 * The target and candidate addresses are both in host byte
3605 * order, NOT network byte order, when passed in.
3609 *------------------------------------------------------------------------*/
3612 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3613 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3614 afs_int32 * a_diffNetworkP)
3615 { /*h_ClassifyAddress */
3617 afs_uint32 targetNet;
3618 afs_uint32 targetSubnet;
3620 afs_uint32 candSubnet;
3623 * Put bad values into the subnet info to start with.
3625 targetSubnet = (afs_uint32) 0;
3626 candSubnet = (afs_uint32) 0;
3629 * Pull out the network and subnetwork numbers from the target
3630 * and candidate addresses. We can short-circuit this whole
3631 * affair if the target and candidate addresses are not of the
3634 if (IN_CLASSA(a_targetAddr)) {
3635 if (!(IN_CLASSA(a_candAddr))) {
3636 (*a_diffNetworkP)++;
3639 targetNet = a_targetAddr & IN_CLASSA_NET;
3640 candNet = a_candAddr & IN_CLASSA_NET;
3641 if (IN_SUBNETA(a_targetAddr))
3642 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3643 if (IN_SUBNETA(a_candAddr))
3644 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3645 } else if (IN_CLASSB(a_targetAddr)) {
3646 if (!(IN_CLASSB(a_candAddr))) {
3647 (*a_diffNetworkP)++;
3650 targetNet = a_targetAddr & IN_CLASSB_NET;
3651 candNet = a_candAddr & IN_CLASSB_NET;
3652 if (IN_SUBNETB(a_targetAddr))
3653 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3654 if (IN_SUBNETB(a_candAddr))
3655 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3656 } /*Class B target */
3657 else if (IN_CLASSC(a_targetAddr)) {
3658 if (!(IN_CLASSC(a_candAddr))) {
3659 (*a_diffNetworkP)++;
3662 targetNet = a_targetAddr & IN_CLASSC_NET;
3663 candNet = a_candAddr & IN_CLASSC_NET;
3666 * Note that class C addresses can't have subnets,
3667 * so we leave the defaults untouched.
3669 } /*Class C target */
3671 targetNet = a_targetAddr;
3672 candNet = a_candAddr;
3673 } /*Class D address */
3676 * Now, simply compare the extracted net and subnet values for
3677 * the two addresses (which at this point are known to be of the
3680 if (targetNet == candNet) {
3681 if (targetSubnet == candSubnet)
3682 (*a_sameNetOrSubnetP)++;
3686 (*a_diffNetworkP)++;
3688 } /*h_ClassifyAddress */
3691 /*------------------------------------------------------------------------
3692 * EXPORTED h_GetHostNetStats
3695 * Iterate through the host table, and classify each (non-deleted)
3696 * host entry into ``proximity'' categories (same net or subnet,
3697 * different subnet, different network).
3700 * a_numHostsP : Set to total number of (non-deleted) hosts.
3701 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3702 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3703 * a_diffNetworkP : Set to # hosts on diff network as server.
3709 * We only count non-deleted hosts. The storage pointed to by our
3710 * parameters is zeroed upon entry.
3714 *------------------------------------------------------------------------*/
3717 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3718 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3719 { /*h_GetHostNetStats */
3721 struct host *hostP; /*Ptr to current host entry */
3722 afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3726 * Clear out the storage pointed to by our parameters.
3728 *a_numHostsP = (afs_int32) 0;
3729 *a_sameNetOrSubnetP = (afs_int32) 0;
3730 *a_diffSubnetP = (afs_int32) 0;
3731 *a_diffNetworkP = (afs_int32) 0;
3734 for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3735 if (!(hostP->hostFlags & HOSTDELETED)) {
3737 * Bump the number of undeleted host entries found.
3738 * In classifying the current entry's address, make
3739 * sure to first convert to host byte order.
3742 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3743 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3744 a_sameNetOrSubnetP, a_diffSubnetP,
3746 } /*Only look at non-deleted hosts */
3747 } /*For each host record hashed to this index */
3748 if (count != hostCount) {
3749 ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3750 } else if (hostP != NULL) {
3751 ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3752 ShutDownAndCore(PANIC);
3755 } /*h_GetHostNetStats */
3757 static afs_uint32 checktime;
3758 static afs_uint32 clientdeletetime;
3759 static struct AFSFid zerofid;
3763 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3764 * Since it can serialize them, and pile up, it should be a separate LWP
3765 * from other events.
3769 CheckHost_r(struct host *host, void *dummy)
3771 struct client *client;
3772 struct rx_connection *cb_conn = NULL;
3775 #ifdef AFS_DEMAND_ATTACH_FS
3776 /* kill the checkhost lwp ASAP during shutdown */
3778 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3780 return H_ENUMERATE_BAIL(0);
3785 /* Host is held by h_Enumerate_r */
3786 for (client = host->FirstClient; client; client = client->next) {
3787 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3788 client->deleted = 1;
3789 host->hostFlags |= CLIENTDELETED;
3792 if (host->LastCall < checktime) {
3794 if (!(host->hostFlags & HOSTDELETED)) {
3795 host->hostFlags |= HWHO_INPROGRESS;
3796 cb_conn = host->callback_rxcon;
3797 rx_GetConnection(cb_conn);
3798 if (host->LastCall < clientdeletetime) {
3799 host->hostFlags |= HOSTDELETED;
3800 if (!(host->hostFlags & VENUSDOWN)) {
3801 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3802 if (host->interface) {
3805 RXAFSCB_InitCallBackState3(cb_conn,
3811 RXAFSCB_InitCallBackState(cb_conn);
3814 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3817 (void)afs_inet_ntoa_r(host->host, hoststr);
3819 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3820 hoststr, ntohs(host->port)));
3821 host->hostFlags |= VENUSDOWN;
3823 /* Note: it's safe to delete hosts even if they have call
3824 * back state, because break delayed callbacks (called when a
3825 * message is received from the workstation) will always send a
3826 * break all call backs to the workstation if there is no
3831 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3833 (void)afs_inet_ntoa_r(host->host, hoststr);
3834 if (host->interface) {
3835 afsUUID uuid = host->interface->uuid;
3837 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3840 if (MultiProbeAlternateAddress_r(host)) {
3841 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3842 hoststr, ntohs(host->port), code));
3843 host->hostFlags |= VENUSDOWN;
3848 code = RXAFSCB_Probe(cb_conn);
3852 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3853 hoststr, ntohs(host->port), code));
3854 host->hostFlags |= VENUSDOWN;
3860 rx_PutConnection(cb_conn);
3863 host->hostFlags &= ~HWHO_INPROGRESS;
3873 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3874 * don't respond to a probe. Note that VenusDown can only be cleared if
3875 * a message is received from the host (see ServerLWP in file.c).
3876 * Delete hosts that have not had any calls in 1 hour, clients that
3877 * have not had any calls in 15 minutes.
3879 * This routine is called roughly every 5 minutes.
3884 afs_uint32 now = time(NULL);
3886 memset(&zerofid, 0, sizeof(zerofid));
3888 * Send a probe to the workstation if it hasn't been heard from in
3891 checktime = now - 15 * 60;
3892 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3895 h_Enumerate_r(CheckHost_r, hostList, NULL);
3900 * This is called with host locked and held. At this point, the
3901 * hostAddrHashTable has an entry for the primary addr/port inserted
3902 * by h_Alloc_r(). No other interfaces should be considered valid.
3904 * The addresses in the interfaceAddr list are in host byte order.
3907 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3914 struct Interface *interface;
3917 afs_uint16 port7001 = htons(7001);
3922 number = interf->numberOfInterfaces;
3923 myAddr = host->host; /* current interface address */
3924 myPort = host->port; /* current port */
3927 ("initInterfaceAddr : host %s:%d numAddr %d\n",
3928 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3930 /* validation checks */
3931 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3933 ("Invalid number of alternate addresses is %d\n", number));
3938 * The client's notion of its own IP addresses is not reliable.
3940 * 1. The client list might contain private address ranges which
3941 * are likely to be re-used by many clients allocated addresses
3944 * 2. The client list will not include any public addresses that
3945 * are hidden by a NAT.
3947 * 3. Private address ranges that are exposed to the server will
3948 * be obtained from the rx connections that use them.
3950 * 4. Lists provided by the client are not necessarily truthful.
3951 * Many existing clients (UNIX) do not refresh the IP address
3952 * list as the actual assigned addresses change. The end result
3953 * is that they report the initial address list for the lifetime
3954 * of the process. In other words, a client can report addresses
3955 * that they are in fact not using. Adding these addresses to
3956 * the host interface list without verification is not only
3957 * pointless, it is downright dangerous.
3959 * We therefore do not add alternate addresses to the addr hash table.
3960 * We only use them for multi-rx callback breaks.
3964 * Convert IP addresses to network byte order, and remove
3965 * duplicate and loopback IP addresses from the interface list, and
3966 * determine whether or not the incoming addr/port is
3967 * listed. Note that if the address matches it is not
3968 * truly a match because the port number for the entries
3969 * in the interface list are port 7001 and the port number
3970 * for this connection might not be 7001.
3972 for (i = 0, count = 0, found = 0; i < number; i++) {
3973 if (rx_IsLoopbackAddr(interf->addr_in[i])) {
3976 interf->addr_in[i] = htonl(interf->addr_in[i]);
3977 for (j = 0; j < count; j++) {
3978 if (interf->addr_in[j] == interf->addr_in[i])
3982 interf->addr_in[count] = interf->addr_in[i];
3983 if (interf->addr_in[count] == myAddr &&
3991 * Allocate and initialize an interface structure for this host.
3994 interface = malloc(sizeof(struct Interface) +
3995 (sizeof(struct AddrPort) * (count - 1)));
3997 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
3999 interface->numberOfInterfaces = count;
4001 interface = malloc(sizeof(struct Interface) +
4002 (sizeof(struct AddrPort) * count));
4004 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4006 interface->numberOfInterfaces = count + 1;
4007 interface->interface[count].addr = myAddr;
4008 interface->interface[count].port = myPort;
4009 interface->interface[count].valid = 1;
4012 for (i = 0; i < count; i++) {
4014 interface->interface[i].addr = interf->addr_in[i];
4015 /* We store the port as 7001 because the addresses reported by
4016 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4017 * are coming from fully connected hosts (no NAT/PATs)
4019 interface->interface[i].port = port7001;
4020 interface->interface[i].valid =
4021 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4024 interface->uuid = interf->uuid;
4026 opr_Assert(!host->interface);
4027 host->interface = interface;
4029 h_AddHostToUuidHashTable_r(&interface->uuid, host);
4031 if (LogLevel >= 125) {
4032 afsUUID_to_string(&interface->uuid, uuidstr, 127);
4034 ViceLog(125, ("--- uuid %s\n", uuidstr));
4035 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
4036 ViceLog(125, ("--- alt address %s:%d\n",
4037 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4038 ntohs(host->interface->interface[i].port)));
4045 /* deleted a HashChain structure for this address and host */
4046 /* returns 1 on success */
4048 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4052 struct h_AddrHashChain **hp, *th;
4054 if (addr == 0 && port == 0)
4057 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4059 opr_Assert(th->hostPtr);
4060 if (th->hostPtr == host && th->addr == addr && th->port == port) {
4061 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4062 host, afs_inet_ntoa_r(host->host, hoststr),
4063 ntohs(host->port)));
4070 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4071 host, afs_inet_ntoa_r(host->host, hoststr),
4072 ntohs(host->port)));
4078 ** prints out all alternate interface address for the host. The 'level'
4079 ** parameter indicates what level of debugging sets this output
4082 printInterfaceAddr(struct host *host, int level)
4087 if (host->interface) {
4088 /* check alternate addresses */
4089 number = host->interface->numberOfInterfaces;
4091 ViceLog(level, ("no-addresses "));
4093 for (i = 0; i < number; i++)
4094 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4095 ntohs(host->interface->interface[i].port)));
4098 ViceLog(level, ("\n"));