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>
19 #ifdef HAVE_SYS_FILE_H
26 #include <afs/afsint.h>
27 #define FSINT_COMMON_XG
28 #include <afs/afscbint.h>
29 #include <afs/rxgen_consts.h>
31 #include <afs/errors.h>
32 #include <afs/ihandle.h>
33 #include <afs/vnode.h>
34 #include <afs/volume.h>
35 #ifdef AFS_ATHENA_STDENV
39 #include <afs/ptclient.h>
40 #include <afs/ptuser.h>
41 #include <afs/prs_fs.h>
43 #include <afs/afsutil.h>
44 #include <afs/com_err.h>
46 #include <afs/cellconfig.h>
47 #include "viced_prototypes.h"
51 #ifdef AFS_DEMAND_ATTACH_FS
52 #include "../util/afsutil_prototypes.h"
53 #include "serialize_state.h"
54 #endif /* AFS_DEMAND_ATTACH_FS */
56 pthread_mutex_t host_glock_mutex;
59 extern int CurrentConnections;
61 extern int AnonymousID;
62 extern prlist AnonCPS;
64 extern struct afsconf_dir *confDir; /* config dir object */
65 extern int lwps; /* the max number of server threads */
66 extern afsUUID FS_HostUUID;
69 int CEs = 0; /* active clients */
70 int CEBlocks = 0; /* number of blocks of CEs */
71 struct client *CEFree = 0; /* first free client */
72 struct host *hostList = 0; /* linked list of all hosts */
73 int hostCount = 0; /* number of hosts in hostList */
77 static struct rx_securityClass *sc = NULL;
79 static void h_SetupCallbackConn_r(struct host * host);
80 static int h_threadquota(int);
82 #define CESPERBLOCK 73
83 struct CEBlock { /* block of CESPERBLOCK file entries */
84 struct client entry[CESPERBLOCK];
87 void h_TossStuff_r(struct host *host);
90 * Make sure the subnet macros have been defined.
93 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
96 #ifndef IN_CLASSA_SUBNET
97 #define IN_CLASSA_SUBNET 0xffff0000
101 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
104 #ifndef IN_CLASSB_SUBNET
105 #define IN_CLASSB_SUBNET 0xffffff00
109 /* get a new block of CEs and chain it on CEFree */
113 struct CEBlock *block;
116 block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
118 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
119 ShutDownAndCore(PANIC);
122 for (i = 0; i < (CESPERBLOCK - 1); i++) {
123 Lock_Init(&block->entry[i].lock);
124 block->entry[i].next = &(block->entry[i + 1]);
126 block->entry[CESPERBLOCK - 1].next = 0;
127 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
128 CEFree = (struct client *)block;
134 /* get the next available CE */
135 static struct client *
138 struct client *entry;
143 ViceLog(0, ("CEFree NULL in GetCE\n"));
144 ShutDownAndCore(PANIC);
148 CEFree = entry->next;
150 memset(entry, 0, CLIENT_TO_ZERO(entry));
156 /* return an entry to the free list */
158 FreeCE(struct client *entry)
160 entry->VenusEpoch = 0;
162 entry->next = CEFree;
169 * The HTs and HTBlocks variables were formerly static, but they are
170 * now referenced elsewhere in the FileServer.
172 int HTs = 0; /* active file entries */
173 int HTBlocks = 0; /* number of blocks of HTs */
174 static struct host *HTFree = 0; /* first free file entry */
177 * Hash tables of host pointers. We need two tables, one
178 * to map IP addresses onto host pointers, and another
179 * to map host UUIDs onto host pointers.
181 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
182 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
183 #define h_HashIndex(hostip) (ntohl(hostip) & (h_HASHENTRIES-1))
184 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
186 struct HTBlock { /* block of HTSPERBLOCK file entries */
187 struct host entry[h_HTSPERBLOCK];
191 /* get a new block of HTs and chain it on HTFree */
195 struct HTBlock *block;
197 static int index = 0;
199 if (HTBlocks == h_MAXHOSTTABLES) {
200 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
204 block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
206 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
207 ShutDownAndCore(PANIC);
209 for (i = 0; i < (h_HTSPERBLOCK); i++)
210 CV_INIT(&block->entry[i].cond, "block entry", CV_DEFAULT, 0);
211 for (i = 0; i < (h_HTSPERBLOCK); i++)
212 Lock_Init(&block->entry[i].lock);
213 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
214 block->entry[i].next = &(block->entry[i + 1]);
215 for (i = 0; i < (h_HTSPERBLOCK); i++)
216 block->entry[i].index = index++;
217 block->entry[h_HTSPERBLOCK - 1].next = 0;
218 HTFree = (struct host *)block;
219 hosttableptrs[HTBlocks++] = block->entry;
224 /* get the next available HT */
235 HTFree = entry->next;
237 memset(entry, 0, HOST_TO_ZERO(entry));
243 /* return an entry to the free list */
245 FreeHT(struct host *entry)
247 entry->next = HTFree;
254 hpr_Initialize(struct ubik_client **uclient)
257 struct rx_connection *serverconns[MAXSERVERS];
258 struct rx_securityClass *sc;
259 struct afsconf_dir *tdir;
261 struct afsconf_cell info;
265 tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
267 ViceLog(0, ("hpr_Initialize: Could not open configuration directory: %s", AFSDIR_SERVER_ETC_DIRPATH));
271 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
273 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
278 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
280 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s",
281 cellstr, confDir->name, AFSDIR_CELLSERVDB_FILE));
288 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
293 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
294 * to force use of the KeyFile. secLevel == 0 implies -noauth was
296 code = afsconf_ClientAuthSecure(tdir, &sc, &scIndex);
298 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s "
299 "(so trying noauth)", code, afs_error_message(code)));
300 scIndex = RX_SECIDX_NULL;
301 sc = rxnull_NewClientSecurityObject();
304 if (scIndex == RX_SECIDX_NULL)
305 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, "
306 "running unauthenticated. [%d]", code));
308 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
309 for (i = 0; i < info.numServers; i++) {
311 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
312 info.hostAddr[i].sin_port, PRSRV,
316 code = ubik_ClientInit(serverconns, uclient);
318 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
321 code = rxs_Release(sc);
326 hpr_End(struct ubik_client *uclient)
331 code = ubik_ClientDestroy(uclient);
337 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
341 struct ubik_client *uclient =
342 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
345 code = hpr_Initialize(&uclient);
347 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
353 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
354 if (code != PRSUCCESS)
357 /* do something about this, probably make a new call */
358 /* don't forget there's a hard limit in the interface */
360 "membership list for host id %d exceeds display limit\n",
367 hpr_NameToId(namelist *names, idlist *ids)
371 struct ubik_client *uclient =
372 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
375 code = hpr_Initialize(&uclient);
377 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
382 for (i = 0; i < names->namelist_len; i++)
383 stolower(names->namelist_val[i]);
384 code = ubik_PR_NameToID(uclient, 0, names, ids);
389 hpr_IdToName(idlist *ids, namelist *names)
392 struct ubik_client *uclient =
393 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
396 code = hpr_Initialize(&uclient);
398 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
403 code = ubik_PR_IDToName(uclient, 0, ids, names);
408 hpr_GetCPS(afs_int32 id, prlist *CPS)
412 struct ubik_client *uclient =
413 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
416 code = hpr_Initialize(&uclient);
418 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
424 code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
425 if (code != PRSUCCESS)
428 /* do something about this, probably make a new call */
429 /* don't forget there's a hard limit in the interface */
430 fprintf(stderr, "membership list for id %d exceeds display limit\n",
436 static short consolePort = 0;
439 h_Lock_r(struct host *host)
449 * returns 1 if already locked
450 * else returns locks and returns 0
454 h_NBLock_r(struct host *host)
456 struct Lock *hostLock = &host->lock;
461 if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
462 hostLock->excl_locked = WRITE_LOCK;
466 LOCK_UNLOCK(hostLock);
475 /*------------------------------------------------------------------------
476 * PRIVATE h_AddrInSameNetwork
479 * Given a target IP address and a candidate IP address (both
480 * in host byte order), return a non-zero value (1) if the
481 * candidate address is in a different network from the target
485 * a_targetAddr : Target address.
486 * a_candAddr : Candidate address.
489 * 1 if the candidate address is in the same net as the target,
493 * The target and candidate addresses are both in host byte
494 * order, NOT network byte order, when passed in. We return
495 * our value as a character, since that's the type of field in
496 * the host structure, where this info will be stored.
500 *------------------------------------------------------------------------*/
503 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
504 { /*h_AddrInSameNetwork */
506 afs_uint32 targetNet;
510 * Pull out the network and subnetwork numbers from the target
511 * and candidate addresses. We can short-circuit this whole
512 * affair if the target and candidate addresses are not of the
515 if (IN_CLASSA(a_targetAddr)) {
516 if (!(IN_CLASSA(a_candAddr))) {
519 targetNet = a_targetAddr & IN_CLASSA_NET;
520 candNet = a_candAddr & IN_CLASSA_NET;
521 } else if (IN_CLASSB(a_targetAddr)) {
522 if (!(IN_CLASSB(a_candAddr))) {
525 targetNet = a_targetAddr & IN_CLASSB_NET;
526 candNet = a_candAddr & IN_CLASSB_NET;
527 } /*Class B target */
528 else if (IN_CLASSC(a_targetAddr)) {
529 if (!(IN_CLASSC(a_candAddr))) {
532 targetNet = a_targetAddr & IN_CLASSC_NET;
533 candNet = a_candAddr & IN_CLASSC_NET;
534 } /*Class C target */
536 targetNet = a_targetAddr;
537 candNet = a_candAddr;
538 } /*Class D address */
541 * Now, simply compare the extracted net values for the two addresses
542 * (which at this point are known to be of the same class)
544 if (targetNet == candNet)
549 } /*h_AddrInSameNetwork */
552 /* Assumptions: called with held host */
554 h_gethostcps_r(struct host *host, afs_int32 now)
559 /* wait if somebody else is already doing the getCPS call */
560 while (host->hostFlags & HCPS_INPROGRESS) {
561 slept = 1; /* I did sleep */
562 host->hostFlags |= HCPS_WAITING; /* I am sleeping now */
563 CV_WAIT(&host->cond, &host_glock_mutex);
567 host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
568 if (host->hcps.prlist_val)
569 free(host->hcps.prlist_val); /* this is for hostaclRefresh */
570 host->hcps.prlist_val = NULL;
571 host->hcps.prlist_len = 0;
572 host->cpsCall = slept ? (FT_ApproxTime()) : (now);
575 code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
580 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
581 * and reevaluates things if no sync server or quorum is found we could still end up
582 * with one of these errors. In such case we would like to reevaluate the rpc call to
583 * find if there's cps for this guy. We treat other errors (except network failures
584 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
585 * we could like to deal this problem the other way around (i.e. if code == NOCPS
586 * ignore else retry next time) but the problem is that there're other errors (i.e.
587 * EPERM) for which we don't want to retry and we don't know the whole code list!
589 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
591 * We would have preferred to use a while loop and try again since ops in protected
592 * acls for this host will fail now but they'll be reevaluated on any subsequent
593 * call. The attempt to wait for a quorum/sync site or network error won't work
594 * since this problems really should only occurs during a complete fileserver
595 * restart. Since the fileserver will start before the ptservers (and thus before
596 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
598 host->hcpsfailed = 1;
600 ("Warning: GetHostCPS failed (%d) for %p (%s:%d); will retry\n",
601 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
603 host->hcpsfailed = 0;
605 ("gethost: GetHostCPS failed (%d) for %p (%s:%d); ignored\n",
606 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
608 if (host->hcps.prlist_val)
609 free(host->hcps.prlist_val);
610 host->hcps.prlist_val = NULL;
611 host->hcps.prlist_len = 0; /* Make sure it's zero */
613 host->hcpsfailed = 0;
615 host->hostFlags &= ~HCPS_INPROGRESS;
616 /* signal all who are waiting */
617 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
618 host->hostFlags &= ~HCPS_WAITING;
619 CV_BROADCAST(&host->cond);
623 /* args in net byte order */
625 h_flushhostcps(afs_uint32 hostaddr, afs_uint16 hport)
630 h_Lookup_r(hostaddr, hport, &host);
632 host->hcpsfailed = 1;
641 * Allocate a host. It will be identified by the peer (ip,port) info in the
642 * rx connection provided. The host is returned held and locked
644 #define DEF_ROPCONS 2115
647 h_Alloc_r(struct rx_connection *r_con)
649 struct servent *serverentry;
651 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
658 /* acquire the host lock withot dropping H_LOCK. we can do this here
659 * because we know we will not block; we just created this host and
660 * nobody else knows about it. */
661 ObtainWriteLock(&host->lock);
663 host->host = rxr_HostOf(r_con);
664 host->port = rxr_PortOf(r_con);
666 h_AddHostToAddrHashTable_r(host->host, host->port, host);
668 if (consolePort == 0) { /* find the portal number for console */
669 #if defined(AFS_OSF_ENV)
670 serverentry = getservbyname("ropcons", "");
672 serverentry = getservbyname("ropcons", 0);
675 consolePort = serverentry->s_port;
677 consolePort = htons(DEF_ROPCONS); /* Use a default */
679 if (host->port == consolePort)
681 /* Make a callback channel even for the console, on the off chance that it
682 * makes a request that causes a break call back. It shouldn't. */
683 h_SetupCallbackConn_r(host);
684 host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
686 host->hcps.prlist_val = NULL;
687 host->hcps.prlist_len = 0;
688 host->interface = NULL;
690 host->hcpsfailed = 0; /* save cycles */
691 h_gethostcps(host); /* do this under host hold/lock */
693 host->FirstClient = NULL;
694 h_InsertList_r(host); /* update global host List */
696 * Compare the new host's IP address (in host byte order) with ours
697 * (the File Server's), remembering if they are in the same network.
699 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
700 host->InSameNetwork =
701 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
708 /* Make a callback channel even for the console, on the off chance that it
709 * makes a request that causes a break call back. It shouldn't. */
711 h_SetupCallbackConn_r(struct host * host)
714 sc = rxnull_NewClientSecurityObject();
715 host->callback_rxcon =
716 rx_NewConnection(host->host, host->port, 1, sc, 0);
717 rx_SetConnDeadTime(host->callback_rxcon, 50);
718 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
719 rx_SetConnSecondsUntilNatPing(host->callback_rxcon, 20);
723 * Lookup a host given an IP address and UDP port number.
724 * hostaddr and hport are in network order
725 * hostaddr and hport are in network order
726 * On return, refCount is incremented.
729 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, struct host **hostp)
732 struct host *host = NULL;
733 struct h_AddrHashChain *chain;
734 int index = h_HashIndex(haddr);
735 extern int hostaclRefresh;
738 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
739 host = chain->hostPtr;
741 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
742 && chain->port == hport) {
743 if ((host->hostFlags & HWHO_INPROGRESS) &&
744 h_threadquota(host->lock.num_waiting)) {
750 if (host->hostFlags & HOSTDELETED) {
757 now = FT_ApproxTime(); /* always evaluate "now" */
758 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
760 * Every hostaclRefresh period (def 2 hrs) get the new
761 * membership list for the host. Note this could be the
762 * first time that the host is added to a group. Also
763 * here we also retry on previous legitimate hcps failures.
765 * If we get here refCount is elevated.
767 h_gethostcps_r(host, now);
777 /* Lookup a host given its UUID. */
779 h_LookupUuid_r(afsUUID * uuidp)
781 struct host *host = 0;
782 struct h_UuidHashChain *chain;
783 int index = h_UuidHashIndex(uuidp);
785 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
786 host = chain->hostPtr;
788 if (!(host->hostFlags & HOSTDELETED) && host->interface
789 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
797 /* h_TossStuff_r: Toss anything in the host structure (the host or
798 * clients marked for deletion. Called from h_Release_r ONLY.
799 * To be called, there must be no holds, and either host->deleted
800 * or host->clientDeleted must be set.
803 h_TossStuff_r(struct host *host)
805 struct client **cp, *client;
808 /* make sure host doesn't go away over h_NBLock_r */
811 code = h_NBLock_r(host);
813 /* don't use h_Release_r, since that may call h_TossStuff_r again */
816 /* if somebody still has this host locked */
820 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was locked.\n",
821 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
827 /* if somebody still has this host held */
828 /* we must check this _after_ h_NBLock_r, since h_NBLock_r can drop and
829 * reacquire H_LOCK */
830 if (host->refCount > 0) {
833 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was held.\n",
834 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
838 /* ASSUMPTION: rxi_FreeConnection() does not yield */
839 for (cp = &host->FirstClient; (client = *cp);) {
840 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
842 ObtainWriteLockNoBlock(&client->lock, code);
846 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
847 "client %p was locked.\n",
848 host, afs_inet_ntoa_r(host->host, hoststr),
849 ntohs(host->port), client));
853 if (client->refCount) {
856 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
857 "client %p refcount %d.\n",
858 host, afs_inet_ntoa_r(host->host, hoststr),
859 ntohs(host->port), client, client->refCount));
860 /* This is the same thing we do if the host is locked */
861 ReleaseWriteLock(&client->lock);
864 client->CPS.prlist_len = 0;
865 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
866 free(client->CPS.prlist_val);
867 client->CPS.prlist_val = NULL;
868 CurrentConnections--;
870 ReleaseWriteLock(&client->lock);
876 /* We've just cleaned out all the deleted clients; clear the flag */
877 host->hostFlags &= ~CLIENTDELETED;
879 if (host->hostFlags & HOSTDELETED) {
880 struct rx_connection *rxconn;
881 struct AddrPort hostAddrPort;
884 if (host->Console & 1)
886 if ((rxconn = host->callback_rxcon)) {
887 host->callback_rxcon = (struct rx_connection *)0;
888 rx_DestroyConnection(rxconn);
890 if (host->hcps.prlist_val)
891 free(host->hcps.prlist_val);
892 host->hcps.prlist_val = NULL;
893 host->hcps.prlist_len = 0;
894 DeleteAllCallBacks_r(host, 1);
895 host->hostFlags &= ~RESETDONE; /* just to be safe */
897 /* if alternate addresses do not exist */
898 if (!(host->interface)) {
899 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
901 h_DeleteHostFromUuidHashTable_r(host);
902 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
903 /* delete the hash entry for each valid alternate addresses */
904 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
905 hostAddrPort = host->interface->interface[i];
907 * if the interface addr/port is the primary, we already
908 * removed it. If the addr/port is not valid, its not
911 if (hostAddrPort.valid &&
912 (host->host != hostAddrPort.addr ||
913 host->port != hostAddrPort.port))
914 h_DeleteHostFromAddrHashTable_r(hostAddrPort.addr, hostAddrPort.port, host);
916 free(host->interface);
917 host->interface = NULL;
918 } /* if alternate address exists */
920 h_DeleteList_r(host); /* remove host from global host List */
927 /* h_Enumerate: Calls (*proc)(host, param) for at least each host in the
928 * system at the start of the enumeration (perhaps more). Hosts may be deleted
929 * (have delete flag set); ditto for clients. refCount is always incremented
930 * before (*proc) is called.
932 * The return value of the proc is a set of flags. The proc should set
933 * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
936 h_Enumerate(int (*proc) (struct host*, void *), void *param)
938 struct host *host, **list;
943 if (hostCount == 0) {
947 list = (struct host **)malloc(hostCount * sizeof(struct host *));
949 ViceLogThenPanic(0, ("Failed malloc in h_Enumerate (list)\n"));
951 for (totalCount = count = 0, host = hostList;
952 host && totalCount < hostCount;
953 host = host->next, totalCount++) {
955 if (!(host->hostFlags & HOSTDELETED)) {
961 if (totalCount != hostCount) {
962 ViceLog(0, ("h_Enumerate found %d of %d hosts\n", totalCount, hostCount));
963 } else if (host != NULL) {
964 ViceLog(0, ("h_Enumerate found more than %d hosts\n", hostCount));
965 ShutDownAndCore(PANIC);
968 for (i = 0; i < count; i++) {
970 flags = (*proc) (list[i], param);
972 h_Release_r(list[i]);
974 /* bail out of the enumeration early */
975 if (H_ENUMERATE_ISSET_BAIL(flags)) {
978 ViceLog(0, ("h_Enumerate got back invalid return value %d\n", flags));
979 ShutDownAndCore(PANIC);
983 /* we bailed out of enumerating hosts early; we still have holds on
984 * some of the hosts in 'list', so release them */
987 for ( ; i < count; i++) {
988 h_Release_r(list[i]);
996 /* h_Enumerate_r (revised):
997 * Calls (*proc)(host, param) for each host in hostList, starting
998 * at enumstart. Called only under H_LOCK. Hosts may be deleted (have
999 * delete flag set); ditto for clients. refCount is always incremented
1000 * before (*proc) is called.
1002 * @note Assumes that hostList is only prepended to, that a host is never
1003 * inserted into the middle. Otherwise this would not be guaranteed to
1006 * The return value of the proc is a set of flags. The proc should set
1007 * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
1010 h_Enumerate_r(int (*proc) (struct host *, void *),
1011 struct host *enumstart, void *param)
1013 struct host *host, *next;
1017 if (hostCount == 0) {
1024 /* find the first non-deleted host, so we know where to actually start
1026 for (count = 0; host && count < hostCount; count++) {
1027 if (!(host->hostFlags & HOSTDELETED)) {
1034 /* we didn't find a non-deleted host... */
1036 if (host && count >= hostCount) {
1037 /* ...because we found a loop */
1038 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", hostCount));
1039 ShutDownAndCore(PANIC);
1042 /* ...because the hostList is full of deleted hosts */
1046 h_Hold_r(enumstart);
1048 /* remember hostCount, lest it change over the potential H_LOCK drop in
1050 origHostCount = hostCount;
1052 for (count = 0, host = enumstart; host && count < origHostCount; host = next, count++) {
1055 /* find the next non-deleted host */
1056 while (next && (next->hostFlags & HOSTDELETED)) {
1058 /* inc count for the skipped-over host */
1059 if (++count > origHostCount) {
1060 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1061 ShutDownAndCore(PANIC);
1067 if (!(host->hostFlags & HOSTDELETED)) {
1069 flags = (*proc) (host, param);
1070 if (H_ENUMERATE_ISSET_BAIL(flags)) {
1071 h_Release_r(host); /* this might free up the host */
1077 ViceLog(0, ("h_Enumerate_r got back invalid return value %d\n", flags));
1078 ShutDownAndCore(PANIC);
1081 h_Release_r(host); /* this might free up the host */
1083 if (host != NULL && count >= origHostCount) {
1084 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1085 ShutDownAndCore(PANIC);
1087 } /*h_Enumerate_r */
1090 /* inserts a new HashChain structure corresponding to this UUID */
1092 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1095 struct h_UuidHashChain *chain;
1096 char uuid1[128], uuid2[128];
1099 /* hash into proper bucket */
1100 index = h_UuidHashIndex(uuid);
1102 /* don't add the same entry multiple times */
1103 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1104 if (!chain->hostPtr)
1107 if (chain->hostPtr->interface &&
1108 afs_uuid_equal(&chain->hostPtr->interface->uuid, uuid)) {
1109 if (LogLevel >= 125) {
1110 afsUUID_to_string(&chain->hostPtr->interface->uuid, uuid1,
1112 afsUUID_to_string(uuid, uuid2, 127);
1113 ViceLog(125, ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s) exists as %s:%d (uuid %s)\n",
1115 afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1116 ntohs(chain->hostPtr->port), uuid2));
1122 /* insert into beginning of list for this bucket */
1123 chain = (struct h_UuidHashChain *)malloc(sizeof(struct h_UuidHashChain));
1125 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1127 chain->hostPtr = host;
1128 chain->next = hostUuidHashTable[index];
1129 hostUuidHashTable[index] = chain;
1132 afsUUID_to_string(uuid, uuid2, 127);
1134 ("h_AddHostToUuidHashTable_r: host %p (%s:%d) added as uuid %s\n",
1135 host, afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1136 ntohs(chain->hostPtr->port), uuid2));
1139 /* deletes a HashChain structure corresponding to this host */
1141 h_DeleteHostFromUuidHashTable_r(struct host *host)
1144 struct h_UuidHashChain **uhp, *uth;
1148 if (!host->interface)
1151 /* hash into proper bucket */
1152 index = h_UuidHashIndex(&host->interface->uuid);
1154 if (LogLevel >= 125)
1155 afsUUID_to_string(&host->interface->uuid, uuid1, 127);
1156 for (uhp = &hostUuidHashTable[index]; (uth = *uhp); uhp = &uth->next) {
1157 osi_Assert(uth->hostPtr);
1158 if (uth->hostPtr == host) {
1160 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d)\n",
1161 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1162 ntohs(host->port)));
1169 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d) not found\n",
1170 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1171 ntohs(host->port)));
1176 * This is called with host locked and held.
1178 * All addresses are in network byte order.
1181 invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1185 struct Interface *interface;
1186 char hoststr[16], hoststr2[16];
1189 osi_Assert(host->interface);
1191 ViceLog(125, ("invalidateInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1192 host, afs_inet_ntoa_r(host->host, hoststr),
1193 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1197 * Make sure this address is on the list of known addresses
1200 interface = host->interface;
1201 number = host->interface->numberOfInterfaces;
1202 for (i = 0; i < number; i++) {
1203 if (interface->interface[i].addr == addr &&
1204 interface->interface[i].port == port) {
1205 if (interface->interface[i].valid) {
1206 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1207 interface->interface[i].valid = 0;
1218 * This is called with host locked and held. This function differs
1219 * from removeInterfaceAddr_r in that it is called when the address
1220 * is being removed from the host regardless of whether or not there
1221 * is an interface list for the host. This function will delete the
1222 * host if there are no addresses left on it.
1224 * All addresses are in network byte order.
1227 removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1230 char hoststr[16], hoststr2[16];
1231 struct rx_connection *rxconn;
1233 if (!host->interface || host->interface->numberOfInterfaces == 1) {
1234 if (host->host == addr && host->port == port) {
1236 ("Removing only address for host %" AFS_PTR_FMT " (%s:%d), deleting host.\n",
1237 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1238 host->hostFlags |= HOSTDELETED;
1240 * Do not remove the primary addr/port from the hash table.
1241 * It will be ignored due to the HOSTDELETED flag and will
1242 * be removed when h_TossStuff_r() cleans up the HOSTDELETED
1243 * host. Removing it here will only result in a search for
1244 * the host/addr/port in the hash chain which will fail.
1248 ("Removing address that does not belong to host %" AFS_PTR_FMT " (%s:%d).\n",
1249 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1252 if (host->host == addr && host->port == port) {
1253 removeInterfaceAddr_r(host, addr, port);
1255 for (i=0; i < host->interface->numberOfInterfaces; i++) {
1256 if (host->interface->interface[i].valid) {
1258 ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
1259 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1260 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
1261 ntohs(host->interface->interface[i].port)));
1262 host->host = host->interface->interface[i].addr;
1263 host->port = host->interface->interface[i].port;
1264 h_AddHostToAddrHashTable_r(host->host, host->port, host);
1269 if (i == host->interface->numberOfInterfaces) {
1271 ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
1272 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1273 host->hostFlags |= HOSTDELETED;
1274 /* addr/port was removed from the hash table */
1278 rxconn = host->callback_rxcon;
1279 host->callback_rxcon = NULL;
1282 rx_DestroyConnection(rxconn);
1286 h_SetupCallbackConn_r(host);
1289 /* not the primary addr/port, just invalidate it */
1290 invalidateInterfaceAddr_r(host, addr, port);
1298 createHostAddrHashChain_r(int index, afs_uint32 addr, afs_uint16 port, struct host *host)
1300 struct h_AddrHashChain *chain;
1303 /* insert into beginning of list for this bucket */
1304 chain = (struct h_AddrHashChain *)malloc(sizeof(struct h_AddrHashChain));
1306 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToAddrHashTable_r\n"));
1308 chain->hostPtr = host;
1309 chain->next = hostAddrHashTable[index];
1312 hostAddrHashTable[index] = chain;
1313 ViceLog(125, ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " added as %s:%d\n",
1314 host, afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1318 * Resolve host address conflicts when hashing by address.
1320 * @param[in] addr an ip address of the interface
1321 * @param[in] port the port of the interface
1322 * @param[in] newHost the host being added with this address
1323 * @param[in] oldHost the host previously added with this address
1326 reconcileHosts_r(afs_uint32 addr, afs_uint16 port, struct host *newHost,
1327 struct host *oldHost)
1329 struct rx_connection *cb = NULL;
1331 struct interfaceAddr interf;
1333 afsUUID *newHostUuid = &nulluuid;
1334 afsUUID *oldHostUuid = &nulluuid;
1338 ("reconcileHosts_r: addr %s:%d newHost %" AFS_PTR_FMT " oldHost %"
1339 AFS_PTR_FMT, afs_inet_ntoa_r(addr, hoststr), ntohs(port),
1342 osi_Assert(oldHost != newHost);
1343 caps.Capabilities_val = NULL;
1346 sc = rxnull_NewClientSecurityObject();
1349 cb = rx_NewConnection(addr, port, 1, sc, 0);
1350 rx_SetConnDeadTime(cb, 50);
1351 rx_SetConnHardDeadTime(cb, AFS_HARDDEADTIME);
1356 code = RXAFSCB_TellMeAboutYourself(cb, &interf, &caps);
1357 if (code == RXGEN_OPCODE) {
1358 code = RXAFSCB_WhoAreYou(cb, &interf);
1362 if (code == RXGEN_OPCODE ||
1363 (code == 0 && afs_uuid_equal(&interf.uuid, &nulluuid))) {
1365 ("reconcileHosts_r: WhoAreYou not supported for connection (%s:%d), error %d\n",
1366 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1371 ("reconcileHosts_r: WhoAreYou failed for connection (%s:%d), error %d\n",
1372 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1376 /* Since lock was dropped, the hosts may have been deleted during the rpcs. */
1377 if ((newHost->hostFlags & HOSTDELETED)
1378 && (oldHost->hostFlags & HOSTDELETED)) {
1380 ("reconcileHosts_r: new and old hosts were deleted during probe.\n"));
1384 /* A check can be done if at least one of the hosts has a uuid. It
1385 * is an error if the hosts have the same (not null) uuid. */
1386 if ((!(newHost->hostFlags & HOSTDELETED)) && newHost->interface) {
1387 newHostUuid = &(newHost->interface->uuid);
1389 if ((!(oldHost->hostFlags & HOSTDELETED)) && oldHost->interface) {
1390 oldHostUuid = &(oldHost->interface->uuid);
1392 if (afs_uuid_equal(newHostUuid, &nulluuid) &&
1393 afs_uuid_equal(oldHostUuid, &nulluuid)) {
1395 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), no uuids\n",
1396 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1399 if (afs_uuid_equal(newHostUuid, oldHostUuid)) {
1401 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), same uuids\n",
1402 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1406 /* Determine which host should be hashed */
1407 if ((!(newHost->hostFlags & HOSTDELETED))
1408 && afs_uuid_equal(newHostUuid, &(interf.uuid))) {
1409 /* Install the new host into the hash before removing the stale
1410 * addresses. Walk the hash chain again since the hash table may have
1411 * been changed when the host lock was dropped to get the uuid. */
1412 struct h_AddrHashChain *chain;
1413 int index = h_HashIndex(addr);
1414 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1415 if (chain->addr == addr && chain->port == port) {
1416 chain->hostPtr = newHost;
1417 removeAddress_r(oldHost, addr, port);
1421 createHostAddrHashChain_r(index, addr, port, newHost);
1422 removeAddress_r(oldHost, addr, port);
1425 if ((!(oldHost->hostFlags & HOSTDELETED))
1426 && afs_uuid_equal(oldHostUuid, &(interf.uuid))) {
1427 removeAddress_r(newHost, addr, port);
1432 if (!(newHost->hostFlags & HOSTDELETED)) {
1433 removeAddress_r(newHost, addr, port);
1435 if (!(oldHost->hostFlags & HOSTDELETED)) {
1436 removeAddress_r(oldHost, addr, port);
1440 h_Release_r(newHost);
1441 h_Release_r(oldHost);
1442 rx_DestroyConnection(cb);
1446 /* inserts a new HashChain structure corresponding to this address */
1448 h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1451 struct h_AddrHashChain *chain;
1454 /* hash into proper bucket */
1455 index = h_HashIndex(addr);
1457 /* don't add the same address:port pair entry multiple times */
1458 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1459 if (chain->addr == addr && chain->port == port) {
1460 if (chain->hostPtr == host) {
1462 ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
1463 host, afs_inet_ntoa_r(chain->addr, hoststr),
1464 ntohs(chain->port)));
1467 if (!(chain->hostPtr->hostFlags & HOSTDELETED)) {
1468 /* attempt to resolve host address collision */
1469 reconcileHosts_r(addr, port, host, chain->hostPtr);
1474 createHostAddrHashChain_r(index, addr, port, host);
1478 * This is called with host locked and held.
1479 * It is called to either validate or add an additional interface
1480 * address/port on the specified host.
1482 * All addresses are in network byte order.
1485 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1489 struct Interface *interface;
1490 char hoststr[16], hoststr2[16];
1493 osi_Assert(host->interface);
1496 * Make sure this address is on the list of known addresses
1499 number = host->interface->numberOfInterfaces;
1500 for (i = 0; i < number; i++) {
1501 if (host->interface->interface[i].addr == addr &&
1502 host->interface->interface[i].port == port) {
1504 ("addInterfaceAddr : found host %" AFS_PTR_FMT " (%s:%d) adding %s:%d%s\n",
1505 host, afs_inet_ntoa_r(host->host, hoststr),
1506 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1507 ntohs(port), host->interface->interface[i].valid ? "" :
1510 if (host->interface->interface[i].valid == 0) {
1511 host->interface->interface[i].valid = 1;
1512 h_AddHostToAddrHashTable_r(addr, port, host);
1518 ViceLog(125, ("addInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) adding %s:%d\n",
1519 host, afs_inet_ntoa_r(host->host, hoststr),
1520 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1523 interface = (struct Interface *)
1524 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1526 ViceLogThenPanic(0, ("Failed malloc in addInterfaceAddr_r\n"));
1528 interface->numberOfInterfaces = number + 1;
1529 interface->uuid = host->interface->uuid;
1530 for (i = 0; i < number; i++)
1531 interface->interface[i] = host->interface->interface[i];
1533 /* Add the new valid interface */
1534 interface->interface[number].addr = addr;
1535 interface->interface[number].port = port;
1536 interface->interface[number].valid = 1;
1537 h_AddHostToAddrHashTable_r(addr, port, host);
1538 free(host->interface);
1539 host->interface = interface;
1546 * This is called with host locked and held.
1548 * All addresses are in network byte order.
1551 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1555 struct Interface *interface;
1556 char hoststr[16], hoststr2[16];
1559 osi_Assert(host->interface);
1561 ViceLog(125, ("removeInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1562 host, afs_inet_ntoa_r(host->host, hoststr),
1563 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1567 * Make sure this address is on the list of known addresses
1570 interface = host->interface;
1571 number = host->interface->numberOfInterfaces;
1572 for (i = 0; i < number; i++) {
1573 if (interface->interface[i].addr == addr &&
1574 interface->interface[i].port == port) {
1575 if (interface->interface[i].valid)
1576 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1578 for (; i < number; i++) {
1579 interface->interface[i] = interface->interface[i+1];
1581 interface->numberOfInterfaces = number;
1592 h_threadquota(int waiting)
1597 } else if (lwps > 32) {
1600 } else if (lwps > 16) {
1610 /* If found, host is returned with refCount incremented */
1612 h_GetHost_r(struct rx_connection *tcon)
1615 struct host *oldHost;
1617 struct interfaceAddr interf;
1618 int interfValid = 0;
1619 struct Identity *identP = NULL;
1622 char hoststr[16], hoststr2[16];
1624 struct rx_connection *cb_conn = NULL;
1625 struct rx_connection *cb_in = NULL;
1627 caps.Capabilities_val = NULL;
1629 haddr = rxr_HostOf(tcon);
1630 hport = rxr_PortOf(tcon);
1633 rx_DestroyConnection(cb_in);
1636 if (caps.Capabilities_val)
1637 free(caps.Capabilities_val);
1638 caps.Capabilities_val = NULL;
1639 caps.Capabilities_len = 0;
1642 if (h_Lookup_r(haddr, hport, &host))
1644 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1645 if (host && !identP && !(host->Console & 1)) {
1646 /* This is a new connection, and we already have a host
1647 * structure for this address. Verify that the identity
1648 * of the caller matches the identity in the host structure.
1650 if ((host->hostFlags & HWHO_INPROGRESS) &&
1651 h_threadquota(host->lock.num_waiting)) {
1657 if (!(host->hostFlags & ALTADDR) ||
1658 (host->hostFlags & HOSTDELETED)) {
1659 /* Another thread is doing initialization
1660 * or this host was deleted while we
1661 * waited for the lock. */
1664 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1665 host, afs_inet_ntoa_r(host->host, hoststr),
1666 ntohs(host->port)));
1670 host->hostFlags |= HWHO_INPROGRESS;
1671 host->hostFlags &= ~ALTADDR;
1673 /* We received a new connection from an IP address/port
1674 * that is associated with 'host' but the address/port of
1675 * the callback connection does not have to match it.
1676 * If there is a match, we can use the existing callback
1677 * connection to verify the UUID. If they do not match
1678 * we need to use a new callback connection to verify the
1679 * UUID of the incoming caller and perhaps use the old
1680 * callback connection to verify that the old address/port
1684 cb_conn = host->callback_rxcon;
1685 rx_GetConnection(cb_conn);
1687 if (haddr == host->host && hport == host->port) {
1688 /* The existing callback connection matches the
1689 * incoming connection so just use it.
1692 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1693 if (code == RXGEN_OPCODE)
1694 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1696 /* We do not have a match. Create a new connection
1697 * for the new addr/port and use multi_Rx to probe
1698 * both of them simultaneously.
1701 sc = rxnull_NewClientSecurityObject();
1702 cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1703 rx_SetConnDeadTime(cb_in, 50);
1704 rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1705 rx_SetConnSecondsUntilNatPing(cb_in, 20);
1708 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1709 if (code == RXGEN_OPCODE)
1710 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1712 rx_PutConnection(cb_conn);
1715 if ((code == RXGEN_OPCODE) ||
1716 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1717 identP = (struct Identity *)malloc(sizeof(struct Identity));
1719 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1722 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1723 if (cb_in == NULL) {
1724 /* The host on this connection was unable to respond to
1725 * the WhoAreYou. We will treat this as a new connection
1726 * from the existing host. The worst that can happen is
1727 * that we maintain some extra callback state information */
1728 if (host->interface) {
1730 ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1732 afs_inet_ntoa_r(host->host, hoststr),
1733 ntohs(host->port)));
1734 host->hostFlags |= HOSTDELETED;
1735 host->hostFlags &= ~HWHO_INPROGRESS;
1742 /* The incoming connection does not support WhoAreYou but
1743 * the original one might have. Use removeAddress_r() to
1744 * remove this addr/port from the host that was found.
1745 * If there are no more addresses left for the host it
1746 * will be deleted. Then we retry.
1748 removeAddress_r(host, haddr, hport);
1749 host->hostFlags &= ~HWHO_INPROGRESS;
1750 host->hostFlags |= ALTADDR;
1756 } else if (code == 0) {
1758 identP = (struct Identity *)malloc(sizeof(struct Identity));
1760 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1763 identP->uuid = interf.uuid;
1764 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1765 /* Check whether the UUID on this connection matches
1766 * the UUID in the host structure. If they don't match
1767 * then this is not the same host as before. */
1768 if (!host->interface
1769 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1772 ("Uuid doesn't match connection (%s:%d).\n",
1773 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1774 removeAddress_r(host, haddr, hport);
1777 ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1778 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1780 removeAddress_r(host, host->host, host->port);
1782 host->hostFlags &= ~HWHO_INPROGRESS;
1783 host->hostFlags |= ALTADDR;
1789 /* the UUID matched the client at the incoming addr/port
1790 * but this is not the address of the active callback
1791 * connection. Try that connection and see if the client
1792 * is still there and if the reported UUID is the same.
1795 afsUUID uuid = host->interface->uuid;
1796 cb_conn = host->callback_rxcon;
1797 rx_GetConnection(cb_conn);
1798 rx_SetConnDeadTime(cb_conn, 2);
1799 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1801 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1803 rx_SetConnDeadTime(cb_conn, 50);
1804 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1805 rx_PutConnection(cb_conn);
1808 /* The primary address is either not responding or
1809 * is not the client we are looking for. Need to
1810 * remove the primary address and add swap in the new
1811 * callback connection, and destroy the old one.
1813 struct rx_connection *rxconn;
1814 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1816 afs_inet_ntoa_r(host->host, hoststr),
1817 ntohs(host->port),code2));
1820 * make sure we add and then remove. otherwise, we
1821 * might end up with no valid interfaces after the
1822 * remove and the host will have been marked deleted.
1824 addInterfaceAddr_r(host, haddr, hport);
1825 removeInterfaceAddr_r(host, host->host, host->port);
1828 rxconn = host->callback_rxcon;
1829 host->callback_rxcon = cb_in;
1834 * If rx_DestroyConnection calls h_FreeConnection we
1835 * will deadlock on the host_glock_mutex. Work around
1836 * the problem by unhooking the client from the
1837 * connection before destroying the connection.
1839 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1840 rx_DestroyConnection(rxconn);
1846 /* A callback to the incoming connection address is failing.
1847 * Assume that the addr/port is no longer associated with the host
1848 * returned by h_Lookup_r.
1851 ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1852 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1853 removeAddress_r(host, haddr, hport);
1854 host->hostFlags &= ~HWHO_INPROGRESS;
1855 host->hostFlags |= ALTADDR;
1859 rx_DestroyConnection(cb_in);
1864 ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1865 host, afs_inet_ntoa_r(host->host, hoststr),
1866 ntohs(host->port), code));
1867 host->hostFlags |= VENUSDOWN;
1870 if (caps.Capabilities_val
1871 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1872 host->hostFlags |= HERRORTRANS;
1874 host->hostFlags &= ~(HERRORTRANS);
1875 host->hostFlags |= ALTADDR;
1876 host->hostFlags &= ~HWHO_INPROGRESS;
1879 if (!(host->hostFlags & ALTADDR)) {
1880 /* another thread is doing the initialisation */
1882 ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1883 host, afs_inet_ntoa_r(host->host, hoststr),
1884 ntohs(host->port)));
1888 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1889 host, afs_inet_ntoa_r(host->host, hoststr),
1890 ntohs(host->port)));
1894 /* We need to check whether the identity in the host structure
1895 * matches the identity on the connection. If they don't match
1896 * then treat this a new host. */
1897 if (!(host->Console & 1)
1898 && ((!identP->valid && host->interface)
1899 || (identP->valid && !host->interface)
1901 && !afs_uuid_equal(&identP->uuid,
1902 &host->interface->uuid)))) {
1903 char uuid1[128], uuid2[128];
1905 afsUUID_to_string(&identP->uuid, uuid1, 127);
1906 if (host->interface)
1907 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1909 ("CB: new identity for host %p (%s:%d), "
1910 "deleting(%x %p %s %s)\n",
1911 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1912 identP->valid, host->interface,
1913 identP->valid ? uuid1 : "no_uuid",
1914 host->interface ? uuid2 : "no_uuid"));
1916 /* The host in the cache is not the host for this connection */
1918 host->hostFlags |= HOSTDELETED;
1924 host = h_Alloc_r(tcon); /* returned held and locked */
1927 h_gethostcps_r(host, FT_ApproxTime());
1928 if (!(host->Console & 1)) {
1930 cb_conn = host->callback_rxcon;
1931 rx_GetConnection(cb_conn);
1932 host->hostFlags |= HWHO_INPROGRESS;
1935 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1936 if (code == RXGEN_OPCODE)
1937 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1938 rx_PutConnection(cb_conn);
1941 if ((code == RXGEN_OPCODE) ||
1942 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1945 (struct Identity *)malloc(sizeof(struct Identity));
1950 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1954 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1956 ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1957 host, afs_inet_ntoa_r(host->host, hoststr),
1958 ntohs(host->port)));
1960 } else if (code == 0) {
1963 (struct Identity *)malloc(sizeof(struct Identity));
1968 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1972 identP->uuid = interf.uuid;
1974 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1976 ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
1977 host, afs_inet_ntoa_r(host->host, hoststr),
1978 ntohs(host->port)));
1980 if (code == 0 && !identP->valid) {
1981 cb_conn = host->callback_rxcon;
1982 rx_GetConnection(cb_conn);
1984 code = RXAFSCB_InitCallBackState(cb_conn);
1985 rx_PutConnection(cb_conn);
1988 } else if (code == 0) {
1989 oldHost = h_LookupUuid_r(&identP->uuid);
1994 if (oldHost->hostFlags & HOSTDELETED) {
1995 h_Unlock_r(oldHost);
1996 h_Release_r(oldHost);
2004 /* This is a new address for an existing host. Update
2005 * the list of interfaces for the existing host and
2006 * delete the host structure we just allocated. */
2008 /* mark the duplicate host as deleted before we do
2009 * anything. The probing code below may try to change
2010 * "oldHost" to the same IP address as "host" currently
2011 * has, and we do not want a pseudo-"collision" to be
2013 host->hostFlags |= HOSTDELETED;
2015 oldHost->hostFlags |= HWHO_INPROGRESS;
2017 if (oldHost->interface) {
2019 afsUUID uuid = oldHost->interface->uuid;
2020 cb_conn = oldHost->callback_rxcon;
2021 rx_GetConnection(cb_conn);
2022 rx_SetConnDeadTime(cb_conn, 2);
2023 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2025 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2027 rx_SetConnDeadTime(cb_conn, 50);
2028 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2029 rx_PutConnection(cb_conn);
2032 /* The primary address is either not responding or
2033 * is not the client we are looking for.
2034 * MultiProbeAlternateAddress_r() will remove the
2035 * alternate interfaces that do not have the same
2037 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
2039 afs_inet_ntoa_r(oldHost->host, hoststr),
2040 ntohs(oldHost->port),code2));
2041 MultiProbeAlternateAddress_r(oldHost);
2048 if (oldHost->host != haddr || oldHost->port != hport) {
2049 struct rx_connection *rxconn;
2052 ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
2054 afs_inet_ntoa_r(oldHost->host, hoststr2),
2055 ntohs(oldHost->port),
2056 afs_inet_ntoa_r(haddr, hoststr),
2059 * add then remove. otherwise the host may get marked
2060 * deleted if we removed the only valid address.
2062 addInterfaceAddr_r(oldHost, haddr, hport);
2063 if (probefail || oldHost->host == haddr) {
2065 * The probe failed which means that the old
2066 * address is either unreachable or is not the
2067 * same host we were just contacted by. We will
2068 * also remove addresses if only the port has
2069 * changed because that indicates the client
2072 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
2075 struct Interface *interface = oldHost->interface;
2076 int number = oldHost->interface->numberOfInterfaces;
2077 for (i = 0; i < number; i++) {
2078 if (interface->interface[i].addr == haddr &&
2079 interface->interface[i].port != hport) {
2081 * We have just been contacted by a client
2082 * that has been seen from behind a NAT
2083 * and at least one other address.
2085 removeInterfaceAddr_r(oldHost, haddr,
2086 interface->interface[i].port);
2091 h_AddHostToAddrHashTable_r(haddr, hport, oldHost);
2092 oldHost->host = haddr;
2093 oldHost->port = hport;
2094 rxconn = oldHost->callback_rxcon;
2095 oldHost->callback_rxcon = host->callback_rxcon;
2096 host->callback_rxcon = rxconn;
2098 /* don't destroy rxconn here; let h_TossStuff_r
2099 * take care of that via h_Release_r below */
2101 host->hostFlags &= ~HWHO_INPROGRESS;
2103 /* release host because it was allocated by h_Alloc_r */
2106 /* the new host is held and locked */
2108 /* This really is a new host */
2109 h_AddHostToUuidHashTable_r(&identP->uuid, host);
2110 cb_conn = host->callback_rxcon;
2111 rx_GetConnection(cb_conn);
2114 RXAFSCB_InitCallBackState3(cb_conn,
2116 rx_PutConnection(cb_conn);
2121 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2122 host, afs_inet_ntoa_r(host->host, hoststr),
2123 ntohs(host->port)));
2124 osi_Assert(interfValid == 1);
2125 initInterfaceAddr_r(host, &interf);
2131 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2132 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2133 host->hostFlags |= VENUSDOWN;
2136 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2137 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2138 host->hostFlags |= RESETDONE;
2141 if (caps.Capabilities_val
2142 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2143 host->hostFlags |= HERRORTRANS;
2145 host->hostFlags &= ~(HERRORTRANS);
2146 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2147 host->hostFlags &= ~HWHO_INPROGRESS;
2152 if (caps.Capabilities_val)
2153 free(caps.Capabilities_val);
2154 caps.Capabilities_val = NULL;
2155 caps.Capabilities_len = 0;
2157 rx_DestroyConnection(cb_in);
2165 static char localcellname[PR_MAXNAMELEN + 1];
2166 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
2167 int num_lrealms = -1;
2171 h_InitHostPackage(void)
2173 memset(&nulluuid, 0, sizeof(afsUUID));
2174 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
2175 if (num_lrealms == -1) {
2177 for (i=0; i<AFS_NUM_LREALMS; i++) {
2178 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
2184 ("afs_krb_get_lrealm failed, using %s.\n",
2186 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
2192 /* initialize the rest of the local realms to nullstring for debugging */
2193 for (; i<AFS_NUM_LREALMS; i++)
2194 local_realms[i][0] = '\0';
2196 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2197 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2198 MUTEX_INIT(&host_glock_mutex, "host glock", MUTEX_DEFAULT, 0);
2202 MapName_r(char *aname, char *acell, afs_int32 * aval)
2207 afs_int32 anamelen, cnamelen;
2211 anamelen = strlen(aname);
2212 if (anamelen >= PR_MAXNAMELEN)
2213 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
2215 lnames.namelist_len = 1;
2216 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
2217 lids.idlist_len = 0;
2218 lids.idlist_val = NULL;
2220 cnamelen = strlen(acell);
2222 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2224 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2225 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2226 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2228 ("MapName: Name too long, using AnonymousID for %s@%s\n",
2230 *aval = AnonymousID;
2233 foreign = 1; /* attempt cross-cell authentication */
2234 tname = (char *)malloc(PR_MAXNAMELEN);
2236 ViceLogThenPanic(0, ("Failed malloc in MapName_r\n"));
2238 strcpy(tname, aname);
2239 tname[anamelen] = '@';
2240 strcpy(tname + anamelen + 1, acell);
2241 lnames.namelist_val = (prname *) tname;
2246 code = hpr_NameToId(&lnames, &lids);
2249 if (lids.idlist_val) {
2250 *aval = lids.idlist_val[0];
2251 if (*aval == AnonymousID) {
2253 ("MapName: NameToId on %s returns anonymousID\n",
2254 lnames.namelist_val[0]));
2256 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2259 ("MapName: NameToId on '%s' is unknown\n",
2260 lnames.namelist_val[0]));
2266 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
2274 /* NOTE: this returns the client with a Write lock and a refCount */
2276 h_ID2Client(afs_int32 vid)
2278 struct client *client;
2283 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
2284 if (host->hostFlags & HOSTDELETED)
2286 for (client = host->FirstClient; client; client = client->next) {
2287 if (!client->deleted && client->ViceId == vid) {
2290 ObtainWriteLock(&client->lock);
2295 if (count != hostCount) {
2296 ViceLog(0, ("h_ID2Client found %d of %d hosts\n", count, hostCount));
2297 } else if (host != NULL) {
2298 ViceLog(0, ("h_ID2Client found more than %d hosts\n", hostCount));
2299 ShutDownAndCore(PANIC);
2307 * Called by the server main loop. Returns a h_Held client, which must be
2308 * released later the main loop. Allocates a client if the matching one
2309 * isn't around. The client is returned with its reference count incremented
2310 * by one. The caller must call h_ReleaseClient_r when finished with
2313 * The refCount on client->host is returned incremented. h_ReleaseClient_r
2314 * does not decrement the refCount on client->host.
2317 h_FindClient_r(struct rx_connection *tcon)
2319 struct client *client;
2320 struct host *host = NULL;
2321 struct client *oldClient;
2322 afs_int32 viceid = 0;
2326 #if (64-MAXKTCNAMELEN)
2327 ticket name length != 64
2331 char uname[PR_MAXNAMELEN];
2332 char tcell[MAXKTCREALMLEN];
2336 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2337 if (client && client->sid == rx_GetConnectionId(tcon)
2338 && client->VenusEpoch == rx_GetConnectionEpoch(tcon)
2339 && !(client->host->hostFlags & HOSTDELETED)
2340 && !client->deleted) {
2343 h_Hold_r(client->host);
2344 if (client->prfail != 2) {
2345 /* Could add shared lock on client here */
2346 /* note that we don't have to lock entry in this path to
2347 * ensure CPS is initialized, since we don't call rx_SetSpecific
2348 * until initialization is done, and we only get here if
2349 * rx_GetSpecific located the client structure.
2354 ObtainWriteLock(&client->lock); /* released at end */
2360 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2362 ("FindClient: authenticating connection: authClass=%d\n",
2364 if (authClass == 1) {
2365 /* A bcrypt tickets, no longer supported */
2366 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2367 viceid = AnonymousID;
2368 expTime = 0x7fffffff;
2369 } else if (authClass == 2) {
2372 /* kerberos ticket */
2373 code = rxkad_GetServerInfo(tcon, /*level */ 0, (afs_uint32 *)&expTime,
2374 tname, tinst, tcell, &kvno);
2376 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2377 viceid = AnonymousID;
2378 expTime = 0x7fffffff;
2380 int ilen = strlen(tinst);
2382 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2383 tname, tinst, tcell, expTime, kvno));
2384 strncpy(uname, tname, sizeof(uname));
2386 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2389 strcat(uname, tinst);
2391 /* translate the name to a vice id */
2392 code = MapName_r(uname, tcell, &viceid);
2396 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2399 viceid = AnonymousID;
2400 expTime = 0x7fffffff;
2404 viceid = AnonymousID; /* unknown security class */
2405 expTime = 0x7fffffff;
2408 if (!client) { /* loop */
2409 host = h_GetHost_r(tcon); /* Returns with incremented refCount */
2415 /* First try to find the client structure */
2416 for (client = host->FirstClient; client; client = client->next) {
2417 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2418 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2421 ObtainWriteLock(&client->lock);
2427 /* Still no client structure - get one */
2430 if (host->hostFlags & HOSTDELETED) {
2435 /* Retry to find the client structure */
2436 for (client = host->FirstClient; client; client = client->next) {
2437 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2438 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2440 goto retryfirstclient;
2445 ObtainWriteLock(&client->lock);
2446 client->refCount = 1;
2447 client->host = host;
2448 client->InSameNetwork = host->InSameNetwork;
2449 client->ViceId = viceid;
2450 client->expTime = expTime; /* rx only */
2451 client->authClass = authClass; /* rx only */
2452 client->sid = rx_GetConnectionId(tcon);
2453 client->VenusEpoch = rx_GetConnectionEpoch(tcon);
2454 client->CPS.prlist_val = NULL;
2455 client->CPS.prlist_len = 0;
2459 client->prfail = fail;
2461 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2462 client->CPS.prlist_len = 0;
2463 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2464 free(client->CPS.prlist_val);
2465 client->CPS.prlist_val = NULL;
2466 client->ViceId = viceid;
2467 client->expTime = expTime;
2469 if (viceid == ANONYMOUSID) {
2470 client->CPS.prlist_len = AnonCPS.prlist_len;
2471 client->CPS.prlist_val = AnonCPS.prlist_val;
2474 code = hpr_GetCPS(viceid, &client->CPS);
2479 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2480 code, viceid, client->host,
2481 afs_inet_ntoa_r(client->host->host,hoststr),
2482 ntohs(client->host->port)));
2484 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2485 * all protection servers and reevaluates things if no
2486 * sync server or quorum is found we could still end up
2487 * with one of these errors. In such case we would like to
2488 * reevaluate the rpc call to find if there's cps for this
2489 * guy. We treat other errors (except network failures
2490 * ones - i.e. code < 0) as an indication that there is no
2491 * CPS for this host. Ideally we could like to deal this
2492 * problem the other way around (i.e. if code == NOCPS
2493 * ignore else retry next time) but the problem is that
2494 * there're other errors (i.e. EPERM) for which we don't
2495 * want to retry and we don't know the whole code list!
2497 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2501 /* the disabling of system:administrators is so iffy and has so many
2502 * possible failure modes that we will disable it again */
2503 /* Turn off System:Administrator for safety
2504 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2505 * osi_Assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2508 /* Now, tcon may already be set to a rock, since we blocked with no host
2509 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2510 * required). So, before setting the RPC's rock, we should disconnect
2511 * the RPC from the other client structure's rock.
2513 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2514 if (oldClient && oldClient != client
2515 && oldClient->sid == rx_GetConnectionId(tcon)
2516 && oldClient->VenusEpoch == rx_GetConnectionEpoch(tcon)
2517 && !(oldClient->host->hostFlags & HOSTDELETED)) {
2519 if (!oldClient->deleted) {
2520 /* if we didn't create it, it's not ours to put back */
2522 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2523 "conn %p (host %s:%d) had client %p(%x)\n",
2524 client, client->sid, tcon,
2525 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2526 ntohs(rxr_PortOf(tcon)),
2527 oldClient, oldClient->sid));
2528 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2529 free(client->CPS.prlist_val);
2530 client->CPS.prlist_val = NULL;
2531 client->CPS.prlist_len = 0;
2533 /* We should perhaps check for 0 here */
2535 ReleaseWriteLock(&client->lock);
2540 oldClient->refCount++;
2542 h_Hold_r(oldClient->host);
2543 h_Release_r(client->host);
2546 ObtainWriteLock(&oldClient->lock);
2549 host = oldClient->host;
2551 ViceLog(0, ("FindClient: deleted client %p(%x ref %d host %p href "
2552 "%d) already had conn %p (host %s:%d, cid %x), stolen "
2553 "by client %p(%x, ref %d host %p href %d)\n",
2554 oldClient, oldClient->sid, oldClient->refCount,
2555 oldClient->host, oldClient->host->refCount, tcon,
2556 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2557 ntohs(rxr_PortOf(tcon)), rx_GetConnectionId(tcon),
2558 client, client->sid, client->refCount,
2559 client->host, client->host->refCount));
2560 /* rx_SetSpecific will be done immediately below */
2563 /* Avoid chaining in more than once. */
2567 if (host->hostFlags & HOSTDELETED) {
2572 client->host = NULL;
2574 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2575 free(client->CPS.prlist_val);
2576 client->CPS.prlist_val = NULL;
2577 client->CPS.prlist_len = 0;
2580 ReleaseWriteLock(&client->lock);
2585 client->next = host->FirstClient;
2586 host->FirstClient = client;
2588 CurrentConnections++; /* increment number of connections */
2590 rx_SetSpecific(tcon, rxcon_client_key, client);
2591 ReleaseWriteLock(&client->lock);
2595 } /*h_FindClient_r */
2598 h_ReleaseClient_r(struct client *client)
2600 osi_Assert(client->refCount > 0);
2607 * Sigh: this one is used to get the client AGAIN within the individual
2608 * server routines. This does not bother h_Holding the host, since
2609 * this is assumed already have been done by the server main loop.
2610 * It does check tokens, since only the server routines can return the
2611 * VICETOKENDEAD error code
2614 GetClient(struct rx_connection *tcon, struct client **cp)
2616 struct client *client;
2621 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2622 if (client == NULL) {
2624 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2625 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2626 ntohs(rxr_PortOf(tcon))));
2630 if (rx_GetConnectionId(tcon) != client->sid
2631 || rx_GetConnectionEpoch(tcon) != client->VenusEpoch) {
2633 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2634 tcon, rx_GetConnectionId(tcon), client->sid));
2638 if (client && client->LastCall > client->expTime && client->expTime) {
2640 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2641 afs_inet_ntoa_r(client->host->host, hoststr),
2642 ntohs(client->host->port), client->expTime));
2644 return VICETOKENDEAD;
2646 if (client->deleted) {
2647 ViceLog(0, ("GetClient: got deleted client, connection will appear "
2648 "anonymous; tcon %p cid %x client %p ref %d host %p "
2649 "(%s:%d) href %d ViceId %d\n",
2650 tcon, rx_GetConnectionId(tcon), client, client->refCount,
2652 afs_inet_ntoa_r(client->host->host, hoststr),
2653 (int)ntohs(client->host->port), client->host->refCount,
2654 (int)client->ViceId));
2664 PutClient(struct client **cp)
2670 h_ReleaseClient_r(*cp);
2677 /* Client user name for short term use. Note that this is NOT inexpensive */
2679 h_UserName(struct client *client)
2681 static char User[PR_MAXNAMELEN + 1];
2685 lids.idlist_len = 1;
2686 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2687 if (!lids.idlist_val) {
2688 ViceLogThenPanic(0, ("Failed malloc in h_UserName\n"));
2690 lnames.namelist_len = 0;
2691 lnames.namelist_val = (prname *) 0;
2692 lids.idlist_val[0] = client->ViceId;
2693 if (hpr_IdToName(&lids, &lnames)) {
2694 /* We need to free id we alloced above! */
2695 free(lids.idlist_val);
2696 return "*UNKNOWN USER NAME*";
2698 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2699 free(lids.idlist_val);
2700 free(lnames.namelist_val);
2709 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2710 CEs, CEBlocks, HTs, HTBlocks));
2716 h_PrintClient(struct host *host, void *rock)
2718 StreamHandle_t *file = (StreamHandle_t *)rock;
2719 struct client *client;
2724 time_t LastCall, expTime;
2728 LastCall = host->LastCall;
2729 if (host->hostFlags & HOSTDELETED) {
2733 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2734 localtime_r(&LastCall, &tm));
2735 snprintf(tmpStr, sizeof tmpStr, "Host %s:%d down = %d, LastCall %s\n",
2736 afs_inet_ntoa_r(host->host, hoststr),
2737 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2739 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2740 for (client = host->FirstClient; client; client = client->next) {
2741 if (!client->deleted) {
2742 expTime = client->expTime;
2743 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2744 localtime_r(&expTime, &tm));
2745 snprintf(tmpStr, sizeof tmpStr,
2746 " user id=%d, name=%s, sl=%s till %s\n",
2747 client->ViceId, h_UserName(client),
2748 client->authClass ? "Authenticated"
2749 : "Not authenticated",
2750 client->authClass ? tbuffer : "No Limit");
2751 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2752 snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2753 client->CPS.prlist_len);
2754 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2755 if (client->CPS.prlist_val) {
2756 for (i = 0; i < client->CPS.prlist_len; i++) {
2757 snprintf(tmpStr, sizeof tmpStr, " %d",
2758 client->CPS.prlist_val[i]);
2759 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2762 sprintf(tmpStr, "]\n");
2763 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2769 } /*h_PrintClient */
2774 * Print a list of clients, with last security level and token value seen,
2778 h_PrintClients(void)
2785 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2789 ("Couldn't create client dump file %s\n",
2790 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2793 now = FT_ApproxTime();
2794 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2795 localtime_r(&now, &tm));
2796 snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n\n",
2798 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2799 h_Enumerate(h_PrintClient, (char *)file);
2800 STREAM_REALLYCLOSE(file);
2801 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2808 h_DumpHost(struct host *host, void *rock)
2810 StreamHandle_t *file = (StreamHandle_t *)rock;
2817 snprintf(tmpStr, sizeof tmpStr,
2818 "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u "
2819 "down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u "
2821 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
2822 host->index, host->cblist, CheckLock(&host->lock),
2823 host->LastCall, host->ActiveCall, (host->hostFlags & VENUSDOWN),
2824 host->hostFlags & HOSTDELETED, host->Console,
2825 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2827 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2828 if (host->hcps.prlist_val)
2829 for (i = 0; i < host->hcps.prlist_len; i++) {
2830 snprintf(tmpStr, sizeof tmpStr, " %d", host->hcps.prlist_val[i]);
2831 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2833 sprintf(tmpStr, "] [");
2834 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2835 if (host->interface)
2836 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2838 sprintf(tmpStr, " %s:%d",
2839 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2840 ntohs(host->interface->interface[i].port));
2841 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2843 sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2844 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2856 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2863 ("Couldn't create host dump file %s\n",
2864 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2867 now = FT_ApproxTime();
2868 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2869 localtime_r(&now, &tm));
2870 snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n\n", tbuffer);
2871 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2872 h_Enumerate(h_DumpHost, (char *)file);
2873 STREAM_REALLYCLOSE(file);
2874 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2878 #ifdef AFS_DEMAND_ATTACH_FS
2881 * host state serialization
2883 static int h_stateFillHeader(struct host_state_header * hdr);
2884 static int h_stateCheckHeader(struct host_state_header * hdr);
2885 static int h_stateAllocMap(struct fs_dump_state * state);
2886 static int h_stateSaveHost(struct host * host, void *rock);
2887 static int h_stateRestoreHost(struct fs_dump_state * state);
2888 static int h_stateRestoreIndex(struct host * h, void *rock);
2889 static int h_stateVerifyHost(struct host * h, void *rock);
2890 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
2891 afs_uint32 addr, afs_uint16 port, int valid);
2892 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2893 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2894 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2897 * Is this host busy?
2899 * This is just a hint and should not be trusted; this should probably only be
2900 * used by the host state serialization code when trying to detect if a host
2901 * can be sanely serialized to disk or not. If this function returns 1, the
2902 * host may be in an invalid state and thus should not be saved to disk.
2905 h_isBusy_r(struct host *host)
2907 struct Lock *hostLock = &host->lock;
2910 LOCK_LOCK(hostLock);
2911 if (hostLock->excl_locked || hostLock->readers_reading) {
2914 LOCK_UNLOCK(hostLock);
2920 if ((host->hostFlags & HWHO_INPROGRESS) || !(host->hostFlags & ALTADDR)) {
2921 /* We shouldn't hit this if the host wasn't locked, but just in case... */
2928 /* this procedure saves all host state to disk for fast startup */
2930 h_stateSave(struct fs_dump_state * state)
2932 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2935 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2937 /* invalidate host state header */
2938 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2940 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2941 sizeof(struct host_state_header))) {
2946 fs_stateIncEOF(state, sizeof(struct host_state_header));
2948 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2953 h_stateFillHeader(state->h_hdr);
2955 /* write the real header to disk */
2956 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2957 sizeof(struct host_state_header));
2964 * host state serialization
2966 * this procedure restores all host state from a disk for fast startup
2969 h_stateRestore(struct fs_dump_state * state)
2973 /* seek to the right position and read in the host state header */
2974 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2975 sizeof(struct host_state_header))) {
2980 /* check the validity of the header */
2981 if (h_stateCheckHeader(state->h_hdr)) {
2986 records = state->h_hdr->records;
2988 if (h_stateAllocMap(state)) {
2993 /* iterate over records restoring host state */
2994 for (i=0; i < records; i++) {
2995 if (h_stateRestoreHost(state) != 0) {
3006 h_stateRestoreIndices(struct fs_dump_state * state)
3008 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
3013 h_stateRestoreIndex(struct host * h, void *rock)
3015 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3016 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
3017 return H_ENUMERATE_BAIL(0);
3023 h_stateVerify(struct fs_dump_state * state)
3025 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
3030 h_stateVerifyHost(struct host * h, void* rock)
3032 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3036 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3037 return H_ENUMERATE_BAIL(0);
3041 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
3042 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
3043 h->interface->interface[i].port,
3044 h->interface->interface[i].valid)) {
3048 if (h_stateVerifyUuidHash(state, h)) {
3051 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
3055 if (cb_stateVerifyHCBList(state, h)) {
3063 * verify a host is either in, or absent from, the addr hash table.
3065 * @param[in] state fs dump state
3066 * @param[in] h host we're dealing with
3067 * @param[in] addr addr to look for (NBO)
3068 * @param[in] port port to look for (NBO)
3069 * @param[in] valid 1 if we're verifying that the specified addr and port
3070 * in the hash table point to the specified host. 0 if we're
3071 * verifying that the specified addr and port do NOT point
3072 * to the specified host
3074 * @return operation status
3075 * @retval 1 failed to verify, bail out
3076 * @retval 0 verified successfully, all is well
3079 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3080 afs_uint32 addr, afs_uint16 port, int valid)
3082 int ret = 0, found = 0;
3083 struct host *host = NULL;
3084 struct h_AddrHashChain *chain;
3085 int index = h_HashIndex(addr);
3089 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3090 host = chain->hostPtr;
3092 afs_inet_ntoa_r(addr, tmp);
3093 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3097 if ((chain->addr == addr) && (chain->port == port)) {
3100 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3101 "points to different host struct (%d, %d)\n",
3102 h->index, host->index));
3103 state->flags.warnings_generated = 1;
3107 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3108 "marked invalid, but points to the containing "
3109 "host\n", afs_inet_ntoa_r(addr, tmp),
3110 (unsigned)htons(port)));
3118 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3119 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3120 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3127 if (!found && valid) {
3128 afs_inet_ntoa_r(addr, tmp);
3129 if (state->mode == FS_STATE_LOAD_MODE) {
3130 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3131 tmp, (unsigned)htons(port)));
3135 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3136 tmp, (unsigned)htons(port)));
3137 state->flags.warnings_generated = 1;
3146 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3148 int ret = 0, found = 0;
3149 struct host *host = NULL;
3150 struct h_UuidHashChain *chain;
3151 afsUUID * uuidp = &h->interface->uuid;
3152 int index = h_UuidHashIndex(uuidp);
3156 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3157 host = chain->hostPtr;
3159 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3160 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3164 if (host->interface &&
3165 afs_uuid_equal(&host->interface->uuid, uuidp)) {
3167 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3168 h->index, host->index));
3169 state->flags.warnings_generated = 1;
3174 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3175 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3176 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3184 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3185 if (state->mode == FS_STATE_LOAD_MODE) {
3186 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3190 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3191 state->flags.warnings_generated = 1;
3199 /* create the host state header structure */
3201 h_stateFillHeader(struct host_state_header * hdr)
3203 hdr->stamp.magic = HOST_STATE_MAGIC;
3204 hdr->stamp.version = HOST_STATE_VERSION;
3208 /* check the contents of the host state header structure */
3210 h_stateCheckHeader(struct host_state_header * hdr)
3214 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3215 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3218 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3219 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3225 /* allocate the host id mapping table */
3227 h_stateAllocMap(struct fs_dump_state * state)
3229 state->h_map.len = state->h_hdr->index_max + 1;
3230 state->h_map.entries = (struct idx_map_entry_t *)
3231 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3232 return (state->h_map.entries != NULL) ? 0 : 1;
3235 /* function called by h_Enumerate to save a host to disk */
3237 h_stateSaveHost(struct host * host, void* rock)
3239 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3240 int if_len=0, hcps_len=0;
3241 struct hostDiskEntry hdsk;
3242 struct host_state_entry_header hdr;
3243 struct Interface * ifp = NULL;
3244 afs_int32 * hcps = NULL;
3245 struct iovec iov[4];
3248 if (h_isBusy_r(host)) {
3250 ViceLog(1, ("Not saving host %s:%d to disk; host appears busy\n",
3251 afs_inet_ntoa_r(host->host, hoststr), (int)ntohs(host->port)));
3252 /* Make sure we don't try to save callbacks to disk for this host, or
3253 * we'll get confused on restore */
3254 DeleteAllCallBacks_r(host, 1);
3258 memset(&hdr, 0, sizeof(hdr));
3260 if (state->h_hdr->index_max < host->index) {
3261 state->h_hdr->index_max = host->index;
3264 h_hostToDiskEntry_r(host, &hdsk);
3265 if (host->interface) {
3266 if_len = sizeof(struct Interface) +
3267 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3268 ifp = (struct Interface *) malloc(if_len);
3269 osi_Assert(ifp != NULL);
3270 memcpy(ifp, host->interface, if_len);
3271 hdr.interfaces = host->interface->numberOfInterfaces;
3272 iov[iovcnt].iov_base = (char *) ifp;
3273 iov[iovcnt].iov_len = if_len;
3276 if (host->hcps.prlist_val) {
3277 hdr.hcps = host->hcps.prlist_len;
3278 hcps_len = hdr.hcps * sizeof(afs_int32);
3279 hcps = (afs_int32 *) malloc(hcps_len);
3280 osi_Assert(hcps != NULL);
3281 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3282 iov[iovcnt].iov_base = (char *) hcps;
3283 iov[iovcnt].iov_len = hcps_len;
3287 if (hdsk.index > state->h_hdr->index_max)
3288 state->h_hdr->index_max = hdsk.index;
3290 hdr.len = sizeof(struct host_state_entry_header) +
3291 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3292 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3294 iov[0].iov_base = (char *) &hdr;
3295 iov[0].iov_len = sizeof(hdr);
3296 iov[1].iov_base = (char *) &hdsk;
3297 iov[1].iov_len = sizeof(struct hostDiskEntry);
3299 if (fs_stateWriteV(state, iov, iovcnt)) {
3300 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3304 fs_stateIncEOF(state, hdr.len);
3306 state->h_hdr->records++;
3313 return H_ENUMERATE_BAIL(0);
3318 /* restores a host from disk */
3320 h_stateRestoreHost(struct fs_dump_state * state)
3322 int ifp_len=0, hcps_len=0, bail=0;
3323 struct host_state_entry_header hdr;
3324 struct hostDiskEntry hdsk;
3325 struct host *host = NULL;
3326 struct Interface *ifp = NULL;
3327 afs_int32 * hcps = NULL;
3328 struct iovec iov[3];
3331 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3332 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3338 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3339 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3345 iov[0].iov_base = (char *) &hdsk;
3346 iov[0].iov_len = sizeof(struct hostDiskEntry);
3348 if (hdr.interfaces) {
3349 ifp_len = sizeof(struct Interface) +
3350 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3351 ifp = (struct Interface *) malloc(ifp_len);
3352 osi_Assert(ifp != NULL);
3353 iov[iovcnt].iov_base = (char *) ifp;
3354 iov[iovcnt].iov_len = ifp_len;
3358 hcps_len = hdr.hcps * sizeof(afs_int32);
3359 hcps = (afs_int32 *) malloc(hcps_len);
3360 osi_Assert(hcps != NULL);
3361 iov[iovcnt].iov_base = (char *) hcps;
3362 iov[iovcnt].iov_len = hcps_len;
3366 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3367 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3372 if (fs_stateReadV(state, iov, iovcnt)) {
3373 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3378 if (!hdr.hcps && hdsk.hcps_valid) {
3379 /* valid, zero-length host cps ; does this ever happen? */
3380 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3381 osi_Assert(hcps != NULL);
3384 if ((hdsk.hostFlags & HWHO_INPROGRESS) || !(hdsk.hostFlags & ALTADDR)) {
3386 ViceLog(0, ("h_stateRestoreHost: skipping host %s:%d due to invalid flags 0x%x\n",
3387 afs_inet_ntoa_r(hdsk.host, hoststr), (int)ntohs(hdsk.port),
3388 (unsigned)hdsk.hostFlags));
3390 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_SKIPPED;
3394 /* for restoring state, we better be able to get a host! */
3396 osi_Assert(host != NULL);
3399 host->interface = ifp;
3402 host->hcps.prlist_val = hcps;
3403 host->hcps.prlist_len = hdr.hcps;
3406 h_diskEntryToHost_r(&hdsk, host);
3407 h_SetupCallbackConn_r(host);
3409 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3412 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3413 if (ifp->interface[i].valid &&
3414 !(ifp->interface[i].addr == host->host &&
3415 ifp->interface[i].port == host->port)) {
3416 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3417 ifp->interface[i].port,
3421 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3423 h_InsertList_r(host);
3425 /* setup host id map entry */
3426 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_VALID;
3427 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3428 state->h_map.entries[hdsk.index].new_idx = host->index;
3440 /* serialize a host structure to disk */
3442 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3444 out->host = in->host;
3445 out->port = in->port;
3446 out->hostFlags = in->hostFlags;
3447 out->Console = in->Console;
3448 out->hcpsfailed = in->hcpsfailed;
3449 out->LastCall = in->LastCall;
3450 out->ActiveCall = in->ActiveCall;
3451 out->cpsCall = in->cpsCall;
3452 out->cblist = in->cblist;
3453 out->InSameNetwork = in->InSameNetwork;
3455 /* special fields we save, but are not memcpy'd back on restore */
3456 out->index = in->index;
3457 out->hcps_len = in->hcps.prlist_len;
3458 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3461 /* restore a host structure from disk */
3463 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3465 out->host = in->host;
3466 out->port = in->port;
3467 out->hostFlags = in->hostFlags;
3468 out->Console = in->Console;
3469 out->hcpsfailed = in->hcpsfailed;
3470 out->LastCall = in->LastCall;
3471 out->ActiveCall = in->ActiveCall;
3472 out->cpsCall = in->cpsCall;
3473 out->cblist = in->cblist;
3474 out->InSameNetwork = in->InSameNetwork;
3477 /* index translation routines */
3479 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3483 /* hosts use a zero-based index, so old==0 is valid */
3485 if (old >= state->h_map.len) {
3486 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3488 } else if (state->h_map.entries[old].valid != FS_STATE_IDX_VALID ||
3489 state->h_map.entries[old].old_idx != old) { /* sanity check */
3490 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3493 *new = state->h_map.entries[old].new_idx;
3498 #endif /* AFS_DEMAND_ATTACH_FS */
3502 * This counts the number of workstations, the number of active workstations,
3503 * and the number of workstations declared "down" (i.e. not heard from
3504 * recently). An active workstation has received a call since the cutoff
3505 * time argument passed.
3508 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3511 int num = 0, active = 0, del = 0;
3515 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3516 if (!(host->hostFlags & HOSTDELETED)) {
3518 if (host->ActiveCall > cutofftime)
3520 if (host->hostFlags & VENUSDOWN)
3524 if (count != hostCount) {
3525 ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3526 } else if (host != NULL) {
3527 ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3528 ShutDownAndCore(PANIC);
3538 } /*h_GetWorkStats */
3541 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp,
3542 afs_int32 cutofftime)
3544 int num, active, del;
3545 h_GetWorkStats(&num, &active, &del, cutofftime);
3554 /*------------------------------------------------------------------------
3555 * PRIVATE h_ClassifyAddress
3558 * Given a target IP address and a candidate IP address (both
3559 * in host byte order), classify the candidate into one of three
3560 * buckets in relation to the target by bumping the counters passed
3564 * a_targetAddr : Target address.
3565 * a_candAddr : Candidate address.
3566 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3567 * addresses are either in the same network
3568 * or the same subnet.
3569 * a_diffSubnetP : ...when the candidate is in a different
3571 * a_diffNetworkP : ...when the candidate is in a different
3578 * The target and candidate addresses are both in host byte
3579 * order, NOT network byte order, when passed in.
3583 *------------------------------------------------------------------------*/
3586 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3587 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3588 afs_int32 * a_diffNetworkP)
3589 { /*h_ClassifyAddress */
3591 afs_uint32 targetNet;
3592 afs_uint32 targetSubnet;
3594 afs_uint32 candSubnet;
3597 * Put bad values into the subnet info to start with.
3599 targetSubnet = (afs_uint32) 0;
3600 candSubnet = (afs_uint32) 0;
3603 * Pull out the network and subnetwork numbers from the target
3604 * and candidate addresses. We can short-circuit this whole
3605 * affair if the target and candidate addresses are not of the
3608 if (IN_CLASSA(a_targetAddr)) {
3609 if (!(IN_CLASSA(a_candAddr))) {
3610 (*a_diffNetworkP)++;
3613 targetNet = a_targetAddr & IN_CLASSA_NET;
3614 candNet = a_candAddr & IN_CLASSA_NET;
3615 if (IN_SUBNETA(a_targetAddr))
3616 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3617 if (IN_SUBNETA(a_candAddr))
3618 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3619 } else if (IN_CLASSB(a_targetAddr)) {
3620 if (!(IN_CLASSB(a_candAddr))) {
3621 (*a_diffNetworkP)++;
3624 targetNet = a_targetAddr & IN_CLASSB_NET;
3625 candNet = a_candAddr & IN_CLASSB_NET;
3626 if (IN_SUBNETB(a_targetAddr))
3627 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3628 if (IN_SUBNETB(a_candAddr))
3629 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3630 } /*Class B target */
3631 else if (IN_CLASSC(a_targetAddr)) {
3632 if (!(IN_CLASSC(a_candAddr))) {
3633 (*a_diffNetworkP)++;
3636 targetNet = a_targetAddr & IN_CLASSC_NET;
3637 candNet = a_candAddr & IN_CLASSC_NET;
3640 * Note that class C addresses can't have subnets,
3641 * so we leave the defaults untouched.
3643 } /*Class C target */
3645 targetNet = a_targetAddr;
3646 candNet = a_candAddr;
3647 } /*Class D address */
3650 * Now, simply compare the extracted net and subnet values for
3651 * the two addresses (which at this point are known to be of the
3654 if (targetNet == candNet) {
3655 if (targetSubnet == candSubnet)
3656 (*a_sameNetOrSubnetP)++;
3660 (*a_diffNetworkP)++;
3662 } /*h_ClassifyAddress */
3665 /*------------------------------------------------------------------------
3666 * EXPORTED h_GetHostNetStats
3669 * Iterate through the host table, and classify each (non-deleted)
3670 * host entry into ``proximity'' categories (same net or subnet,
3671 * different subnet, different network).
3674 * a_numHostsP : Set to total number of (non-deleted) hosts.
3675 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3676 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3677 * a_diffNetworkP : Set to # hosts on diff network as server.
3683 * We only count non-deleted hosts. The storage pointed to by our
3684 * parameters is zeroed upon entry.
3688 *------------------------------------------------------------------------*/
3691 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3692 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3693 { /*h_GetHostNetStats */
3695 struct host *hostP; /*Ptr to current host entry */
3696 afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3700 * Clear out the storage pointed to by our parameters.
3702 *a_numHostsP = (afs_int32) 0;
3703 *a_sameNetOrSubnetP = (afs_int32) 0;
3704 *a_diffSubnetP = (afs_int32) 0;
3705 *a_diffNetworkP = (afs_int32) 0;
3708 for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3709 if (!(hostP->hostFlags & HOSTDELETED)) {
3711 * Bump the number of undeleted host entries found.
3712 * In classifying the current entry's address, make
3713 * sure to first convert to host byte order.
3716 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3717 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3718 a_sameNetOrSubnetP, a_diffSubnetP,
3720 } /*Only look at non-deleted hosts */
3721 } /*For each host record hashed to this index */
3722 if (count != hostCount) {
3723 ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3724 } else if (hostP != NULL) {
3725 ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3726 ShutDownAndCore(PANIC);
3729 } /*h_GetHostNetStats */
3731 static afs_uint32 checktime;
3732 static afs_uint32 clientdeletetime;
3733 static struct AFSFid zerofid;
3737 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3738 * Since it can serialize them, and pile up, it should be a separate LWP
3739 * from other events.
3743 CheckHost(struct host *host, int flags, void *rock)
3745 struct client *client;
3746 struct rx_connection *cb_conn = NULL;
3749 #ifdef AFS_DEMAND_ATTACH_FS
3750 /* kill the checkhost lwp ASAP during shutdown */
3752 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3754 return H_ENUMERATE_BAIL(flags);
3759 /* Host is held by h_Enumerate */
3761 for (client = host->FirstClient; client; client = client->next) {
3762 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3763 client->deleted = 1;
3764 host->hostFlags |= CLIENTDELETED;
3767 if (host->LastCall < checktime) {
3769 if (!(host->hostFlags & HOSTDELETED)) {
3770 host->hostFlags |= HWHO_INPROGRESS;
3771 cb_conn = host->callback_rxcon;
3772 rx_GetConnection(cb_conn);
3773 if (host->LastCall < clientdeletetime) {
3774 host->hostFlags |= HOSTDELETED;
3775 if (!(host->hostFlags & VENUSDOWN)) {
3776 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3777 if (host->interface) {
3780 RXAFSCB_InitCallBackState3(cb_conn,
3786 RXAFSCB_InitCallBackState(cb_conn);
3789 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3792 (void)afs_inet_ntoa_r(host->host, hoststr);
3794 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3795 hoststr, ntohs(host->port)));
3796 host->hostFlags |= VENUSDOWN;
3798 /* Note: it's safe to delete hosts even if they have call
3799 * back state, because break delayed callbacks (called when a
3800 * message is received from the workstation) will always send a
3801 * break all call backs to the workstation if there is no
3806 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3808 (void)afs_inet_ntoa_r(host->host, hoststr);
3809 if (host->interface) {
3810 afsUUID uuid = host->interface->uuid;
3812 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3815 if (MultiProbeAlternateAddress_r(host)) {
3816 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3817 hoststr, ntohs(host->port), code));
3818 host->hostFlags |= VENUSDOWN;
3823 code = RXAFSCB_Probe(cb_conn);
3827 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3828 hoststr, ntohs(host->port), code));
3829 host->hostFlags |= VENUSDOWN;
3835 rx_PutConnection(cb_conn);
3838 host->hostFlags &= ~HWHO_INPROGRESS;
3849 CheckHost_r(struct host *host, void *dummy)
3851 struct client *client;
3852 struct rx_connection *cb_conn = NULL;
3855 #ifdef AFS_DEMAND_ATTACH_FS
3856 /* kill the checkhost lwp ASAP during shutdown */
3858 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3860 return H_ENUMERATE_BAIL(0);
3865 /* Host is held by h_Enumerate_r */
3866 for (client = host->FirstClient; client; client = client->next) {
3867 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3868 client->deleted = 1;
3869 host->hostFlags |= CLIENTDELETED;
3872 if (host->LastCall < checktime) {
3874 if (!(host->hostFlags & HOSTDELETED)) {
3875 host->hostFlags |= HWHO_INPROGRESS;
3876 cb_conn = host->callback_rxcon;
3877 rx_GetConnection(cb_conn);
3878 if (host->LastCall < clientdeletetime) {
3879 host->hostFlags |= HOSTDELETED;
3880 if (!(host->hostFlags & VENUSDOWN)) {
3881 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3882 if (host->interface) {
3885 RXAFSCB_InitCallBackState3(cb_conn,
3891 RXAFSCB_InitCallBackState(cb_conn);
3894 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3897 (void)afs_inet_ntoa_r(host->host, hoststr);
3899 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3900 hoststr, ntohs(host->port)));
3901 host->hostFlags |= VENUSDOWN;
3903 /* Note: it's safe to delete hosts even if they have call
3904 * back state, because break delayed callbacks (called when a
3905 * message is received from the workstation) will always send a
3906 * break all call backs to the workstation if there is no
3911 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3913 (void)afs_inet_ntoa_r(host->host, hoststr);
3914 if (host->interface) {
3915 afsUUID uuid = host->interface->uuid;
3917 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3920 if (MultiProbeAlternateAddress_r(host)) {
3921 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3922 hoststr, ntohs(host->port), code));
3923 host->hostFlags |= VENUSDOWN;
3928 code = RXAFSCB_Probe(cb_conn);
3932 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3933 hoststr, ntohs(host->port), code));
3934 host->hostFlags |= VENUSDOWN;
3940 rx_PutConnection(cb_conn);
3943 host->hostFlags &= ~HWHO_INPROGRESS;
3953 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3954 * don't respond to a probe. Note that VenusDown can only be cleared if
3955 * a message is received from the host (see ServerLWP in file.c).
3956 * Delete hosts that have not had any calls in 1 hour, clients that
3957 * have not had any calls in 15 minutes.
3959 * This routine is called roughly every 5 minutes.
3964 afs_uint32 now = FT_ApproxTime();
3966 memset(&zerofid, 0, sizeof(zerofid));
3968 * Send a probe to the workstation if it hasn't been heard from in
3971 checktime = now - 15 * 60;
3972 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3975 h_Enumerate_r(CheckHost_r, hostList, NULL);
3980 * This is called with host locked and held. At this point, the
3981 * hostAddrHashTable has an entry for the primary addr/port inserted
3982 * by h_Alloc_r(). No other interfaces should be considered valid.
3984 * The addresses in the interfaceAddr list are in host byte order.
3987 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3994 struct Interface *interface;
3997 afs_uint16 port7001 = htons(7001);
4002 number = interf->numberOfInterfaces;
4003 myAddr = host->host; /* current interface address */
4004 myPort = host->port; /* current port */
4007 ("initInterfaceAddr : host %s:%d numAddr %d\n",
4008 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
4010 /* validation checks */
4011 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
4013 ("Invalid number of alternate addresses is %d\n", number));
4018 * The client's notion of its own IP addresses is not reliable.
4020 * 1. The client list might contain private address ranges which
4021 * are likely to be re-used by many clients allocated addresses
4024 * 2. The client list will not include any public addresses that
4025 * are hidden by a NAT.
4027 * 3. Private address ranges that are exposed to the server will
4028 * be obtained from the rx connections that use them.
4030 * 4. Lists provided by the client are not necessarily truthful.
4031 * Many existing clients (UNIX) do not refresh the IP address
4032 * list as the actual assigned addresses change. The end result
4033 * is that they report the initial address list for the lifetime
4034 * of the process. In other words, a client can report addresses
4035 * that they are in fact not using. Adding these addresses to
4036 * the host interface list without verification is not only
4037 * pointless, it is downright dangerous.
4039 * We therefore do not add alternate addresses to the addr hash table.
4040 * We only use them for multi-rx callback breaks.
4044 * Convert IP addresses to network byte order, and remove
4045 * duplicate IP addresses from the interface list, and
4046 * determine whether or not the incoming addr/port is
4047 * listed. Note that if the address matches it is not
4048 * truly a match because the port number for the entries
4049 * in the interface list are port 7001 and the port number
4050 * for this connection might not be 7001.
4052 for (i = 0, count = 0, found = 0; i < number; i++) {
4053 interf->addr_in[i] = htonl(interf->addr_in[i]);
4054 for (j = 0; j < count; j++) {
4055 if (interf->addr_in[j] == interf->addr_in[i])
4059 interf->addr_in[count] = interf->addr_in[i];
4060 if (interf->addr_in[count] == myAddr &&
4068 * Allocate and initialize an interface structure for this host.
4071 interface = (struct Interface *)
4072 malloc(sizeof(struct Interface) +
4073 (sizeof(struct AddrPort) * (count - 1)));
4075 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
4077 interface->numberOfInterfaces = count;
4079 interface = (struct Interface *)
4080 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
4082 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4084 interface->numberOfInterfaces = count + 1;
4085 interface->interface[count].addr = myAddr;
4086 interface->interface[count].port = myPort;
4087 interface->interface[count].valid = 1;
4090 for (i = 0; i < count; i++) {
4092 interface->interface[i].addr = interf->addr_in[i];
4093 /* We store the port as 7001 because the addresses reported by
4094 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4095 * are coming from fully connected hosts (no NAT/PATs)
4097 interface->interface[i].port = port7001;
4098 interface->interface[i].valid =
4099 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4102 interface->uuid = interf->uuid;
4104 osi_Assert(!host->interface);
4105 host->interface = interface;
4107 if (LogLevel >= 125) {
4108 afsUUID_to_string(&interface->uuid, uuidstr, 127);
4110 ViceLog(125, ("--- uuid %s\n", uuidstr));
4111 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
4112 ViceLog(125, ("--- alt address %s:%d\n",
4113 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4114 ntohs(host->interface->interface[i].port)));
4121 /* deleted a HashChain structure for this address and host */
4122 /* returns 1 on success */
4124 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4128 struct h_AddrHashChain **hp, *th;
4130 if (addr == 0 && port == 0)
4133 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4135 osi_Assert(th->hostPtr);
4136 if (th->hostPtr == host && th->addr == addr && th->port == port) {
4137 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4138 host, afs_inet_ntoa_r(host->host, hoststr),
4139 ntohs(host->port)));
4146 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4147 host, afs_inet_ntoa_r(host->host, hoststr),
4148 ntohs(host->port)));
4154 ** prints out all alternate interface address for the host. The 'level'
4155 ** parameter indicates what level of debugging sets this output
4158 printInterfaceAddr(struct host *host, int level)
4163 if (host->interface) {
4164 /* check alternate addresses */
4165 number = host->interface->numberOfInterfaces;
4167 ViceLog(level, ("no-addresses "));
4169 for (i = 0; i < number; i++)
4170 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4171 ntohs(host->interface->interface[i].port)));
4174 ViceLog(level, ("\n"));