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 cb_conn = host->callback_rxcon;
2131 rx_GetConnection(cb_conn);
2134 RXAFSCB_InitCallBackState3(cb_conn,
2136 rx_PutConnection(cb_conn);
2141 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2142 host, afs_inet_ntoa_r(host->host, hoststr),
2143 ntohs(host->port)));
2144 opr_Assert(interfValid == 1);
2145 initInterfaceAddr_r(host, &interf);
2151 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2152 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2153 host->hostFlags |= VENUSDOWN;
2156 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2157 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2158 host->hostFlags |= RESETDONE;
2161 if (caps.Capabilities_val
2162 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2163 host->hostFlags |= HERRORTRANS;
2165 host->hostFlags &= ~(HERRORTRANS);
2166 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2167 host->hostFlags &= ~HWHO_INPROGRESS;
2172 if (caps.Capabilities_val)
2173 free(caps.Capabilities_val);
2174 caps.Capabilities_val = NULL;
2175 caps.Capabilities_len = 0;
2177 rx_DestroyConnection(cb_in);
2187 h_InitHostPackage(void)
2189 memset(&nulluuid, 0, sizeof(afsUUID));
2190 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2191 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2192 opr_mutex_init(&host_glock_mutex);
2196 MapName_r(char *uname, afs_int32 * aval)
2202 lnames.namelist_len = 1;
2203 lnames.namelist_val = (prname *) uname;
2204 lids.idlist_len = 0;
2205 lids.idlist_val = NULL;
2208 code = hpr_NameToId(&lnames, &lids);
2211 if (lids.idlist_val) {
2212 *aval = lids.idlist_val[0];
2213 if (*aval == AnonymousID) {
2215 ("MapName: NameToId on %s returns anonymousID\n",
2216 lnames.namelist_val[0]));
2218 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2221 ("MapName: NameToId on '%s' is unknown\n",
2222 lnames.namelist_val[0]));
2233 PerHost_EnumerateClient(struct host *host, void *arock)
2235 struct enumclient_args *args = arock;
2236 struct client *client;
2239 for (client = host->FirstClient; client; client = client->next) {
2240 if (!client->deleted && client->ViceId == args->vid) {
2245 code = (*args->proc)(client, args->rock);
2248 h_ReleaseClient_r(client);
2251 return H_ENUMERATE_BAIL(0);
2260 h_EnumerateClients(VolumeId vid,
2261 int (*proc)(struct client *client, void *rock),
2264 struct enumclient_args args;
2270 h_Enumerate_r(PerHost_EnumerateClient, hostList, &args);
2275 format_vname(char *vname, int usize, const char *tname, const char *tinst,
2276 const char *tcell, afs_int32 islocal)
2280 len = strlcpy(vname, tname, usize);
2284 len = strlcat(vname, ".", usize);
2287 len = strlcat(vname, tinst, usize);
2291 if (tcell[0] && !islocal) {
2292 len = strlcat(vname, "@", usize);
2295 len = strlcat(vname, tcell, usize);
2303 getPeerDetails(struct rx_connection *conn,
2304 afs_int32 *viceid, afs_int32 *expTime, int authClass)
2307 #if (64-MAXKTCNAMELEN)
2308 ticket name length != 64
2312 char tcell[MAXKTCREALMLEN];
2313 char uname[PR_MAXNAMELEN];
2315 *viceid = AnonymousID;
2316 *expTime = 0x7fffffff;
2319 ("FindClient: authenticating connection: authClass=%d\n",
2321 if (authClass == 1) {
2322 /* A bcrypt tickets, no longer supported */
2323 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2327 if (authClass == 2) {
2328 /* an rxkad ticket */
2332 /* kerberos ticket */
2333 code = rxkad_GetServerInfo(conn, /*level */ 0, (afs_uint32 *)expTime,
2334 tname, tinst, tcell, &kvno);
2336 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2341 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2342 tname, tinst, tcell, *expTime, kvno));
2343 code = afsconf_IsLocalRealmMatch(confDir, &islocal, tname, tinst, tcell);
2346 ViceLog(0, ("FindClient: local realm check failed; code=%d", code));
2350 code = format_vname(uname, sizeof(uname), tname, tinst, tcell, islocal);
2352 ViceLog(0, ("FindClient: uname truncated."));
2356 /* translate the name to a vice id */
2357 code = MapName_r(uname, viceid);
2359 ViceLog(1, ("failed to map name=%s -> code=%d\n", uname,
2361 return code; /* Actually flag this is a failure */
2371 * Called by the server main loop. Returns a h_Held client, which must be
2372 * released later the main loop. Allocates a client if the matching one
2373 * isn't around. The client is returned with its reference count incremented
2374 * by one. The caller must call h_ReleaseClient_r when finished with
2377 * The refCount on client->host is returned incremented. h_ReleaseClient_r
2378 * does not decrement the refCount on client->host.
2381 h_FindClient_r(struct rx_connection *tcon)
2383 struct client *client;
2384 struct host *host = NULL;
2385 struct client *oldClient;
2386 afs_int32 viceid = 0;
2394 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2395 if (client && client->sid == rx_GetConnectionId(tcon)
2396 && client->VenusEpoch == rx_GetConnectionEpoch(tcon)
2397 && !(client->host->hostFlags & HOSTDELETED)
2398 && !client->deleted) {
2401 h_Hold_r(client->host);
2402 if (client->prfail != 2) {
2403 /* Could add shared lock on client here */
2404 /* note that we don't have to lock entry in this path to
2405 * ensure CPS is initialized, since we don't call rx_SetSpecific
2406 * until initialization is done, and we only get here if
2407 * rx_GetSpecific located the client structure.
2412 ObtainWriteLock(&client->lock); /* released at end */
2418 authClass = rx_SecurityClassOf(tcon);
2420 code = getPeerDetails(tcon, &viceid, &expTime, authClass);
2424 if (!client) { /* loop */
2425 host = h_GetHost_r(tcon); /* Returns with incremented refCount */
2431 /* First try to find the client structure */
2432 for (client = host->FirstClient; client; client = client->next) {
2433 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2434 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2437 ObtainWriteLock(&client->lock);
2443 /* Still no client structure - get one */
2446 if (host->hostFlags & HOSTDELETED) {
2451 /* Retry to find the client structure */
2452 for (client = host->FirstClient; client; client = client->next) {
2453 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2454 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2456 goto retryfirstclient;
2461 ObtainWriteLock(&client->lock);
2462 client->refCount = 1;
2463 client->host = host;
2464 client->InSameNetwork = host->InSameNetwork;
2465 client->ViceId = viceid;
2466 client->expTime = expTime; /* rx only */
2467 client->authClass = authClass; /* rx only */
2468 client->sid = rx_GetConnectionId(tcon);
2469 client->VenusEpoch = rx_GetConnectionEpoch(tcon);
2470 client->CPS.prlist_val = NULL;
2471 client->CPS.prlist_len = 0;
2475 client->prfail = fail;
2477 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2478 client->CPS.prlist_len = 0;
2479 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2480 free(client->CPS.prlist_val);
2481 client->CPS.prlist_val = NULL;
2482 client->ViceId = viceid;
2483 client->expTime = expTime;
2485 if (viceid == ANONYMOUSID) {
2486 client->CPS.prlist_len = AnonCPS.prlist_len;
2487 client->CPS.prlist_val = AnonCPS.prlist_val;
2490 code = hpr_GetCPS(viceid, &client->CPS);
2495 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2496 code, viceid, client->host,
2497 afs_inet_ntoa_r(client->host->host,hoststr),
2498 ntohs(client->host->port)));
2500 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2501 * all protection servers and reevaluates things if no
2502 * sync server or quorum is found we could still end up
2503 * with one of these errors. In such case we would like to
2504 * reevaluate the rpc call to find if there's cps for this
2505 * guy. We treat other errors (except network failures
2506 * ones - i.e. code < 0) as an indication that there is no
2507 * CPS for this host. Ideally we could like to deal this
2508 * problem the other way around (i.e. if code == NOCPS
2509 * ignore else retry next time) but the problem is that
2510 * there're other errors (i.e. EPERM) for which we don't
2511 * want to retry and we don't know the whole code list!
2513 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2517 /* the disabling of system:administrators is so iffy and has so many
2518 * possible failure modes that we will disable it again */
2519 /* Turn off System:Administrator for safety
2520 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2521 * osi_Assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2524 /* Now, tcon may already be set to a rock, since we blocked with no host
2525 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2526 * required). So, before setting the RPC's rock, we should disconnect
2527 * the RPC from the other client structure's rock.
2529 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2530 if (oldClient && oldClient != client
2531 && oldClient->sid == rx_GetConnectionId(tcon)
2532 && oldClient->VenusEpoch == rx_GetConnectionEpoch(tcon)
2533 && !(oldClient->host->hostFlags & HOSTDELETED)) {
2535 if (!oldClient->deleted) {
2536 /* if we didn't create it, it's not ours to put back */
2538 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2539 "conn %p (host %s:%d) had client %p(%x)\n",
2540 client, client->sid, tcon,
2541 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2542 ntohs(rxr_PortOf(tcon)),
2543 oldClient, oldClient->sid));
2544 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2545 free(client->CPS.prlist_val);
2546 client->CPS.prlist_val = NULL;
2547 client->CPS.prlist_len = 0;
2549 /* We should perhaps check for 0 here */
2551 ReleaseWriteLock(&client->lock);
2556 oldClient->refCount++;
2558 h_Hold_r(oldClient->host);
2559 h_Release_r(client->host);
2562 ObtainWriteLock(&oldClient->lock);
2565 host = oldClient->host;
2567 ViceLog(0, ("FindClient: deleted client %p(%x ref %d host %p href "
2568 "%d) already had conn %p (host %s:%d, cid %x), stolen "
2569 "by client %p(%x, ref %d host %p href %d)\n",
2570 oldClient, oldClient->sid, oldClient->refCount,
2571 oldClient->host, oldClient->host->refCount, tcon,
2572 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2573 ntohs(rxr_PortOf(tcon)), rx_GetConnectionId(tcon),
2574 client, client->sid, client->refCount,
2575 client->host, client->host->refCount));
2576 /* rx_SetSpecific will be done immediately below */
2579 /* Avoid chaining in more than once. */
2583 if (host->hostFlags & HOSTDELETED) {
2588 client->host = NULL;
2590 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2591 free(client->CPS.prlist_val);
2592 client->CPS.prlist_val = NULL;
2593 client->CPS.prlist_len = 0;
2596 ReleaseWriteLock(&client->lock);
2601 client->next = host->FirstClient;
2602 host->FirstClient = client;
2604 CurrentConnections++; /* increment number of connections */
2606 rx_SetSpecific(tcon, rxcon_client_key, client);
2607 ReleaseWriteLock(&client->lock);
2611 } /*h_FindClient_r */
2614 h_ReleaseClient_r(struct client *client)
2616 opr_Assert(client->refCount > 0);
2623 * Sigh: this one is used to get the client AGAIN within the individual
2624 * server routines. This does not bother h_Holding the host, since
2625 * this is assumed already have been done by the server main loop.
2626 * It does check tokens, since only the server routines can return the
2627 * VICETOKENDEAD error code
2630 GetClient(struct rx_connection *tcon, struct client **cp)
2632 struct client *client;
2637 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2638 if (client == NULL) {
2640 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2641 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2642 ntohs(rxr_PortOf(tcon))));
2646 if (rx_GetConnectionId(tcon) != client->sid
2647 || rx_GetConnectionEpoch(tcon) != client->VenusEpoch) {
2649 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2650 tcon, rx_GetConnectionId(tcon), client->sid));
2654 if (client && client->LastCall > client->expTime && client->expTime) {
2656 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2657 afs_inet_ntoa_r(client->host->host, hoststr),
2658 ntohs(client->host->port), client->expTime));
2660 return VICETOKENDEAD;
2662 if (client->deleted) {
2663 ViceLog(0, ("GetClient: got deleted client, connection will appear "
2664 "anonymous; tcon %p cid %x client %p ref %d host %p "
2665 "(%s:%d) href %d ViceId %d\n",
2666 tcon, rx_GetConnectionId(tcon), client, client->refCount,
2668 afs_inet_ntoa_r(client->host->host, hoststr),
2669 (int)ntohs(client->host->port), client->host->refCount,
2670 (int)client->ViceId));
2680 PutClient(struct client **cp)
2686 h_ReleaseClient_r(*cp);
2693 /* Client user name for short term use. Note that this is NOT inexpensive */
2695 h_UserName(struct client *client)
2697 static char User[PR_MAXNAMELEN + 1];
2701 lids.idlist_len = 1;
2702 lids.idlist_val = malloc(1 * sizeof(afs_int32));
2703 if (!lids.idlist_val) {
2704 ViceLogThenPanic(0, ("Failed malloc in h_UserName\n"));
2706 lnames.namelist_len = 0;
2707 lnames.namelist_val = (prname *) 0;
2708 lids.idlist_val[0] = client->ViceId;
2709 if (hpr_IdToName(&lids, &lnames)) {
2710 /* We need to free id we alloced above! */
2711 free(lids.idlist_val);
2712 return "*UNKNOWN USER NAME*";
2714 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2715 free(lids.idlist_val);
2716 free(lnames.namelist_val);
2725 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2726 CEs, CEBlocks, HTs, HTBlocks));
2732 h_PrintClient(struct host *host, void *rock)
2734 StreamHandle_t *file = (StreamHandle_t *)rock;
2735 struct client *client;
2740 time_t LastCall, expTime;
2744 LastCall = host->LastCall;
2745 if (host->hostFlags & HOSTDELETED) {
2749 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2750 localtime_r(&LastCall, &tm));
2751 snprintf(tmpStr, sizeof tmpStr, "Host %s:%d down = %d, LastCall %s\n",
2752 afs_inet_ntoa_r(host->host, hoststr),
2753 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2755 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2756 for (client = host->FirstClient; client; client = client->next) {
2757 if (!client->deleted) {
2758 expTime = client->expTime;
2759 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2760 localtime_r(&expTime, &tm));
2761 snprintf(tmpStr, sizeof tmpStr,
2762 " user id=%d, name=%s, sl=%s till %s\n",
2763 client->ViceId, h_UserName(client),
2764 client->authClass ? "Authenticated"
2765 : "Not authenticated",
2766 client->authClass ? tbuffer : "No Limit");
2767 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2768 snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2769 client->CPS.prlist_len);
2770 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2771 if (client->CPS.prlist_val) {
2772 for (i = 0; i < client->CPS.prlist_len; i++) {
2773 snprintf(tmpStr, sizeof tmpStr, " %d",
2774 client->CPS.prlist_val[i]);
2775 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2778 sprintf(tmpStr, "]\n");
2779 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2785 } /*h_PrintClient */
2790 * Print a list of clients, with last security level and token value seen,
2794 h_PrintClients(void)
2801 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2805 ("Couldn't create client dump file %s\n",
2806 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2810 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2811 localtime_r(&now, &tm));
2812 snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n\n",
2814 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2815 h_Enumerate(h_PrintClient, (char *)file);
2816 STREAM_REALLYCLOSE(file);
2817 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2824 h_DumpHost(struct host *host, void *rock)
2826 StreamHandle_t *file = (StreamHandle_t *)rock;
2833 snprintf(tmpStr, sizeof tmpStr,
2834 "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u "
2835 "down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u "
2837 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
2838 host->index, host->cblist, CheckLock(&host->lock),
2839 host->LastCall, host->ActiveCall, (host->hostFlags & VENUSDOWN),
2840 host->hostFlags & HOSTDELETED, host->Console,
2841 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2843 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2844 if (host->hcps.prlist_val)
2845 for (i = 0; i < host->hcps.prlist_len; i++) {
2846 snprintf(tmpStr, sizeof tmpStr, " %d", host->hcps.prlist_val[i]);
2847 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2849 sprintf(tmpStr, "] [");
2850 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2851 if (host->interface)
2852 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2854 sprintf(tmpStr, " %s:%d",
2855 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2856 ntohs(host->interface->interface[i].port));
2857 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2859 sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2860 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2872 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2879 ("Couldn't create host dump file %s\n",
2880 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2884 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2885 localtime_r(&now, &tm));
2886 snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n\n", tbuffer);
2887 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2888 h_Enumerate(h_DumpHost, (char *)file);
2889 STREAM_REALLYCLOSE(file);
2890 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2894 #ifdef AFS_DEMAND_ATTACH_FS
2897 * host state serialization
2899 static int h_stateFillHeader(struct host_state_header * hdr);
2900 static int h_stateCheckHeader(struct host_state_header * hdr);
2901 static int h_stateAllocMap(struct fs_dump_state * state);
2902 static int h_stateSaveHost(struct host * host, void *rock);
2903 static int h_stateRestoreHost(struct fs_dump_state * state);
2904 static int h_stateRestoreIndex(struct host * h, void *rock);
2905 static int h_stateVerifyHost(struct host * h, void *rock);
2906 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
2907 afs_uint32 addr, afs_uint16 port, int valid);
2908 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2909 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2910 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2913 * Is this host busy?
2915 * This is just a hint and should not be trusted; this should probably only be
2916 * used by the host state serialization code when trying to detect if a host
2917 * can be sanely serialized to disk or not. If this function returns 1, the
2918 * host may be in an invalid state and thus should not be saved to disk.
2921 h_isBusy_r(struct host *host)
2923 struct Lock *hostLock = &host->lock;
2926 LOCK_LOCK(hostLock);
2927 if (hostLock->excl_locked || hostLock->readers_reading) {
2930 LOCK_UNLOCK(hostLock);
2936 if ((host->hostFlags & HWHO_INPROGRESS) || !(host->hostFlags & ALTADDR)) {
2937 /* We shouldn't hit this if the host wasn't locked, but just in case... */
2944 /* this procedure saves all host state to disk for fast startup */
2946 h_stateSave(struct fs_dump_state * state)
2948 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2951 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2953 /* invalidate host state header */
2954 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2956 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2957 sizeof(struct host_state_header))) {
2962 fs_stateIncEOF(state, sizeof(struct host_state_header));
2964 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2969 h_stateFillHeader(state->h_hdr);
2971 /* write the real header to disk */
2972 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2973 sizeof(struct host_state_header));
2980 * host state serialization
2982 * this procedure restores all host state from a disk for fast startup
2985 h_stateRestore(struct fs_dump_state * state)
2989 /* seek to the right position and read in the host state header */
2990 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2991 sizeof(struct host_state_header))) {
2996 /* check the validity of the header */
2997 if (h_stateCheckHeader(state->h_hdr)) {
3002 records = state->h_hdr->records;
3004 if (h_stateAllocMap(state)) {
3009 /* iterate over records restoring host state */
3010 for (i=0; i < records; i++) {
3011 if (h_stateRestoreHost(state) != 0) {
3022 h_stateRestoreIndices(struct fs_dump_state * state)
3024 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
3029 h_stateRestoreIndex(struct host * h, void *rock)
3031 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3032 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
3033 return H_ENUMERATE_BAIL(0);
3039 h_stateVerify(struct fs_dump_state * state)
3041 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
3046 h_stateVerifyHost(struct host * h, void* rock)
3048 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3052 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3053 return H_ENUMERATE_BAIL(0);
3057 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
3058 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
3059 h->interface->interface[i].port,
3060 h->interface->interface[i].valid)) {
3064 if (h_stateVerifyUuidHash(state, h)) {
3067 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
3071 if (cb_stateVerifyHCBList(state, h)) {
3079 * verify a host is either in, or absent from, the addr hash table.
3081 * @param[in] state fs dump state
3082 * @param[in] h host we're dealing with
3083 * @param[in] addr addr to look for (NBO)
3084 * @param[in] port port to look for (NBO)
3085 * @param[in] valid 1 if we're verifying that the specified addr and port
3086 * in the hash table point to the specified host. 0 if we're
3087 * verifying that the specified addr and port do NOT point
3088 * to the specified host
3090 * @return operation status
3091 * @retval 1 failed to verify, bail out
3092 * @retval 0 verified successfully, all is well
3095 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3096 afs_uint32 addr, afs_uint16 port, int valid)
3098 int ret = 0, found = 0;
3099 struct host *host = NULL;
3100 struct h_AddrHashChain *chain;
3101 int index = h_HashIndex(addr);
3105 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3106 host = chain->hostPtr;
3108 afs_inet_ntoa_r(addr, tmp);
3109 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3113 if ((chain->addr == addr) && (chain->port == port)) {
3116 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3117 "points to different host struct (%d, %d)\n",
3118 h->index, host->index));
3119 state->flags.warnings_generated = 1;
3123 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3124 "marked invalid, but points to the containing "
3125 "host\n", afs_inet_ntoa_r(addr, tmp),
3126 (unsigned)htons(port)));
3134 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3135 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3136 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3143 if (!found && valid) {
3144 afs_inet_ntoa_r(addr, tmp);
3145 if (state->mode == FS_STATE_LOAD_MODE) {
3146 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3147 tmp, (unsigned)htons(port)));
3151 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3152 tmp, (unsigned)htons(port)));
3153 state->flags.warnings_generated = 1;
3162 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3164 int ret = 0, found = 0;
3165 struct host *host = NULL;
3166 struct h_UuidHashChain *chain;
3167 afsUUID * uuidp = &h->interface->uuid;
3168 int index = h_UuidHashIndex(uuidp);
3172 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3173 host = chain->hostPtr;
3175 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3176 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3180 if (host->interface &&
3181 afs_uuid_equal(&host->interface->uuid, uuidp)) {
3183 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3184 h->index, host->index));
3185 state->flags.warnings_generated = 1;
3190 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3191 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3192 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3200 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3201 if (state->mode == FS_STATE_LOAD_MODE) {
3202 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3206 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3207 state->flags.warnings_generated = 1;
3215 /* create the host state header structure */
3217 h_stateFillHeader(struct host_state_header * hdr)
3219 hdr->stamp.magic = HOST_STATE_MAGIC;
3220 hdr->stamp.version = HOST_STATE_VERSION;
3224 /* check the contents of the host state header structure */
3226 h_stateCheckHeader(struct host_state_header * hdr)
3230 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3231 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3234 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3235 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3241 /* allocate the host id mapping table */
3243 h_stateAllocMap(struct fs_dump_state * state)
3245 state->h_map.len = state->h_hdr->index_max + 1;
3246 state->h_map.entries = (struct idx_map_entry_t *)
3247 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3248 return (state->h_map.entries != NULL) ? 0 : 1;
3251 /* function called by h_Enumerate to save a host to disk */
3253 h_stateSaveHost(struct host * host, void* rock)
3255 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3256 int if_len=0, hcps_len=0;
3257 struct hostDiskEntry hdsk;
3258 struct host_state_entry_header hdr;
3259 struct Interface * ifp = NULL;
3260 afs_int32 * hcps = NULL;
3261 struct iovec iov[4];
3264 if (h_isBusy_r(host)) {
3266 ViceLog(1, ("Not saving host %s:%d to disk; host appears busy\n",
3267 afs_inet_ntoa_r(host->host, hoststr), (int)ntohs(host->port)));
3268 /* Make sure we don't try to save callbacks to disk for this host, or
3269 * we'll get confused on restore */
3270 DeleteAllCallBacks_r(host, 1);
3274 memset(&hdr, 0, sizeof(hdr));
3276 if (state->h_hdr->index_max < host->index) {
3277 state->h_hdr->index_max = host->index;
3280 h_hostToDiskEntry_r(host, &hdsk);
3281 if (host->interface) {
3282 if_len = sizeof(struct Interface) +
3283 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3284 ifp = malloc(if_len);
3285 opr_Assert(ifp != NULL);
3286 memcpy(ifp, host->interface, if_len);
3287 hdr.interfaces = host->interface->numberOfInterfaces;
3288 iov[iovcnt].iov_base = (char *) ifp;
3289 iov[iovcnt].iov_len = if_len;
3292 if (host->hcps.prlist_val) {
3293 hdr.hcps = host->hcps.prlist_len;
3294 hcps_len = hdr.hcps * sizeof(afs_int32);
3295 hcps = malloc(hcps_len);
3296 opr_Assert(hcps != NULL);
3297 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3298 iov[iovcnt].iov_base = (char *) hcps;
3299 iov[iovcnt].iov_len = hcps_len;
3303 if (hdsk.index > state->h_hdr->index_max)
3304 state->h_hdr->index_max = hdsk.index;
3306 hdr.len = sizeof(struct host_state_entry_header) +
3307 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3308 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3310 iov[0].iov_base = (char *) &hdr;
3311 iov[0].iov_len = sizeof(hdr);
3312 iov[1].iov_base = (char *) &hdsk;
3313 iov[1].iov_len = sizeof(struct hostDiskEntry);
3315 if (fs_stateWriteV(state, iov, iovcnt)) {
3316 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3320 fs_stateIncEOF(state, hdr.len);
3322 state->h_hdr->records++;
3329 return H_ENUMERATE_BAIL(0);
3334 /* restores a host from disk */
3336 h_stateRestoreHost(struct fs_dump_state * state)
3338 int ifp_len=0, hcps_len=0, bail=0;
3339 struct host_state_entry_header hdr;
3340 struct hostDiskEntry hdsk;
3341 struct host *host = NULL;
3342 struct Interface *ifp = NULL;
3343 afs_int32 * hcps = NULL;
3344 struct iovec iov[3];
3347 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3348 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3354 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3355 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3361 iov[0].iov_base = (char *) &hdsk;
3362 iov[0].iov_len = sizeof(struct hostDiskEntry);
3364 if (hdr.interfaces) {
3365 ifp_len = sizeof(struct Interface) +
3366 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3367 ifp = malloc(ifp_len);
3368 opr_Assert(ifp != NULL);
3369 iov[iovcnt].iov_base = (char *) ifp;
3370 iov[iovcnt].iov_len = ifp_len;
3374 hcps_len = hdr.hcps * sizeof(afs_int32);
3375 hcps = malloc(hcps_len);
3376 opr_Assert(hcps != NULL);
3377 iov[iovcnt].iov_base = (char *) hcps;
3378 iov[iovcnt].iov_len = hcps_len;
3382 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3383 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3388 if (fs_stateReadV(state, iov, iovcnt)) {
3389 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3394 if (!hdr.hcps && hdsk.hcps_valid) {
3395 /* valid, zero-length host cps ; does this ever happen? */
3396 hcps = malloc(sizeof(afs_int32));
3397 opr_Assert(hcps != NULL);
3400 if ((hdsk.hostFlags & HWHO_INPROGRESS) || !(hdsk.hostFlags & ALTADDR)) {
3402 ViceLog(0, ("h_stateRestoreHost: skipping host %s:%d due to invalid flags 0x%x\n",
3403 afs_inet_ntoa_r(hdsk.host, hoststr), (int)ntohs(hdsk.port),
3404 (unsigned)hdsk.hostFlags));
3406 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_SKIPPED;
3410 /* for restoring state, we better be able to get a host! */
3412 opr_Assert(host != NULL);
3415 host->interface = ifp;
3418 host->hcps.prlist_val = hcps;
3419 host->hcps.prlist_len = hdr.hcps;
3422 h_diskEntryToHost_r(&hdsk, host);
3423 h_SetupCallbackConn_r(host);
3425 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3428 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3429 if (ifp->interface[i].valid &&
3430 !(ifp->interface[i].addr == host->host &&
3431 ifp->interface[i].port == host->port)) {
3432 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3433 ifp->interface[i].port,
3437 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3439 h_InsertList_r(host);
3441 /* setup host id map entry */
3442 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_VALID;
3443 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3444 state->h_map.entries[hdsk.index].new_idx = host->index;
3456 /* serialize a host structure to disk */
3458 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3460 out->host = in->host;
3461 out->port = in->port;
3462 out->hostFlags = in->hostFlags;
3463 out->Console = in->Console;
3464 out->hcpsfailed = in->hcpsfailed;
3465 out->LastCall = in->LastCall;
3466 out->ActiveCall = in->ActiveCall;
3467 out->cpsCall = in->cpsCall;
3468 out->cblist = in->cblist;
3469 out->InSameNetwork = in->InSameNetwork;
3471 /* special fields we save, but are not memcpy'd back on restore */
3472 out->index = in->index;
3473 out->hcps_len = in->hcps.prlist_len;
3474 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3477 /* restore a host structure from disk */
3479 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3481 out->host = in->host;
3482 out->port = in->port;
3483 out->hostFlags = in->hostFlags;
3484 out->Console = in->Console;
3485 out->hcpsfailed = in->hcpsfailed;
3486 out->LastCall = in->LastCall;
3487 out->ActiveCall = in->ActiveCall;
3488 out->cpsCall = in->cpsCall;
3489 out->cblist = in->cblist;
3490 out->InSameNetwork = in->InSameNetwork;
3493 /* index translation routines */
3495 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3499 /* hosts use a zero-based index, so old==0 is valid */
3501 if (old >= state->h_map.len) {
3502 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3504 } else if (state->h_map.entries[old].valid != FS_STATE_IDX_VALID ||
3505 state->h_map.entries[old].old_idx != old) { /* sanity check */
3506 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3509 *new = state->h_map.entries[old].new_idx;
3514 #endif /* AFS_DEMAND_ATTACH_FS */
3518 * This counts the number of workstations, the number of active workstations,
3519 * and the number of workstations declared "down" (i.e. not heard from
3520 * recently). An active workstation has received a call since the cutoff
3521 * time argument passed.
3524 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3527 int num = 0, active = 0, del = 0;
3531 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3532 if (!(host->hostFlags & HOSTDELETED)) {
3534 if (host->ActiveCall > cutofftime)
3536 if (host->hostFlags & VENUSDOWN)
3540 if (count != hostCount) {
3541 ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3542 } else if (host != NULL) {
3543 ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3544 ShutDownAndCore(PANIC);
3554 } /*h_GetWorkStats */
3557 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp,
3558 afs_int32 cutofftime)
3560 int num, active, del;
3561 h_GetWorkStats(&num, &active, &del, cutofftime);
3570 /*------------------------------------------------------------------------
3571 * PRIVATE h_ClassifyAddress
3574 * Given a target IP address and a candidate IP address (both
3575 * in host byte order), classify the candidate into one of three
3576 * buckets in relation to the target by bumping the counters passed
3580 * a_targetAddr : Target address.
3581 * a_candAddr : Candidate address.
3582 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3583 * addresses are either in the same network
3584 * or the same subnet.
3585 * a_diffSubnetP : ...when the candidate is in a different
3587 * a_diffNetworkP : ...when the candidate is in a different
3594 * The target and candidate addresses are both in host byte
3595 * order, NOT network byte order, when passed in.
3599 *------------------------------------------------------------------------*/
3602 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3603 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3604 afs_int32 * a_diffNetworkP)
3605 { /*h_ClassifyAddress */
3607 afs_uint32 targetNet;
3608 afs_uint32 targetSubnet;
3610 afs_uint32 candSubnet;
3613 * Put bad values into the subnet info to start with.
3615 targetSubnet = (afs_uint32) 0;
3616 candSubnet = (afs_uint32) 0;
3619 * Pull out the network and subnetwork numbers from the target
3620 * and candidate addresses. We can short-circuit this whole
3621 * affair if the target and candidate addresses are not of the
3624 if (IN_CLASSA(a_targetAddr)) {
3625 if (!(IN_CLASSA(a_candAddr))) {
3626 (*a_diffNetworkP)++;
3629 targetNet = a_targetAddr & IN_CLASSA_NET;
3630 candNet = a_candAddr & IN_CLASSA_NET;
3631 if (IN_SUBNETA(a_targetAddr))
3632 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3633 if (IN_SUBNETA(a_candAddr))
3634 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3635 } else if (IN_CLASSB(a_targetAddr)) {
3636 if (!(IN_CLASSB(a_candAddr))) {
3637 (*a_diffNetworkP)++;
3640 targetNet = a_targetAddr & IN_CLASSB_NET;
3641 candNet = a_candAddr & IN_CLASSB_NET;
3642 if (IN_SUBNETB(a_targetAddr))
3643 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3644 if (IN_SUBNETB(a_candAddr))
3645 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3646 } /*Class B target */
3647 else if (IN_CLASSC(a_targetAddr)) {
3648 if (!(IN_CLASSC(a_candAddr))) {
3649 (*a_diffNetworkP)++;
3652 targetNet = a_targetAddr & IN_CLASSC_NET;
3653 candNet = a_candAddr & IN_CLASSC_NET;
3656 * Note that class C addresses can't have subnets,
3657 * so we leave the defaults untouched.
3659 } /*Class C target */
3661 targetNet = a_targetAddr;
3662 candNet = a_candAddr;
3663 } /*Class D address */
3666 * Now, simply compare the extracted net and subnet values for
3667 * the two addresses (which at this point are known to be of the
3670 if (targetNet == candNet) {
3671 if (targetSubnet == candSubnet)
3672 (*a_sameNetOrSubnetP)++;
3676 (*a_diffNetworkP)++;
3678 } /*h_ClassifyAddress */
3681 /*------------------------------------------------------------------------
3682 * EXPORTED h_GetHostNetStats
3685 * Iterate through the host table, and classify each (non-deleted)
3686 * host entry into ``proximity'' categories (same net or subnet,
3687 * different subnet, different network).
3690 * a_numHostsP : Set to total number of (non-deleted) hosts.
3691 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3692 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3693 * a_diffNetworkP : Set to # hosts on diff network as server.
3699 * We only count non-deleted hosts. The storage pointed to by our
3700 * parameters is zeroed upon entry.
3704 *------------------------------------------------------------------------*/
3707 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3708 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3709 { /*h_GetHostNetStats */
3711 struct host *hostP; /*Ptr to current host entry */
3712 afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3716 * Clear out the storage pointed to by our parameters.
3718 *a_numHostsP = (afs_int32) 0;
3719 *a_sameNetOrSubnetP = (afs_int32) 0;
3720 *a_diffSubnetP = (afs_int32) 0;
3721 *a_diffNetworkP = (afs_int32) 0;
3724 for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3725 if (!(hostP->hostFlags & HOSTDELETED)) {
3727 * Bump the number of undeleted host entries found.
3728 * In classifying the current entry's address, make
3729 * sure to first convert to host byte order.
3732 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3733 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3734 a_sameNetOrSubnetP, a_diffSubnetP,
3736 } /*Only look at non-deleted hosts */
3737 } /*For each host record hashed to this index */
3738 if (count != hostCount) {
3739 ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3740 } else if (hostP != NULL) {
3741 ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3742 ShutDownAndCore(PANIC);
3745 } /*h_GetHostNetStats */
3747 static afs_uint32 checktime;
3748 static afs_uint32 clientdeletetime;
3749 static struct AFSFid zerofid;
3753 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3754 * Since it can serialize them, and pile up, it should be a separate LWP
3755 * from other events.
3759 CheckHost(struct host *host, int flags, void *rock)
3761 struct client *client;
3762 struct rx_connection *cb_conn = NULL;
3765 #ifdef AFS_DEMAND_ATTACH_FS
3766 /* kill the checkhost lwp ASAP during shutdown */
3768 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3770 return H_ENUMERATE_BAIL(flags);
3775 /* Host is held by h_Enumerate */
3777 for (client = host->FirstClient; client; client = client->next) {
3778 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3779 client->deleted = 1;
3780 host->hostFlags |= CLIENTDELETED;
3783 if (host->LastCall < checktime) {
3785 if (!(host->hostFlags & HOSTDELETED)) {
3786 host->hostFlags |= HWHO_INPROGRESS;
3787 cb_conn = host->callback_rxcon;
3788 rx_GetConnection(cb_conn);
3789 if (host->LastCall < clientdeletetime) {
3790 host->hostFlags |= HOSTDELETED;
3791 if (!(host->hostFlags & VENUSDOWN)) {
3792 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3793 if (host->interface) {
3796 RXAFSCB_InitCallBackState3(cb_conn,
3802 RXAFSCB_InitCallBackState(cb_conn);
3805 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3808 (void)afs_inet_ntoa_r(host->host, hoststr);
3810 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3811 hoststr, ntohs(host->port)));
3812 host->hostFlags |= VENUSDOWN;
3814 /* Note: it's safe to delete hosts even if they have call
3815 * back state, because break delayed callbacks (called when a
3816 * message is received from the workstation) will always send a
3817 * break all call backs to the workstation if there is no
3822 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3824 (void)afs_inet_ntoa_r(host->host, hoststr);
3825 if (host->interface) {
3826 afsUUID uuid = host->interface->uuid;
3828 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3831 if (MultiProbeAlternateAddress_r(host)) {
3832 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3833 hoststr, ntohs(host->port), code));
3834 host->hostFlags |= VENUSDOWN;
3839 code = RXAFSCB_Probe(cb_conn);
3843 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3844 hoststr, ntohs(host->port), code));
3845 host->hostFlags |= VENUSDOWN;
3851 rx_PutConnection(cb_conn);
3854 host->hostFlags &= ~HWHO_INPROGRESS;
3865 CheckHost_r(struct host *host, void *dummy)
3867 struct client *client;
3868 struct rx_connection *cb_conn = NULL;
3871 #ifdef AFS_DEMAND_ATTACH_FS
3872 /* kill the checkhost lwp ASAP during shutdown */
3874 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3876 return H_ENUMERATE_BAIL(0);
3881 /* Host is held by h_Enumerate_r */
3882 for (client = host->FirstClient; client; client = client->next) {
3883 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3884 client->deleted = 1;
3885 host->hostFlags |= CLIENTDELETED;
3888 if (host->LastCall < checktime) {
3890 if (!(host->hostFlags & HOSTDELETED)) {
3891 host->hostFlags |= HWHO_INPROGRESS;
3892 cb_conn = host->callback_rxcon;
3893 rx_GetConnection(cb_conn);
3894 if (host->LastCall < clientdeletetime) {
3895 host->hostFlags |= HOSTDELETED;
3896 if (!(host->hostFlags & VENUSDOWN)) {
3897 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3898 if (host->interface) {
3901 RXAFSCB_InitCallBackState3(cb_conn,
3907 RXAFSCB_InitCallBackState(cb_conn);
3910 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3913 (void)afs_inet_ntoa_r(host->host, hoststr);
3915 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3916 hoststr, ntohs(host->port)));
3917 host->hostFlags |= VENUSDOWN;
3919 /* Note: it's safe to delete hosts even if they have call
3920 * back state, because break delayed callbacks (called when a
3921 * message is received from the workstation) will always send a
3922 * break all call backs to the workstation if there is no
3927 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3929 (void)afs_inet_ntoa_r(host->host, hoststr);
3930 if (host->interface) {
3931 afsUUID uuid = host->interface->uuid;
3933 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3936 if (MultiProbeAlternateAddress_r(host)) {
3937 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3938 hoststr, ntohs(host->port), code));
3939 host->hostFlags |= VENUSDOWN;
3944 code = RXAFSCB_Probe(cb_conn);
3948 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3949 hoststr, ntohs(host->port), code));
3950 host->hostFlags |= VENUSDOWN;
3956 rx_PutConnection(cb_conn);
3959 host->hostFlags &= ~HWHO_INPROGRESS;
3969 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3970 * don't respond to a probe. Note that VenusDown can only be cleared if
3971 * a message is received from the host (see ServerLWP in file.c).
3972 * Delete hosts that have not had any calls in 1 hour, clients that
3973 * have not had any calls in 15 minutes.
3975 * This routine is called roughly every 5 minutes.
3980 afs_uint32 now = time(NULL);
3982 memset(&zerofid, 0, sizeof(zerofid));
3984 * Send a probe to the workstation if it hasn't been heard from in
3987 checktime = now - 15 * 60;
3988 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3991 h_Enumerate_r(CheckHost_r, hostList, NULL);
3996 * This is called with host locked and held. At this point, the
3997 * hostAddrHashTable has an entry for the primary addr/port inserted
3998 * by h_Alloc_r(). No other interfaces should be considered valid.
4000 * The addresses in the interfaceAddr list are in host byte order.
4003 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
4010 struct Interface *interface;
4013 afs_uint16 port7001 = htons(7001);
4018 number = interf->numberOfInterfaces;
4019 myAddr = host->host; /* current interface address */
4020 myPort = host->port; /* current port */
4023 ("initInterfaceAddr : host %s:%d numAddr %d\n",
4024 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
4026 /* validation checks */
4027 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
4029 ("Invalid number of alternate addresses is %d\n", number));
4034 * The client's notion of its own IP addresses is not reliable.
4036 * 1. The client list might contain private address ranges which
4037 * are likely to be re-used by many clients allocated addresses
4040 * 2. The client list will not include any public addresses that
4041 * are hidden by a NAT.
4043 * 3. Private address ranges that are exposed to the server will
4044 * be obtained from the rx connections that use them.
4046 * 4. Lists provided by the client are not necessarily truthful.
4047 * Many existing clients (UNIX) do not refresh the IP address
4048 * list as the actual assigned addresses change. The end result
4049 * is that they report the initial address list for the lifetime
4050 * of the process. In other words, a client can report addresses
4051 * that they are in fact not using. Adding these addresses to
4052 * the host interface list without verification is not only
4053 * pointless, it is downright dangerous.
4055 * We therefore do not add alternate addresses to the addr hash table.
4056 * We only use them for multi-rx callback breaks.
4060 * Convert IP addresses to network byte order, and remove
4061 * duplicate and loopback IP addresses from the interface list, and
4062 * determine whether or not the incoming addr/port is
4063 * listed. Note that if the address matches it is not
4064 * truly a match because the port number for the entries
4065 * in the interface list are port 7001 and the port number
4066 * for this connection might not be 7001.
4068 for (i = 0, count = 0, found = 0; i < number; i++) {
4069 if (rx_IsLoopbackAddr(interf->addr_in[i])) {
4072 interf->addr_in[i] = htonl(interf->addr_in[i]);
4073 for (j = 0; j < count; j++) {
4074 if (interf->addr_in[j] == interf->addr_in[i])
4078 interf->addr_in[count] = interf->addr_in[i];
4079 if (interf->addr_in[count] == myAddr &&
4087 * Allocate and initialize an interface structure for this host.
4090 interface = malloc(sizeof(struct Interface) +
4091 (sizeof(struct AddrPort) * (count - 1)));
4093 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
4095 interface->numberOfInterfaces = count;
4097 interface = malloc(sizeof(struct Interface) +
4098 (sizeof(struct AddrPort) * count));
4100 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4102 interface->numberOfInterfaces = count + 1;
4103 interface->interface[count].addr = myAddr;
4104 interface->interface[count].port = myPort;
4105 interface->interface[count].valid = 1;
4108 for (i = 0; i < count; i++) {
4110 interface->interface[i].addr = interf->addr_in[i];
4111 /* We store the port as 7001 because the addresses reported by
4112 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4113 * are coming from fully connected hosts (no NAT/PATs)
4115 interface->interface[i].port = port7001;
4116 interface->interface[i].valid =
4117 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4120 interface->uuid = interf->uuid;
4122 opr_Assert(!host->interface);
4123 host->interface = interface;
4125 h_AddHostToUuidHashTable_r(&interface->uuid, host);
4127 if (LogLevel >= 125) {
4128 afsUUID_to_string(&interface->uuid, uuidstr, 127);
4130 ViceLog(125, ("--- uuid %s\n", uuidstr));
4131 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
4132 ViceLog(125, ("--- alt address %s:%d\n",
4133 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4134 ntohs(host->interface->interface[i].port)));
4141 /* deleted a HashChain structure for this address and host */
4142 /* returns 1 on success */
4144 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4148 struct h_AddrHashChain **hp, *th;
4150 if (addr == 0 && port == 0)
4153 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4155 opr_Assert(th->hostPtr);
4156 if (th->hostPtr == host && th->addr == addr && th->port == port) {
4157 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4158 host, afs_inet_ntoa_r(host->host, hoststr),
4159 ntohs(host->port)));
4166 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4167 host, afs_inet_ntoa_r(host->host, hoststr),
4168 ntohs(host->port)));
4174 ** prints out all alternate interface address for the host. The 'level'
4175 ** parameter indicates what level of debugging sets this output
4178 printInterfaceAddr(struct host *host, int level)
4183 if (host->interface) {
4184 /* check alternate addresses */
4185 number = host->interface->numberOfInterfaces;
4187 ViceLog(level, ("no-addresses "));
4189 for (i = 0; i < number; i++)
4190 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4191 ntohs(host->interface->interface[i].port)));
4194 ViceLog(level, ("\n"));