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>
25 #include <netinet/in.h>
30 #include <afs/assert.h>
33 #include <afs/afsint.h>
34 #include <afs/rxgen_consts.h>
36 #include <afs/errors.h>
37 #include <afs/ihandle.h>
38 #include <afs/vnode.h>
39 #include <afs/volume.h>
40 #ifdef AFS_ATHENA_STDENV
44 #include <afs/ptclient.h>
45 #include <afs/ptuser.h>
46 #include <afs/prs_fs.h>
48 #include <afs/afsutil.h>
49 #include <afs/com_err.h>
51 #include <afs/cellconfig.h>
53 #include "viced_prototypes.h"
57 #ifdef AFS_DEMAND_ATTACH_FS
58 #include "../util/afsutil_prototypes.h"
59 #include "../tviced/serialize_state.h"
60 #endif /* AFS_DEMAND_ATTACH_FS */
62 #ifdef AFS_PTHREAD_ENV
63 pthread_mutex_t host_glock_mutex;
64 #endif /* AFS_PTHREAD_ENV */
67 extern int CurrentConnections;
69 extern int AnonymousID;
70 extern prlist AnonCPS;
72 extern struct afsconf_dir *confDir; /* config dir object */
73 extern int lwps; /* the max number of server threads */
74 extern afsUUID FS_HostUUID;
77 int CEs = 0; /* active clients */
78 int CEBlocks = 0; /* number of blocks of CEs */
79 struct client *CEFree = 0; /* first free client */
80 struct host *hostList = 0; /* linked list of all hosts */
81 int hostCount = 0; /* number of hosts in hostList */
85 static struct rx_securityClass *sc = NULL;
87 static void h_SetupCallbackConn_r(struct host * host);
88 static int h_threadquota(int);
90 #define CESPERBLOCK 73
91 struct CEBlock { /* block of CESPERBLOCK file entries */
92 struct client entry[CESPERBLOCK];
95 static void h_TossStuff_r(register struct host *host);
98 * Make sure the subnet macros have been defined.
101 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
104 #ifndef IN_CLASSA_SUBNET
105 #define IN_CLASSA_SUBNET 0xffff0000
109 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
112 #ifndef IN_CLASSB_SUBNET
113 #define IN_CLASSB_SUBNET 0xffffff00
117 /* get a new block of CEs and chain it on CEFree */
121 register struct CEBlock *block;
124 block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
126 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
127 ShutDownAndCore(PANIC);
130 for (i = 0; i < (CESPERBLOCK - 1); i++) {
131 Lock_Init(&block->entry[i].lock);
132 block->entry[i].next = &(block->entry[i + 1]);
134 block->entry[CESPERBLOCK - 1].next = 0;
135 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
136 CEFree = (struct client *)block;
142 /* get the next available CE */
143 static struct client *
146 register struct client *entry;
151 ViceLog(0, ("CEFree NULL in GetCE\n"));
152 ShutDownAndCore(PANIC);
156 CEFree = entry->next;
158 memset((char *)entry, 0, CLIENT_TO_ZERO(entry));
164 /* return an entry to the free list */
166 FreeCE(register struct client *entry)
168 entry->VenusEpoch = 0;
170 entry->next = CEFree;
177 * The HTs and HTBlocks variables were formerly static, but they are
178 * now referenced elsewhere in the FileServer.
180 int HTs = 0; /* active file entries */
181 int HTBlocks = 0; /* number of blocks of HTs */
182 static struct host *HTFree = 0; /* first free file entry */
185 * Hash tables of host pointers. We need two tables, one
186 * to map IP addresses onto host pointers, and another
187 * to map host UUIDs onto host pointers.
189 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
190 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
191 #define h_HashIndex(hostip) (ntohl(hostip) & (h_HASHENTRIES-1))
192 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
194 struct HTBlock { /* block of HTSPERBLOCK file entries */
195 struct host entry[h_HTSPERBLOCK];
199 /* get a new block of HTs and chain it on HTFree */
203 register struct HTBlock *block;
205 static int index = 0;
207 if (HTBlocks == h_MAXHOSTTABLES) {
208 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
209 ShutDownAndCore(PANIC);
212 block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
214 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
215 ShutDownAndCore(PANIC);
217 #ifdef AFS_PTHREAD_ENV
218 for (i = 0; i < (h_HTSPERBLOCK); i++)
219 assert(pthread_cond_init(&block->entry[i].cond, NULL) == 0);
220 #endif /* AFS_PTHREAD_ENV */
221 for (i = 0; i < (h_HTSPERBLOCK); i++)
222 Lock_Init(&block->entry[i].lock);
223 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
224 block->entry[i].next = &(block->entry[i + 1]);
225 for (i = 0; i < (h_HTSPERBLOCK); i++)
226 block->entry[i].index = index++;
227 block->entry[h_HTSPERBLOCK - 1].next = 0;
228 HTFree = (struct host *)block;
229 hosttableptrs[HTBlocks++] = block->entry;
234 /* get the next available HT */
238 register struct host *entry;
242 assert(HTFree != NULL);
244 HTFree = entry->next;
246 memset((char *)entry, 0, HOST_TO_ZERO(entry));
252 /* return an entry to the free list */
254 FreeHT(register struct host *entry)
256 entry->next = HTFree;
263 hpr_Initialize(struct ubik_client **uclient)
266 struct rx_connection *serverconns[MAXSERVERS];
267 struct rx_securityClass *sc[3];
268 struct afsconf_dir *tdir;
269 struct ktc_token ttoken;
271 struct afsconf_cell info;
275 tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
277 ViceLog(0, ("hpr_Initialize: Could not open configuration directory: %s", AFSDIR_SERVER_ETC_DIRPATH));
281 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
283 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
288 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
290 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s", cellstr, confDir, AFSDIR_CELLSERVDB_FILE));
297 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
306 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
307 * to force use of the KeyFile. secLevel == 0 implies -noauth was
309 if ((afsconf_GetLatestKey(tdir, 0, 0) == 0)) {
310 code = afsconf_ClientAuthSecure(tdir, &sc[2], &scIndex);
312 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s (so trying noauth)", code, afs_error_message(code)));
314 scIndex = 0; /* use noauth */
316 /* if there was a problem, an unauthenticated conn is returned */
319 struct ktc_principal sname;
320 strcpy(sname.cell, info.name);
321 sname.instance[0] = 0;
322 strcpy(sname.name, "afs");
323 code = ktc_GetToken(&sname, &ttoken, sizeof(ttoken), NULL);
327 if (ttoken.kvno >= 0 && ttoken.kvno <= 256)
328 /* this is a kerberos ticket, set scIndex accordingly */
331 ViceLog(0, ("hpr_Initialize: funny kvno (%d) in ticket, proceeding", ttoken.kvno));
335 rxkad_NewClientSecurityObject(rxkad_clear, &ttoken.sessionKey,
336 ttoken.kvno, ttoken.ticketLen,
340 if ((scIndex == 0) && (sc[0] == 0))
341 sc[0] = rxnull_NewClientSecurityObject();
343 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, running unauthenticated. [%d]", code));
345 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
346 for (i = 0; i < info.numServers; i++) {
348 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
349 info.hostAddr[i].sin_port, PRSRV, sc[scIndex],
353 code = ubik_ClientInit(serverconns, uclient);
355 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
358 code = rxs_Release(sc[scIndex]);
363 hpr_End(struct ubik_client *uclient)
368 code = ubik_ClientDestroy(uclient);
374 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
376 #ifdef AFS_PTHREAD_ENV
377 register afs_int32 code;
379 struct ubik_client *uclient =
380 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
383 code = hpr_Initialize(&uclient);
385 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
391 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
392 if (code != PRSUCCESS)
395 /* do something about this, probably make a new call */
396 /* don't forget there's a hard limit in the interface */
398 "membership list for host id %d exceeds display limit\n",
403 return pr_GetHostCPS(host, CPS);
408 hpr_NameToId(namelist *names, idlist *ids)
410 #ifdef AFS_PTHREAD_ENV
411 register afs_int32 code;
412 register afs_int32 i;
413 struct ubik_client *uclient =
414 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
417 code = hpr_Initialize(&uclient);
419 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
424 for (i = 0; i < names->namelist_len; i++)
425 stolower(names->namelist_val[i]);
426 code = ubik_PR_NameToID(uclient, 0, names, ids);
429 return pr_NameToId(names, ids);
434 hpr_IdToName(idlist *ids, namelist *names)
436 #ifdef AFS_PTHREAD_ENV
437 register afs_int32 code;
438 struct ubik_client *uclient =
439 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
442 code = hpr_Initialize(&uclient);
444 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
449 code = ubik_PR_IDToName(uclient, 0, ids, names);
452 return pr_IdToName(ids, names);
457 hpr_GetCPS(afs_int32 id, prlist *CPS)
459 #ifdef AFS_PTHREAD_ENV
460 register afs_int32 code;
462 struct ubik_client *uclient =
463 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
466 code = hpr_Initialize(&uclient);
468 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
474 code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
475 if (code != PRSUCCESS)
478 /* do something about this, probably make a new call */
479 /* don't forget there's a hard limit in the interface */
480 fprintf(stderr, "membership list for id %d exceeds display limit\n",
485 return pr_GetCPS(id, CPS);
489 static short consolePort = 0;
492 h_Release(register struct host *host)
501 * If this thread does not have a hold on this host AND
502 * if other threads also dont have any holds on this host AND
503 * If either the HOSTDELETED or CLIENTDELETED flags are set
507 h_Release_r(register struct host *host)
510 if (!((host)->holds[h_holdSlot()] & ~h_holdbit())) {
511 if (!h_OtherHolds_r(host)) {
512 /* must avoid masking this until after h_OtherHolds_r runs
513 * but it should be run before h_TossStuff_r */
514 (host)->holds[h_holdSlot()] &= ~h_holdbit();
515 if ((host->hostFlags & HOSTDELETED)
516 || (host->hostFlags & CLIENTDELETED)) {
520 (host)->holds[h_holdSlot()] &= ~h_holdbit();
522 (host)->holds[h_holdSlot()] &= ~h_holdbit();
528 h_OtherHolds_r(register struct host *host)
530 register int i, bit, slot;
533 for (i = 0; i < h_maxSlots; i++) {
534 if (host->holds[i] != ((i == slot) ? bit : 0)) {
542 h_Lock_r(register struct host *host)
552 * returns 1 if already locked
553 * else returns locks and returns 0
557 h_NBLock_r(register struct host *host)
559 struct Lock *hostLock = &host->lock;
564 if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
565 hostLock->excl_locked = WRITE_LOCK;
569 LOCK_UNLOCK(hostLock);
578 #if FS_STATS_DETAILED
579 /*------------------------------------------------------------------------
580 * PRIVATE h_AddrInSameNetwork
583 * Given a target IP address and a candidate IP address (both
584 * in host byte order), return a non-zero value (1) if the
585 * candidate address is in a different network from the target
589 * a_targetAddr : Target address.
590 * a_candAddr : Candidate address.
593 * 1 if the candidate address is in the same net as the target,
597 * The target and candidate addresses are both in host byte
598 * order, NOT network byte order, when passed in. We return
599 * our value as a character, since that's the type of field in
600 * the host structure, where this info will be stored.
604 *------------------------------------------------------------------------*/
607 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
608 { /*h_AddrInSameNetwork */
610 afs_uint32 targetNet;
614 * Pull out the network and subnetwork numbers from the target
615 * and candidate addresses. We can short-circuit this whole
616 * affair if the target and candidate addresses are not of the
619 if (IN_CLASSA(a_targetAddr)) {
620 if (!(IN_CLASSA(a_candAddr))) {
623 targetNet = a_targetAddr & IN_CLASSA_NET;
624 candNet = a_candAddr & IN_CLASSA_NET;
625 } else if (IN_CLASSB(a_targetAddr)) {
626 if (!(IN_CLASSB(a_candAddr))) {
629 targetNet = a_targetAddr & IN_CLASSB_NET;
630 candNet = a_candAddr & IN_CLASSB_NET;
631 } /*Class B target */
632 else if (IN_CLASSC(a_targetAddr)) {
633 if (!(IN_CLASSC(a_candAddr))) {
636 targetNet = a_targetAddr & IN_CLASSC_NET;
637 candNet = a_candAddr & IN_CLASSC_NET;
638 } /*Class C target */
640 targetNet = a_targetAddr;
641 candNet = a_candAddr;
642 } /*Class D address */
645 * Now, simply compare the extracted net values for the two addresses
646 * (which at this point are known to be of the same class)
648 if (targetNet == candNet)
653 } /*h_AddrInSameNetwork */
654 #endif /* FS_STATS_DETAILED */
657 /* Assumptions: called with held host */
659 h_gethostcps_r(register struct host *host, register afs_int32 now)
664 /* wait if somebody else is already doing the getCPS call */
665 while (host->hostFlags & HCPS_INPROGRESS) {
666 slept = 1; /* I did sleep */
667 host->hostFlags |= HCPS_WAITING; /* I am sleeping now */
668 #ifdef AFS_PTHREAD_ENV
669 pthread_cond_wait(&host->cond, &host_glock_mutex);
670 #else /* AFS_PTHREAD_ENV */
671 if ((code = LWP_WaitProcess(&(host->hostFlags))) != LWP_SUCCESS)
672 ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
673 #endif /* AFS_PTHREAD_ENV */
677 host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
678 if (host->hcps.prlist_val)
679 free(host->hcps.prlist_val); /* this is for hostaclRefresh */
680 host->hcps.prlist_val = NULL;
681 host->hcps.prlist_len = 0;
682 host->cpsCall = slept ? (FT_ApproxTime()) : (now);
685 code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
690 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
691 * and reevaluates things if no sync server or quorum is found we could still end up
692 * with one of these errors. In such case we would like to reevaluate the rpc call to
693 * find if there's cps for this guy. We treat other errors (except network failures
694 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
695 * we could like to deal this problem the other way around (i.e. if code == NOCPS
696 * ignore else retry next time) but the problem is that there're other errors (i.e.
697 * EPERM) for which we don't want to retry and we don't know the whole code list!
699 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
701 * We would have preferred to use a while loop and try again since ops in protected
702 * acls for this host will fail now but they'll be reevaluated on any subsequent
703 * call. The attempt to wait for a quorum/sync site or network error won't work
704 * since this problems really should only occurs during a complete fileserver
705 * restart. Since the fileserver will start before the ptservers (and thus before
706 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
708 host->hcpsfailed = 1;
710 ("Warning: GetHostCPS failed (%d) for %x (%s:%d); will retry\n",
711 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
713 host->hcpsfailed = 0;
715 ("gethost: GetHostCPS failed (%d) for %x (%s:%d); ignored\n",
716 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
718 if (host->hcps.prlist_val)
719 free(host->hcps.prlist_val);
720 host->hcps.prlist_val = NULL;
721 host->hcps.prlist_len = 0; /* Make sure it's zero */
723 host->hcpsfailed = 0;
725 host->hostFlags &= ~HCPS_INPROGRESS;
726 /* signal all who are waiting */
727 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
728 host->hostFlags &= ~HCPS_WAITING;
729 #ifdef AFS_PTHREAD_ENV
730 assert(pthread_cond_broadcast(&host->cond) == 0);
731 #else /* AFS_PTHREAD_ENV */
732 if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
733 ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
734 #endif /* AFS_PTHREAD_ENV */
738 /* args in net byte order */
740 h_flushhostcps(register afs_uint32 hostaddr, register afs_uint16 hport)
746 h_Lookup_r(hostaddr, hport, &held, &host);
748 host->hcpsfailed = 1;
758 * Allocate a host. It will be identified by the peer (ip,port) info in the
759 * rx connection provided. The host is returned held and locked
761 #define DEF_ROPCONS 2115
764 h_Alloc_r(register struct rx_connection *r_con)
766 struct servent *serverentry;
769 #if FS_STATS_DETAILED
770 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
771 #endif /* FS_STATS_DETAILED */
775 host->host = rxr_HostOf(r_con);
776 host->port = rxr_PortOf(r_con);
778 h_AddHostToAddrHashTable_r(host->host, host->port, host);
780 if (consolePort == 0) { /* find the portal number for console */
781 #if defined(AFS_OSF_ENV)
782 serverentry = getservbyname("ropcons", "");
784 serverentry = getservbyname("ropcons", 0);
787 consolePort = serverentry->s_port;
789 consolePort = htons(DEF_ROPCONS); /* Use a default */
791 if (host->port == consolePort)
793 /* Make a callback channel even for the console, on the off chance that it
794 * makes a request that causes a break call back. It shouldn't. */
795 h_SetupCallbackConn_r(host);
796 now = host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
798 host->hcps.prlist_val = NULL;
799 host->hcps.prlist_len = 0;
800 host->interface = NULL;
802 host->hcpsfailed = 0; /* save cycles */
803 h_gethostcps(host); /* do this under host hold/lock */
805 host->FirstClient = NULL;
808 h_InsertList_r(host); /* update global host List */
809 #if FS_STATS_DETAILED
811 * Compare the new host's IP address (in host byte order) with ours
812 * (the File Server's), remembering if they are in the same network.
814 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
815 host->InSameNetwork =
816 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
817 #endif /* FS_STATS_DETAILED */
824 /* Make a callback channel even for the console, on the off chance that it
825 * makes a request that causes a break call back. It shouldn't. */
827 h_SetupCallbackConn_r(struct host * host)
830 sc = rxnull_NewClientSecurityObject();
831 host->callback_rxcon =
832 rx_NewConnection(host->host, host->port, 1, sc, 0);
833 rx_SetConnDeadTime(host->callback_rxcon, 50);
834 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
837 /* Lookup a host given an IP address and UDP port number. */
838 /* hostaddr and hport are in network order */
839 /* Note: host should be released by caller if 0 == *heldp and non-null */
840 /* hostaddr and hport are in network order */
842 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, int *heldp, struct host **hostp)
845 struct host *host = NULL;
846 struct h_AddrHashChain *chain;
847 int index = h_HashIndex(haddr);
848 extern int hostaclRefresh;
851 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
852 host = chain->hostPtr;
854 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
855 && chain->port == hport) {
856 if ((host->hostFlags & HWHO_INPROGRESS) &&
857 h_threadquota(host->lock.num_waiting)) {
861 *heldp = h_Held_r(host);
865 if (host->hostFlags & HOSTDELETED) {
872 now = FT_ApproxTime(); /* always evaluate "now" */
873 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
875 * Every hostaclRefresh period (def 2 hrs) get the new
876 * membership list for the host. Note this could be the
877 * first time that the host is added to a group. Also
878 * here we also retry on previous legitimate hcps failures.
880 * If we get here we still have a host hold.
882 h_gethostcps_r(host, now);
892 /* Lookup a host given its UUID. */
894 h_LookupUuid_r(afsUUID * uuidp)
896 struct host *host = 0;
897 struct h_UuidHashChain *chain;
898 int index = h_UuidHashIndex(uuidp);
900 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
901 host = chain->hostPtr;
903 if (!(host->hostFlags & HOSTDELETED) && host->interface
904 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
913 * h_Hold_r: Establish a hold by the current LWP on this host--the host
914 * or its clients will not be physically deleted until all holds have
916 * NOTE: h_Hold_r is a macro defined in host.h.
919 /* h_TossStuff_r: Toss anything in the host structure (the host or
920 * clients marked for deletion. Called from h_Release_r ONLY.
921 * To be called, there must be no holds, and either host->deleted
922 * or host->clientDeleted must be set.
925 h_TossStuff_r(register struct host *host)
927 register struct client **cp, *client;
930 /* if somebody still has this host held */
931 for (i = 0; (i < h_maxSlots) && (!(host)->holds[i]); i++);
935 /* if somebody still has this host locked */
936 if (h_NBLock_r(host) != 0) {
939 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was locked.\n",
940 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
946 /* ASSUMPTION: rxi_FreeConnection() does not yield */
947 for (cp = &host->FirstClient; (client = *cp);) {
948 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
950 ObtainWriteLockNoBlock(&client->lock, code);
954 ("Warning: h_TossStuff_r failed: Host %" AFS_PTR_FMT " (%s:%d) client %x was locked.\n",
955 host, afs_inet_ntoa_r(host->host, hoststr),
956 ntohs(host->port), client));
960 if (client->refCount) {
963 ("Warning: h_TossStuff_r failed: Host %" AFS_PTR_FMT " (%s:%d) client %x refcount %d.\n",
964 host, afs_inet_ntoa_r(host->host, hoststr),
965 ntohs(host->port), client, client->refCount));
966 /* This is the same thing we do if the host is locked */
967 ReleaseWriteLock(&client->lock);
970 client->CPS.prlist_len = 0;
971 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
972 free(client->CPS.prlist_val);
973 client->CPS.prlist_val = NULL;
974 CurrentConnections--;
976 ReleaseWriteLock(&client->lock);
982 /* We've just cleaned out all the deleted clients; clear the flag */
983 host->hostFlags &= ~CLIENTDELETED;
985 if (host->hostFlags & HOSTDELETED) {
986 register struct rx_connection *rxconn;
987 struct AddrPort hostAddrPort;
990 if (host->Console & 1)
992 if ((rxconn = host->callback_rxcon)) {
993 host->callback_rxcon = (struct rx_connection *)0;
994 rx_DestroyConnection(rxconn);
996 if (host->hcps.prlist_val)
997 free(host->hcps.prlist_val);
998 host->hcps.prlist_val = NULL;
999 host->hcps.prlist_len = 0;
1000 DeleteAllCallBacks_r(host, 1);
1001 host->hostFlags &= ~RESETDONE; /* just to be safe */
1003 /* if alternate addresses do not exist */
1004 if (!(host->interface)) {
1005 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
1007 h_DeleteHostFromUuidHashTable_r(host);
1008 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
1009 /* delete the hash entry for each valid alternate addresses */
1010 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
1011 hostAddrPort = host->interface->interface[i];
1013 * if the interface addr/port is the primary, we already
1014 * removed it. If the addr/port is not valid, its not
1015 * in the hash table.
1017 if (hostAddrPort.valid &&
1018 (host->host != hostAddrPort.addr ||
1019 host->port != hostAddrPort.port))
1020 h_DeleteHostFromAddrHashTable_r(hostAddrPort.addr, hostAddrPort.port, host);
1022 free(host->interface);
1023 host->interface = NULL;
1024 } /* if alternate address exists */
1026 h_DeleteList_r(host); /* remove host from global host List */
1029 } /*h_TossStuff_r */
1032 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
1033 * system at the start of the enumeration (perhaps more). Hosts may be deleted
1034 * (have delete flag set); ditto for clients. (*proc) is always called with
1035 * host h_held(). The hold state of the host with respect to this lwp is passed
1036 * to (*proc) as the param held. The proc should return 0 if the host should be
1037 * released, 1 if it should be held after enumeration.
1040 h_Enumerate(int (*proc) (struct host*, int, void *), void *param)
1042 register struct host *host, **list;
1044 register int i, count;
1047 if (hostCount == 0) {
1051 list = (struct host **)malloc(hostCount * sizeof(struct host *));
1053 ViceLog(0, ("Failed malloc in h_Enumerate\n"));
1056 held = (int *)malloc(hostCount * sizeof(int));
1058 ViceLog(0, ("Failed malloc in h_Enumerate\n"));
1061 for (count = 0, host = hostList; host; host = host->next, count++) {
1063 if (!(held[count] = h_Held_r(host)))
1066 if (count != hostCount) {
1067 ViceLog(0, ("h_Enumerate found %d of %d hosts\n", count, hostCount));
1069 assert(count <= hostCount);
1071 for (i = 0; i < count; i++) {
1072 held[i] = (*proc) (list[i], held[i], param);
1073 if (!H_ENUMERATE_ISSET_HELD(held[i]))
1074 h_Release(list[i]); /* this might free up the host */
1075 /* bail out of the enumeration early */
1076 if (H_ENUMERATE_ISSET_BAIL(held[i]))
1083 /* h_Enumerate_r (revised):
1084 * Calls (*proc)(host, held, param) for each host in hostList, starting
1086 * Hosts may be deleted (have delete flag set); ditto for clients.
1087 * (*proc) is always called with
1088 * host h_held() and the global host lock (H_LOCK) locked.The hold state of the
1089 * host with respect to this lwp is passed to (*proc) as the param held.
1090 * The proc should return 0 if the host should be released, 1 if it should
1091 * be held after enumeration.
1094 h_Enumerate_r(int (*proc) (struct host *, int, void *),
1095 struct host *enumstart, void *param)
1097 register struct host *host, *next;
1101 if (hostCount == 0) {
1104 if (enumstart && !(held = h_Held_r(enumstart)))
1105 h_Hold_r(enumstart);
1106 for (host = enumstart; host; host = next, held = nheld) {
1108 if (next && !(nheld = h_Held_r(next)) && !H_ENUMERATE_ISSET_BAIL(held))
1110 held = (*proc) (host, held, param);
1111 if (!H_ENUMERATE_ISSET_HELD(held))
1112 h_Release_r(host); /* this might free up the host */
1113 if (H_ENUMERATE_ISSET_BAIL(held)) {
1114 if (!H_ENUMERATE_ISSET_HELD(nheld))
1115 h_Release_r(next); /* this might free up the host */
1119 } /*h_Enumerate_r */
1121 /* inserts a new HashChain structure corresponding to this UUID */
1123 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1126 struct h_UuidHashChain *chain;
1127 char uuid1[128], uuid2[128];
1130 /* hash into proper bucket */
1131 index = h_UuidHashIndex(uuid);
1133 /* don't add the same entry multiple times */
1134 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1135 if (!chain->hostPtr)
1138 if (chain->hostPtr->interface &&
1139 afs_uuid_equal(&chain->hostPtr->interface->uuid, uuid)) {
1140 if (LogLevel >= 125) {
1141 afsUUID_to_string(&chain->hostPtr->interface->uuid, uuid1,
1143 afsUUID_to_string(uuid, uuid2, 127);
1144 ViceLog(125, ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s) exists as %s:%d (uuid %s)\n",
1146 afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1147 ntohs(chain->hostPtr->port), uuid2));
1153 /* insert into beginning of list for this bucket */
1154 chain = (struct h_UuidHashChain *)malloc(sizeof(struct h_UuidHashChain));
1156 ViceLog(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1159 chain->hostPtr = host;
1160 chain->next = hostUuidHashTable[index];
1161 hostUuidHashTable[index] = chain;
1164 afsUUID_to_string(uuid, uuid2, 127);
1166 ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (%s:%d) added as uuid %s\n",
1167 host, afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1168 ntohs(chain->hostPtr->port), uuid));
1171 /* deletes a HashChain structure corresponding to this host */
1173 h_DeleteHostFromUuidHashTable_r(struct host *host)
1176 register struct h_UuidHashChain **uhp, *uth;
1180 if (!host->interface)
1183 /* hash into proper bucket */
1184 index = h_UuidHashIndex(&host->interface->uuid);
1186 if (LogLevel >= 125)
1187 afsUUID_to_string(&host->interface->uuid, uuid1, 127);
1188 for (uhp = &hostUuidHashTable[index]; (uth = *uhp); uhp = &uth->next) {
1189 assert(uth->hostPtr);
1190 if (uth->hostPtr == host) {
1192 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d)\n",
1193 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1194 ntohs(host->port)));
1201 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d) not found\n",
1202 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1203 ntohs(host->port)));
1207 /* inserts a new HashChain structure corresponding to this address */
1209 h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1212 struct h_AddrHashChain *chain;
1213 char hoststr[16], hoststr2[16];
1215 /* hash into proper bucket */
1216 index = h_HashIndex(addr);
1218 /* don't add the same entry multiple times */
1219 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1220 if (chain->hostPtr == host) {
1221 if (chain->addr != addr || chain->port != port) {
1223 ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " exists as %s:%d when adding %s:%d\n",
1224 host, afs_inet_ntoa_r(chain->addr, hoststr),
1225 ntohs(chain->port), afs_inet_ntoa_r(addr, hoststr2),
1229 ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
1230 host, afs_inet_ntoa_r(chain->addr, hoststr),
1231 ntohs(chain->port)));
1237 /* insert into beginning of list for this bucket */
1238 chain = (struct h_AddrHashChain *)malloc(sizeof(struct h_AddrHashChain));
1240 ViceLog(0, ("Failed malloc in h_AddHostToAddrHashTable_r\n"));
1243 chain->hostPtr = host;
1244 chain->next = hostAddrHashTable[index];
1247 hostAddrHashTable[index] = chain;
1248 ViceLog(125, ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " added as %s:%d\n",
1249 host, afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1253 * This is called with host locked and held.
1254 * It is called to either validate or add an additional interface
1255 * address/port on the specified host.
1257 * All addresses are in network byte order.
1260 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1264 struct Interface *interface;
1265 char hoststr[16], hoststr2[16];
1268 assert(host->interface);
1271 * Make sure this address is on the list of known addresses
1274 number = host->interface->numberOfInterfaces;
1275 for (i = 0; i < number; i++) {
1276 if (host->interface->interface[i].addr == addr &&
1277 host->interface->interface[i].port == port) {
1279 ("addInterfaceAddr : found host %" AFS_PTR_FMT " (%s:%d) adding %s:%d%s\n",
1280 host, afs_inet_ntoa_r(host->host, hoststr),
1281 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1282 ntohs(port), host->interface->interface[i].valid ? "" :
1285 if (host->interface->interface[i].valid == 0) {
1286 host->interface->interface[i].valid = 1;
1287 h_AddHostToAddrHashTable_r(addr, port, host);
1293 ViceLog(125, ("addInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) adding %s:%d\n",
1294 host, afs_inet_ntoa_r(host->host, hoststr),
1295 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1298 interface = (struct Interface *)
1299 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1301 ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
1304 interface->numberOfInterfaces = number + 1;
1305 interface->uuid = host->interface->uuid;
1306 for (i = 0; i < number; i++)
1307 interface->interface[i] = host->interface->interface[i];
1309 /* Add the new valid interface */
1310 interface->interface[number].addr = addr;
1311 interface->interface[number].port = port;
1312 interface->interface[number].valid = 1;
1313 h_AddHostToAddrHashTable_r(addr, port, host);
1314 free(host->interface);
1315 host->interface = interface;
1322 * This is called with host locked and held.
1324 * All addresses are in network byte order.
1327 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1331 struct Interface *interface;
1332 char hoststr[16], hoststr2[16];
1335 assert(host->interface);
1337 ViceLog(125, ("removeInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1338 host, afs_inet_ntoa_r(host->host, hoststr),
1339 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1343 * Make sure this address is on the list of known addresses
1346 interface = host->interface;
1347 number = host->interface->numberOfInterfaces;
1348 for (i = 0; i < number; i++) {
1349 if (interface->interface[i].addr == addr &&
1350 interface->interface[i].port == port) {
1351 if (interface->interface[i].valid)
1352 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1354 for (; i < number; i++) {
1355 interface->interface[i] = interface->interface[i+1];
1357 interface->numberOfInterfaces = number;
1366 * This is called with host locked and held.
1368 * All addresses are in network byte order.
1371 invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1375 struct Interface *interface;
1376 char hoststr[16], hoststr2[16];
1379 assert(host->interface);
1381 ViceLog(125, ("invalidateInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1382 host, afs_inet_ntoa_r(host->host, hoststr),
1383 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1387 * Make sure this address is on the list of known addresses
1390 interface = host->interface;
1391 number = host->interface->numberOfInterfaces;
1392 for (i = 0; i < number; i++) {
1393 if (interface->interface[i].addr == addr &&
1394 interface->interface[i].port == port) {
1395 if (interface->interface[i].valid) {
1396 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1397 interface->interface[i].valid = 0;
1408 * This is called with host locked and held. This function differs
1409 * from removeInterfaceAddr_r in that it is called when the address
1410 * is being removed from the host regardless of whether or not there
1411 * is an interface list for the host. This function will delete the
1412 * host if there are no addresses left on it.
1414 * All addresses are in network byte order.
1417 removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1420 char hoststr[16], hoststr2[16];
1421 struct rx_connection *rxconn;
1423 if (!host->interface || host->interface->numberOfInterfaces == 1) {
1424 if (host->host == addr && host->port == port) {
1426 ("Removing only address for host %" AFS_PTR_FMT " (%s:%d), deleting host.\n",
1427 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1428 host->hostFlags |= HOSTDELETED;
1430 * Do not remove the primary addr/port from the hash table.
1431 * It will be ignored due to the HOSTDELETED flag and will
1432 * be removed when h_TossStuff_r() cleans up the HOSTDELETED
1433 * host. Removing it here will only result in a search for
1434 * the host/addr/port in the hash chain which will fail.
1438 ("Removing address that does not belong to host %" AFS_PTR_FMT " (%s:%d).\n",
1439 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1442 if (host->host == addr && host->port == port) {
1443 removeInterfaceAddr_r(host, addr, port);
1445 rxconn = host->callback_rxcon;
1446 host->callback_rxcon = NULL;
1449 struct client *client;
1451 * If rx_DestroyConnection calls h_FreeConnection we will
1452 * deadlock on the host_glock_mutex. Work around the problem
1453 * by unhooking the client from the connection before
1454 * destroying the connection.
1456 client = rx_GetSpecific(rxconn, rxcon_client_key);
1457 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1458 rx_DestroyConnection(rxconn);
1461 for (i=0; i < host->interface->numberOfInterfaces; i++) {
1462 if (host->interface->interface[i].valid) {
1464 ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
1465 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1466 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
1467 ntohs(host->interface->interface[i].port)));
1468 host->host = host->interface->interface[i].addr;
1469 host->port = host->interface->interface[i].port;
1470 h_AddHostToAddrHashTable_r(host->host, host->port, host);
1475 if (i == host->interface->numberOfInterfaces) {
1477 ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
1478 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1479 host->hostFlags |= HOSTDELETED;
1480 /* addr/port was removed from the hash table */
1485 sc = rxnull_NewClientSecurityObject();
1486 host->callback_rxcon =
1487 rx_NewConnection(host->host, host->port, 1, sc, 0);
1488 rx_SetConnDeadTime(host->callback_rxcon, 50);
1489 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
1492 /* not the primary addr/port, just invalidate it */
1493 invalidateInterfaceAddr_r(host, addr, port);
1500 h_threadquota(int waiting)
1505 } else if (lwps > 32) {
1508 } else if (lwps > 16) {
1518 /* Host is returned held */
1520 h_GetHost_r(struct rx_connection *tcon)
1523 struct host *oldHost;
1526 struct interfaceAddr interf;
1527 int interfValid = 0;
1528 struct Identity *identP = NULL;
1531 char hoststr[16], hoststr2[16];
1533 struct rx_connection *cb_conn = NULL;
1534 struct rx_connection *cb_in = NULL;
1536 caps.Capabilities_val = NULL;
1538 haddr = rxr_HostOf(tcon);
1539 hport = rxr_PortOf(tcon);
1542 rx_DestroyConnection(cb_in);
1545 if (caps.Capabilities_val)
1546 free(caps.Capabilities_val);
1547 caps.Capabilities_val = NULL;
1548 caps.Capabilities_len = 0;
1551 if (h_Lookup_r(haddr, hport, &held, &host))
1553 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1554 if (host && !identP && !(host->Console & 1)) {
1555 /* This is a new connection, and we already have a host
1556 * structure for this address. Verify that the identity
1557 * of the caller matches the identity in the host structure.
1559 if ((host->hostFlags & HWHO_INPROGRESS) &&
1560 h_threadquota(host->lock.num_waiting)) {
1566 if (!(host->hostFlags & ALTADDR)) {
1567 /* Another thread is doing initialization */
1572 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1573 host, afs_inet_ntoa_r(host->host, hoststr),
1574 ntohs(host->port)));
1577 host->hostFlags |= HWHO_INPROGRESS;
1578 host->hostFlags &= ~ALTADDR;
1580 /* We received a new connection from an IP address/port
1581 * that is associated with 'host' but the address/port of
1582 * the callback connection does not have to match it.
1583 * If there is a match, we can use the existing callback
1584 * connection to verify the UUID. If they do not match
1585 * we need to use a new callback connection to verify the
1586 * UUID of the incoming caller and perhaps use the old
1587 * callback connection to verify that the old address/port
1591 cb_conn = host->callback_rxcon;
1592 rx_GetConnection(cb_conn);
1594 if (haddr == host->host && hport == host->port) {
1595 /* The existing callback connection matches the
1596 * incoming connection so just use it.
1599 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1600 if (code == RXGEN_OPCODE)
1601 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1603 /* We do not have a match. Create a new connection
1604 * for the new addr/port and use multi_Rx to probe
1605 * both of them simultaneously.
1608 sc = rxnull_NewClientSecurityObject();
1609 cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1610 rx_SetConnDeadTime(cb_in, 50);
1611 rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1614 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1615 if (code == RXGEN_OPCODE)
1616 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1618 rx_PutConnection(cb_conn);
1621 if ((code == RXGEN_OPCODE) ||
1622 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1623 identP = (struct Identity *)malloc(sizeof(struct Identity));
1625 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1629 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1630 if (cb_in == NULL) {
1631 /* The host on this connection was unable to respond to
1632 * the WhoAreYou. We will treat this as a new connection
1633 * from the existing host. The worst that can happen is
1634 * that we maintain some extra callback state information */
1635 if (host->interface) {
1637 ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1639 afs_inet_ntoa_r(host->host, hoststr),
1640 ntohs(host->port)));
1641 host->hostFlags |= HOSTDELETED;
1642 host->hostFlags &= ~HWHO_INPROGRESS;
1650 /* The incoming connection does not support WhoAreYou but
1651 * the original one might have. Use removeAddress_r() to
1652 * remove this addr/port from the host that was found.
1653 * If there are no more addresses left for the host it
1654 * will be deleted. Then we retry.
1656 removeAddress_r(host, haddr, hport);
1657 host->hostFlags &= ~HWHO_INPROGRESS;
1658 host->hostFlags |= ALTADDR;
1665 } else if (code == 0) {
1667 identP = (struct Identity *)malloc(sizeof(struct Identity));
1669 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1673 identP->uuid = interf.uuid;
1674 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1675 /* Check whether the UUID on this connection matches
1676 * the UUID in the host structure. If they don't match
1677 * then this is not the same host as before. */
1678 if (!host->interface
1679 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1682 ("Uuid doesn't match connection (%s:%d).\n",
1683 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1685 removeAddress_r(host, haddr, hport);
1688 ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1689 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1691 removeAddress_r(host, host->host, host->port);
1693 host->hostFlags &= ~HWHO_INPROGRESS;
1694 host->hostFlags |= ALTADDR;
1701 /* the UUID matched the client at the incoming addr/port
1702 * but this is not the address of the active callback
1703 * connection. Try that connection and see if the client
1704 * is still there and if the reported UUID is the same.
1707 afsUUID uuid = host->interface->uuid;
1708 cb_conn = host->callback_rxcon;
1709 rx_GetConnection(cb_conn);
1710 rx_SetConnDeadTime(cb_conn, 2);
1711 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1713 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1715 rx_SetConnDeadTime(cb_conn, 50);
1716 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1717 rx_PutConnection(cb_conn);
1720 /* The primary address is either not responding or
1721 * is not the client we are looking for. Need to
1722 * remove the primary address and add swap in the new
1723 * callback connection, and destroy the old one.
1725 struct rx_connection *rxconn;
1726 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1728 afs_inet_ntoa_r(host->host, hoststr),
1729 ntohs(host->port),code2));
1732 * make sure we add and then remove. otherwise, we
1733 * might end up with no valid interfaces after the
1734 * remove and the host will have been marked deleted.
1736 addInterfaceAddr_r(host, haddr, hport);
1737 removeInterfaceAddr_r(host, host->host, host->port);
1740 rxconn = host->callback_rxcon;
1741 host->callback_rxcon = cb_in;
1745 struct client *client;
1747 * If rx_DestroyConnection calls h_FreeConnection we will
1748 * deadlock on the host_glock_mutex. Work around the problem
1749 * by unhooking the client from the connection before
1750 * destroying the connection.
1752 client = rx_GetSpecific(rxconn, rxcon_client_key);
1753 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1754 rx_DestroyConnection(rxconn);
1760 /* A callback to the incoming connection address is failing.
1761 * Assume that the addr/port is no longer associated with the host
1762 * returned by h_Lookup_r.
1765 ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1766 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1767 removeAddress_r(host, haddr, hport);
1768 host->hostFlags &= ~HWHO_INPROGRESS;
1769 host->hostFlags |= ALTADDR;
1774 rx_DestroyConnection(cb_in);
1778 ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1779 host, afs_inet_ntoa_r(host->host, hoststr),
1780 ntohs(host->port), code));
1781 host->hostFlags |= VENUSDOWN;
1784 if (caps.Capabilities_val
1785 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1786 host->hostFlags |= HERRORTRANS;
1788 host->hostFlags &= ~(HERRORTRANS);
1789 host->hostFlags |= ALTADDR;
1790 host->hostFlags &= ~HWHO_INPROGRESS;
1793 if (!(host->hostFlags & ALTADDR)) {
1794 /* another thread is doing the initialisation */
1796 ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1797 host, afs_inet_ntoa_r(host->host, hoststr),
1798 ntohs(host->port)));
1804 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1805 host, afs_inet_ntoa_r(host->host, hoststr),
1806 ntohs(host->port)));
1809 /* We need to check whether the identity in the host structure
1810 * matches the identity on the connection. If they don't match
1811 * then treat this a new host. */
1812 if (!(host->Console & 1)
1813 && ((!identP->valid && host->interface)
1814 || (identP->valid && !host->interface)
1816 && !afs_uuid_equal(&identP->uuid,
1817 &host->interface->uuid)))) {
1818 char uuid1[128], uuid2[128];
1820 afsUUID_to_string(&identP->uuid, uuid1, 127);
1821 if (host->interface)
1822 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1824 ("CB: new identity for host %" AFS_PTR_FMT " (%s:%d), deleting(%x %x %s %s)\n",
1825 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1826 identP->valid, host->interface,
1827 identP->valid ? uuid1 : "no_uuid",
1828 host->interface ? uuid2 : "no_uuid"));
1830 /* The host in the cache is not the host for this connection */
1832 host->hostFlags |= HOSTDELETED;
1839 host = h_Alloc_r(tcon); /* returned held and locked */
1840 h_gethostcps_r(host, FT_ApproxTime());
1841 if (!(host->Console & 1)) {
1843 cb_conn = host->callback_rxcon;
1844 rx_GetConnection(cb_conn);
1845 host->hostFlags |= HWHO_INPROGRESS;
1848 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1849 if (code == RXGEN_OPCODE)
1850 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1851 rx_PutConnection(cb_conn);
1854 if ((code == RXGEN_OPCODE) ||
1855 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1858 (struct Identity *)malloc(sizeof(struct Identity));
1863 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1868 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1870 ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1871 host, afs_inet_ntoa_r(host->host, hoststr),
1872 ntohs(host->port)));
1874 } else if (code == 0) {
1877 (struct Identity *)malloc(sizeof(struct Identity));
1882 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1887 identP->uuid = interf.uuid;
1889 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1891 ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
1892 host, afs_inet_ntoa_r(host->host, hoststr),
1893 ntohs(host->port)));
1895 if (code == 0 && !identP->valid) {
1896 cb_conn = host->callback_rxcon;
1897 rx_GetConnection(cb_conn);
1899 code = RXAFSCB_InitCallBackState(cb_conn);
1900 rx_PutConnection(cb_conn);
1903 } else if (code == 0) {
1904 oldHost = h_LookupUuid_r(&identP->uuid);
1908 if (!h_Held_r(oldHost))
1911 oldHost->hostFlags |= HWHO_INPROGRESS;
1913 if (oldHost->interface) {
1915 afsUUID uuid = oldHost->interface->uuid;
1916 cb_conn = oldHost->callback_rxcon;
1917 rx_GetConnection(cb_conn);
1918 rx_SetConnDeadTime(cb_conn, 2);
1919 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1921 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1923 rx_SetConnDeadTime(cb_conn, 50);
1924 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1925 rx_PutConnection(cb_conn);
1928 /* The primary address is either not responding or
1929 * is not the client we are looking for.
1930 * MultiProbeAlternateAddress_r() will remove the
1931 * alternate interfaces that do not have the same
1933 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1935 afs_inet_ntoa_r(oldHost->host, hoststr),
1936 ntohs(oldHost->port),code2));
1937 MultiProbeAlternateAddress_r(oldHost);
1944 /* This is a new address for an existing host. Update
1945 * the list of interfaces for the existing host and
1946 * delete the host structure we just allocated. */
1948 /* prevent warnings while manipulating interface lists */
1949 host->hostFlags |= HOSTDELETED;
1951 if (oldHost->host != haddr || oldHost->port != hport) {
1952 struct rx_connection *rxconn;
1955 ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
1957 afs_inet_ntoa_r(oldHost->host, hoststr2),
1958 ntohs(oldHost->port),
1959 afs_inet_ntoa_r(haddr, hoststr),
1962 * add then remove. otherwise the host may get marked
1963 * deleted if we removed the only valid address.
1965 addInterfaceAddr_r(oldHost, haddr, hport);
1966 if (probefail || oldHost->host == haddr) {
1968 * The probe failed which means that the old
1969 * address is either unreachable or is not the
1970 * same host we were just contacted by. We will
1971 * also remove addresses if only the port has
1972 * changed because that indicates the client
1975 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
1978 struct Interface *interface = oldHost->interface;
1979 int number = oldHost->interface->numberOfInterfaces;
1980 for (i = 0; i < number; i++) {
1981 if (interface->interface[i].addr == haddr &&
1982 interface->interface[i].port != hport) {
1984 * We have just been contacted by a client
1985 * that has been seen from behind a NAT
1986 * and at least one other address.
1988 removeInterfaceAddr_r(oldHost, haddr,
1989 interface->interface[i].port);
1994 h_AddHostToAddrHashTable_r(haddr, hport, oldHost);
1995 oldHost->host = haddr;
1996 oldHost->port = hport;
1997 rxconn = oldHost->callback_rxcon;
1998 oldHost->callback_rxcon = host->callback_rxcon;
1999 host->callback_rxcon = NULL;
2002 struct client *client;
2004 * If rx_DestroyConnection calls h_FreeConnection we will
2005 * deadlock on the host_glock_mutex. Work around the problem
2006 * by unhooking the client from the connection before
2007 * destroying the connection.
2009 client = rx_GetSpecific(rxconn, rxcon_client_key);
2010 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
2011 rx_DestroyConnection(rxconn);
2014 host->hostFlags &= ~HWHO_INPROGRESS;
2016 /* release host because it was allocated by h_Alloc_r */
2019 /* the new host is held and locked */
2021 /* This really is a new host */
2022 h_AddHostToUuidHashTable_r(&identP->uuid, host);
2023 cb_conn = host->callback_rxcon;
2024 rx_GetConnection(cb_conn);
2027 RXAFSCB_InitCallBackState3(cb_conn,
2029 rx_PutConnection(cb_conn);
2034 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2035 host, afs_inet_ntoa_r(host->host, hoststr),
2036 ntohs(host->port)));
2037 assert(interfValid == 1);
2038 initInterfaceAddr_r(host, &interf);
2044 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2045 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2046 host->hostFlags |= VENUSDOWN;
2049 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2050 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2051 host->hostFlags |= RESETDONE;
2054 if (caps.Capabilities_val
2055 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2056 host->hostFlags |= HERRORTRANS;
2058 host->hostFlags &= ~(HERRORTRANS);
2059 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2060 host->hostFlags &= ~HWHO_INPROGRESS;
2063 if (caps.Capabilities_val)
2064 free(caps.Capabilities_val);
2065 caps.Capabilities_val = NULL;
2066 caps.Capabilities_len = 0;
2072 static char localcellname[PR_MAXNAMELEN + 1];
2073 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
2074 int num_lrealms = -1;
2078 h_InitHostPackage(void)
2080 memset(&nulluuid, 0, sizeof(afsUUID));
2081 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
2082 if (num_lrealms == -1) {
2084 for (i=0; i<AFS_NUM_LREALMS; i++) {
2085 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
2091 ("afs_krb_get_lrealm failed, using %s.\n",
2093 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
2099 /* initialize the rest of the local realms to nullstring for debugging */
2100 for (; i<AFS_NUM_LREALMS; i++)
2101 local_realms[i][0] = '\0';
2103 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2104 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2105 #ifdef AFS_PTHREAD_ENV
2106 assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
2107 #endif /* AFS_PTHREAD_ENV */
2111 MapName_r(char *aname, char *acell, afs_int32 * aval)
2116 afs_int32 anamelen, cnamelen;
2120 anamelen = strlen(aname);
2121 if (anamelen >= PR_MAXNAMELEN)
2122 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
2124 lnames.namelist_len = 1;
2125 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
2126 lids.idlist_len = 0;
2127 lids.idlist_val = NULL;
2129 cnamelen = strlen(acell);
2131 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2133 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2134 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2135 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2137 ("MapName: Name too long, using AnonymousID for %s@%s\n",
2139 *aval = AnonymousID;
2142 foreign = 1; /* attempt cross-cell authentication */
2143 tname = (char *)malloc(PR_MAXNAMELEN);
2145 ViceLog(0, ("Failed malloc in MapName_r\n"));
2148 strcpy(tname, aname);
2149 tname[anamelen] = '@';
2150 strcpy(tname + anamelen + 1, acell);
2151 lnames.namelist_val = (prname *) tname;
2156 code = hpr_NameToId(&lnames, &lids);
2159 if (lids.idlist_val) {
2160 *aval = lids.idlist_val[0];
2161 if (*aval == AnonymousID) {
2163 ("MapName: NameToId on %s returns anonymousID\n",
2164 lnames.namelist_val));
2166 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2169 ("MapName: NameToId on '%s' is unknown\n",
2170 lnames.namelist_val));
2176 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
2184 /* NOTE: this returns the client with a Write lock and a refCount */
2186 h_ID2Client(afs_int32 vid)
2188 register struct client *client;
2189 register struct host *host;
2192 for (host = hostList; host; host = host->next) {
2193 if (host->hostFlags & HOSTDELETED)
2195 for (client = host->FirstClient; client; client = client->next) {
2196 if (!client->deleted && client->ViceId == vid) {
2199 ObtainWriteLock(&client->lock);
2210 * Called by the server main loop. Returns a h_Held client, which must be
2211 * released later the main loop. Allocates a client if the matching one
2212 * isn't around. The client is returned with its reference count incremented
2213 * by one. The caller must call h_ReleaseClient_r when finished with
2216 * the client->host is returned held. h_ReleaseClient_r does not release
2217 * the hold on client->host.
2220 h_FindClient_r(struct rx_connection *tcon)
2222 register struct client *client;
2223 struct host *host = NULL;
2224 struct client *oldClient;
2225 afs_int32 viceid = 0;
2229 #if (64-MAXKTCNAMELEN)
2230 ticket name length != 64
2234 char uname[PR_MAXNAMELEN];
2235 char tcell[MAXKTCREALMLEN];
2239 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2240 if (client && client->sid == rxr_CidOf(tcon)
2241 && client->VenusEpoch == rxr_GetEpoch(tcon)) {
2243 h_Hold_r(client->host);
2244 if (!client->deleted && client->prfail != 2) {
2245 /* Could add shared lock on client here */
2246 /* note that we don't have to lock entry in this path to
2247 * ensure CPS is initialized, since we don't call rx_SetSpecific
2248 * until initialization is done, and we only get here if
2249 * rx_GetSpecific located the client structure.
2254 ObtainWriteLock(&client->lock); /* released at end */
2260 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2262 ("FindClient: authenticating connection: authClass=%d\n",
2264 if (authClass == 1) {
2265 /* A bcrypt tickets, no longer supported */
2266 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2267 viceid = AnonymousID;
2268 expTime = 0x7fffffff;
2269 } else if (authClass == 2) {
2272 /* kerberos ticket */
2273 code = rxkad_GetServerInfo(tcon, /*level */ 0, &expTime,
2274 tname, tinst, tcell, &kvno);
2276 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2277 viceid = AnonymousID;
2278 expTime = 0x7fffffff;
2280 int ilen = strlen(tinst);
2282 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2283 tname, tinst, tcell, expTime, kvno));
2284 strncpy(uname, tname, sizeof(uname));
2286 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2289 strcat(uname, tinst);
2291 /* translate the name to a vice id */
2292 code = MapName_r(uname, tcell, &viceid);
2296 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2299 viceid = AnonymousID;
2300 expTime = 0x7fffffff;
2304 viceid = AnonymousID; /* unknown security class */
2305 expTime = 0x7fffffff;
2308 if (!client) { /* loop */
2309 host = h_GetHost_r(tcon); /* Returns it h_Held */
2315 /* First try to find the client structure */
2316 for (client = host->FirstClient; client; client = client->next) {
2317 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2318 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2321 ObtainWriteLock(&client->lock);
2327 /* Still no client structure - get one */
2330 /* Retry to find the client structure */
2331 for (client = host->FirstClient; client; client = client->next) {
2332 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2333 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2335 goto retryfirstclient;
2340 ObtainWriteLock(&client->lock);
2341 client->refCount = 1;
2342 client->host = host;
2343 #if FS_STATS_DETAILED
2344 client->InSameNetwork = host->InSameNetwork;
2345 #endif /* FS_STATS_DETAILED */
2346 client->ViceId = viceid;
2347 client->expTime = expTime; /* rx only */
2348 client->authClass = authClass; /* rx only */
2349 client->sid = rxr_CidOf(tcon);
2350 client->VenusEpoch = rxr_GetEpoch(tcon);
2351 client->CPS.prlist_val = NULL;
2352 client->CPS.prlist_len = 0;
2356 client->prfail = fail;
2358 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2359 client->CPS.prlist_len = 0;
2360 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2361 free(client->CPS.prlist_val);
2362 client->CPS.prlist_val = NULL;
2363 client->ViceId = viceid;
2364 client->expTime = expTime;
2366 if (viceid == ANONYMOUSID) {
2367 client->CPS.prlist_len = AnonCPS.prlist_len;
2368 client->CPS.prlist_val = AnonCPS.prlist_val;
2371 code = hpr_GetCPS(viceid, &client->CPS);
2376 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2377 code, viceid, client->host,
2378 afs_inet_ntoa_r(client->host->host,hoststr),
2379 ntohs(client->host->port)));
2381 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2382 * all protection servers and reevaluates things if no
2383 * sync server or quorum is found we could still end up
2384 * with one of these errors. In such case we would like to
2385 * reevaluate the rpc call to find if there's cps for this
2386 * guy. We treat other errors (except network failures
2387 * ones - i.e. code < 0) as an indication that there is no
2388 * CPS for this host. Ideally we could like to deal this
2389 * problem the other way around (i.e. if code == NOCPS
2390 * ignore else retry next time) but the problem is that
2391 * there're other errors (i.e. EPERM) for which we don't
2392 * want to retry and we don't know the whole code list!
2394 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2398 /* the disabling of system:administrators is so iffy and has so many
2399 * possible failure modes that we will disable it again */
2400 /* Turn off System:Administrator for safety
2401 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2402 * assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2405 /* Now, tcon may already be set to a rock, since we blocked with no host
2406 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2407 * required). So, before setting the RPC's rock, we should disconnect
2408 * the RPC from the other client structure's rock.
2410 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2411 if (oldClient && oldClient != client && oldClient->sid == rxr_CidOf(tcon)
2412 && oldClient->VenusEpoch == rxr_GetEpoch(tcon)) {
2414 if (!oldClient->deleted) {
2415 /* if we didn't create it, it's not ours to put back */
2417 ViceLog(0, ("FindClient: stillborn client %x(%x); conn %x (host %s:%d) had client %x(%x)\n",
2418 client, client->sid, tcon,
2419 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2420 ntohs(rxr_PortOf(tcon)),
2421 oldClient, oldClient->sid));
2422 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2423 free(client->CPS.prlist_val);
2424 client->CPS.prlist_val = NULL;
2425 client->CPS.prlist_len = 0;
2427 /* We should perhaps check for 0 here */
2429 ReleaseWriteLock(&client->lock);
2434 oldClient->refCount++;
2436 ObtainWriteLock(&oldClient->lock);
2440 ViceLog(0, ("FindClient: deleted client %x(%x) already had conn %x (host %s:%d), stolen by client %x(%x)\n",
2441 oldClient, oldClient->sid, tcon,
2442 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2443 ntohs(rxr_PortOf(tcon)),
2444 client, client->sid));
2445 /* rx_SetSpecific will be done immediately below */
2448 /* Avoid chaining in more than once. */
2451 client->next = host->FirstClient;
2452 host->FirstClient = client;
2454 CurrentConnections++; /* increment number of connections */
2456 rx_SetSpecific(tcon, rxcon_client_key, client);
2457 ReleaseWriteLock(&client->lock);
2461 } /*h_FindClient_r */
2464 h_ReleaseClient_r(struct client *client)
2466 assert(client->refCount > 0);
2473 * Sigh: this one is used to get the client AGAIN within the individual
2474 * server routines. This does not bother h_Holding the host, since
2475 * this is assumed already have been done by the server main loop.
2476 * It does check tokens, since only the server routines can return the
2477 * VICETOKENDEAD error code
2480 GetClient(struct rx_connection *tcon, struct client **cp)
2482 register struct client *client;
2487 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2488 if (client == NULL) {
2490 ("GetClient: no client in conn %x (host %s:%d), VBUSYING\n",
2491 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2492 ntohs(rxr_PortOf(tcon))));
2496 if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2498 ("GetClient: tcon %x tcon sid %d client sid %d\n",
2499 tcon, rxr_CidOf(tcon), client->sid));
2503 if (client && client->LastCall > client->expTime && client->expTime) {
2505 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2506 afs_inet_ntoa_r(client->host->host, hoststr),
2507 ntohs(client->host->port), client->expTime));
2509 return VICETOKENDEAD;
2519 PutClient(struct client **cp)
2525 h_ReleaseClient_r(*cp);
2532 /* Client user name for short term use. Note that this is NOT inexpensive */
2534 h_UserName(struct client *client)
2536 static char User[PR_MAXNAMELEN + 1];
2540 lids.idlist_len = 1;
2541 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2542 if (!lids.idlist_val) {
2543 ViceLog(0, ("Failed malloc in h_UserName\n"));
2546 lnames.namelist_len = 0;
2547 lnames.namelist_val = (prname *) 0;
2548 lids.idlist_val[0] = client->ViceId;
2549 if (hpr_IdToName(&lids, &lnames)) {
2550 /* We need to free id we alloced above! */
2551 free(lids.idlist_val);
2552 return "*UNKNOWN USER NAME*";
2554 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2555 free(lids.idlist_val);
2556 free(lnames.namelist_val);
2565 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2566 CEs, CEBlocks, HTs, HTBlocks));
2572 h_PrintClient(register struct host *host, int held, void *rock)
2574 StreamHandle_t *file = (StreamHandle_t *)rock;
2575 register struct client *client;
2580 time_t LastCall, expTime;
2583 LastCall = host->LastCall;
2584 if (host->hostFlags & HOSTDELETED) {
2588 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2589 "Host %s:%d down = %d, LastCall %s",
2590 afs_inet_ntoa_r(host->host, hoststr),
2591 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2592 afs_ctime(&LastCall, tbuffer,
2594 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2595 for (client = host->FirstClient; client; client = client->next) {
2596 if (!client->deleted) {
2597 expTime = client->expTime;
2598 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2599 " user id=%d, name=%s, sl=%s till %s",
2600 client->ViceId, h_UserName(client),
2602 authClass ? "Authenticated" :
2603 "Not authenticated",
2605 authClass ? afs_ctime(&expTime, tbuffer,
2608 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2609 (void)afs_snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2610 client->CPS.prlist_len);
2611 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2612 if (client->CPS.prlist_val) {
2613 for (i = 0; i > client->CPS.prlist_len; i++) {
2614 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2615 client->CPS.prlist_val[i]);
2616 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2619 sprintf(tmpStr, "]\n");
2620 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2626 } /*h_PrintClient */
2631 * Print a list of clients, with last security level and token value seen,
2635 h_PrintClients(void)
2641 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2645 ("Couldn't create client dump file %s\n",
2646 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2649 now = FT_ApproxTime();
2650 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
2651 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2652 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2653 h_Enumerate(h_PrintClient, (char *)file);
2654 STREAM_REALLYCLOSE(file);
2655 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2662 h_DumpHost(register struct host *host, int held, void *rock)
2664 StreamHandle_t *file = (StreamHandle_t *)rock;
2671 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2672 "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u hcps [",
2673 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), host->index,
2674 host->cblist, CheckLock(&host->lock), host->LastCall,
2675 host->ActiveCall, (host->hostFlags & VENUSDOWN),
2676 host->hostFlags & HOSTDELETED, host->Console,
2677 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2679 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2680 if (host->hcps.prlist_val)
2681 for (i = 0; i < host->hcps.prlist_len; i++) {
2682 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2683 host->hcps.prlist_val[i]);
2684 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2686 sprintf(tmpStr, "] [");
2687 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2688 if (host->interface)
2689 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2691 sprintf(tmpStr, " %s:%d",
2692 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2693 ntohs(host->interface->interface[i].port));
2694 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2696 sprintf(tmpStr, "] holds: ");
2697 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2699 for (i = 0; i < h_maxSlots; i++) {
2700 sprintf(tmpStr, "%04x", host->holds[i]);
2701 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2703 sprintf(tmpStr, " slot/bit: %ld/%d\n", h_holdSlot(), h_holdbit());
2704 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2716 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2722 ("Couldn't create host dump file %s\n",
2723 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2726 now = FT_ApproxTime();
2727 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
2728 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2729 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2730 h_Enumerate(h_DumpHost, (char *)file);
2731 STREAM_REALLYCLOSE(file);
2732 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2736 #ifdef AFS_DEMAND_ATTACH_FS
2739 * host state serialization
2741 static int h_stateFillHeader(struct host_state_header * hdr);
2742 static int h_stateCheckHeader(struct host_state_header * hdr);
2743 static int h_stateAllocMap(struct fs_dump_state * state);
2744 static int h_stateSaveHost(register struct host * host, int held, struct fs_dump_state * state);
2745 static int h_stateRestoreHost(struct fs_dump_state * state);
2746 static int h_stateRestoreIndex(struct host * h, int held, struct fs_dump_state * state);
2747 static int h_stateVerifyHost(struct host * h, int held, struct fs_dump_state * state);
2748 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port);
2749 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2750 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2751 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2754 /* this procedure saves all host state to disk for fast startup */
2756 h_stateSave(struct fs_dump_state * state)
2758 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2761 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2763 /* invalidate host state header */
2764 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2766 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2767 sizeof(struct host_state_header))) {
2772 fs_stateIncEOF(state, sizeof(struct host_state_header));
2774 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2779 h_stateFillHeader(state->h_hdr);
2781 /* write the real header to disk */
2782 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2783 sizeof(struct host_state_header));
2790 * host state serialization
2792 * this procedure restores all host state from a disk for fast startup
2795 h_stateRestore(struct fs_dump_state * state)
2799 /* seek to the right position and read in the host state header */
2800 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2801 sizeof(struct host_state_header))) {
2806 /* check the validity of the header */
2807 if (h_stateCheckHeader(state->h_hdr)) {
2812 records = state->h_hdr->records;
2814 if (h_stateAllocMap(state)) {
2819 /* iterate over records restoring host state */
2820 for (i=0; i < records; i++) {
2821 if (h_stateRestoreHost(state) != 0) {
2832 h_stateRestoreIndices(struct fs_dump_state * state)
2834 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
2839 h_stateRestoreIndex(struct host * h, int held, struct fs_dump_state * state)
2841 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
2842 return H_ENUMERATE_BAIL(held);
2848 h_stateVerify(struct fs_dump_state * state)
2850 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
2855 h_stateVerifyHost(struct host * h, int held, struct fs_dump_state * state)
2860 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
2861 return H_ENUMERATE_BAIL(held);
2865 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
2866 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
2867 h->interface->interface[i].port)) {
2871 if (h_stateVerifyUuidHash(state, h)) {
2874 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port)) {
2878 if (cb_stateVerifyHCBList(state, h)) {
2887 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port)
2889 int ret = 0, found = 0;
2890 struct host *host = NULL;
2891 struct h_AddrHashChain *chain;
2892 int index = h_HashIndex(addr);
2896 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
2897 host = chain->hostPtr;
2899 afs_inet_ntoa_r(addr, tmp);
2900 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
2904 if ((chain->addr == addr) && (chain->port == port)) {
2906 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry points to different host struct (%d, %d)\n",
2907 h->index, host->index));
2908 state->flags.warnings_generated = 1;
2913 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
2914 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2915 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
2923 afs_inet_ntoa_r(addr, tmp);
2924 if (state->mode == FS_STATE_LOAD_MODE) {
2925 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s not found in hash\n", tmp));
2929 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s not found in hash\n", tmp));
2930 state->flags.warnings_generated = 1;
2939 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
2941 int ret = 0, found = 0;
2942 struct host *host = NULL;
2943 struct h_UuidHashChain *chain;
2944 afsUUID * uuidp = &h->interface->uuid;
2945 int index = h_UuidHashIndex(uuidp);
2949 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
2950 host = chain->hostPtr;
2952 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2953 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
2957 if (host->interface &&
2958 afs_uuid_equal(&host->interface->uuid, uuidp)) {
2960 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
2961 h->index, host->index));
2962 state->flags.warnings_generated = 1;
2967 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
2968 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2969 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
2977 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2978 if (state->mode == FS_STATE_LOAD_MODE) {
2979 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
2983 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
2984 state->flags.warnings_generated = 1;
2992 /* create the host state header structure */
2994 h_stateFillHeader(struct host_state_header * hdr)
2996 hdr->stamp.magic = HOST_STATE_MAGIC;
2997 hdr->stamp.version = HOST_STATE_VERSION;
3000 /* check the contents of the host state header structure */
3002 h_stateCheckHeader(struct host_state_header * hdr)
3006 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3007 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3010 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3011 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3017 /* allocate the host id mapping table */
3019 h_stateAllocMap(struct fs_dump_state * state)
3021 state->h_map.len = state->h_hdr->index_max + 1;
3022 state->h_map.entries = (struct idx_map_entry_t *)
3023 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3024 return (state->h_map.entries != NULL) ? 0 : 1;
3027 /* function called by h_Enumerate to save a host to disk */
3029 h_stateSaveHost(register struct host * host, int held, struct fs_dump_state * state)
3031 int i, if_len=0, hcps_len=0;
3032 struct hostDiskEntry hdsk;
3033 struct host_state_entry_header hdr;
3034 struct Interface * ifp = NULL;
3035 afs_int32 * hcps = NULL;
3036 struct iovec iov[4];
3039 memset(&hdr, 0, sizeof(hdr));
3041 if (state->h_hdr->index_max < host->index) {
3042 state->h_hdr->index_max = host->index;
3045 h_hostToDiskEntry_r(host, &hdsk);
3046 if (host->interface) {
3047 if_len = sizeof(struct Interface) +
3048 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3049 ifp = (struct Interface *) malloc(if_len);
3050 assert(ifp != NULL);
3051 memcpy(ifp, host->interface, if_len);
3052 hdr.interfaces = host->interface->numberOfInterfaces;
3053 iov[iovcnt].iov_base = (char *) ifp;
3054 iov[iovcnt].iov_len = if_len;
3057 if (host->hcps.prlist_val) {
3058 hdr.hcps = host->hcps.prlist_len;
3059 hcps_len = hdr.hcps * sizeof(afs_int32);
3060 hcps = (afs_int32 *) malloc(hcps_len);
3061 assert(hcps != NULL);
3062 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3063 iov[iovcnt].iov_base = (char *) hcps;
3064 iov[iovcnt].iov_len = hcps_len;
3068 if (hdsk.index > state->h_hdr->index_max)
3069 state->h_hdr->index_max = hdsk.index;
3071 hdr.len = sizeof(struct host_state_entry_header) +
3072 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3073 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3075 iov[0].iov_base = (char *) &hdr;
3076 iov[0].iov_len = sizeof(hdr);
3077 iov[1].iov_base = (char *) &hdsk;
3078 iov[1].iov_len = sizeof(struct hostDiskEntry);
3080 if (fs_stateWriteV(state, iov, iovcnt)) {
3081 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3085 fs_stateIncEOF(state, hdr.len);
3087 state->h_hdr->records++;
3095 return H_ENUMERATE_BAIL(held);
3100 /* restores a host from disk */
3102 h_stateRestoreHost(struct fs_dump_state * state)
3104 int ifp_len=0, hcps_len=0, bail=0;
3105 struct host_state_entry_header hdr;
3106 struct hostDiskEntry hdsk;
3107 struct host *host = NULL;
3108 struct Interface *ifp = NULL;
3109 afs_int32 * hcps = NULL;
3110 struct iovec iov[3];
3113 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3114 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3120 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3121 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3127 iov[0].iov_base = (char *) &hdsk;
3128 iov[0].iov_len = sizeof(struct hostDiskEntry);
3130 if (hdr.interfaces) {
3131 ifp_len = sizeof(struct Interface) +
3132 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3133 ifp = (struct Interface *) malloc(ifp_len);
3134 assert(ifp != NULL);
3135 iov[iovcnt].iov_base = (char *) ifp;
3136 iov[iovcnt].iov_len = ifp_len;
3140 hcps_len = hdr.hcps * sizeof(afs_int32);
3141 hcps = (afs_int32 *) malloc(hcps_len);
3142 assert(hcps != NULL);
3143 iov[iovcnt].iov_base = (char *) hcps;
3144 iov[iovcnt].iov_len = hcps_len;
3148 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3149 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3154 if (fs_stateReadV(state, iov, iovcnt)) {
3155 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3160 if (!hdr.hcps && hdsk.hcps_valid) {
3161 /* valid, zero-length host cps ; does this ever happen? */
3162 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3163 assert(hcps != NULL);
3167 assert(host != NULL);
3170 host->interface = ifp;
3173 host->hcps.prlist_val = hcps;
3174 host->hcps.prlist_len = hdr.hcps;
3177 h_diskEntryToHost_r(&hdsk, host);
3178 h_SetupCallbackConn_r(host);
3180 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3183 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3184 if (ifp->interface[i].valid &&
3185 !(ifp->interface[i].addr == host->host &&
3186 ifp->interface[i].port == host->port)) {
3187 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3188 ifp->interface[i].port,
3192 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3194 h_InsertList_r(host);
3196 /* setup host id map entry */
3197 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3198 state->h_map.entries[hdsk.index].new_idx = host->index;
3210 /* serialize a host structure to disk */
3212 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3214 out->host = in->host;
3215 out->port = in->port;
3216 out->hostFlags = in->hostFlags;
3217 out->Console = in->Console;
3218 out->hcpsfailed = in->hcpsfailed;
3219 out->LastCall = in->LastCall;
3220 out->ActiveCall = in->ActiveCall;
3221 out->cpsCall = in->cpsCall;
3222 out->cblist = in->cblist;
3223 #ifdef FS_STATS_DETAILED
3224 out->InSameNetwork = in->InSameNetwork;
3227 /* special fields we save, but are not memcpy'd back on restore */
3228 out->index = in->index;
3229 out->hcps_len = in->hcps.prlist_len;
3230 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3233 /* restore a host structure from disk */
3235 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3237 out->host = in->host;
3238 out->port = in->port;
3239 out->hostFlags = in->hostFlags;
3240 out->Console = in->Console;
3241 out->hcpsfailed = in->hcpsfailed;
3242 out->LastCall = in->LastCall;
3243 out->ActiveCall = in->ActiveCall;
3244 out->cpsCall = in->cpsCall;
3245 out->cblist = in->cblist;
3246 #ifdef FS_STATS_DETAILED
3247 out->InSameNetwork = in->InSameNetwork;
3251 /* index translation routines */
3253 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3257 /* hosts use a zero-based index, so old==0 is valid */
3259 if (old >= state->h_map.len) {
3260 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3262 } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
3263 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3266 *new = state->h_map.entries[old].new_idx;
3272 #endif /* AFS_DEMAND_ATTACH_FS */
3276 * This counts the number of workstations, the number of active workstations,
3277 * and the number of workstations declared "down" (i.e. not heard from
3278 * recently). An active workstation has received a call since the cutoff
3279 * time argument passed.
3282 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3284 register struct host *host;
3285 register int num = 0, active = 0, del = 0;
3288 for (host = hostList; host; host = host->next) {
3289 if (!(host->hostFlags & HOSTDELETED)) {
3291 if (host->ActiveCall > cutofftime)
3293 if (host->hostFlags & VENUSDOWN)
3305 } /*h_GetWorkStats */
3308 /*------------------------------------------------------------------------
3309 * PRIVATE h_ClassifyAddress
3312 * Given a target IP address and a candidate IP address (both
3313 * in host byte order), classify the candidate into one of three
3314 * buckets in relation to the target by bumping the counters passed
3318 * a_targetAddr : Target address.
3319 * a_candAddr : Candidate address.
3320 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3321 * addresses are either in the same network
3322 * or the same subnet.
3323 * a_diffSubnetP : ...when the candidate is in a different
3325 * a_diffNetworkP : ...when the candidate is in a different
3332 * The target and candidate addresses are both in host byte
3333 * order, NOT network byte order, when passed in.
3337 *------------------------------------------------------------------------*/
3340 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3341 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3342 afs_int32 * a_diffNetworkP)
3343 { /*h_ClassifyAddress */
3345 afs_uint32 targetNet;
3346 afs_uint32 targetSubnet;
3348 afs_uint32 candSubnet;
3351 * Put bad values into the subnet info to start with.
3353 targetSubnet = (afs_uint32) 0;
3354 candSubnet = (afs_uint32) 0;
3357 * Pull out the network and subnetwork numbers from the target
3358 * and candidate addresses. We can short-circuit this whole
3359 * affair if the target and candidate addresses are not of the
3362 if (IN_CLASSA(a_targetAddr)) {
3363 if (!(IN_CLASSA(a_candAddr))) {
3364 (*a_diffNetworkP)++;
3367 targetNet = a_targetAddr & IN_CLASSA_NET;
3368 candNet = a_candAddr & IN_CLASSA_NET;
3369 if (IN_SUBNETA(a_targetAddr))
3370 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3371 if (IN_SUBNETA(a_candAddr))
3372 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3373 } else if (IN_CLASSB(a_targetAddr)) {
3374 if (!(IN_CLASSB(a_candAddr))) {
3375 (*a_diffNetworkP)++;
3378 targetNet = a_targetAddr & IN_CLASSB_NET;
3379 candNet = a_candAddr & IN_CLASSB_NET;
3380 if (IN_SUBNETB(a_targetAddr))
3381 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3382 if (IN_SUBNETB(a_candAddr))
3383 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3384 } /*Class B target */
3385 else if (IN_CLASSC(a_targetAddr)) {
3386 if (!(IN_CLASSC(a_candAddr))) {
3387 (*a_diffNetworkP)++;
3390 targetNet = a_targetAddr & IN_CLASSC_NET;
3391 candNet = a_candAddr & IN_CLASSC_NET;
3394 * Note that class C addresses can't have subnets,
3395 * so we leave the defaults untouched.
3397 } /*Class C target */
3399 targetNet = a_targetAddr;
3400 candNet = a_candAddr;
3401 } /*Class D address */
3404 * Now, simply compare the extracted net and subnet values for
3405 * the two addresses (which at this point are known to be of the
3408 if (targetNet == candNet) {
3409 if (targetSubnet == candSubnet)
3410 (*a_sameNetOrSubnetP)++;
3414 (*a_diffNetworkP)++;
3416 } /*h_ClassifyAddress */
3419 /*------------------------------------------------------------------------
3420 * EXPORTED h_GetHostNetStats
3423 * Iterate through the host table, and classify each (non-deleted)
3424 * host entry into ``proximity'' categories (same net or subnet,
3425 * different subnet, different network).
3428 * a_numHostsP : Set to total number of (non-deleted) hosts.
3429 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3430 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3431 * a_diffNetworkP : Set to # hosts on diff network as server.
3437 * We only count non-deleted hosts. The storage pointed to by our
3438 * parameters is zeroed upon entry.
3442 *------------------------------------------------------------------------*/
3445 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3446 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3447 { /*h_GetHostNetStats */
3449 register struct host *hostP; /*Ptr to current host entry */
3450 register afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3453 * Clear out the storage pointed to by our parameters.
3455 *a_numHostsP = (afs_int32) 0;
3456 *a_sameNetOrSubnetP = (afs_int32) 0;
3457 *a_diffSubnetP = (afs_int32) 0;
3458 *a_diffNetworkP = (afs_int32) 0;
3461 for (hostP = hostList; hostP; hostP = hostP->next) {
3462 if (!(hostP->hostFlags & HOSTDELETED)) {
3464 * Bump the number of undeleted host entries found.
3465 * In classifying the current entry's address, make
3466 * sure to first convert to host byte order.
3469 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3470 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3471 a_sameNetOrSubnetP, a_diffSubnetP,
3473 } /*Only look at non-deleted hosts */
3474 } /*For each host record hashed to this index */
3476 } /*h_GetHostNetStats */
3478 static afs_uint32 checktime;
3479 static afs_uint32 clientdeletetime;
3480 static struct AFSFid zerofid;
3484 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3485 * Since it can serialize them, and pile up, it should be a separate LWP
3486 * from other events.
3490 CheckHost(register struct host *host, int held, void *rock)
3492 register struct client *client;
3493 struct rx_connection *cb_conn = NULL;
3496 #ifdef AFS_DEMAND_ATTACH_FS
3497 /* kill the checkhost lwp ASAP during shutdown */
3499 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3501 return H_ENUMERATE_BAIL(held);
3506 /* Host is held by h_Enumerate */
3508 for (client = host->FirstClient; client; client = client->next) {
3509 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3510 client->deleted = 1;
3511 host->hostFlags |= CLIENTDELETED;
3514 if (host->LastCall < checktime) {
3516 host->hostFlags |= HWHO_INPROGRESS;
3517 if (!(host->hostFlags & HOSTDELETED)) {
3518 cb_conn = host->callback_rxcon;
3519 rx_GetConnection(cb_conn);
3520 if (host->LastCall < clientdeletetime) {
3521 host->hostFlags |= HOSTDELETED;
3522 if (!(host->hostFlags & VENUSDOWN)) {
3523 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3524 if (host->interface) {
3527 RXAFSCB_InitCallBackState3(cb_conn,
3533 RXAFSCB_InitCallBackState(cb_conn);
3536 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3539 (void)afs_inet_ntoa_r(host->host, hoststr);
3541 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3542 hoststr, ntohs(host->port)));
3543 host->hostFlags |= VENUSDOWN;
3545 /* Note: it's safe to delete hosts even if they have call
3546 * back state, because break delayed callbacks (called when a
3547 * message is received from the workstation) will always send a
3548 * break all call backs to the workstation if there is no
3553 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3555 (void)afs_inet_ntoa_r(host->host, hoststr);
3556 if (host->interface) {
3557 afsUUID uuid = host->interface->uuid;
3559 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3562 if (MultiProbeAlternateAddress_r(host)) {
3563 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3564 hoststr, ntohs(host->port), code));
3565 host->hostFlags |= VENUSDOWN;
3570 code = RXAFSCB_Probe(cb_conn);
3574 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3575 hoststr, ntohs(host->port), code));
3576 host->hostFlags |= VENUSDOWN;
3582 rx_PutConnection(cb_conn);
3586 host->hostFlags &= ~HWHO_INPROGRESS;
3596 CheckHost_r(register struct host *host, int held, void *dummy)
3598 register struct client *client;
3599 struct rx_connection *cb_conn = NULL;
3602 #ifdef AFS_DEMAND_ATTACH_FS
3603 /* kill the checkhost lwp ASAP during shutdown */
3605 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3607 return H_ENUMERATE_BAIL(held);
3612 /* Host is held by h_Enumerate_r */
3613 for (client = host->FirstClient; client; client = client->next) {
3614 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3615 client->deleted = 1;
3616 host->hostFlags |= CLIENTDELETED;
3619 if (host->LastCall < checktime) {
3621 if (!(host->hostFlags & HOSTDELETED)) {
3622 cb_conn = host->callback_rxcon;
3623 rx_GetConnection(cb_conn);
3624 if (host->LastCall < clientdeletetime) {
3625 host->hostFlags |= HOSTDELETED;
3626 if (!(host->hostFlags & VENUSDOWN)) {
3627 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3628 if (host->interface) {
3631 RXAFSCB_InitCallBackState3(cb_conn,
3637 RXAFSCB_InitCallBackState(cb_conn);
3640 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3643 (void)afs_inet_ntoa_r(host->host, hoststr);
3645 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3646 hoststr, ntohs(host->port)));
3647 host->hostFlags |= VENUSDOWN;
3649 /* Note: it's safe to delete hosts even if they have call
3650 * back state, because break delayed callbacks (called when a
3651 * message is received from the workstation) will always send a
3652 * break all call backs to the workstation if there is no
3657 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3659 (void)afs_inet_ntoa_r(host->host, hoststr);
3660 if (host->interface) {
3661 afsUUID uuid = host->interface->uuid;
3663 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3666 if (MultiProbeAlternateAddress_r(host)) {
3667 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3668 hoststr, ntohs(host->port), code));
3669 host->hostFlags |= VENUSDOWN;
3674 code = RXAFSCB_Probe(cb_conn);
3678 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3679 hoststr, ntohs(host->port), code));
3680 host->hostFlags |= VENUSDOWN;
3686 rx_PutConnection(cb_conn);
3698 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3699 * don't respond to a probe. Note that VenusDown can only be cleared if
3700 * a message is received from the host (see ServerLWP in file.c).
3701 * Delete hosts that have not had any calls in 1 hour, clients that
3702 * have not had any calls in 15 minutes.
3704 * This routine is called roughly every 5 minutes.
3709 afs_uint32 now = FT_ApproxTime();
3711 memset((char *)&zerofid, 0, sizeof(zerofid));
3713 * Send a probe to the workstation if it hasn't been heard from in
3716 checktime = now - 15 * 60;
3717 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3720 h_Enumerate_r(CheckHost_r, hostList, NULL);
3725 * This is called with host locked and held. At this point, the
3726 * hostAddrHashTable has an entry for the primary addr/port inserted
3727 * by h_Alloc_r(). No other interfaces should be considered valid.
3729 * The addresses in the interfaceAddr list are in host byte order.
3732 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3739 struct Interface *interface;
3742 afs_uint16 port7001 = htons(7001);
3747 number = interf->numberOfInterfaces;
3748 myAddr = host->host; /* current interface address */
3749 myPort = host->port; /* current port */
3752 ("initInterfaceAddr : host %s:%d numAddr %d\n",
3753 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3755 /* validation checks */
3756 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3758 ("Invalid number of alternate addresses is %d\n", number));
3763 * The client's notion of its own IP addresses is not reliable.
3765 * 1. The client list might contain private address ranges which
3766 * are likely to be re-used by many clients allocated addresses
3769 * 2. The client list will not include any public addresses that
3770 * are hidden by a NAT.
3772 * 3. Private address ranges that are exposed to the server will
3773 * be obtained from the rx connections that use them.
3775 * 4. Lists provided by the client are not necessarily truthful.
3776 * Many existing clients (UNIX) do not refresh the IP address
3777 * list as the actual assigned addresses change. The end result
3778 * is that they report the initial address list for the lifetime
3779 * of the process. In other words, a client can report addresses
3780 * that they are in fact not using. Adding these addresses to
3781 * the host interface list without verification is not only
3782 * pointless, it is downright dangerous.
3784 * We therefore do not add alternate addresses to the addr hash table.
3785 * We only use them for multi-rx callback breaks.
3789 * Convert IP addresses to network byte order, and remove
3790 * duplicate IP addresses from the interface list, and
3791 * determine whether or not the incoming addr/port is
3792 * listed. Note that if the address matches it is not
3793 * truly a match because the port number for the entries
3794 * in the interface list are port 7001 and the port number
3795 * for this connection might not be 7001.
3797 for (i = 0, count = 0, found = 0; i < number; i++) {
3798 interf->addr_in[i] = htonl(interf->addr_in[i]);
3799 for (j = 0; j < count; j++) {
3800 if (interf->addr_in[j] == interf->addr_in[i])
3804 interf->addr_in[count] = interf->addr_in[i];
3805 if (interf->addr_in[count] == myAddr &&
3813 * Allocate and initialize an interface structure for this host.
3816 interface = (struct Interface *)
3817 malloc(sizeof(struct Interface) +
3818 (sizeof(struct AddrPort) * (count - 1)));
3820 ViceLog(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
3823 interface->numberOfInterfaces = count;
3825 interface = (struct Interface *)
3826 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
3828 ViceLog(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
3831 interface->numberOfInterfaces = count + 1;
3832 interface->interface[count].addr = myAddr;
3833 interface->interface[count].port = myPort;
3834 interface->interface[count].valid = 1;
3837 for (i = 0; i < count; i++) {
3839 interface->interface[i].addr = interf->addr_in[i];
3840 /* We store the port as 7001 because the addresses reported by
3841 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
3842 * are coming from fully connected hosts (no NAT/PATs)
3844 interface->interface[i].port = port7001;
3845 interface->interface[i].valid =
3846 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
3849 interface->uuid = interf->uuid;
3851 assert(!host->interface);
3852 host->interface = interface;
3854 if (LogLevel >= 125) {
3855 afsUUID_to_string(&interface->uuid, uuidstr, 127);
3857 ViceLog(125, ("--- uuid %s\n", uuidstr));
3858 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
3859 ViceLog(125, ("--- alt address %s:%d\n",
3860 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3861 ntohs(host->interface->interface[i].port)));
3868 /* deleted a HashChain structure for this address and host */
3869 /* returns 1 on success */
3871 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
3875 register struct h_AddrHashChain **hp, *th;
3877 if (addr == 0 && port == 0)
3880 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
3882 assert(th->hostPtr);
3883 if (th->hostPtr == host && th->addr == addr && th->port == port) {
3884 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
3885 host, afs_inet_ntoa_r(host->host, hoststr),
3886 ntohs(host->port)));
3893 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
3894 host, afs_inet_ntoa_r(host->host, hoststr),
3895 ntohs(host->port)));
3901 ** prints out all alternate interface address for the host. The 'level'
3902 ** parameter indicates what level of debugging sets this output
3905 printInterfaceAddr(struct host *host, int level)
3910 if (host->interface) {
3911 /* check alternate addresses */
3912 number = host->interface->numberOfInterfaces;
3914 ViceLog(level, ("no-addresses "));
3916 for (i = 0; i < number; i++)
3917 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3918 ntohs(host->interface->interface[i].port)));
3921 ViceLog(level, ("\n"));