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 oldHost->hostFlags |= HWHO_INPROGRESS;
2006 if (oldHost->interface) {
2008 afsUUID uuid = oldHost->interface->uuid;
2009 cb_conn = oldHost->callback_rxcon;
2010 rx_GetConnection(cb_conn);
2011 rx_SetConnDeadTime(cb_conn, 2);
2012 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2014 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2016 rx_SetConnDeadTime(cb_conn, 50);
2017 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2018 rx_PutConnection(cb_conn);
2021 /* The primary address is either not responding or
2022 * is not the client we are looking for.
2023 * MultiProbeAlternateAddress_r() will remove the
2024 * alternate interfaces that do not have the same
2026 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
2028 afs_inet_ntoa_r(oldHost->host, hoststr),
2029 ntohs(oldHost->port),code2));
2030 MultiProbeAlternateAddress_r(oldHost);
2037 /* This is a new address for an existing host. Update
2038 * the list of interfaces for the existing host and
2039 * delete the host structure we just allocated. */
2041 /* prevent warnings while manipulating interface lists */
2042 host->hostFlags |= HOSTDELETED;
2044 if (oldHost->host != haddr || oldHost->port != hport) {
2045 struct rx_connection *rxconn;
2048 ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
2050 afs_inet_ntoa_r(oldHost->host, hoststr2),
2051 ntohs(oldHost->port),
2052 afs_inet_ntoa_r(haddr, hoststr),
2055 * add then remove. otherwise the host may get marked
2056 * deleted if we removed the only valid address.
2058 addInterfaceAddr_r(oldHost, haddr, hport);
2059 if (probefail || oldHost->host == haddr) {
2061 * The probe failed which means that the old
2062 * address is either unreachable or is not the
2063 * same host we were just contacted by. We will
2064 * also remove addresses if only the port has
2065 * changed because that indicates the client
2068 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
2071 struct Interface *interface = oldHost->interface;
2072 int number = oldHost->interface->numberOfInterfaces;
2073 for (i = 0; i < number; i++) {
2074 if (interface->interface[i].addr == haddr &&
2075 interface->interface[i].port != hport) {
2077 * We have just been contacted by a client
2078 * that has been seen from behind a NAT
2079 * and at least one other address.
2081 removeInterfaceAddr_r(oldHost, haddr,
2082 interface->interface[i].port);
2087 h_AddHostToAddrHashTable_r(haddr, hport, oldHost);
2088 oldHost->host = haddr;
2089 oldHost->port = hport;
2090 rxconn = oldHost->callback_rxcon;
2091 oldHost->callback_rxcon = host->callback_rxcon;
2092 host->callback_rxcon = rxconn;
2094 /* don't destroy rxconn here; let h_TossStuff_r
2095 * take care of that via h_Release_r below */
2097 host->hostFlags &= ~HWHO_INPROGRESS;
2099 /* release host because it was allocated by h_Alloc_r */
2102 /* the new host is held and locked */
2104 /* This really is a new host */
2105 h_AddHostToUuidHashTable_r(&identP->uuid, host);
2106 cb_conn = host->callback_rxcon;
2107 rx_GetConnection(cb_conn);
2110 RXAFSCB_InitCallBackState3(cb_conn,
2112 rx_PutConnection(cb_conn);
2117 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2118 host, afs_inet_ntoa_r(host->host, hoststr),
2119 ntohs(host->port)));
2120 osi_Assert(interfValid == 1);
2121 initInterfaceAddr_r(host, &interf);
2127 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2128 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2129 host->hostFlags |= VENUSDOWN;
2132 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2133 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2134 host->hostFlags |= RESETDONE;
2137 if (caps.Capabilities_val
2138 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2139 host->hostFlags |= HERRORTRANS;
2141 host->hostFlags &= ~(HERRORTRANS);
2142 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2143 host->hostFlags &= ~HWHO_INPROGRESS;
2148 if (caps.Capabilities_val)
2149 free(caps.Capabilities_val);
2150 caps.Capabilities_val = NULL;
2151 caps.Capabilities_len = 0;
2153 rx_DestroyConnection(cb_in);
2161 static char localcellname[PR_MAXNAMELEN + 1];
2162 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
2163 int num_lrealms = -1;
2167 h_InitHostPackage(void)
2169 memset(&nulluuid, 0, sizeof(afsUUID));
2170 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
2171 if (num_lrealms == -1) {
2173 for (i=0; i<AFS_NUM_LREALMS; i++) {
2174 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
2180 ("afs_krb_get_lrealm failed, using %s.\n",
2182 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
2188 /* initialize the rest of the local realms to nullstring for debugging */
2189 for (; i<AFS_NUM_LREALMS; i++)
2190 local_realms[i][0] = '\0';
2192 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2193 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2194 MUTEX_INIT(&host_glock_mutex, "host glock", MUTEX_DEFAULT, 0);
2198 MapName_r(char *aname, char *acell, afs_int32 * aval)
2203 afs_int32 anamelen, cnamelen;
2207 anamelen = strlen(aname);
2208 if (anamelen >= PR_MAXNAMELEN)
2209 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
2211 lnames.namelist_len = 1;
2212 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
2213 lids.idlist_len = 0;
2214 lids.idlist_val = NULL;
2216 cnamelen = strlen(acell);
2218 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2220 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2221 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2222 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2224 ("MapName: Name too long, using AnonymousID for %s@%s\n",
2226 *aval = AnonymousID;
2229 foreign = 1; /* attempt cross-cell authentication */
2230 tname = (char *)malloc(PR_MAXNAMELEN);
2232 ViceLogThenPanic(0, ("Failed malloc in MapName_r\n"));
2234 strcpy(tname, aname);
2235 tname[anamelen] = '@';
2236 strcpy(tname + anamelen + 1, acell);
2237 lnames.namelist_val = (prname *) tname;
2242 code = hpr_NameToId(&lnames, &lids);
2245 if (lids.idlist_val) {
2246 *aval = lids.idlist_val[0];
2247 if (*aval == AnonymousID) {
2249 ("MapName: NameToId on %s returns anonymousID\n",
2250 lnames.namelist_val[0]));
2252 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2255 ("MapName: NameToId on '%s' is unknown\n",
2256 lnames.namelist_val[0]));
2262 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
2270 /* NOTE: this returns the client with a Write lock and a refCount */
2272 h_ID2Client(afs_int32 vid)
2274 struct client *client;
2279 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
2280 if (host->hostFlags & HOSTDELETED)
2282 for (client = host->FirstClient; client; client = client->next) {
2283 if (!client->deleted && client->ViceId == vid) {
2286 ObtainWriteLock(&client->lock);
2291 if (count != hostCount) {
2292 ViceLog(0, ("h_ID2Client found %d of %d hosts\n", count, hostCount));
2293 } else if (host != NULL) {
2294 ViceLog(0, ("h_ID2Client found more than %d hosts\n", hostCount));
2295 ShutDownAndCore(PANIC);
2303 * Called by the server main loop. Returns a h_Held client, which must be
2304 * released later the main loop. Allocates a client if the matching one
2305 * isn't around. The client is returned with its reference count incremented
2306 * by one. The caller must call h_ReleaseClient_r when finished with
2309 * The refCount on client->host is returned incremented. h_ReleaseClient_r
2310 * does not decrement the refCount on client->host.
2313 h_FindClient_r(struct rx_connection *tcon)
2315 struct client *client;
2316 struct host *host = NULL;
2317 struct client *oldClient;
2318 afs_int32 viceid = 0;
2322 #if (64-MAXKTCNAMELEN)
2323 ticket name length != 64
2327 char uname[PR_MAXNAMELEN];
2328 char tcell[MAXKTCREALMLEN];
2332 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2333 if (client && client->sid == rx_GetConnectionId(tcon)
2334 && client->VenusEpoch == rx_GetConnectionEpoch(tcon)
2335 && !(client->host->hostFlags & HOSTDELETED)
2336 && !client->deleted) {
2339 h_Hold_r(client->host);
2340 if (client->prfail != 2) {
2341 /* Could add shared lock on client here */
2342 /* note that we don't have to lock entry in this path to
2343 * ensure CPS is initialized, since we don't call rx_SetSpecific
2344 * until initialization is done, and we only get here if
2345 * rx_GetSpecific located the client structure.
2350 ObtainWriteLock(&client->lock); /* released at end */
2356 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2358 ("FindClient: authenticating connection: authClass=%d\n",
2360 if (authClass == 1) {
2361 /* A bcrypt tickets, no longer supported */
2362 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2363 viceid = AnonymousID;
2364 expTime = 0x7fffffff;
2365 } else if (authClass == 2) {
2368 /* kerberos ticket */
2369 code = rxkad_GetServerInfo(tcon, /*level */ 0, (afs_uint32 *)&expTime,
2370 tname, tinst, tcell, &kvno);
2372 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2373 viceid = AnonymousID;
2374 expTime = 0x7fffffff;
2376 int ilen = strlen(tinst);
2378 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2379 tname, tinst, tcell, expTime, kvno));
2380 strncpy(uname, tname, sizeof(uname));
2382 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2385 strcat(uname, tinst);
2387 /* translate the name to a vice id */
2388 code = MapName_r(uname, tcell, &viceid);
2392 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2395 viceid = AnonymousID;
2396 expTime = 0x7fffffff;
2400 viceid = AnonymousID; /* unknown security class */
2401 expTime = 0x7fffffff;
2404 if (!client) { /* loop */
2405 host = h_GetHost_r(tcon); /* Returns with incremented refCount */
2411 /* First try to find the client structure */
2412 for (client = host->FirstClient; client; client = client->next) {
2413 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2414 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2417 ObtainWriteLock(&client->lock);
2423 /* Still no client structure - get one */
2426 if (host->hostFlags & HOSTDELETED) {
2431 /* Retry to find the client structure */
2432 for (client = host->FirstClient; client; client = client->next) {
2433 if (!client->deleted && (client->sid == rx_GetConnectionId(tcon))
2434 && (client->VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2436 goto retryfirstclient;
2441 ObtainWriteLock(&client->lock);
2442 client->refCount = 1;
2443 client->host = host;
2444 client->InSameNetwork = host->InSameNetwork;
2445 client->ViceId = viceid;
2446 client->expTime = expTime; /* rx only */
2447 client->authClass = authClass; /* rx only */
2448 client->sid = rx_GetConnectionId(tcon);
2449 client->VenusEpoch = rx_GetConnectionEpoch(tcon);
2450 client->CPS.prlist_val = NULL;
2451 client->CPS.prlist_len = 0;
2455 client->prfail = fail;
2457 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2458 client->CPS.prlist_len = 0;
2459 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2460 free(client->CPS.prlist_val);
2461 client->CPS.prlist_val = NULL;
2462 client->ViceId = viceid;
2463 client->expTime = expTime;
2465 if (viceid == ANONYMOUSID) {
2466 client->CPS.prlist_len = AnonCPS.prlist_len;
2467 client->CPS.prlist_val = AnonCPS.prlist_val;
2470 code = hpr_GetCPS(viceid, &client->CPS);
2475 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2476 code, viceid, client->host,
2477 afs_inet_ntoa_r(client->host->host,hoststr),
2478 ntohs(client->host->port)));
2480 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2481 * all protection servers and reevaluates things if no
2482 * sync server or quorum is found we could still end up
2483 * with one of these errors. In such case we would like to
2484 * reevaluate the rpc call to find if there's cps for this
2485 * guy. We treat other errors (except network failures
2486 * ones - i.e. code < 0) as an indication that there is no
2487 * CPS for this host. Ideally we could like to deal this
2488 * problem the other way around (i.e. if code == NOCPS
2489 * ignore else retry next time) but the problem is that
2490 * there're other errors (i.e. EPERM) for which we don't
2491 * want to retry and we don't know the whole code list!
2493 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2497 /* the disabling of system:administrators is so iffy and has so many
2498 * possible failure modes that we will disable it again */
2499 /* Turn off System:Administrator for safety
2500 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2501 * osi_Assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2504 /* Now, tcon may already be set to a rock, since we blocked with no host
2505 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2506 * required). So, before setting the RPC's rock, we should disconnect
2507 * the RPC from the other client structure's rock.
2509 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2510 if (oldClient && oldClient != client
2511 && oldClient->sid == rx_GetConnectionId(tcon)
2512 && oldClient->VenusEpoch == rx_GetConnectionEpoch(tcon)
2513 && !(oldClient->host->hostFlags & HOSTDELETED)) {
2515 if (!oldClient->deleted) {
2516 /* if we didn't create it, it's not ours to put back */
2518 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2519 "conn %p (host %s:%d) had client %p(%x)\n",
2520 client, client->sid, tcon,
2521 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2522 ntohs(rxr_PortOf(tcon)),
2523 oldClient, oldClient->sid));
2524 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2525 free(client->CPS.prlist_val);
2526 client->CPS.prlist_val = NULL;
2527 client->CPS.prlist_len = 0;
2529 /* We should perhaps check for 0 here */
2531 ReleaseWriteLock(&client->lock);
2536 oldClient->refCount++;
2538 h_Hold_r(oldClient->host);
2539 h_Release_r(client->host);
2542 ObtainWriteLock(&oldClient->lock);
2545 host = oldClient->host;
2547 ViceLog(0, ("FindClient: deleted client %p(%x ref %d host %p href "
2548 "%d) already had conn %p (host %s:%d, cid %x), stolen "
2549 "by client %p(%x, ref %d host %p href %d)\n",
2550 oldClient, oldClient->sid, oldClient->refCount,
2551 oldClient->host, oldClient->host->refCount, tcon,
2552 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2553 ntohs(rxr_PortOf(tcon)), rx_GetConnectionId(tcon),
2554 client, client->sid, client->refCount,
2555 client->host, client->host->refCount));
2556 /* rx_SetSpecific will be done immediately below */
2559 /* Avoid chaining in more than once. */
2563 if (host->hostFlags & HOSTDELETED) {
2568 client->host = NULL;
2570 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2571 free(client->CPS.prlist_val);
2572 client->CPS.prlist_val = NULL;
2573 client->CPS.prlist_len = 0;
2576 ReleaseWriteLock(&client->lock);
2581 client->next = host->FirstClient;
2582 host->FirstClient = client;
2584 CurrentConnections++; /* increment number of connections */
2586 rx_SetSpecific(tcon, rxcon_client_key, client);
2587 ReleaseWriteLock(&client->lock);
2591 } /*h_FindClient_r */
2594 h_ReleaseClient_r(struct client *client)
2596 osi_Assert(client->refCount > 0);
2603 * Sigh: this one is used to get the client AGAIN within the individual
2604 * server routines. This does not bother h_Holding the host, since
2605 * this is assumed already have been done by the server main loop.
2606 * It does check tokens, since only the server routines can return the
2607 * VICETOKENDEAD error code
2610 GetClient(struct rx_connection *tcon, struct client **cp)
2612 struct client *client;
2617 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2618 if (client == NULL) {
2620 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2621 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2622 ntohs(rxr_PortOf(tcon))));
2626 if (rx_GetConnectionId(tcon) != client->sid
2627 || rx_GetConnectionEpoch(tcon) != client->VenusEpoch) {
2629 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2630 tcon, rx_GetConnectionId(tcon), client->sid));
2634 if (client && client->LastCall > client->expTime && client->expTime) {
2636 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2637 afs_inet_ntoa_r(client->host->host, hoststr),
2638 ntohs(client->host->port), client->expTime));
2640 return VICETOKENDEAD;
2642 if (client->deleted) {
2643 ViceLog(0, ("GetClient: got deleted client, connection will appear "
2644 "anonymous; tcon %p cid %x client %p ref %d host %p "
2645 "(%s:%d) href %d ViceId %d\n",
2646 tcon, rx_GetConnectionId(tcon), client, client->refCount,
2648 afs_inet_ntoa_r(client->host->host, hoststr),
2649 (int)ntohs(client->host->port), client->host->refCount,
2650 (int)client->ViceId));
2660 PutClient(struct client **cp)
2666 h_ReleaseClient_r(*cp);
2673 /* Client user name for short term use. Note that this is NOT inexpensive */
2675 h_UserName(struct client *client)
2677 static char User[PR_MAXNAMELEN + 1];
2681 lids.idlist_len = 1;
2682 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2683 if (!lids.idlist_val) {
2684 ViceLogThenPanic(0, ("Failed malloc in h_UserName\n"));
2686 lnames.namelist_len = 0;
2687 lnames.namelist_val = (prname *) 0;
2688 lids.idlist_val[0] = client->ViceId;
2689 if (hpr_IdToName(&lids, &lnames)) {
2690 /* We need to free id we alloced above! */
2691 free(lids.idlist_val);
2692 return "*UNKNOWN USER NAME*";
2694 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2695 free(lids.idlist_val);
2696 free(lnames.namelist_val);
2705 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2706 CEs, CEBlocks, HTs, HTBlocks));
2712 h_PrintClient(struct host *host, void *rock)
2714 StreamHandle_t *file = (StreamHandle_t *)rock;
2715 struct client *client;
2720 time_t LastCall, expTime;
2724 LastCall = host->LastCall;
2725 if (host->hostFlags & HOSTDELETED) {
2729 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2730 localtime_r(&LastCall, &tm));
2731 snprintf(tmpStr, sizeof tmpStr, "Host %s:%d down = %d, LastCall %s\n",
2732 afs_inet_ntoa_r(host->host, hoststr),
2733 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2735 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2736 for (client = host->FirstClient; client; client = client->next) {
2737 if (!client->deleted) {
2738 expTime = client->expTime;
2739 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2740 localtime_r(&expTime, &tm));
2741 snprintf(tmpStr, sizeof tmpStr,
2742 " user id=%d, name=%s, sl=%s till %s\n",
2743 client->ViceId, h_UserName(client),
2744 client->authClass ? "Authenticated"
2745 : "Not authenticated",
2746 client->authClass ? tbuffer : "No Limit");
2747 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2748 snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2749 client->CPS.prlist_len);
2750 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2751 if (client->CPS.prlist_val) {
2752 for (i = 0; i < client->CPS.prlist_len; i++) {
2753 snprintf(tmpStr, sizeof tmpStr, " %d",
2754 client->CPS.prlist_val[i]);
2755 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2758 sprintf(tmpStr, "]\n");
2759 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2765 } /*h_PrintClient */
2770 * Print a list of clients, with last security level and token value seen,
2774 h_PrintClients(void)
2781 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2785 ("Couldn't create client dump file %s\n",
2786 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2789 now = FT_ApproxTime();
2790 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2791 localtime_r(&now, &tm));
2792 snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n\n",
2794 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2795 h_Enumerate(h_PrintClient, (char *)file);
2796 STREAM_REALLYCLOSE(file);
2797 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2804 h_DumpHost(struct host *host, void *rock)
2806 StreamHandle_t *file = (StreamHandle_t *)rock;
2813 snprintf(tmpStr, sizeof tmpStr,
2814 "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u "
2815 "down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u "
2817 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
2818 host->index, host->cblist, CheckLock(&host->lock),
2819 host->LastCall, host->ActiveCall, (host->hostFlags & VENUSDOWN),
2820 host->hostFlags & HOSTDELETED, host->Console,
2821 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2823 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2824 if (host->hcps.prlist_val)
2825 for (i = 0; i < host->hcps.prlist_len; i++) {
2826 snprintf(tmpStr, sizeof tmpStr, " %d", host->hcps.prlist_val[i]);
2827 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2829 sprintf(tmpStr, "] [");
2830 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2831 if (host->interface)
2832 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2834 sprintf(tmpStr, " %s:%d",
2835 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2836 ntohs(host->interface->interface[i].port));
2837 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2839 sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2840 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2852 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2859 ("Couldn't create host dump file %s\n",
2860 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2863 now = FT_ApproxTime();
2864 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2865 localtime_r(&now, &tm));
2866 snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n\n", tbuffer);
2867 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2868 h_Enumerate(h_DumpHost, (char *)file);
2869 STREAM_REALLYCLOSE(file);
2870 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2874 #ifdef AFS_DEMAND_ATTACH_FS
2877 * host state serialization
2879 static int h_stateFillHeader(struct host_state_header * hdr);
2880 static int h_stateCheckHeader(struct host_state_header * hdr);
2881 static int h_stateAllocMap(struct fs_dump_state * state);
2882 static int h_stateSaveHost(struct host * host, void *rock);
2883 static int h_stateRestoreHost(struct fs_dump_state * state);
2884 static int h_stateRestoreIndex(struct host * h, void *rock);
2885 static int h_stateVerifyHost(struct host * h, void *rock);
2886 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
2887 afs_uint32 addr, afs_uint16 port, int valid);
2888 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2889 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2890 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2893 * Is this host busy?
2895 * This is just a hint and should not be trusted; this should probably only be
2896 * used by the host state serialization code when trying to detect if a host
2897 * can be sanely serialized to disk or not. If this function returns 1, the
2898 * host may be in an invalid state and thus should not be saved to disk.
2901 h_isBusy_r(struct host *host)
2903 struct Lock *hostLock = &host->lock;
2906 LOCK_LOCK(hostLock);
2907 if (hostLock->excl_locked || hostLock->readers_reading) {
2910 LOCK_UNLOCK(hostLock);
2916 if ((host->hostFlags & HWHO_INPROGRESS) || !(host->hostFlags & ALTADDR)) {
2917 /* We shouldn't hit this if the host wasn't locked, but just in case... */
2924 /* this procedure saves all host state to disk for fast startup */
2926 h_stateSave(struct fs_dump_state * state)
2928 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2931 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2933 /* invalidate host state header */
2934 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2936 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2937 sizeof(struct host_state_header))) {
2942 fs_stateIncEOF(state, sizeof(struct host_state_header));
2944 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2949 h_stateFillHeader(state->h_hdr);
2951 /* write the real header to disk */
2952 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2953 sizeof(struct host_state_header));
2960 * host state serialization
2962 * this procedure restores all host state from a disk for fast startup
2965 h_stateRestore(struct fs_dump_state * state)
2969 /* seek to the right position and read in the host state header */
2970 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2971 sizeof(struct host_state_header))) {
2976 /* check the validity of the header */
2977 if (h_stateCheckHeader(state->h_hdr)) {
2982 records = state->h_hdr->records;
2984 if (h_stateAllocMap(state)) {
2989 /* iterate over records restoring host state */
2990 for (i=0; i < records; i++) {
2991 if (h_stateRestoreHost(state) != 0) {
3002 h_stateRestoreIndices(struct fs_dump_state * state)
3004 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
3009 h_stateRestoreIndex(struct host * h, void *rock)
3011 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3012 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
3013 return H_ENUMERATE_BAIL(0);
3019 h_stateVerify(struct fs_dump_state * state)
3021 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
3026 h_stateVerifyHost(struct host * h, void* rock)
3028 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3032 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3033 return H_ENUMERATE_BAIL(0);
3037 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
3038 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
3039 h->interface->interface[i].port,
3040 h->interface->interface[i].valid)) {
3044 if (h_stateVerifyUuidHash(state, h)) {
3047 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
3051 if (cb_stateVerifyHCBList(state, h)) {
3059 * verify a host is either in, or absent from, the addr hash table.
3061 * @param[in] state fs dump state
3062 * @param[in] h host we're dealing with
3063 * @param[in] addr addr to look for (NBO)
3064 * @param[in] port port to look for (NBO)
3065 * @param[in] valid 1 if we're verifying that the specified addr and port
3066 * in the hash table point to the specified host. 0 if we're
3067 * verifying that the specified addr and port do NOT point
3068 * to the specified host
3070 * @return operation status
3071 * @retval 1 failed to verify, bail out
3072 * @retval 0 verified successfully, all is well
3075 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3076 afs_uint32 addr, afs_uint16 port, int valid)
3078 int ret = 0, found = 0;
3079 struct host *host = NULL;
3080 struct h_AddrHashChain *chain;
3081 int index = h_HashIndex(addr);
3085 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3086 host = chain->hostPtr;
3088 afs_inet_ntoa_r(addr, tmp);
3089 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3093 if ((chain->addr == addr) && (chain->port == port)) {
3096 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3097 "points to different host struct (%d, %d)\n",
3098 h->index, host->index));
3099 state->flags.warnings_generated = 1;
3103 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3104 "marked invalid, but points to the containing "
3105 "host\n", afs_inet_ntoa_r(addr, tmp),
3106 (unsigned)htons(port)));
3114 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3115 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3116 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3123 if (!found && valid) {
3124 afs_inet_ntoa_r(addr, tmp);
3125 if (state->mode == FS_STATE_LOAD_MODE) {
3126 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3127 tmp, (unsigned)htons(port)));
3131 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3132 tmp, (unsigned)htons(port)));
3133 state->flags.warnings_generated = 1;
3142 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3144 int ret = 0, found = 0;
3145 struct host *host = NULL;
3146 struct h_UuidHashChain *chain;
3147 afsUUID * uuidp = &h->interface->uuid;
3148 int index = h_UuidHashIndex(uuidp);
3152 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3153 host = chain->hostPtr;
3155 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3156 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3160 if (host->interface &&
3161 afs_uuid_equal(&host->interface->uuid, uuidp)) {
3163 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3164 h->index, host->index));
3165 state->flags.warnings_generated = 1;
3170 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3171 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3172 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3180 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3181 if (state->mode == FS_STATE_LOAD_MODE) {
3182 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3186 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3187 state->flags.warnings_generated = 1;
3195 /* create the host state header structure */
3197 h_stateFillHeader(struct host_state_header * hdr)
3199 hdr->stamp.magic = HOST_STATE_MAGIC;
3200 hdr->stamp.version = HOST_STATE_VERSION;
3204 /* check the contents of the host state header structure */
3206 h_stateCheckHeader(struct host_state_header * hdr)
3210 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3211 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3214 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3215 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3221 /* allocate the host id mapping table */
3223 h_stateAllocMap(struct fs_dump_state * state)
3225 state->h_map.len = state->h_hdr->index_max + 1;
3226 state->h_map.entries = (struct idx_map_entry_t *)
3227 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3228 return (state->h_map.entries != NULL) ? 0 : 1;
3231 /* function called by h_Enumerate to save a host to disk */
3233 h_stateSaveHost(struct host * host, void* rock)
3235 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3236 int if_len=0, hcps_len=0;
3237 struct hostDiskEntry hdsk;
3238 struct host_state_entry_header hdr;
3239 struct Interface * ifp = NULL;
3240 afs_int32 * hcps = NULL;
3241 struct iovec iov[4];
3244 if (h_isBusy_r(host)) {
3246 ViceLog(1, ("Not saving host %s:%d to disk; host appears busy\n",
3247 afs_inet_ntoa_r(host->host, hoststr), (int)ntohs(host->port)));
3248 /* Make sure we don't try to save callbacks to disk for this host, or
3249 * we'll get confused on restore */
3250 DeleteAllCallBacks_r(host, 1);
3254 memset(&hdr, 0, sizeof(hdr));
3256 if (state->h_hdr->index_max < host->index) {
3257 state->h_hdr->index_max = host->index;
3260 h_hostToDiskEntry_r(host, &hdsk);
3261 if (host->interface) {
3262 if_len = sizeof(struct Interface) +
3263 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3264 ifp = (struct Interface *) malloc(if_len);
3265 osi_Assert(ifp != NULL);
3266 memcpy(ifp, host->interface, if_len);
3267 hdr.interfaces = host->interface->numberOfInterfaces;
3268 iov[iovcnt].iov_base = (char *) ifp;
3269 iov[iovcnt].iov_len = if_len;
3272 if (host->hcps.prlist_val) {
3273 hdr.hcps = host->hcps.prlist_len;
3274 hcps_len = hdr.hcps * sizeof(afs_int32);
3275 hcps = (afs_int32 *) malloc(hcps_len);
3276 osi_Assert(hcps != NULL);
3277 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3278 iov[iovcnt].iov_base = (char *) hcps;
3279 iov[iovcnt].iov_len = hcps_len;
3283 if (hdsk.index > state->h_hdr->index_max)
3284 state->h_hdr->index_max = hdsk.index;
3286 hdr.len = sizeof(struct host_state_entry_header) +
3287 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3288 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3290 iov[0].iov_base = (char *) &hdr;
3291 iov[0].iov_len = sizeof(hdr);
3292 iov[1].iov_base = (char *) &hdsk;
3293 iov[1].iov_len = sizeof(struct hostDiskEntry);
3295 if (fs_stateWriteV(state, iov, iovcnt)) {
3296 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3300 fs_stateIncEOF(state, hdr.len);
3302 state->h_hdr->records++;
3309 return H_ENUMERATE_BAIL(0);
3314 /* restores a host from disk */
3316 h_stateRestoreHost(struct fs_dump_state * state)
3318 int ifp_len=0, hcps_len=0, bail=0;
3319 struct host_state_entry_header hdr;
3320 struct hostDiskEntry hdsk;
3321 struct host *host = NULL;
3322 struct Interface *ifp = NULL;
3323 afs_int32 * hcps = NULL;
3324 struct iovec iov[3];
3327 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3328 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3334 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3335 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3341 iov[0].iov_base = (char *) &hdsk;
3342 iov[0].iov_len = sizeof(struct hostDiskEntry);
3344 if (hdr.interfaces) {
3345 ifp_len = sizeof(struct Interface) +
3346 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3347 ifp = (struct Interface *) malloc(ifp_len);
3348 osi_Assert(ifp != NULL);
3349 iov[iovcnt].iov_base = (char *) ifp;
3350 iov[iovcnt].iov_len = ifp_len;
3354 hcps_len = hdr.hcps * sizeof(afs_int32);
3355 hcps = (afs_int32 *) malloc(hcps_len);
3356 osi_Assert(hcps != NULL);
3357 iov[iovcnt].iov_base = (char *) hcps;
3358 iov[iovcnt].iov_len = hcps_len;
3362 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3363 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3368 if (fs_stateReadV(state, iov, iovcnt)) {
3369 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3374 if (!hdr.hcps && hdsk.hcps_valid) {
3375 /* valid, zero-length host cps ; does this ever happen? */
3376 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3377 osi_Assert(hcps != NULL);
3380 if ((hdsk.hostFlags & HWHO_INPROGRESS) || !(hdsk.hostFlags & ALTADDR)) {
3382 ViceLog(0, ("h_stateRestoreHost: skipping host %s:%d due to invalid flags 0x%x\n",
3383 afs_inet_ntoa_r(hdsk.host, hoststr), (int)ntohs(hdsk.port),
3384 (unsigned)hdsk.hostFlags));
3386 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_SKIPPED;
3390 /* for restoring state, we better be able to get a host! */
3392 osi_Assert(host != NULL);
3395 host->interface = ifp;
3398 host->hcps.prlist_val = hcps;
3399 host->hcps.prlist_len = hdr.hcps;
3402 h_diskEntryToHost_r(&hdsk, host);
3403 h_SetupCallbackConn_r(host);
3405 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3408 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3409 if (ifp->interface[i].valid &&
3410 !(ifp->interface[i].addr == host->host &&
3411 ifp->interface[i].port == host->port)) {
3412 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3413 ifp->interface[i].port,
3417 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3419 h_InsertList_r(host);
3421 /* setup host id map entry */
3422 state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_VALID;
3423 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3424 state->h_map.entries[hdsk.index].new_idx = host->index;
3436 /* serialize a host structure to disk */
3438 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3440 out->host = in->host;
3441 out->port = in->port;
3442 out->hostFlags = in->hostFlags;
3443 out->Console = in->Console;
3444 out->hcpsfailed = in->hcpsfailed;
3445 out->LastCall = in->LastCall;
3446 out->ActiveCall = in->ActiveCall;
3447 out->cpsCall = in->cpsCall;
3448 out->cblist = in->cblist;
3449 out->InSameNetwork = in->InSameNetwork;
3451 /* special fields we save, but are not memcpy'd back on restore */
3452 out->index = in->index;
3453 out->hcps_len = in->hcps.prlist_len;
3454 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3457 /* restore a host structure from disk */
3459 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3461 out->host = in->host;
3462 out->port = in->port;
3463 out->hostFlags = in->hostFlags;
3464 out->Console = in->Console;
3465 out->hcpsfailed = in->hcpsfailed;
3466 out->LastCall = in->LastCall;
3467 out->ActiveCall = in->ActiveCall;
3468 out->cpsCall = in->cpsCall;
3469 out->cblist = in->cblist;
3470 out->InSameNetwork = in->InSameNetwork;
3473 /* index translation routines */
3475 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3479 /* hosts use a zero-based index, so old==0 is valid */
3481 if (old >= state->h_map.len) {
3482 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3484 } else if (state->h_map.entries[old].valid != FS_STATE_IDX_VALID ||
3485 state->h_map.entries[old].old_idx != old) { /* sanity check */
3486 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3489 *new = state->h_map.entries[old].new_idx;
3494 #endif /* AFS_DEMAND_ATTACH_FS */
3498 * This counts the number of workstations, the number of active workstations,
3499 * and the number of workstations declared "down" (i.e. not heard from
3500 * recently). An active workstation has received a call since the cutoff
3501 * time argument passed.
3504 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3507 int num = 0, active = 0, del = 0;
3511 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3512 if (!(host->hostFlags & HOSTDELETED)) {
3514 if (host->ActiveCall > cutofftime)
3516 if (host->hostFlags & VENUSDOWN)
3520 if (count != hostCount) {
3521 ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3522 } else if (host != NULL) {
3523 ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3524 ShutDownAndCore(PANIC);
3534 } /*h_GetWorkStats */
3537 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp,
3538 afs_int32 cutofftime)
3540 int num, active, del;
3541 h_GetWorkStats(&num, &active, &del, cutofftime);
3550 /*------------------------------------------------------------------------
3551 * PRIVATE h_ClassifyAddress
3554 * Given a target IP address and a candidate IP address (both
3555 * in host byte order), classify the candidate into one of three
3556 * buckets in relation to the target by bumping the counters passed
3560 * a_targetAddr : Target address.
3561 * a_candAddr : Candidate address.
3562 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3563 * addresses are either in the same network
3564 * or the same subnet.
3565 * a_diffSubnetP : ...when the candidate is in a different
3567 * a_diffNetworkP : ...when the candidate is in a different
3574 * The target and candidate addresses are both in host byte
3575 * order, NOT network byte order, when passed in.
3579 *------------------------------------------------------------------------*/
3582 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3583 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3584 afs_int32 * a_diffNetworkP)
3585 { /*h_ClassifyAddress */
3587 afs_uint32 targetNet;
3588 afs_uint32 targetSubnet;
3590 afs_uint32 candSubnet;
3593 * Put bad values into the subnet info to start with.
3595 targetSubnet = (afs_uint32) 0;
3596 candSubnet = (afs_uint32) 0;
3599 * Pull out the network and subnetwork numbers from the target
3600 * and candidate addresses. We can short-circuit this whole
3601 * affair if the target and candidate addresses are not of the
3604 if (IN_CLASSA(a_targetAddr)) {
3605 if (!(IN_CLASSA(a_candAddr))) {
3606 (*a_diffNetworkP)++;
3609 targetNet = a_targetAddr & IN_CLASSA_NET;
3610 candNet = a_candAddr & IN_CLASSA_NET;
3611 if (IN_SUBNETA(a_targetAddr))
3612 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3613 if (IN_SUBNETA(a_candAddr))
3614 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3615 } else if (IN_CLASSB(a_targetAddr)) {
3616 if (!(IN_CLASSB(a_candAddr))) {
3617 (*a_diffNetworkP)++;
3620 targetNet = a_targetAddr & IN_CLASSB_NET;
3621 candNet = a_candAddr & IN_CLASSB_NET;
3622 if (IN_SUBNETB(a_targetAddr))
3623 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3624 if (IN_SUBNETB(a_candAddr))
3625 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3626 } /*Class B target */
3627 else if (IN_CLASSC(a_targetAddr)) {
3628 if (!(IN_CLASSC(a_candAddr))) {
3629 (*a_diffNetworkP)++;
3632 targetNet = a_targetAddr & IN_CLASSC_NET;
3633 candNet = a_candAddr & IN_CLASSC_NET;
3636 * Note that class C addresses can't have subnets,
3637 * so we leave the defaults untouched.
3639 } /*Class C target */
3641 targetNet = a_targetAddr;
3642 candNet = a_candAddr;
3643 } /*Class D address */
3646 * Now, simply compare the extracted net and subnet values for
3647 * the two addresses (which at this point are known to be of the
3650 if (targetNet == candNet) {
3651 if (targetSubnet == candSubnet)
3652 (*a_sameNetOrSubnetP)++;
3656 (*a_diffNetworkP)++;
3658 } /*h_ClassifyAddress */
3661 /*------------------------------------------------------------------------
3662 * EXPORTED h_GetHostNetStats
3665 * Iterate through the host table, and classify each (non-deleted)
3666 * host entry into ``proximity'' categories (same net or subnet,
3667 * different subnet, different network).
3670 * a_numHostsP : Set to total number of (non-deleted) hosts.
3671 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3672 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3673 * a_diffNetworkP : Set to # hosts on diff network as server.
3679 * We only count non-deleted hosts. The storage pointed to by our
3680 * parameters is zeroed upon entry.
3684 *------------------------------------------------------------------------*/
3687 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3688 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3689 { /*h_GetHostNetStats */
3691 struct host *hostP; /*Ptr to current host entry */
3692 afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3696 * Clear out the storage pointed to by our parameters.
3698 *a_numHostsP = (afs_int32) 0;
3699 *a_sameNetOrSubnetP = (afs_int32) 0;
3700 *a_diffSubnetP = (afs_int32) 0;
3701 *a_diffNetworkP = (afs_int32) 0;
3704 for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3705 if (!(hostP->hostFlags & HOSTDELETED)) {
3707 * Bump the number of undeleted host entries found.
3708 * In classifying the current entry's address, make
3709 * sure to first convert to host byte order.
3712 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3713 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3714 a_sameNetOrSubnetP, a_diffSubnetP,
3716 } /*Only look at non-deleted hosts */
3717 } /*For each host record hashed to this index */
3718 if (count != hostCount) {
3719 ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3720 } else if (hostP != NULL) {
3721 ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3722 ShutDownAndCore(PANIC);
3725 } /*h_GetHostNetStats */
3727 static afs_uint32 checktime;
3728 static afs_uint32 clientdeletetime;
3729 static struct AFSFid zerofid;
3733 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3734 * Since it can serialize them, and pile up, it should be a separate LWP
3735 * from other events.
3739 CheckHost(struct host *host, int flags, void *rock)
3741 struct client *client;
3742 struct rx_connection *cb_conn = NULL;
3745 #ifdef AFS_DEMAND_ATTACH_FS
3746 /* kill the checkhost lwp ASAP during shutdown */
3748 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3750 return H_ENUMERATE_BAIL(flags);
3755 /* Host is held by h_Enumerate */
3757 for (client = host->FirstClient; client; client = client->next) {
3758 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3759 client->deleted = 1;
3760 host->hostFlags |= CLIENTDELETED;
3763 if (host->LastCall < checktime) {
3765 if (!(host->hostFlags & HOSTDELETED)) {
3766 host->hostFlags |= HWHO_INPROGRESS;
3767 cb_conn = host->callback_rxcon;
3768 rx_GetConnection(cb_conn);
3769 if (host->LastCall < clientdeletetime) {
3770 host->hostFlags |= HOSTDELETED;
3771 if (!(host->hostFlags & VENUSDOWN)) {
3772 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3773 if (host->interface) {
3776 RXAFSCB_InitCallBackState3(cb_conn,
3782 RXAFSCB_InitCallBackState(cb_conn);
3785 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3788 (void)afs_inet_ntoa_r(host->host, hoststr);
3790 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3791 hoststr, ntohs(host->port)));
3792 host->hostFlags |= VENUSDOWN;
3794 /* Note: it's safe to delete hosts even if they have call
3795 * back state, because break delayed callbacks (called when a
3796 * message is received from the workstation) will always send a
3797 * break all call backs to the workstation if there is no
3802 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3804 (void)afs_inet_ntoa_r(host->host, hoststr);
3805 if (host->interface) {
3806 afsUUID uuid = host->interface->uuid;
3808 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3811 if (MultiProbeAlternateAddress_r(host)) {
3812 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3813 hoststr, ntohs(host->port), code));
3814 host->hostFlags |= VENUSDOWN;
3819 code = RXAFSCB_Probe(cb_conn);
3823 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3824 hoststr, ntohs(host->port), code));
3825 host->hostFlags |= VENUSDOWN;
3831 rx_PutConnection(cb_conn);
3834 host->hostFlags &= ~HWHO_INPROGRESS;
3845 CheckHost_r(struct host *host, void *dummy)
3847 struct client *client;
3848 struct rx_connection *cb_conn = NULL;
3851 #ifdef AFS_DEMAND_ATTACH_FS
3852 /* kill the checkhost lwp ASAP during shutdown */
3854 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3856 return H_ENUMERATE_BAIL(0);
3861 /* Host is held by h_Enumerate_r */
3862 for (client = host->FirstClient; client; client = client->next) {
3863 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3864 client->deleted = 1;
3865 host->hostFlags |= CLIENTDELETED;
3868 if (host->LastCall < checktime) {
3870 if (!(host->hostFlags & HOSTDELETED)) {
3871 host->hostFlags |= HWHO_INPROGRESS;
3872 cb_conn = host->callback_rxcon;
3873 rx_GetConnection(cb_conn);
3874 if (host->LastCall < clientdeletetime) {
3875 host->hostFlags |= HOSTDELETED;
3876 if (!(host->hostFlags & VENUSDOWN)) {
3877 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3878 if (host->interface) {
3881 RXAFSCB_InitCallBackState3(cb_conn,
3887 RXAFSCB_InitCallBackState(cb_conn);
3890 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3893 (void)afs_inet_ntoa_r(host->host, hoststr);
3895 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3896 hoststr, ntohs(host->port)));
3897 host->hostFlags |= VENUSDOWN;
3899 /* Note: it's safe to delete hosts even if they have call
3900 * back state, because break delayed callbacks (called when a
3901 * message is received from the workstation) will always send a
3902 * break all call backs to the workstation if there is no
3907 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3909 (void)afs_inet_ntoa_r(host->host, hoststr);
3910 if (host->interface) {
3911 afsUUID uuid = host->interface->uuid;
3913 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3916 if (MultiProbeAlternateAddress_r(host)) {
3917 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3918 hoststr, ntohs(host->port), code));
3919 host->hostFlags |= VENUSDOWN;
3924 code = RXAFSCB_Probe(cb_conn);
3928 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3929 hoststr, ntohs(host->port), code));
3930 host->hostFlags |= VENUSDOWN;
3936 rx_PutConnection(cb_conn);
3939 host->hostFlags &= ~HWHO_INPROGRESS;
3949 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3950 * don't respond to a probe. Note that VenusDown can only be cleared if
3951 * a message is received from the host (see ServerLWP in file.c).
3952 * Delete hosts that have not had any calls in 1 hour, clients that
3953 * have not had any calls in 15 minutes.
3955 * This routine is called roughly every 5 minutes.
3960 afs_uint32 now = FT_ApproxTime();
3962 memset(&zerofid, 0, sizeof(zerofid));
3964 * Send a probe to the workstation if it hasn't been heard from in
3967 checktime = now - 15 * 60;
3968 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3971 h_Enumerate_r(CheckHost_r, hostList, NULL);
3976 * This is called with host locked and held. At this point, the
3977 * hostAddrHashTable has an entry for the primary addr/port inserted
3978 * by h_Alloc_r(). No other interfaces should be considered valid.
3980 * The addresses in the interfaceAddr list are in host byte order.
3983 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3990 struct Interface *interface;
3993 afs_uint16 port7001 = htons(7001);
3998 number = interf->numberOfInterfaces;
3999 myAddr = host->host; /* current interface address */
4000 myPort = host->port; /* current port */
4003 ("initInterfaceAddr : host %s:%d numAddr %d\n",
4004 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
4006 /* validation checks */
4007 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
4009 ("Invalid number of alternate addresses is %d\n", number));
4014 * The client's notion of its own IP addresses is not reliable.
4016 * 1. The client list might contain private address ranges which
4017 * are likely to be re-used by many clients allocated addresses
4020 * 2. The client list will not include any public addresses that
4021 * are hidden by a NAT.
4023 * 3. Private address ranges that are exposed to the server will
4024 * be obtained from the rx connections that use them.
4026 * 4. Lists provided by the client are not necessarily truthful.
4027 * Many existing clients (UNIX) do not refresh the IP address
4028 * list as the actual assigned addresses change. The end result
4029 * is that they report the initial address list for the lifetime
4030 * of the process. In other words, a client can report addresses
4031 * that they are in fact not using. Adding these addresses to
4032 * the host interface list without verification is not only
4033 * pointless, it is downright dangerous.
4035 * We therefore do not add alternate addresses to the addr hash table.
4036 * We only use them for multi-rx callback breaks.
4040 * Convert IP addresses to network byte order, and remove
4041 * duplicate IP addresses from the interface list, and
4042 * determine whether or not the incoming addr/port is
4043 * listed. Note that if the address matches it is not
4044 * truly a match because the port number for the entries
4045 * in the interface list are port 7001 and the port number
4046 * for this connection might not be 7001.
4048 for (i = 0, count = 0, found = 0; i < number; i++) {
4049 interf->addr_in[i] = htonl(interf->addr_in[i]);
4050 for (j = 0; j < count; j++) {
4051 if (interf->addr_in[j] == interf->addr_in[i])
4055 interf->addr_in[count] = interf->addr_in[i];
4056 if (interf->addr_in[count] == myAddr &&
4064 * Allocate and initialize an interface structure for this host.
4067 interface = (struct Interface *)
4068 malloc(sizeof(struct Interface) +
4069 (sizeof(struct AddrPort) * (count - 1)));
4071 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
4073 interface->numberOfInterfaces = count;
4075 interface = (struct Interface *)
4076 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
4078 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4080 interface->numberOfInterfaces = count + 1;
4081 interface->interface[count].addr = myAddr;
4082 interface->interface[count].port = myPort;
4083 interface->interface[count].valid = 1;
4086 for (i = 0; i < count; i++) {
4088 interface->interface[i].addr = interf->addr_in[i];
4089 /* We store the port as 7001 because the addresses reported by
4090 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4091 * are coming from fully connected hosts (no NAT/PATs)
4093 interface->interface[i].port = port7001;
4094 interface->interface[i].valid =
4095 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4098 interface->uuid = interf->uuid;
4100 osi_Assert(!host->interface);
4101 host->interface = interface;
4103 if (LogLevel >= 125) {
4104 afsUUID_to_string(&interface->uuid, uuidstr, 127);
4106 ViceLog(125, ("--- uuid %s\n", uuidstr));
4107 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
4108 ViceLog(125, ("--- alt address %s:%d\n",
4109 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4110 ntohs(host->interface->interface[i].port)));
4117 /* deleted a HashChain structure for this address and host */
4118 /* returns 1 on success */
4120 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4124 struct h_AddrHashChain **hp, *th;
4126 if (addr == 0 && port == 0)
4129 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4131 osi_Assert(th->hostPtr);
4132 if (th->hostPtr == host && th->addr == addr && th->port == port) {
4133 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4134 host, afs_inet_ntoa_r(host->host, hoststr),
4135 ntohs(host->port)));
4142 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4143 host, afs_inet_ntoa_r(host->host, hoststr),
4144 ntohs(host->port)));
4150 ** prints out all alternate interface address for the host. The 'level'
4151 ** parameter indicates what level of debugging sets this output
4154 printInterfaceAddr(struct host *host, int level)
4159 if (host->interface) {
4160 /* check alternate addresses */
4161 number = host->interface->numberOfInterfaces;
4163 ViceLog(level, ("no-addresses "));
4165 for (i = 0; i < number; i++)
4166 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4167 ntohs(host->interface->interface[i].port)));
4170 ViceLog(level, ("\n"));