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 h_AddHostToUuidHashTable_r(&identP->uuid, host);
2131 cb_conn = host->callback_rxcon;
2132 rx_GetConnection(cb_conn);
2135 RXAFSCB_InitCallBackState3(cb_conn,
2137 rx_PutConnection(cb_conn);
2142 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2143 host, afs_inet_ntoa_r(host->host, hoststr),
2144 ntohs(host->port)));
2145 opr_Assert(interfValid == 1);
2146 initInterfaceAddr_r(host, &interf);
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.
2382 h_FindClient_r(struct rx_connection *tcon)
2384 struct client *client;
2385 struct host *host = NULL;
2386 struct client *oldClient;
2387 afs_int32 viceid = 0;
2395 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2396 if (client && client->sid == rx_GetConnectionId(tcon)
2397 && client->VenusEpoch == rx_GetConnectionEpoch(tcon)
2398 && !(client->host->hostFlags & HOSTDELETED)
2399 && !client->deleted) {
2402 h_Hold_r(client->host);
2403 if (client->prfail != 2) {
2404 /* Could add shared lock on client here */
2405 /* note that we don't have to lock entry in this path to
2406 * ensure CPS is initialized, since we don't call rx_SetSpecific
2407 * until initialization is done, and we only get here if
2408 * rx_GetSpecific located the client structure.
2413 ObtainWriteLock(&client->lock); /* released at end */
2419 authClass = rx_SecurityClassOf(tcon);
2421 code = getPeerDetails(tcon, &viceid, &expTime, authClass);
2425 if (!client) { /* loop */
2426 host = h_GetHost_r(tcon); /* Returns with incremented refCount */
2432 /* First try to find the client structure */
2433 for (client = host->FirstClient; client; client = client->next) {
2434 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2435 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2438 ObtainWriteLock(&client->lock);
2444 /* Still no client structure - get one */
2447 if (host->hostFlags & HOSTDELETED) {
2452 /* Retry to find the client structure */
2453 for (client = host->FirstClient; client; client = client->next) {
2454 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2455 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2457 goto retryfirstclient;
2462 ObtainWriteLock(&client->lock);
2463 client->refCount = 1;
2464 client->host = host;
2465 client->InSameNetwork = host->InSameNetwork;
2466 client->ViceId = viceid;
2467 client->expTime = expTime; /* rx only */
2468 client->authClass = authClass; /* rx only */
2469 client->sid = rx_GetConnectionId(tcon);
2470 client->VenusEpoch = rx_GetConnectionEpoch(tcon);
2471 client->CPS.prlist_val = NULL;
2472 client->CPS.prlist_len = 0;
2476 client->prfail = fail;
2478 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2479 client->CPS.prlist_len = 0;
2480 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2481 free(client->CPS.prlist_val);
2482 client->CPS.prlist_val = NULL;
2483 client->ViceId = viceid;
2484 client->expTime = expTime;
2486 if (viceid == ANONYMOUSID) {
2487 client->CPS.prlist_len = AnonCPS.prlist_len;
2488 client->CPS.prlist_val = AnonCPS.prlist_val;
2491 code = hpr_GetCPS(viceid, &client->CPS);
2496 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2497 code, viceid, client->host,
2498 afs_inet_ntoa_r(client->host->host,hoststr),
2499 ntohs(client->host->port)));
2501 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2502 * all protection servers and reevaluates things if no
2503 * sync server or quorum is found we could still end up
2504 * with one of these errors. In such case we would like to
2505 * reevaluate the rpc call to find if there's cps for this
2506 * guy. We treat other errors (except network failures
2507 * ones - i.e. code < 0) as an indication that there is no
2508 * CPS for this host. Ideally we could like to deal this
2509 * problem the other way around (i.e. if code == NOCPS
2510 * ignore else retry next time) but the problem is that
2511 * there're other errors (i.e. EPERM) for which we don't
2512 * want to retry and we don't know the whole code list!
2514 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2518 /* the disabling of system:administrators is so iffy and has so many
2519 * possible failure modes that we will disable it again */
2520 /* Turn off System:Administrator for safety
2521 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2522 * osi_Assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2525 /* Now, tcon may already be set to a rock, since we blocked with no host
2526 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2527 * required). So, before setting the RPC's rock, we should disconnect
2528 * the RPC from the other client structure's rock.
2530 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2531 if (oldClient && oldClient != client
2532 && oldClient->sid == rx_GetConnectionId(tcon)
2533 && oldClient->VenusEpoch == rx_GetConnectionEpoch(tcon)
2534 && !(oldClient->host->hostFlags & HOSTDELETED)) {
2536 if (!oldClient->deleted) {
2537 /* if we didn't create it, it's not ours to put back */
2539 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2540 "conn %p (host %s:%d) had client %p(%x)\n",
2541 client, client->sid, tcon,
2542 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2543 ntohs(rxr_PortOf(tcon)),
2544 oldClient, oldClient->sid));
2545 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2546 free(client->CPS.prlist_val);
2547 client->CPS.prlist_val = NULL;
2548 client->CPS.prlist_len = 0;
2550 /* We should perhaps check for 0 here */
2552 ReleaseWriteLock(&client->lock);
2557 oldClient->refCount++;
2559 h_Hold_r(oldClient->host);
2560 h_Release_r(client->host);
2563 ObtainWriteLock(&oldClient->lock);
2566 host = oldClient->host;
2568 ViceLog(0, ("FindClient: deleted client %p(%x ref %d host %p href "
2569 "%d) already had conn %p (host %s:%d, cid %x), stolen "
2570 "by client %p(%x, ref %d host %p href %d)\n",
2571 oldClient, oldClient->sid, oldClient->refCount,
2572 oldClient->host, oldClient->host->refCount, tcon,
2573 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2574 ntohs(rxr_PortOf(tcon)), rx_GetConnectionId(tcon),
2575 client, client->sid, client->refCount,
2576 client->host, client->host->refCount));
2577 /* rx_SetSpecific will be done immediately below */
2580 /* Avoid chaining in more than once. */
2584 if (host->hostFlags & HOSTDELETED) {
2589 client->host = NULL;
2591 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2592 free(client->CPS.prlist_val);
2593 client->CPS.prlist_val = NULL;
2594 client->CPS.prlist_len = 0;
2597 ReleaseWriteLock(&client->lock);
2602 client->next = host->FirstClient;
2603 host->FirstClient = client;
2605 CurrentConnections++; /* increment number of connections */
2607 rx_SetSpecific(tcon, rxcon_client_key, client);
2608 ReleaseWriteLock(&client->lock);
2612 } /*h_FindClient_r */
2615 h_ReleaseClient_r(struct client *client)
2617 opr_Assert(client->refCount > 0);
2624 * Sigh: this one is used to get the client AGAIN within the individual
2625 * server routines. This does not bother h_Holding the host, since
2626 * this is assumed already have been done by the server main loop.
2627 * It does check tokens, since only the server routines can return the
2628 * VICETOKENDEAD error code
2631 GetClient(struct rx_connection *tcon, struct client **cp)
2633 struct client *client;
2638 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2639 if (client == NULL) {
2641 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2642 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2643 ntohs(rxr_PortOf(tcon))));
2647 if (rx_GetConnectionId(tcon) != client->sid
2648 || rx_GetConnectionEpoch(tcon) != client->VenusEpoch) {
2650 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2651 tcon, rx_GetConnectionId(tcon), client->sid));
2655 if (client && client->LastCall > client->expTime && client->expTime) {
2657 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2658 afs_inet_ntoa_r(client->host->host, hoststr),
2659 ntohs(client->host->port), client->expTime));
2661 return VICETOKENDEAD;
2663 if (client->deleted) {
2664 ViceLog(0, ("GetClient: got deleted client, connection will appear "
2665 "anonymous; tcon %p cid %x client %p ref %d host %p "
2666 "(%s:%d) href %d ViceId %d\n",
2667 tcon, rx_GetConnectionId(tcon), client, client->refCount,
2669 afs_inet_ntoa_r(client->host->host, hoststr),
2670 (int)ntohs(client->host->port), client->host->refCount,
2671 (int)client->ViceId));
2681 PutClient(struct client **cp)
2687 h_ReleaseClient_r(*cp);
2694 /* Client user name for short term use. Note that this is NOT inexpensive */
2696 h_UserName(struct client *client)
2698 static char User[PR_MAXNAMELEN + 1];
2702 lids.idlist_len = 1;
2703 lids.idlist_val = malloc(1 * sizeof(afs_int32));
2704 if (!lids.idlist_val) {
2705 ViceLogThenPanic(0, ("Failed malloc in h_UserName\n"));
2707 lnames.namelist_len = 0;
2708 lnames.namelist_val = (prname *) 0;
2709 lids.idlist_val[0] = client->ViceId;
2710 if (hpr_IdToName(&lids, &lnames)) {
2711 /* We need to free id we alloced above! */
2712 free(lids.idlist_val);
2713 return "*UNKNOWN USER NAME*";
2715 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2716 free(lids.idlist_val);
2717 free(lnames.namelist_val);
2726 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2727 CEs, CEBlocks, HTs, HTBlocks));
2733 h_PrintClient(struct host *host, void *rock)
2735 StreamHandle_t *file = (StreamHandle_t *)rock;
2736 struct client *client;
2741 time_t LastCall, expTime;
2745 LastCall = host->LastCall;
2746 if (host->hostFlags & HOSTDELETED) {
2750 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2751 localtime_r(&LastCall, &tm));
2752 snprintf(tmpStr, sizeof tmpStr, "Host %s:%d down = %d, LastCall %s\n",
2753 afs_inet_ntoa_r(host->host, hoststr),
2754 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2756 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2757 for (client = host->FirstClient; client; client = client->next) {
2758 if (!client->deleted) {
2759 expTime = client->expTime;
2760 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2761 localtime_r(&expTime, &tm));
2762 snprintf(tmpStr, sizeof tmpStr,
2763 " user id=%d, name=%s, sl=%s till %s\n",
2764 client->ViceId, h_UserName(client),
2765 client->authClass ? "Authenticated"
2766 : "Not authenticated",
2767 client->authClass ? tbuffer : "No Limit");
2768 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2769 snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2770 client->CPS.prlist_len);
2771 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2772 if (client->CPS.prlist_val) {
2773 for (i = 0; i < client->CPS.prlist_len; i++) {
2774 snprintf(tmpStr, sizeof tmpStr, " %d",
2775 client->CPS.prlist_val[i]);
2776 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2779 sprintf(tmpStr, "]\n");
2780 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2786 } /*h_PrintClient */
2791 * Print a list of clients, with last security level and token value seen,
2795 h_PrintClients(void)
2802 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2806 ("Couldn't create client dump file %s\n",
2807 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2811 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2812 localtime_r(&now, &tm));
2813 snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n\n",
2815 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2816 h_Enumerate(h_PrintClient, (char *)file);
2817 STREAM_REALLYCLOSE(file);
2818 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2825 h_DumpHost(struct host *host, void *rock)
2827 StreamHandle_t *file = (StreamHandle_t *)rock;
2834 snprintf(tmpStr, sizeof tmpStr,
2835 "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u "
2836 "down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u "
2838 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
2839 host->index, host->cblist, CheckLock(&host->lock),
2840 host->LastCall, host->ActiveCall, (host->hostFlags & VENUSDOWN),
2841 host->hostFlags & HOSTDELETED, host->Console,
2842 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2844 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2845 if (host->hcps.prlist_val)
2846 for (i = 0; i < host->hcps.prlist_len; i++) {
2847 snprintf(tmpStr, sizeof tmpStr, " %d", host->hcps.prlist_val[i]);
2848 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2850 sprintf(tmpStr, "] [");
2851 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2852 if (host->interface)
2853 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2855 sprintf(tmpStr, " %s:%d",
2856 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2857 ntohs(host->interface->interface[i].port));
2858 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2860 sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2861 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2873 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2880 ("Couldn't create host dump file %s\n",
2881 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2885 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2886 localtime_r(&now, &tm));
2887 snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n\n", tbuffer);
2888 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2889 h_Enumerate(h_DumpHost, (char *)file);
2890 STREAM_REALLYCLOSE(file);
2891 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2895 #ifdef AFS_DEMAND_ATTACH_FS
2898 * host state serialization
2900 static int h_stateFillHeader(struct host_state_header * hdr);
2901 static int h_stateCheckHeader(struct host_state_header * hdr);
2902 static int h_stateAllocMap(struct fs_dump_state * state);
2903 static int h_stateSaveHost(struct host * host, void *rock);
2904 static int h_stateRestoreHost(struct fs_dump_state * state);
2905 static int h_stateRestoreIndex(struct host * h, void *rock);
2906 static int h_stateVerifyHost(struct host * h, void *rock);
2907 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
2908 afs_uint32 addr, afs_uint16 port, int valid);
2909 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2910 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2911 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2914 * Is this host busy?
2916 * This is just a hint and should not be trusted; this should probably only be
2917 * used by the host state serialization code when trying to detect if a host
2918 * can be sanely serialized to disk or not. If this function returns 1, the
2919 * host may be in an invalid state and thus should not be saved to disk.
2922 h_isBusy_r(struct host *host)
2924 struct Lock *hostLock = &host->lock;
2927 LOCK_LOCK(hostLock);
2928 if (hostLock->excl_locked || hostLock->readers_reading) {
2931 LOCK_UNLOCK(hostLock);
2937 if ((host->hostFlags & HWHO_INPROGRESS) || !(host->hostFlags & ALTADDR)) {
2938 /* We shouldn't hit this if the host wasn't locked, but just in case... */
2945 /* this procedure saves all host state to disk for fast startup */
2947 h_stateSave(struct fs_dump_state * state)
2949 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2952 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2954 /* invalidate host state header */
2955 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2957 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2958 sizeof(struct host_state_header))) {
2963 fs_stateIncEOF(state, sizeof(struct host_state_header));
2965 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2970 h_stateFillHeader(state->h_hdr);
2972 /* write the real header to disk */
2973 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2974 sizeof(struct host_state_header));
2981 * host state serialization
2983 * this procedure restores all host state from a disk for fast startup
2986 h_stateRestore(struct fs_dump_state * state)
2990 /* seek to the right position and read in the host state header */
2991 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2992 sizeof(struct host_state_header))) {
2997 /* check the validity of the header */
2998 if (h_stateCheckHeader(state->h_hdr)) {
3003 records = state->h_hdr->records;
3005 if (h_stateAllocMap(state)) {
3010 /* iterate over records restoring host state */
3011 for (i=0; i < records; i++) {
3012 if (h_stateRestoreHost(state) != 0) {
3023 h_stateRestoreIndices(struct fs_dump_state * state)
3025 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
3030 h_stateRestoreIndex(struct host * h, void *rock)
3032 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3033 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
3034 return H_ENUMERATE_BAIL(0);
3040 h_stateVerify(struct fs_dump_state * state)
3042 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
3047 h_stateVerifyHost(struct host * h, void* rock)
3049 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3053 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3054 return H_ENUMERATE_BAIL(0);
3058 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
3059 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
3060 h->interface->interface[i].port,
3061 h->interface->interface[i].valid)) {
3065 if (h_stateVerifyUuidHash(state, h)) {
3068 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
3072 if (cb_stateVerifyHCBList(state, h)) {
3080 * verify a host is either in, or absent from, the addr hash table.
3082 * @param[in] state fs dump state
3083 * @param[in] h host we're dealing with
3084 * @param[in] addr addr to look for (NBO)
3085 * @param[in] port port to look for (NBO)
3086 * @param[in] valid 1 if we're verifying that the specified addr and port
3087 * in the hash table point to the specified host. 0 if we're
3088 * verifying that the specified addr and port do NOT point
3089 * to the specified host
3091 * @return operation status
3092 * @retval 1 failed to verify, bail out
3093 * @retval 0 verified successfully, all is well
3096 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3097 afs_uint32 addr, afs_uint16 port, int valid)
3099 int ret = 0, found = 0;
3100 struct host *host = NULL;
3101 struct h_AddrHashChain *chain;
3102 int index = h_HashIndex(addr);
3106 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3107 host = chain->hostPtr;
3109 afs_inet_ntoa_r(addr, tmp);
3110 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3114 if ((chain->addr == addr) && (chain->port == port)) {
3117 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3118 "points to different host struct (%d, %d)\n",
3119 h->index, host->index));
3120 state->flags.warnings_generated = 1;
3124 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3125 "marked invalid, but points to the containing "
3126 "host\n", afs_inet_ntoa_r(addr, tmp),
3127 (unsigned)htons(port)));
3135 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3136 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3137 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3144 if (!found && valid) {
3145 afs_inet_ntoa_r(addr, tmp);
3146 if (state->mode == FS_STATE_LOAD_MODE) {
3147 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3148 tmp, (unsigned)htons(port)));
3152 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3153 tmp, (unsigned)htons(port)));
3154 state->flags.warnings_generated = 1;
3163 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3165 int ret = 0, found = 0;
3166 struct host *host = NULL;
3167 struct h_UuidHashChain *chain;
3168 afsUUID * uuidp = &h->interface->uuid;
3169 int index = h_UuidHashIndex(uuidp);
3173 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3174 host = chain->hostPtr;
3176 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3177 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3181 if (host->interface &&
3182 afs_uuid_equal(&host->interface->uuid, uuidp)) {
3184 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3185 h->index, host->index));
3186 state->flags.warnings_generated = 1;
3191 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3192 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3193 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3201 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3202 if (state->mode == FS_STATE_LOAD_MODE) {
3203 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3207 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3208 state->flags.warnings_generated = 1;
3216 /* create the host state header structure */
3218 h_stateFillHeader(struct host_state_header * hdr)
3220 hdr->stamp.magic = HOST_STATE_MAGIC;
3221 hdr->stamp.version = HOST_STATE_VERSION;
3225 /* check the contents of the host state header structure */
3227 h_stateCheckHeader(struct host_state_header * hdr)
3231 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3232 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3235 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3236 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3242 /* allocate the host id mapping table */
3244 h_stateAllocMap(struct fs_dump_state * state)
3246 state->h_map.len = state->h_hdr->index_max + 1;
3247 state->h_map.entries = (struct idx_map_entry_t *)
3248 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3249 return (state->h_map.entries != NULL) ? 0 : 1;
3252 /* function called by h_Enumerate to save a host to disk */
3254 h_stateSaveHost(struct host * host, void* rock)
3256 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3257 int if_len=0, hcps_len=0;
3258 struct hostDiskEntry hdsk;
3259 struct host_state_entry_header hdr;
3260 struct Interface * ifp = NULL;
3261 afs_int32 * hcps = NULL;
3262 struct iovec iov[4];
3265 if (h_isBusy_r(host)) {
3267 ViceLog(1, ("Not saving host %s:%d to disk; host appears busy\n",
3268 afs_inet_ntoa_r(host->host, hoststr), (int)ntohs(host->port)));
3269 /* Make sure we don't try to save callbacks to disk for this host, or
3270 * we'll get confused on restore */
3271 DeleteAllCallBacks_r(host, 1);
3275 memset(&hdr, 0, sizeof(hdr));
3277 if (state->h_hdr->index_max < host->index) {
3278 state->h_hdr->index_max = host->index;
3281 h_hostToDiskEntry_r(host, &hdsk);
3282 if (host->interface) {
3283 if_len = sizeof(struct Interface) +
3284 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3285 ifp = malloc(if_len);
3286 opr_Assert(ifp != NULL);
3287 memcpy(ifp, host->interface, if_len);
3288 hdr.interfaces = host->interface->numberOfInterfaces;
3289 iov[iovcnt].iov_base = (char *) ifp;
3290 iov[iovcnt].iov_len = if_len;
3293 if (host->hcps.prlist_val) {
3294 hdr.hcps = host->hcps.prlist_len;
3295 hcps_len = hdr.hcps * sizeof(afs_int32);
3296 hcps = malloc(hcps_len);
3297 opr_Assert(hcps != NULL);
3298 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3299 iov[iovcnt].iov_base = (char *) hcps;
3300 iov[iovcnt].iov_len = hcps_len;
3304 if (hdsk.index > state->h_hdr->index_max)
3305 state->h_hdr->index_max = hdsk.index;
3307 hdr.len = sizeof(struct host_state_entry_header) +
3308 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3309 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3311 iov[0].iov_base = (char *) &hdr;
3312 iov[0].iov_len = sizeof(hdr);
3313 iov[1].iov_base = (char *) &hdsk;
3314 iov[1].iov_len = sizeof(struct hostDiskEntry);
3316 if (fs_stateWriteV(state, iov, iovcnt)) {
3317 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3321 fs_stateIncEOF(state, hdr.len);
3323 state->h_hdr->records++;
3330 return H_ENUMERATE_BAIL(0);
3335 /* restores a host from disk */
3337 h_stateRestoreHost(struct fs_dump_state * state)
3339 int ifp_len=0, hcps_len=0, bail=0;
3340 struct host_state_entry_header hdr;
3341 struct hostDiskEntry hdsk;
3342 struct host *host = NULL;
3343 struct Interface *ifp = NULL;
3344 afs_int32 * hcps = NULL;
3345 struct iovec iov[3];
3348 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3349 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3355 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3356 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3362 iov[0].iov_base = (char *) &hdsk;
3363 iov[0].iov_len = sizeof(struct hostDiskEntry);
3365 if (hdr.interfaces) {
3366 ifp_len = sizeof(struct Interface) +
3367 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3368 ifp = malloc(ifp_len);
3369 opr_Assert(ifp != NULL);
3370 iov[iovcnt].iov_base = (char *) ifp;
3371 iov[iovcnt].iov_len = ifp_len;
3375 hcps_len = hdr.hcps * sizeof(afs_int32);
3376 hcps = malloc(hcps_len);
3377 opr_Assert(hcps != NULL);
3378 iov[iovcnt].iov_base = (char *) hcps;
3379 iov[iovcnt].iov_len = hcps_len;
3383 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3384 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3389 if (fs_stateReadV(state, iov, iovcnt)) {
3390 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3395 if (!hdr.hcps && hdsk.hcps_valid) {
3396 /* valid, zero-length host cps ; does this ever happen? */
3397 hcps = malloc(sizeof(afs_int32));
3398 opr_Assert(hcps != NULL);
3401 if ((hdsk.hostFlags & HWHO_INPROGRESS) || !(hdsk.hostFlags & ALTADDR)) {
3403 ViceLog(0, ("h_stateRestoreHost: skipping host %s:%d due to invalid flags 0x%x\n",
3404 afs_inet_ntoa_r(hdsk.host, hoststr), (int)ntohs(hdsk.port),
3405 (unsigned)hdsk.hostFlags));
3407 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_SKIPPED;
3411 /* for restoring state, we better be able to get a host! */
3413 opr_Assert(host != NULL);
3416 host->interface = ifp;
3419 host->hcps.prlist_val = hcps;
3420 host->hcps.prlist_len = hdr.hcps;
3423 h_diskEntryToHost_r(&hdsk, host);
3424 h_SetupCallbackConn_r(host);
3426 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3429 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3430 if (ifp->interface[i].valid &&
3431 !(ifp->interface[i].addr == host->host &&
3432 ifp->interface[i].port == host->port)) {
3433 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3434 ifp->interface[i].port,
3438 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3440 h_InsertList_r(host);
3442 /* setup host id map entry */
3443 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_VALID;
3444 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3445 state->h_map.entries[hdsk.index].new_idx = host->index;
3457 /* serialize a host structure to disk */
3459 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3461 out->host = in->host;
3462 out->port = in->port;
3463 out->hostFlags = in->hostFlags;
3464 out->Console = in->Console;
3465 out->hcpsfailed = in->hcpsfailed;
3466 out->LastCall = in->LastCall;
3467 out->ActiveCall = in->ActiveCall;
3468 out->cpsCall = in->cpsCall;
3469 out->cblist = in->cblist;
3470 out->InSameNetwork = in->InSameNetwork;
3472 /* special fields we save, but are not memcpy'd back on restore */
3473 out->index = in->index;
3474 out->hcps_len = in->hcps.prlist_len;
3475 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3478 /* restore a host structure from disk */
3480 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3482 out->host = in->host;
3483 out->port = in->port;
3484 out->hostFlags = in->hostFlags;
3485 out->Console = in->Console;
3486 out->hcpsfailed = in->hcpsfailed;
3487 out->LastCall = in->LastCall;
3488 out->ActiveCall = in->ActiveCall;
3489 out->cpsCall = in->cpsCall;
3490 out->cblist = in->cblist;
3491 out->InSameNetwork = in->InSameNetwork;
3494 /* index translation routines */
3496 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3500 /* hosts use a zero-based index, so old==0 is valid */
3502 if (old >= state->h_map.len) {
3503 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3505 } else if (state->h_map.entries[old].valid != FS_STATE_IDX_VALID ||
3506 state->h_map.entries[old].old_idx != old) { /* sanity check */
3507 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3510 *new = state->h_map.entries[old].new_idx;
3515 #endif /* AFS_DEMAND_ATTACH_FS */
3519 * This counts the number of workstations, the number of active workstations,
3520 * and the number of workstations declared "down" (i.e. not heard from
3521 * recently). An active workstation has received a call since the cutoff
3522 * time argument passed.
3525 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3528 int num = 0, active = 0, del = 0;
3532 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3533 if (!(host->hostFlags & HOSTDELETED)) {
3535 if (host->ActiveCall > cutofftime)
3537 if (host->hostFlags & VENUSDOWN)
3541 if (count != hostCount) {
3542 ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3543 } else if (host != NULL) {
3544 ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3545 ShutDownAndCore(PANIC);
3555 } /*h_GetWorkStats */
3558 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp,
3559 afs_int32 cutofftime)
3561 int num, active, del;
3562 h_GetWorkStats(&num, &active, &del, cutofftime);
3571 /*------------------------------------------------------------------------
3572 * PRIVATE h_ClassifyAddress
3575 * Given a target IP address and a candidate IP address (both
3576 * in host byte order), classify the candidate into one of three
3577 * buckets in relation to the target by bumping the counters passed
3581 * a_targetAddr : Target address.
3582 * a_candAddr : Candidate address.
3583 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3584 * addresses are either in the same network
3585 * or the same subnet.
3586 * a_diffSubnetP : ...when the candidate is in a different
3588 * a_diffNetworkP : ...when the candidate is in a different
3595 * The target and candidate addresses are both in host byte
3596 * order, NOT network byte order, when passed in.
3600 *------------------------------------------------------------------------*/
3603 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3604 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3605 afs_int32 * a_diffNetworkP)
3606 { /*h_ClassifyAddress */
3608 afs_uint32 targetNet;
3609 afs_uint32 targetSubnet;
3611 afs_uint32 candSubnet;
3614 * Put bad values into the subnet info to start with.
3616 targetSubnet = (afs_uint32) 0;
3617 candSubnet = (afs_uint32) 0;
3620 * Pull out the network and subnetwork numbers from the target
3621 * and candidate addresses. We can short-circuit this whole
3622 * affair if the target and candidate addresses are not of the
3625 if (IN_CLASSA(a_targetAddr)) {
3626 if (!(IN_CLASSA(a_candAddr))) {
3627 (*a_diffNetworkP)++;
3630 targetNet = a_targetAddr & IN_CLASSA_NET;
3631 candNet = a_candAddr & IN_CLASSA_NET;
3632 if (IN_SUBNETA(a_targetAddr))
3633 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3634 if (IN_SUBNETA(a_candAddr))
3635 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3636 } else if (IN_CLASSB(a_targetAddr)) {
3637 if (!(IN_CLASSB(a_candAddr))) {
3638 (*a_diffNetworkP)++;
3641 targetNet = a_targetAddr & IN_CLASSB_NET;
3642 candNet = a_candAddr & IN_CLASSB_NET;
3643 if (IN_SUBNETB(a_targetAddr))
3644 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3645 if (IN_SUBNETB(a_candAddr))
3646 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3647 } /*Class B target */
3648 else if (IN_CLASSC(a_targetAddr)) {
3649 if (!(IN_CLASSC(a_candAddr))) {
3650 (*a_diffNetworkP)++;
3653 targetNet = a_targetAddr & IN_CLASSC_NET;
3654 candNet = a_candAddr & IN_CLASSC_NET;
3657 * Note that class C addresses can't have subnets,
3658 * so we leave the defaults untouched.
3660 } /*Class C target */
3662 targetNet = a_targetAddr;
3663 candNet = a_candAddr;
3664 } /*Class D address */
3667 * Now, simply compare the extracted net and subnet values for
3668 * the two addresses (which at this point are known to be of the
3671 if (targetNet == candNet) {
3672 if (targetSubnet == candSubnet)
3673 (*a_sameNetOrSubnetP)++;
3677 (*a_diffNetworkP)++;
3679 } /*h_ClassifyAddress */
3682 /*------------------------------------------------------------------------
3683 * EXPORTED h_GetHostNetStats
3686 * Iterate through the host table, and classify each (non-deleted)
3687 * host entry into ``proximity'' categories (same net or subnet,
3688 * different subnet, different network).
3691 * a_numHostsP : Set to total number of (non-deleted) hosts.
3692 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3693 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3694 * a_diffNetworkP : Set to # hosts on diff network as server.
3700 * We only count non-deleted hosts. The storage pointed to by our
3701 * parameters is zeroed upon entry.
3705 *------------------------------------------------------------------------*/
3708 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3709 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3710 { /*h_GetHostNetStats */
3712 struct host *hostP; /*Ptr to current host entry */
3713 afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3717 * Clear out the storage pointed to by our parameters.
3719 *a_numHostsP = (afs_int32) 0;
3720 *a_sameNetOrSubnetP = (afs_int32) 0;
3721 *a_diffSubnetP = (afs_int32) 0;
3722 *a_diffNetworkP = (afs_int32) 0;
3725 for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3726 if (!(hostP->hostFlags & HOSTDELETED)) {
3728 * Bump the number of undeleted host entries found.
3729 * In classifying the current entry's address, make
3730 * sure to first convert to host byte order.
3733 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3734 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3735 a_sameNetOrSubnetP, a_diffSubnetP,
3737 } /*Only look at non-deleted hosts */
3738 } /*For each host record hashed to this index */
3739 if (count != hostCount) {
3740 ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3741 } else if (hostP != NULL) {
3742 ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3743 ShutDownAndCore(PANIC);
3746 } /*h_GetHostNetStats */
3748 static afs_uint32 checktime;
3749 static afs_uint32 clientdeletetime;
3750 static struct AFSFid zerofid;
3754 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3755 * Since it can serialize them, and pile up, it should be a separate LWP
3756 * from other events.
3760 CheckHost(struct host *host, int flags, void *rock)
3762 struct client *client;
3763 struct rx_connection *cb_conn = NULL;
3766 #ifdef AFS_DEMAND_ATTACH_FS
3767 /* kill the checkhost lwp ASAP during shutdown */
3769 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3771 return H_ENUMERATE_BAIL(flags);
3776 /* Host is held by h_Enumerate */
3778 for (client = host->FirstClient; client; client = client->next) {
3779 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3780 client->deleted = 1;
3781 host->hostFlags |= CLIENTDELETED;
3784 if (host->LastCall < checktime) {
3786 if (!(host->hostFlags & HOSTDELETED)) {
3787 host->hostFlags |= HWHO_INPROGRESS;
3788 cb_conn = host->callback_rxcon;
3789 rx_GetConnection(cb_conn);
3790 if (host->LastCall < clientdeletetime) {
3791 host->hostFlags |= HOSTDELETED;
3792 if (!(host->hostFlags & VENUSDOWN)) {
3793 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3794 if (host->interface) {
3797 RXAFSCB_InitCallBackState3(cb_conn,
3803 RXAFSCB_InitCallBackState(cb_conn);
3806 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3809 (void)afs_inet_ntoa_r(host->host, hoststr);
3811 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3812 hoststr, ntohs(host->port)));
3813 host->hostFlags |= VENUSDOWN;
3815 /* Note: it's safe to delete hosts even if they have call
3816 * back state, because break delayed callbacks (called when a
3817 * message is received from the workstation) will always send a
3818 * break all call backs to the workstation if there is no
3823 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3825 (void)afs_inet_ntoa_r(host->host, hoststr);
3826 if (host->interface) {
3827 afsUUID uuid = host->interface->uuid;
3829 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3832 if (MultiProbeAlternateAddress_r(host)) {
3833 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3834 hoststr, ntohs(host->port), code));
3835 host->hostFlags |= VENUSDOWN;
3840 code = RXAFSCB_Probe(cb_conn);
3844 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3845 hoststr, ntohs(host->port), code));
3846 host->hostFlags |= VENUSDOWN;
3852 rx_PutConnection(cb_conn);
3855 host->hostFlags &= ~HWHO_INPROGRESS;
3866 CheckHost_r(struct host *host, void *dummy)
3868 struct client *client;
3869 struct rx_connection *cb_conn = NULL;
3872 #ifdef AFS_DEMAND_ATTACH_FS
3873 /* kill the checkhost lwp ASAP during shutdown */
3875 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3877 return H_ENUMERATE_BAIL(0);
3882 /* Host is held by h_Enumerate_r */
3883 for (client = host->FirstClient; client; client = client->next) {
3884 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3885 client->deleted = 1;
3886 host->hostFlags |= CLIENTDELETED;
3889 if (host->LastCall < checktime) {
3891 if (!(host->hostFlags & HOSTDELETED)) {
3892 host->hostFlags |= HWHO_INPROGRESS;
3893 cb_conn = host->callback_rxcon;
3894 rx_GetConnection(cb_conn);
3895 if (host->LastCall < clientdeletetime) {
3896 host->hostFlags |= HOSTDELETED;
3897 if (!(host->hostFlags & VENUSDOWN)) {
3898 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3899 if (host->interface) {
3902 RXAFSCB_InitCallBackState3(cb_conn,
3908 RXAFSCB_InitCallBackState(cb_conn);
3911 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3914 (void)afs_inet_ntoa_r(host->host, hoststr);
3916 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3917 hoststr, ntohs(host->port)));
3918 host->hostFlags |= VENUSDOWN;
3920 /* Note: it's safe to delete hosts even if they have call
3921 * back state, because break delayed callbacks (called when a
3922 * message is received from the workstation) will always send a
3923 * break all call backs to the workstation if there is no
3928 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3930 (void)afs_inet_ntoa_r(host->host, hoststr);
3931 if (host->interface) {
3932 afsUUID uuid = host->interface->uuid;
3934 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3937 if (MultiProbeAlternateAddress_r(host)) {
3938 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3939 hoststr, ntohs(host->port), code));
3940 host->hostFlags |= VENUSDOWN;
3945 code = RXAFSCB_Probe(cb_conn);
3949 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3950 hoststr, ntohs(host->port), code));
3951 host->hostFlags |= VENUSDOWN;
3957 rx_PutConnection(cb_conn);
3960 host->hostFlags &= ~HWHO_INPROGRESS;
3970 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3971 * don't respond to a probe. Note that VenusDown can only be cleared if
3972 * a message is received from the host (see ServerLWP in file.c).
3973 * Delete hosts that have not had any calls in 1 hour, clients that
3974 * have not had any calls in 15 minutes.
3976 * This routine is called roughly every 5 minutes.
3981 afs_uint32 now = time(NULL);
3983 memset(&zerofid, 0, sizeof(zerofid));
3985 * Send a probe to the workstation if it hasn't been heard from in
3988 checktime = now - 15 * 60;
3989 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3992 h_Enumerate_r(CheckHost_r, hostList, NULL);
3997 * This is called with host locked and held. At this point, the
3998 * hostAddrHashTable has an entry for the primary addr/port inserted
3999 * by h_Alloc_r(). No other interfaces should be considered valid.
4001 * The addresses in the interfaceAddr list are in host byte order.
4004 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
4011 struct Interface *interface;
4014 afs_uint16 port7001 = htons(7001);
4019 number = interf->numberOfInterfaces;
4020 myAddr = host->host; /* current interface address */
4021 myPort = host->port; /* current port */
4024 ("initInterfaceAddr : host %s:%d numAddr %d\n",
4025 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
4027 /* validation checks */
4028 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
4030 ("Invalid number of alternate addresses is %d\n", number));
4035 * The client's notion of its own IP addresses is not reliable.
4037 * 1. The client list might contain private address ranges which
4038 * are likely to be re-used by many clients allocated addresses
4041 * 2. The client list will not include any public addresses that
4042 * are hidden by a NAT.
4044 * 3. Private address ranges that are exposed to the server will
4045 * be obtained from the rx connections that use them.
4047 * 4. Lists provided by the client are not necessarily truthful.
4048 * Many existing clients (UNIX) do not refresh the IP address
4049 * list as the actual assigned addresses change. The end result
4050 * is that they report the initial address list for the lifetime
4051 * of the process. In other words, a client can report addresses
4052 * that they are in fact not using. Adding these addresses to
4053 * the host interface list without verification is not only
4054 * pointless, it is downright dangerous.
4056 * We therefore do not add alternate addresses to the addr hash table.
4057 * We only use them for multi-rx callback breaks.
4061 * Convert IP addresses to network byte order, and remove
4062 * duplicate and loopback IP addresses from the interface list, and
4063 * determine whether or not the incoming addr/port is
4064 * listed. Note that if the address matches it is not
4065 * truly a match because the port number for the entries
4066 * in the interface list are port 7001 and the port number
4067 * for this connection might not be 7001.
4069 for (i = 0, count = 0, found = 0; i < number; i++) {
4070 if (rx_IsLoopbackAddr(interf->addr_in[i])) {
4073 interf->addr_in[i] = htonl(interf->addr_in[i]);
4074 for (j = 0; j < count; j++) {
4075 if (interf->addr_in[j] == interf->addr_in[i])
4079 interf->addr_in[count] = interf->addr_in[i];
4080 if (interf->addr_in[count] == myAddr &&
4088 * Allocate and initialize an interface structure for this host.
4091 interface = malloc(sizeof(struct Interface) +
4092 (sizeof(struct AddrPort) * (count - 1)));
4094 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
4096 interface->numberOfInterfaces = count;
4098 interface = malloc(sizeof(struct Interface) +
4099 (sizeof(struct AddrPort) * count));
4101 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4103 interface->numberOfInterfaces = count + 1;
4104 interface->interface[count].addr = myAddr;
4105 interface->interface[count].port = myPort;
4106 interface->interface[count].valid = 1;
4109 for (i = 0; i < count; i++) {
4111 interface->interface[i].addr = interf->addr_in[i];
4112 /* We store the port as 7001 because the addresses reported by
4113 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4114 * are coming from fully connected hosts (no NAT/PATs)
4116 interface->interface[i].port = port7001;
4117 interface->interface[i].valid =
4118 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4121 interface->uuid = interf->uuid;
4123 opr_Assert(!host->interface);
4124 host->interface = interface;
4126 if (LogLevel >= 125) {
4127 afsUUID_to_string(&interface->uuid, uuidstr, 127);
4129 ViceLog(125, ("--- uuid %s\n", uuidstr));
4130 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
4131 ViceLog(125, ("--- alt address %s:%d\n",
4132 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4133 ntohs(host->interface->interface[i].port)));
4140 /* deleted a HashChain structure for this address and host */
4141 /* returns 1 on success */
4143 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4147 struct h_AddrHashChain **hp, *th;
4149 if (addr == 0 && port == 0)
4152 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4154 opr_Assert(th->hostPtr);
4155 if (th->hostPtr == host && th->addr == addr && th->port == port) {
4156 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4157 host, afs_inet_ntoa_r(host->host, hoststr),
4158 ntohs(host->port)));
4165 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4166 host, afs_inet_ntoa_r(host->host, hoststr),
4167 ntohs(host->port)));
4173 ** prints out all alternate interface address for the host. The 'level'
4174 ** parameter indicates what level of debugging sets this output
4177 printInterfaceAddr(struct host *host, int level)
4182 if (host->interface) {
4183 /* check alternate addresses */
4184 number = host->interface->numberOfInterfaces;
4186 ViceLog(level, ("no-addresses "));
4188 for (i = 0; i < number; i++)
4189 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4190 ntohs(host->interface->interface[i].port)));
4193 ViceLog(level, ("\n"));