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 #define FSINT_COMMON_XG
35 #include <afs/afscbint.h>
36 #include <afs/rxgen_consts.h>
38 #include <afs/errors.h>
39 #include <afs/ihandle.h>
40 #include <afs/vnode.h>
41 #include <afs/volume.h>
42 #ifdef AFS_ATHENA_STDENV
46 #include <afs/ptclient.h>
47 #include <afs/ptuser.h>
48 #include <afs/prs_fs.h>
50 #include <afs/afsutil.h>
51 #include <afs/com_err.h>
53 #include <afs/cellconfig.h>
55 #include "viced_prototypes.h"
59 #ifdef AFS_DEMAND_ATTACH_FS
60 #include "../util/afsutil_prototypes.h"
61 #include "../tviced/serialize_state.h"
62 #endif /* AFS_DEMAND_ATTACH_FS */
64 #ifdef AFS_PTHREAD_ENV
65 pthread_mutex_t host_glock_mutex;
66 #endif /* AFS_PTHREAD_ENV */
69 extern int CurrentConnections;
71 extern int AnonymousID;
72 extern prlist AnonCPS;
74 extern struct afsconf_dir *confDir; /* config dir object */
75 extern int lwps; /* the max number of server threads */
76 extern afsUUID FS_HostUUID;
79 int CEs = 0; /* active clients */
80 int CEBlocks = 0; /* number of blocks of CEs */
81 struct client *CEFree = 0; /* first free client */
82 struct host *hostList = 0; /* linked list of all hosts */
83 int hostCount = 0; /* number of hosts in hostList */
87 static struct rx_securityClass *sc = NULL;
89 static void h_SetupCallbackConn_r(struct host * host);
90 static int h_threadquota(int);
92 #define CESPERBLOCK 73
93 struct CEBlock { /* block of CESPERBLOCK file entries */
94 struct client entry[CESPERBLOCK];
97 static void h_TossStuff_r(register struct host *host);
100 * Make sure the subnet macros have been defined.
103 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
106 #ifndef IN_CLASSA_SUBNET
107 #define IN_CLASSA_SUBNET 0xffff0000
111 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
114 #ifndef IN_CLASSB_SUBNET
115 #define IN_CLASSB_SUBNET 0xffffff00
119 /* get a new block of CEs and chain it on CEFree */
123 register struct CEBlock *block;
126 block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
128 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
129 ShutDownAndCore(PANIC);
132 for (i = 0; i < (CESPERBLOCK - 1); i++) {
133 Lock_Init(&block->entry[i].lock);
134 block->entry[i].next = &(block->entry[i + 1]);
136 block->entry[CESPERBLOCK - 1].next = 0;
137 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
138 CEFree = (struct client *)block;
144 /* get the next available CE */
145 static struct client *
148 register struct client *entry;
153 ViceLog(0, ("CEFree NULL in GetCE\n"));
154 ShutDownAndCore(PANIC);
158 CEFree = entry->next;
160 memset(entry, 0, CLIENT_TO_ZERO(entry));
166 /* return an entry to the free list */
168 FreeCE(register struct client *entry)
170 entry->VenusEpoch = 0;
172 entry->next = CEFree;
179 * The HTs and HTBlocks variables were formerly static, but they are
180 * now referenced elsewhere in the FileServer.
182 int HTs = 0; /* active file entries */
183 int HTBlocks = 0; /* number of blocks of HTs */
184 static struct host *HTFree = 0; /* first free file entry */
187 * Hash tables of host pointers. We need two tables, one
188 * to map IP addresses onto host pointers, and another
189 * to map host UUIDs onto host pointers.
191 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
192 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
193 #define h_HashIndex(hostip) (ntohl(hostip) & (h_HASHENTRIES-1))
194 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
196 struct HTBlock { /* block of HTSPERBLOCK file entries */
197 struct host entry[h_HTSPERBLOCK];
201 /* get a new block of HTs and chain it on HTFree */
205 register struct HTBlock *block;
207 static int index = 0;
209 if (HTBlocks == h_MAXHOSTTABLES) {
210 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
211 ShutDownAndCore(PANIC);
214 block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
216 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
217 ShutDownAndCore(PANIC);
219 #ifdef AFS_PTHREAD_ENV
220 for (i = 0; i < (h_HTSPERBLOCK); i++)
221 assert(pthread_cond_init(&block->entry[i].cond, NULL) == 0);
222 #endif /* AFS_PTHREAD_ENV */
223 for (i = 0; i < (h_HTSPERBLOCK); i++)
224 Lock_Init(&block->entry[i].lock);
225 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
226 block->entry[i].next = &(block->entry[i + 1]);
227 for (i = 0; i < (h_HTSPERBLOCK); i++)
228 block->entry[i].index = index++;
229 block->entry[h_HTSPERBLOCK - 1].next = 0;
230 HTFree = (struct host *)block;
231 hosttableptrs[HTBlocks++] = block->entry;
236 /* get the next available HT */
240 register struct host *entry;
244 assert(HTFree != NULL);
246 HTFree = entry->next;
248 memset(entry, 0, HOST_TO_ZERO(entry));
254 /* return an entry to the free list */
256 FreeHT(register struct host *entry)
258 entry->next = HTFree;
265 hpr_Initialize(struct ubik_client **uclient)
268 struct rx_connection *serverconns[MAXSERVERS];
269 struct rx_securityClass *sc[3];
270 struct afsconf_dir *tdir;
271 struct ktc_token ttoken;
273 struct afsconf_cell info;
277 tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
279 ViceLog(0, ("hpr_Initialize: Could not open configuration directory: %s", AFSDIR_SERVER_ETC_DIRPATH));
283 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
285 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
290 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
292 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s", cellstr, confDir, AFSDIR_CELLSERVDB_FILE));
299 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
308 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
309 * to force use of the KeyFile. secLevel == 0 implies -noauth was
311 if ((afsconf_GetLatestKey(tdir, 0, 0) == 0)) {
312 code = afsconf_ClientAuthSecure(tdir, &sc[2], &scIndex);
314 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s (so trying noauth)", code, afs_error_message(code)));
316 scIndex = 0; /* use noauth */
318 /* if there was a problem, an unauthenticated conn is returned */
321 struct ktc_principal sname;
322 strcpy(sname.cell, info.name);
323 sname.instance[0] = 0;
324 strcpy(sname.name, "afs");
325 code = ktc_GetToken(&sname, &ttoken, sizeof(ttoken), NULL);
329 if (ttoken.kvno >= 0 && ttoken.kvno <= 256)
330 /* this is a kerberos ticket, set scIndex accordingly */
333 ViceLog(0, ("hpr_Initialize: funny kvno (%d) in ticket, proceeding", ttoken.kvno));
337 rxkad_NewClientSecurityObject(rxkad_clear, &ttoken.sessionKey,
338 ttoken.kvno, ttoken.ticketLen,
342 if ((scIndex == 0) && (sc[0] == 0))
343 sc[0] = rxnull_NewClientSecurityObject();
345 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, running unauthenticated. [%d]", code));
347 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
348 for (i = 0; i < info.numServers; i++) {
350 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
351 info.hostAddr[i].sin_port, PRSRV, sc[scIndex],
355 code = ubik_ClientInit(serverconns, uclient);
357 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
360 code = rxs_Release(sc[scIndex]);
365 hpr_End(struct ubik_client *uclient)
370 code = ubik_ClientDestroy(uclient);
376 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
378 #ifdef AFS_PTHREAD_ENV
379 register afs_int32 code;
381 struct ubik_client *uclient =
382 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
385 code = hpr_Initialize(&uclient);
387 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
393 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
394 if (code != PRSUCCESS)
397 /* do something about this, probably make a new call */
398 /* don't forget there's a hard limit in the interface */
400 "membership list for host id %d exceeds display limit\n",
405 return pr_GetHostCPS(host, CPS);
410 hpr_NameToId(namelist *names, idlist *ids)
412 #ifdef AFS_PTHREAD_ENV
413 register afs_int32 code;
414 register afs_int32 i;
415 struct ubik_client *uclient =
416 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
419 code = hpr_Initialize(&uclient);
421 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
426 for (i = 0; i < names->namelist_len; i++)
427 stolower(names->namelist_val[i]);
428 code = ubik_PR_NameToID(uclient, 0, names, ids);
431 return pr_NameToId(names, ids);
436 hpr_IdToName(idlist *ids, namelist *names)
438 #ifdef AFS_PTHREAD_ENV
439 register afs_int32 code;
440 struct ubik_client *uclient =
441 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
444 code = hpr_Initialize(&uclient);
446 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
451 code = ubik_PR_IDToName(uclient, 0, ids, names);
454 return pr_IdToName(ids, names);
459 hpr_GetCPS(afs_int32 id, prlist *CPS)
461 #ifdef AFS_PTHREAD_ENV
462 register afs_int32 code;
464 struct ubik_client *uclient =
465 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
468 code = hpr_Initialize(&uclient);
470 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
476 code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
477 if (code != PRSUCCESS)
480 /* do something about this, probably make a new call */
481 /* don't forget there's a hard limit in the interface */
482 fprintf(stderr, "membership list for id %d exceeds display limit\n",
487 return pr_GetCPS(id, CPS);
491 static short consolePort = 0;
494 h_Release(register struct host *host)
503 * If this thread does not have a hold on this host AND
504 * if other threads also dont have any holds on this host AND
505 * If either the HOSTDELETED or CLIENTDELETED flags are set
509 h_Release_r(register struct host *host)
512 if (!((host)->holds[h_holdSlot()] & ~h_holdbit())) {
513 if (!h_OtherHolds_r(host)) {
514 /* must avoid masking this until after h_OtherHolds_r runs
515 * but it should be run before h_TossStuff_r */
516 (host)->holds[h_holdSlot()] &= ~h_holdbit();
517 if ((host->hostFlags & HOSTDELETED)
518 || (host->hostFlags & CLIENTDELETED)) {
522 (host)->holds[h_holdSlot()] &= ~h_holdbit();
524 (host)->holds[h_holdSlot()] &= ~h_holdbit();
530 h_OtherHolds_r(register struct host *host)
532 register int i, bit, slot;
535 for (i = 0; i < h_maxSlots; i++) {
536 if (host->holds[i] != ((i == slot) ? bit : 0)) {
544 h_Lock_r(register struct host *host)
554 * returns 1 if already locked
555 * else returns locks and returns 0
559 h_NBLock_r(register struct host *host)
561 struct Lock *hostLock = &host->lock;
566 if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
567 hostLock->excl_locked = WRITE_LOCK;
571 LOCK_UNLOCK(hostLock);
580 #if FS_STATS_DETAILED
581 /*------------------------------------------------------------------------
582 * PRIVATE h_AddrInSameNetwork
585 * Given a target IP address and a candidate IP address (both
586 * in host byte order), return a non-zero value (1) if the
587 * candidate address is in a different network from the target
591 * a_targetAddr : Target address.
592 * a_candAddr : Candidate address.
595 * 1 if the candidate address is in the same net as the target,
599 * The target and candidate addresses are both in host byte
600 * order, NOT network byte order, when passed in. We return
601 * our value as a character, since that's the type of field in
602 * the host structure, where this info will be stored.
606 *------------------------------------------------------------------------*/
609 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
610 { /*h_AddrInSameNetwork */
612 afs_uint32 targetNet;
616 * Pull out the network and subnetwork numbers from the target
617 * and candidate addresses. We can short-circuit this whole
618 * affair if the target and candidate addresses are not of the
621 if (IN_CLASSA(a_targetAddr)) {
622 if (!(IN_CLASSA(a_candAddr))) {
625 targetNet = a_targetAddr & IN_CLASSA_NET;
626 candNet = a_candAddr & IN_CLASSA_NET;
627 } else if (IN_CLASSB(a_targetAddr)) {
628 if (!(IN_CLASSB(a_candAddr))) {
631 targetNet = a_targetAddr & IN_CLASSB_NET;
632 candNet = a_candAddr & IN_CLASSB_NET;
633 } /*Class B target */
634 else if (IN_CLASSC(a_targetAddr)) {
635 if (!(IN_CLASSC(a_candAddr))) {
638 targetNet = a_targetAddr & IN_CLASSC_NET;
639 candNet = a_candAddr & IN_CLASSC_NET;
640 } /*Class C target */
642 targetNet = a_targetAddr;
643 candNet = a_candAddr;
644 } /*Class D address */
647 * Now, simply compare the extracted net values for the two addresses
648 * (which at this point are known to be of the same class)
650 if (targetNet == candNet)
655 } /*h_AddrInSameNetwork */
656 #endif /* FS_STATS_DETAILED */
659 /* Assumptions: called with held host */
661 h_gethostcps_r(register struct host *host, register afs_int32 now)
666 /* wait if somebody else is already doing the getCPS call */
667 while (host->hostFlags & HCPS_INPROGRESS) {
668 slept = 1; /* I did sleep */
669 host->hostFlags |= HCPS_WAITING; /* I am sleeping now */
670 #ifdef AFS_PTHREAD_ENV
671 pthread_cond_wait(&host->cond, &host_glock_mutex);
672 #else /* AFS_PTHREAD_ENV */
673 if ((code = LWP_WaitProcess(&(host->hostFlags))) != LWP_SUCCESS)
674 ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
675 #endif /* AFS_PTHREAD_ENV */
679 host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
680 if (host->hcps.prlist_val)
681 free(host->hcps.prlist_val); /* this is for hostaclRefresh */
682 host->hcps.prlist_val = NULL;
683 host->hcps.prlist_len = 0;
684 host->cpsCall = slept ? (FT_ApproxTime()) : (now);
687 code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
692 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
693 * and reevaluates things if no sync server or quorum is found we could still end up
694 * with one of these errors. In such case we would like to reevaluate the rpc call to
695 * find if there's cps for this guy. We treat other errors (except network failures
696 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
697 * we could like to deal this problem the other way around (i.e. if code == NOCPS
698 * ignore else retry next time) but the problem is that there're other errors (i.e.
699 * EPERM) for which we don't want to retry and we don't know the whole code list!
701 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
703 * We would have preferred to use a while loop and try again since ops in protected
704 * acls for this host will fail now but they'll be reevaluated on any subsequent
705 * call. The attempt to wait for a quorum/sync site or network error won't work
706 * since this problems really should only occurs during a complete fileserver
707 * restart. Since the fileserver will start before the ptservers (and thus before
708 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
710 host->hcpsfailed = 1;
712 ("Warning: GetHostCPS failed (%d) for %x (%s:%d); will retry\n",
713 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
715 host->hcpsfailed = 0;
717 ("gethost: GetHostCPS failed (%d) for %x (%s:%d); ignored\n",
718 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
720 if (host->hcps.prlist_val)
721 free(host->hcps.prlist_val);
722 host->hcps.prlist_val = NULL;
723 host->hcps.prlist_len = 0; /* Make sure it's zero */
725 host->hcpsfailed = 0;
727 host->hostFlags &= ~HCPS_INPROGRESS;
728 /* signal all who are waiting */
729 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
730 host->hostFlags &= ~HCPS_WAITING;
731 #ifdef AFS_PTHREAD_ENV
732 assert(pthread_cond_broadcast(&host->cond) == 0);
733 #else /* AFS_PTHREAD_ENV */
734 if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
735 ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
736 #endif /* AFS_PTHREAD_ENV */
740 /* args in net byte order */
742 h_flushhostcps(register afs_uint32 hostaddr, register afs_uint16 hport)
748 h_Lookup_r(hostaddr, hport, &held, &host);
750 host->hcpsfailed = 1;
760 * Allocate a host. It will be identified by the peer (ip,port) info in the
761 * rx connection provided. The host is returned held and locked
763 #define DEF_ROPCONS 2115
766 h_Alloc_r(register struct rx_connection *r_con)
768 struct servent *serverentry;
771 #if FS_STATS_DETAILED
772 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
773 #endif /* FS_STATS_DETAILED */
777 host->host = rxr_HostOf(r_con);
778 host->port = rxr_PortOf(r_con);
780 h_AddHostToAddrHashTable_r(host->host, host->port, host);
782 if (consolePort == 0) { /* find the portal number for console */
783 #if defined(AFS_OSF_ENV)
784 serverentry = getservbyname("ropcons", "");
786 serverentry = getservbyname("ropcons", 0);
789 consolePort = serverentry->s_port;
791 consolePort = htons(DEF_ROPCONS); /* Use a default */
793 if (host->port == consolePort)
795 /* Make a callback channel even for the console, on the off chance that it
796 * makes a request that causes a break call back. It shouldn't. */
797 h_SetupCallbackConn_r(host);
798 now = host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
800 host->hcps.prlist_val = NULL;
801 host->hcps.prlist_len = 0;
802 host->interface = NULL;
804 host->hcpsfailed = 0; /* save cycles */
805 h_gethostcps(host); /* do this under host hold/lock */
807 host->FirstClient = NULL;
810 h_InsertList_r(host); /* update global host List */
811 #if FS_STATS_DETAILED
813 * Compare the new host's IP address (in host byte order) with ours
814 * (the File Server's), remembering if they are in the same network.
816 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
817 host->InSameNetwork =
818 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
819 #endif /* FS_STATS_DETAILED */
826 /* Make a callback channel even for the console, on the off chance that it
827 * makes a request that causes a break call back. It shouldn't. */
829 h_SetupCallbackConn_r(struct host * host)
832 sc = rxnull_NewClientSecurityObject();
833 host->callback_rxcon =
834 rx_NewConnection(host->host, host->port, 1, sc, 0);
835 rx_SetConnDeadTime(host->callback_rxcon, 50);
836 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
839 /* Lookup a host given an IP address and UDP port number. */
840 /* hostaddr and hport are in network order */
841 /* Note: host should be released by caller if 0 == *heldp and non-null */
842 /* hostaddr and hport are in network order */
844 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, int *heldp, struct host **hostp)
847 struct host *host = NULL;
848 struct h_AddrHashChain *chain;
849 int index = h_HashIndex(haddr);
850 extern int hostaclRefresh;
853 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
854 host = chain->hostPtr;
856 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
857 && chain->port == hport) {
858 if ((host->hostFlags & HWHO_INPROGRESS) &&
859 h_threadquota(host->lock.num_waiting)) {
863 *heldp = h_Held_r(host);
867 if (host->hostFlags & HOSTDELETED) {
874 now = FT_ApproxTime(); /* always evaluate "now" */
875 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
877 * Every hostaclRefresh period (def 2 hrs) get the new
878 * membership list for the host. Note this could be the
879 * first time that the host is added to a group. Also
880 * here we also retry on previous legitimate hcps failures.
882 * If we get here we still have a host hold.
884 h_gethostcps_r(host, now);
894 /* Lookup a host given its UUID. */
896 h_LookupUuid_r(afsUUID * uuidp)
898 struct host *host = 0;
899 struct h_UuidHashChain *chain;
900 int index = h_UuidHashIndex(uuidp);
902 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
903 host = chain->hostPtr;
905 if (!(host->hostFlags & HOSTDELETED) && host->interface
906 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
915 * h_Hold_r: Establish a hold by the current LWP on this host--the host
916 * or its clients will not be physically deleted until all holds have
918 * NOTE: h_Hold_r is a macro defined in host.h.
921 /* h_TossStuff_r: Toss anything in the host structure (the host or
922 * clients marked for deletion. Called from h_Release_r ONLY.
923 * To be called, there must be no holds, and either host->deleted
924 * or host->clientDeleted must be set.
927 h_TossStuff_r(register struct host *host)
929 register struct client **cp, *client;
932 /* if somebody still has this host held */
933 for (i = 0; (i < h_maxSlots) && (!(host)->holds[i]); i++);
937 /* if somebody still has this host locked */
938 if (h_NBLock_r(host) != 0) {
941 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was locked.\n",
942 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
948 /* ASSUMPTION: rxi_FreeConnection() does not yield */
949 for (cp = &host->FirstClient; (client = *cp);) {
950 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
952 ObtainWriteLockNoBlock(&client->lock, code);
956 ("Warning: h_TossStuff_r failed: Host %" AFS_PTR_FMT " (%s:%d) client %x was locked.\n",
957 host, afs_inet_ntoa_r(host->host, hoststr),
958 ntohs(host->port), client));
962 if (client->refCount) {
965 ("Warning: h_TossStuff_r failed: Host %" AFS_PTR_FMT " (%s:%d) client %x refcount %d.\n",
966 host, afs_inet_ntoa_r(host->host, hoststr),
967 ntohs(host->port), client, client->refCount));
968 /* This is the same thing we do if the host is locked */
969 ReleaseWriteLock(&client->lock);
972 client->CPS.prlist_len = 0;
973 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
974 free(client->CPS.prlist_val);
975 client->CPS.prlist_val = NULL;
976 CurrentConnections--;
978 ReleaseWriteLock(&client->lock);
984 /* We've just cleaned out all the deleted clients; clear the flag */
985 host->hostFlags &= ~CLIENTDELETED;
987 if (host->hostFlags & HOSTDELETED) {
988 register struct rx_connection *rxconn;
989 struct AddrPort hostAddrPort;
992 if (host->Console & 1)
994 if ((rxconn = host->callback_rxcon)) {
995 host->callback_rxcon = (struct rx_connection *)0;
996 rx_DestroyConnection(rxconn);
998 if (host->hcps.prlist_val)
999 free(host->hcps.prlist_val);
1000 host->hcps.prlist_val = NULL;
1001 host->hcps.prlist_len = 0;
1002 DeleteAllCallBacks_r(host, 1);
1003 host->hostFlags &= ~RESETDONE; /* just to be safe */
1005 /* if alternate addresses do not exist */
1006 if (!(host->interface)) {
1007 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
1009 h_DeleteHostFromUuidHashTable_r(host);
1010 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
1011 /* delete the hash entry for each valid alternate addresses */
1012 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
1013 hostAddrPort = host->interface->interface[i];
1015 * if the interface addr/port is the primary, we already
1016 * removed it. If the addr/port is not valid, its not
1017 * in the hash table.
1019 if (hostAddrPort.valid &&
1020 (host->host != hostAddrPort.addr ||
1021 host->port != hostAddrPort.port))
1022 h_DeleteHostFromAddrHashTable_r(hostAddrPort.addr, hostAddrPort.port, host);
1024 free(host->interface);
1025 host->interface = NULL;
1026 } /* if alternate address exists */
1028 h_DeleteList_r(host); /* remove host from global host List */
1031 } /*h_TossStuff_r */
1034 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
1035 * system at the start of the enumeration (perhaps more). Hosts may be deleted
1036 * (have delete flag set); ditto for clients. (*proc) is always called with
1037 * host h_held(). The hold state of the host with respect to this lwp is passed
1038 * to (*proc) as the param held. The proc should return 0 if the host should be
1039 * released, 1 if it should be held after enumeration.
1042 h_Enumerate(int (*proc) (struct host*, int, void *), void *param)
1044 register struct host *host, **list;
1046 register int i, count;
1049 if (hostCount == 0) {
1053 list = (struct host **)malloc(hostCount * sizeof(struct host *));
1055 ViceLog(0, ("Failed malloc in h_Enumerate\n"));
1058 held = (int *)malloc(hostCount * sizeof(int));
1060 ViceLog(0, ("Failed malloc in h_Enumerate\n"));
1063 for (count = 0, host = hostList; host; host = host->next, count++) {
1065 if (!(held[count] = h_Held_r(host)))
1068 if (count != hostCount) {
1069 ViceLog(0, ("h_Enumerate found %d of %d hosts\n", count, hostCount));
1071 assert(count <= hostCount);
1073 for (i = 0; i < count; i++) {
1074 held[i] = (*proc) (list[i], held[i], param);
1075 if (!H_ENUMERATE_ISSET_HELD(held[i]))
1076 h_Release(list[i]); /* this might free up the host */
1077 /* bail out of the enumeration early */
1078 if (H_ENUMERATE_ISSET_BAIL(held[i]))
1085 /* h_Enumerate_r (revised):
1086 * Calls (*proc)(host, held, param) for each host in hostList, starting
1088 * Hosts may be deleted (have delete flag set); ditto for clients.
1089 * (*proc) is always called with
1090 * host h_held() and the global host lock (H_LOCK) locked.The hold state of the
1091 * host with respect to this lwp is passed to (*proc) as the param held.
1092 * The proc should return 0 if the host should be released, 1 if it should
1093 * be held after enumeration.
1096 h_Enumerate_r(int (*proc) (struct host *, int, void *),
1097 struct host *enumstart, void *param)
1099 register struct host *host, *next;
1103 if (hostCount == 0) {
1106 if (enumstart && !(held = h_Held_r(enumstart)))
1107 h_Hold_r(enumstart);
1108 for (host = enumstart; host; host = next, held = nheld) {
1110 if (next && !(nheld = h_Held_r(next)) && !H_ENUMERATE_ISSET_BAIL(held))
1112 held = (*proc) (host, held, param);
1113 if (!H_ENUMERATE_ISSET_HELD(held))
1114 h_Release_r(host); /* this might free up the host */
1115 if (H_ENUMERATE_ISSET_BAIL(held)) {
1116 if (!H_ENUMERATE_ISSET_HELD(nheld))
1117 h_Release_r(next); /* this might free up the host */
1121 } /*h_Enumerate_r */
1123 /* inserts a new HashChain structure corresponding to this UUID */
1125 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1128 struct h_UuidHashChain *chain;
1129 char uuid1[128], uuid2[128];
1132 /* hash into proper bucket */
1133 index = h_UuidHashIndex(uuid);
1135 /* don't add the same entry multiple times */
1136 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1137 if (!chain->hostPtr)
1140 if (chain->hostPtr->interface &&
1141 afs_uuid_equal(&chain->hostPtr->interface->uuid, uuid)) {
1142 if (LogLevel >= 125) {
1143 afsUUID_to_string(&chain->hostPtr->interface->uuid, uuid1,
1145 afsUUID_to_string(uuid, uuid2, 127);
1146 ViceLog(125, ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s) exists as %s:%d (uuid %s)\n",
1148 afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1149 ntohs(chain->hostPtr->port), uuid2));
1155 /* insert into beginning of list for this bucket */
1156 chain = (struct h_UuidHashChain *)malloc(sizeof(struct h_UuidHashChain));
1158 ViceLog(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1161 chain->hostPtr = host;
1162 chain->next = hostUuidHashTable[index];
1163 hostUuidHashTable[index] = chain;
1166 afsUUID_to_string(uuid, uuid2, 127);
1168 ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (%s:%d) added as uuid %s\n",
1169 host, afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1170 ntohs(chain->hostPtr->port), uuid));
1173 /* deletes a HashChain structure corresponding to this host */
1175 h_DeleteHostFromUuidHashTable_r(struct host *host)
1178 register struct h_UuidHashChain **uhp, *uth;
1182 if (!host->interface)
1185 /* hash into proper bucket */
1186 index = h_UuidHashIndex(&host->interface->uuid);
1188 if (LogLevel >= 125)
1189 afsUUID_to_string(&host->interface->uuid, uuid1, 127);
1190 for (uhp = &hostUuidHashTable[index]; (uth = *uhp); uhp = &uth->next) {
1191 assert(uth->hostPtr);
1192 if (uth->hostPtr == host) {
1194 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d)\n",
1195 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1196 ntohs(host->port)));
1203 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d) not found\n",
1204 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1205 ntohs(host->port)));
1209 /* inserts a new HashChain structure corresponding to this address */
1211 h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1214 struct h_AddrHashChain *chain;
1215 char hoststr[16], hoststr2[16];
1217 /* hash into proper bucket */
1218 index = h_HashIndex(addr);
1220 /* don't add the same entry multiple times */
1221 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1222 if (chain->hostPtr == host) {
1223 if (chain->addr != addr || chain->port != port) {
1225 ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " exists as %s:%d when adding %s:%d\n",
1226 host, afs_inet_ntoa_r(chain->addr, hoststr),
1227 ntohs(chain->port), afs_inet_ntoa_r(addr, hoststr2),
1231 ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
1232 host, afs_inet_ntoa_r(chain->addr, hoststr),
1233 ntohs(chain->port)));
1239 /* insert into beginning of list for this bucket */
1240 chain = (struct h_AddrHashChain *)malloc(sizeof(struct h_AddrHashChain));
1242 ViceLog(0, ("Failed malloc in h_AddHostToAddrHashTable_r\n"));
1245 chain->hostPtr = host;
1246 chain->next = hostAddrHashTable[index];
1249 hostAddrHashTable[index] = chain;
1250 ViceLog(125, ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " added as %s:%d\n",
1251 host, afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1255 * This is called with host locked and held.
1256 * It is called to either validate or add an additional interface
1257 * address/port on the specified host.
1259 * All addresses are in network byte order.
1262 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1266 struct Interface *interface;
1267 char hoststr[16], hoststr2[16];
1270 assert(host->interface);
1273 * Make sure this address is on the list of known addresses
1276 number = host->interface->numberOfInterfaces;
1277 for (i = 0; i < number; i++) {
1278 if (host->interface->interface[i].addr == addr &&
1279 host->interface->interface[i].port == port) {
1281 ("addInterfaceAddr : found host %" AFS_PTR_FMT " (%s:%d) adding %s:%d%s\n",
1282 host, afs_inet_ntoa_r(host->host, hoststr),
1283 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1284 ntohs(port), host->interface->interface[i].valid ? "" :
1287 if (host->interface->interface[i].valid == 0) {
1288 host->interface->interface[i].valid = 1;
1289 h_AddHostToAddrHashTable_r(addr, port, host);
1295 ViceLog(125, ("addInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) adding %s:%d\n",
1296 host, afs_inet_ntoa_r(host->host, hoststr),
1297 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1300 interface = (struct Interface *)
1301 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1303 ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
1306 interface->numberOfInterfaces = number + 1;
1307 interface->uuid = host->interface->uuid;
1308 for (i = 0; i < number; i++)
1309 interface->interface[i] = host->interface->interface[i];
1311 /* Add the new valid interface */
1312 interface->interface[number].addr = addr;
1313 interface->interface[number].port = port;
1314 interface->interface[number].valid = 1;
1315 h_AddHostToAddrHashTable_r(addr, port, host);
1316 free(host->interface);
1317 host->interface = interface;
1324 * This is called with host locked and held.
1326 * All addresses are in network byte order.
1329 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1333 struct Interface *interface;
1334 char hoststr[16], hoststr2[16];
1337 assert(host->interface);
1339 ViceLog(125, ("removeInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1340 host, afs_inet_ntoa_r(host->host, hoststr),
1341 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1345 * Make sure this address is on the list of known addresses
1348 interface = host->interface;
1349 number = host->interface->numberOfInterfaces;
1350 for (i = 0; i < number; i++) {
1351 if (interface->interface[i].addr == addr &&
1352 interface->interface[i].port == port) {
1353 if (interface->interface[i].valid)
1354 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1356 for (; i < number; i++) {
1357 interface->interface[i] = interface->interface[i+1];
1359 interface->numberOfInterfaces = number;
1368 * This is called with host locked and held.
1370 * All addresses are in network byte order.
1373 invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1377 struct Interface *interface;
1378 char hoststr[16], hoststr2[16];
1381 assert(host->interface);
1383 ViceLog(125, ("invalidateInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1384 host, afs_inet_ntoa_r(host->host, hoststr),
1385 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1389 * Make sure this address is on the list of known addresses
1392 interface = host->interface;
1393 number = host->interface->numberOfInterfaces;
1394 for (i = 0; i < number; i++) {
1395 if (interface->interface[i].addr == addr &&
1396 interface->interface[i].port == port) {
1397 if (interface->interface[i].valid) {
1398 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1399 interface->interface[i].valid = 0;
1410 * This is called with host locked and held. This function differs
1411 * from removeInterfaceAddr_r in that it is called when the address
1412 * is being removed from the host regardless of whether or not there
1413 * is an interface list for the host. This function will delete the
1414 * host if there are no addresses left on it.
1416 * All addresses are in network byte order.
1419 removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1422 char hoststr[16], hoststr2[16];
1423 struct rx_connection *rxconn;
1425 if (!host->interface || host->interface->numberOfInterfaces == 1) {
1426 if (host->host == addr && host->port == port) {
1428 ("Removing only address for host %" AFS_PTR_FMT " (%s:%d), deleting host.\n",
1429 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1430 host->hostFlags |= HOSTDELETED;
1432 * Do not remove the primary addr/port from the hash table.
1433 * It will be ignored due to the HOSTDELETED flag and will
1434 * be removed when h_TossStuff_r() cleans up the HOSTDELETED
1435 * host. Removing it here will only result in a search for
1436 * the host/addr/port in the hash chain which will fail.
1440 ("Removing address that does not belong to host %" AFS_PTR_FMT " (%s:%d).\n",
1441 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1444 if (host->host == addr && host->port == port) {
1445 removeInterfaceAddr_r(host, addr, port);
1447 rxconn = host->callback_rxcon;
1448 host->callback_rxcon = NULL;
1451 struct client *client;
1453 * If rx_DestroyConnection calls h_FreeConnection we will
1454 * deadlock on the host_glock_mutex. Work around the problem
1455 * by unhooking the client from the connection before
1456 * destroying the connection.
1458 client = rx_GetSpecific(rxconn, rxcon_client_key);
1459 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1460 rx_DestroyConnection(rxconn);
1463 for (i=0; i < host->interface->numberOfInterfaces; i++) {
1464 if (host->interface->interface[i].valid) {
1466 ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
1467 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1468 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
1469 ntohs(host->interface->interface[i].port)));
1470 host->host = host->interface->interface[i].addr;
1471 host->port = host->interface->interface[i].port;
1472 h_AddHostToAddrHashTable_r(host->host, host->port, host);
1477 if (i == host->interface->numberOfInterfaces) {
1479 ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
1480 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1481 host->hostFlags |= HOSTDELETED;
1482 /* addr/port was removed from the hash table */
1487 sc = rxnull_NewClientSecurityObject();
1488 host->callback_rxcon =
1489 rx_NewConnection(host->host, host->port, 1, sc, 0);
1490 rx_SetConnDeadTime(host->callback_rxcon, 50);
1491 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
1494 /* not the primary addr/port, just invalidate it */
1495 invalidateInterfaceAddr_r(host, addr, port);
1502 h_threadquota(int waiting)
1507 } else if (lwps > 32) {
1510 } else if (lwps > 16) {
1520 /* Host is returned held */
1522 h_GetHost_r(struct rx_connection *tcon)
1525 struct host *oldHost;
1528 struct interfaceAddr interf;
1529 int interfValid = 0;
1530 struct Identity *identP = NULL;
1533 char hoststr[16], hoststr2[16];
1535 struct rx_connection *cb_conn = NULL;
1536 struct rx_connection *cb_in = NULL;
1538 caps.Capabilities_val = NULL;
1540 haddr = rxr_HostOf(tcon);
1541 hport = rxr_PortOf(tcon);
1544 rx_DestroyConnection(cb_in);
1547 if (caps.Capabilities_val)
1548 free(caps.Capabilities_val);
1549 caps.Capabilities_val = NULL;
1550 caps.Capabilities_len = 0;
1553 if (h_Lookup_r(haddr, hport, &held, &host))
1555 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1556 if (host && !identP && !(host->Console & 1)) {
1557 /* This is a new connection, and we already have a host
1558 * structure for this address. Verify that the identity
1559 * of the caller matches the identity in the host structure.
1561 if ((host->hostFlags & HWHO_INPROGRESS) &&
1562 h_threadquota(host->lock.num_waiting)) {
1569 if (!(host->hostFlags & ALTADDR)) {
1570 /* Another thread is doing initialization */
1575 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1576 host, afs_inet_ntoa_r(host->host, hoststr),
1577 ntohs(host->port)));
1580 host->hostFlags |= HWHO_INPROGRESS;
1581 host->hostFlags &= ~ALTADDR;
1583 /* We received a new connection from an IP address/port
1584 * that is associated with 'host' but the address/port of
1585 * the callback connection does not have to match it.
1586 * If there is a match, we can use the existing callback
1587 * connection to verify the UUID. If they do not match
1588 * we need to use a new callback connection to verify the
1589 * UUID of the incoming caller and perhaps use the old
1590 * callback connection to verify that the old address/port
1594 cb_conn = host->callback_rxcon;
1595 rx_GetConnection(cb_conn);
1597 if (haddr == host->host && hport == host->port) {
1598 /* The existing callback connection matches the
1599 * incoming connection so just use it.
1602 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1603 if (code == RXGEN_OPCODE)
1604 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1606 /* We do not have a match. Create a new connection
1607 * for the new addr/port and use multi_Rx to probe
1608 * both of them simultaneously.
1611 sc = rxnull_NewClientSecurityObject();
1612 cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1613 rx_SetConnDeadTime(cb_in, 50);
1614 rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1617 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1618 if (code == RXGEN_OPCODE)
1619 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1621 rx_PutConnection(cb_conn);
1624 if ((code == RXGEN_OPCODE) ||
1625 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1626 identP = (struct Identity *)malloc(sizeof(struct Identity));
1628 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1632 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1633 if (cb_in == NULL) {
1634 /* The host on this connection was unable to respond to
1635 * the WhoAreYou. We will treat this as a new connection
1636 * from the existing host. The worst that can happen is
1637 * that we maintain some extra callback state information */
1638 if (host->interface) {
1640 ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1642 afs_inet_ntoa_r(host->host, hoststr),
1643 ntohs(host->port)));
1644 host->hostFlags |= HOSTDELETED;
1645 host->hostFlags &= ~HWHO_INPROGRESS;
1653 /* The incoming connection does not support WhoAreYou but
1654 * the original one might have. Use removeAddress_r() to
1655 * remove this addr/port from the host that was found.
1656 * If there are no more addresses left for the host it
1657 * will be deleted. Then we retry.
1659 removeAddress_r(host, haddr, hport);
1660 host->hostFlags &= ~HWHO_INPROGRESS;
1661 host->hostFlags |= ALTADDR;
1668 } else if (code == 0) {
1670 identP = (struct Identity *)malloc(sizeof(struct Identity));
1672 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1676 identP->uuid = interf.uuid;
1677 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1678 /* Check whether the UUID on this connection matches
1679 * the UUID in the host structure. If they don't match
1680 * then this is not the same host as before. */
1681 if (!host->interface
1682 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1685 ("Uuid doesn't match connection (%s:%d).\n",
1686 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1688 removeAddress_r(host, haddr, hport);
1691 ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1692 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1694 removeAddress_r(host, host->host, host->port);
1696 host->hostFlags &= ~HWHO_INPROGRESS;
1697 host->hostFlags |= ALTADDR;
1704 /* the UUID matched the client at the incoming addr/port
1705 * but this is not the address of the active callback
1706 * connection. Try that connection and see if the client
1707 * is still there and if the reported UUID is the same.
1710 afsUUID uuid = host->interface->uuid;
1711 cb_conn = host->callback_rxcon;
1712 rx_GetConnection(cb_conn);
1713 rx_SetConnDeadTime(cb_conn, 2);
1714 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1716 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1718 rx_SetConnDeadTime(cb_conn, 50);
1719 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1720 rx_PutConnection(cb_conn);
1723 /* The primary address is either not responding or
1724 * is not the client we are looking for. Need to
1725 * remove the primary address and add swap in the new
1726 * callback connection, and destroy the old one.
1728 struct rx_connection *rxconn;
1729 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1731 afs_inet_ntoa_r(host->host, hoststr),
1732 ntohs(host->port),code2));
1735 * make sure we add and then remove. otherwise, we
1736 * might end up with no valid interfaces after the
1737 * remove and the host will have been marked deleted.
1739 addInterfaceAddr_r(host, haddr, hport);
1740 removeInterfaceAddr_r(host, host->host, host->port);
1743 rxconn = host->callback_rxcon;
1744 host->callback_rxcon = cb_in;
1748 struct client *client;
1750 * If rx_DestroyConnection calls h_FreeConnection we will
1751 * deadlock on the host_glock_mutex. Work around the problem
1752 * by unhooking the client from the connection before
1753 * destroying the connection.
1755 client = rx_GetSpecific(rxconn, rxcon_client_key);
1756 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1757 rx_DestroyConnection(rxconn);
1763 /* A callback to the incoming connection address is failing.
1764 * Assume that the addr/port is no longer associated with the host
1765 * returned by h_Lookup_r.
1768 ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1769 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1770 removeAddress_r(host, haddr, hport);
1771 host->hostFlags &= ~HWHO_INPROGRESS;
1772 host->hostFlags |= ALTADDR;
1777 rx_DestroyConnection(cb_in);
1782 ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1783 host, afs_inet_ntoa_r(host->host, hoststr),
1784 ntohs(host->port), code));
1785 host->hostFlags |= VENUSDOWN;
1788 if (caps.Capabilities_val
1789 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1790 host->hostFlags |= HERRORTRANS;
1792 host->hostFlags &= ~(HERRORTRANS);
1793 host->hostFlags |= ALTADDR;
1794 host->hostFlags &= ~HWHO_INPROGRESS;
1797 if (!(host->hostFlags & ALTADDR)) {
1798 /* another thread is doing the initialisation */
1800 ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1801 host, afs_inet_ntoa_r(host->host, hoststr),
1802 ntohs(host->port)));
1808 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1809 host, afs_inet_ntoa_r(host->host, hoststr),
1810 ntohs(host->port)));
1813 /* We need to check whether the identity in the host structure
1814 * matches the identity on the connection. If they don't match
1815 * then treat this a new host. */
1816 if (!(host->Console & 1)
1817 && ((!identP->valid && host->interface)
1818 || (identP->valid && !host->interface)
1820 && !afs_uuid_equal(&identP->uuid,
1821 &host->interface->uuid)))) {
1822 char uuid1[128], uuid2[128];
1824 afsUUID_to_string(&identP->uuid, uuid1, 127);
1825 if (host->interface)
1826 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1828 ("CB: new identity for host %" AFS_PTR_FMT " (%s:%d), deleting(%x %x %s %s)\n",
1829 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1830 identP->valid, host->interface,
1831 identP->valid ? uuid1 : "no_uuid",
1832 host->interface ? uuid2 : "no_uuid"));
1834 /* The host in the cache is not the host for this connection */
1836 host->hostFlags |= HOSTDELETED;
1843 host = h_Alloc_r(tcon); /* returned held and locked */
1844 h_gethostcps_r(host, FT_ApproxTime());
1845 if (!(host->Console & 1)) {
1847 cb_conn = host->callback_rxcon;
1848 rx_GetConnection(cb_conn);
1849 host->hostFlags |= HWHO_INPROGRESS;
1852 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1853 if (code == RXGEN_OPCODE)
1854 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1855 rx_PutConnection(cb_conn);
1858 if ((code == RXGEN_OPCODE) ||
1859 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1862 (struct Identity *)malloc(sizeof(struct Identity));
1867 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1872 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1874 ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1875 host, afs_inet_ntoa_r(host->host, hoststr),
1876 ntohs(host->port)));
1878 } else if (code == 0) {
1881 (struct Identity *)malloc(sizeof(struct Identity));
1886 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1891 identP->uuid = interf.uuid;
1893 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1895 ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
1896 host, afs_inet_ntoa_r(host->host, hoststr),
1897 ntohs(host->port)));
1899 if (code == 0 && !identP->valid) {
1900 cb_conn = host->callback_rxcon;
1901 rx_GetConnection(cb_conn);
1903 code = RXAFSCB_InitCallBackState(cb_conn);
1904 rx_PutConnection(cb_conn);
1907 } else if (code == 0) {
1908 oldHost = h_LookupUuid_r(&identP->uuid);
1912 if (!h_Held_r(oldHost))
1915 oldHost->hostFlags |= HWHO_INPROGRESS;
1917 if (oldHost->interface) {
1919 afsUUID uuid = oldHost->interface->uuid;
1920 cb_conn = oldHost->callback_rxcon;
1921 rx_GetConnection(cb_conn);
1922 rx_SetConnDeadTime(cb_conn, 2);
1923 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1925 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1927 rx_SetConnDeadTime(cb_conn, 50);
1928 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1929 rx_PutConnection(cb_conn);
1932 /* The primary address is either not responding or
1933 * is not the client we are looking for.
1934 * MultiProbeAlternateAddress_r() will remove the
1935 * alternate interfaces that do not have the same
1937 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1939 afs_inet_ntoa_r(oldHost->host, hoststr),
1940 ntohs(oldHost->port),code2));
1941 MultiProbeAlternateAddress_r(oldHost);
1948 /* This is a new address for an existing host. Update
1949 * the list of interfaces for the existing host and
1950 * delete the host structure we just allocated. */
1952 /* prevent warnings while manipulating interface lists */
1953 host->hostFlags |= HOSTDELETED;
1955 if (oldHost->host != haddr || oldHost->port != hport) {
1956 struct rx_connection *rxconn;
1959 ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
1961 afs_inet_ntoa_r(oldHost->host, hoststr2),
1962 ntohs(oldHost->port),
1963 afs_inet_ntoa_r(haddr, hoststr),
1966 * add then remove. otherwise the host may get marked
1967 * deleted if we removed the only valid address.
1969 addInterfaceAddr_r(oldHost, haddr, hport);
1970 if (probefail || oldHost->host == haddr) {
1972 * The probe failed which means that the old
1973 * address is either unreachable or is not the
1974 * same host we were just contacted by. We will
1975 * also remove addresses if only the port has
1976 * changed because that indicates the client
1979 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
1982 struct Interface *interface = oldHost->interface;
1983 int number = oldHost->interface->numberOfInterfaces;
1984 for (i = 0; i < number; i++) {
1985 if (interface->interface[i].addr == haddr &&
1986 interface->interface[i].port != hport) {
1988 * We have just been contacted by a client
1989 * that has been seen from behind a NAT
1990 * and at least one other address.
1992 removeInterfaceAddr_r(oldHost, haddr,
1993 interface->interface[i].port);
1998 h_AddHostToAddrHashTable_r(haddr, hport, oldHost);
1999 oldHost->host = haddr;
2000 oldHost->port = hport;
2001 rxconn = oldHost->callback_rxcon;
2002 oldHost->callback_rxcon = host->callback_rxcon;
2003 host->callback_rxcon = NULL;
2006 struct client *client;
2008 * If rx_DestroyConnection calls h_FreeConnection we will
2009 * deadlock on the host_glock_mutex. Work around the problem
2010 * by unhooking the client from the connection before
2011 * destroying the connection.
2013 client = rx_GetSpecific(rxconn, rxcon_client_key);
2014 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
2015 rx_DestroyConnection(rxconn);
2018 host->hostFlags &= ~HWHO_INPROGRESS;
2020 /* release host because it was allocated by h_Alloc_r */
2023 /* the new host is held and locked */
2025 /* This really is a new host */
2026 h_AddHostToUuidHashTable_r(&identP->uuid, host);
2027 cb_conn = host->callback_rxcon;
2028 rx_GetConnection(cb_conn);
2031 RXAFSCB_InitCallBackState3(cb_conn,
2033 rx_PutConnection(cb_conn);
2038 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2039 host, afs_inet_ntoa_r(host->host, hoststr),
2040 ntohs(host->port)));
2041 assert(interfValid == 1);
2042 initInterfaceAddr_r(host, &interf);
2048 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2049 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2050 host->hostFlags |= VENUSDOWN;
2053 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2054 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2055 host->hostFlags |= RESETDONE;
2058 if (caps.Capabilities_val
2059 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2060 host->hostFlags |= HERRORTRANS;
2062 host->hostFlags &= ~(HERRORTRANS);
2063 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2064 host->hostFlags &= ~HWHO_INPROGRESS;
2069 if (caps.Capabilities_val)
2070 free(caps.Capabilities_val);
2071 caps.Capabilities_val = NULL;
2072 caps.Capabilities_len = 0;
2074 rx_DestroyConnection(cb_in);
2082 static char localcellname[PR_MAXNAMELEN + 1];
2083 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
2084 int num_lrealms = -1;
2088 h_InitHostPackage(void)
2090 memset(&nulluuid, 0, sizeof(afsUUID));
2091 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
2092 if (num_lrealms == -1) {
2094 for (i=0; i<AFS_NUM_LREALMS; i++) {
2095 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
2101 ("afs_krb_get_lrealm failed, using %s.\n",
2103 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
2109 /* initialize the rest of the local realms to nullstring for debugging */
2110 for (; i<AFS_NUM_LREALMS; i++)
2111 local_realms[i][0] = '\0';
2113 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2114 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2115 #ifdef AFS_PTHREAD_ENV
2116 assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
2117 #endif /* AFS_PTHREAD_ENV */
2121 MapName_r(char *aname, char *acell, afs_int32 * aval)
2126 afs_int32 anamelen, cnamelen;
2130 anamelen = strlen(aname);
2131 if (anamelen >= PR_MAXNAMELEN)
2132 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
2134 lnames.namelist_len = 1;
2135 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
2136 lids.idlist_len = 0;
2137 lids.idlist_val = NULL;
2139 cnamelen = strlen(acell);
2141 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2143 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2144 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2145 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2147 ("MapName: Name too long, using AnonymousID for %s@%s\n",
2149 *aval = AnonymousID;
2152 foreign = 1; /* attempt cross-cell authentication */
2153 tname = (char *)malloc(PR_MAXNAMELEN);
2155 ViceLog(0, ("Failed malloc in MapName_r\n"));
2158 strcpy(tname, aname);
2159 tname[anamelen] = '@';
2160 strcpy(tname + anamelen + 1, acell);
2161 lnames.namelist_val = (prname *) tname;
2166 code = hpr_NameToId(&lnames, &lids);
2169 if (lids.idlist_val) {
2170 *aval = lids.idlist_val[0];
2171 if (*aval == AnonymousID) {
2173 ("MapName: NameToId on %s returns anonymousID\n",
2174 lnames.namelist_val));
2176 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2179 ("MapName: NameToId on '%s' is unknown\n",
2180 lnames.namelist_val));
2186 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
2194 /* NOTE: this returns the client with a Write lock and a refCount */
2196 h_ID2Client(afs_int32 vid)
2198 register struct client *client;
2199 register struct host *host;
2202 for (host = hostList; host; host = host->next) {
2203 if (host->hostFlags & HOSTDELETED)
2205 for (client = host->FirstClient; client; client = client->next) {
2206 if (!client->deleted && client->ViceId == vid) {
2209 ObtainWriteLock(&client->lock);
2220 * Called by the server main loop. Returns a h_Held client, which must be
2221 * released later the main loop. Allocates a client if the matching one
2222 * isn't around. The client is returned with its reference count incremented
2223 * by one. The caller must call h_ReleaseClient_r when finished with
2226 * the client->host is returned held. h_ReleaseClient_r does not release
2227 * the hold on client->host.
2230 h_FindClient_r(struct rx_connection *tcon)
2232 register struct client *client;
2233 struct host *host = NULL;
2234 struct client *oldClient;
2235 afs_int32 viceid = 0;
2239 #if (64-MAXKTCNAMELEN)
2240 ticket name length != 64
2244 char uname[PR_MAXNAMELEN];
2245 char tcell[MAXKTCREALMLEN];
2249 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2250 if (client && client->sid == rxr_CidOf(tcon)
2251 && client->VenusEpoch == rxr_GetEpoch(tcon)) {
2253 h_Hold_r(client->host);
2254 if (!client->deleted && client->prfail != 2) {
2255 /* Could add shared lock on client here */
2256 /* note that we don't have to lock entry in this path to
2257 * ensure CPS is initialized, since we don't call rx_SetSpecific
2258 * until initialization is done, and we only get here if
2259 * rx_GetSpecific located the client structure.
2264 ObtainWriteLock(&client->lock); /* released at end */
2270 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2272 ("FindClient: authenticating connection: authClass=%d\n",
2274 if (authClass == 1) {
2275 /* A bcrypt tickets, no longer supported */
2276 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2277 viceid = AnonymousID;
2278 expTime = 0x7fffffff;
2279 } else if (authClass == 2) {
2282 /* kerberos ticket */
2283 code = rxkad_GetServerInfo(tcon, /*level */ 0, (afs_uint32 *)&expTime,
2284 tname, tinst, tcell, &kvno);
2286 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2287 viceid = AnonymousID;
2288 expTime = 0x7fffffff;
2290 int ilen = strlen(tinst);
2292 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2293 tname, tinst, tcell, expTime, kvno));
2294 strncpy(uname, tname, sizeof(uname));
2296 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2299 strcat(uname, tinst);
2301 /* translate the name to a vice id */
2302 code = MapName_r(uname, tcell, &viceid);
2306 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2309 viceid = AnonymousID;
2310 expTime = 0x7fffffff;
2314 viceid = AnonymousID; /* unknown security class */
2315 expTime = 0x7fffffff;
2318 if (!client) { /* loop */
2319 host = h_GetHost_r(tcon); /* Returns it h_Held */
2325 /* First try to find the client structure */
2326 for (client = host->FirstClient; client; client = client->next) {
2327 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2328 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2331 ObtainWriteLock(&client->lock);
2337 /* Still no client structure - get one */
2340 /* Retry to find the client structure */
2341 for (client = host->FirstClient; client; client = client->next) {
2342 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2343 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2345 goto retryfirstclient;
2350 ObtainWriteLock(&client->lock);
2351 client->refCount = 1;
2352 client->host = host;
2353 #if FS_STATS_DETAILED
2354 client->InSameNetwork = host->InSameNetwork;
2355 #endif /* FS_STATS_DETAILED */
2356 client->ViceId = viceid;
2357 client->expTime = expTime; /* rx only */
2358 client->authClass = authClass; /* rx only */
2359 client->sid = rxr_CidOf(tcon);
2360 client->VenusEpoch = rxr_GetEpoch(tcon);
2361 client->CPS.prlist_val = NULL;
2362 client->CPS.prlist_len = 0;
2366 client->prfail = fail;
2368 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2369 client->CPS.prlist_len = 0;
2370 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2371 free(client->CPS.prlist_val);
2372 client->CPS.prlist_val = NULL;
2373 client->ViceId = viceid;
2374 client->expTime = expTime;
2376 if (viceid == ANONYMOUSID) {
2377 client->CPS.prlist_len = AnonCPS.prlist_len;
2378 client->CPS.prlist_val = AnonCPS.prlist_val;
2381 code = hpr_GetCPS(viceid, &client->CPS);
2386 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2387 code, viceid, client->host,
2388 afs_inet_ntoa_r(client->host->host,hoststr),
2389 ntohs(client->host->port)));
2391 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2392 * all protection servers and reevaluates things if no
2393 * sync server or quorum is found we could still end up
2394 * with one of these errors. In such case we would like to
2395 * reevaluate the rpc call to find if there's cps for this
2396 * guy. We treat other errors (except network failures
2397 * ones - i.e. code < 0) as an indication that there is no
2398 * CPS for this host. Ideally we could like to deal this
2399 * problem the other way around (i.e. if code == NOCPS
2400 * ignore else retry next time) but the problem is that
2401 * there're other errors (i.e. EPERM) for which we don't
2402 * want to retry and we don't know the whole code list!
2404 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2408 /* the disabling of system:administrators is so iffy and has so many
2409 * possible failure modes that we will disable it again */
2410 /* Turn off System:Administrator for safety
2411 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2412 * assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2415 /* Now, tcon may already be set to a rock, since we blocked with no host
2416 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2417 * required). So, before setting the RPC's rock, we should disconnect
2418 * the RPC from the other client structure's rock.
2420 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2421 if (oldClient && oldClient != client && oldClient->sid == rxr_CidOf(tcon)
2422 && oldClient->VenusEpoch == rxr_GetEpoch(tcon)) {
2424 if (!oldClient->deleted) {
2425 /* if we didn't create it, it's not ours to put back */
2427 ViceLog(0, ("FindClient: stillborn client %x(%x); conn %x (host %s:%d) had client %x(%x)\n",
2428 client, client->sid, tcon,
2429 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2430 ntohs(rxr_PortOf(tcon)),
2431 oldClient, oldClient->sid));
2432 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2433 free(client->CPS.prlist_val);
2434 client->CPS.prlist_val = NULL;
2435 client->CPS.prlist_len = 0;
2437 /* We should perhaps check for 0 here */
2439 ReleaseWriteLock(&client->lock);
2444 oldClient->refCount++;
2446 ObtainWriteLock(&oldClient->lock);
2450 ViceLog(0, ("FindClient: deleted client %x(%x) already had conn %x (host %s:%d), stolen by client %x(%x)\n",
2451 oldClient, oldClient->sid, tcon,
2452 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2453 ntohs(rxr_PortOf(tcon)),
2454 client, client->sid));
2455 /* rx_SetSpecific will be done immediately below */
2458 /* Avoid chaining in more than once. */
2461 client->next = host->FirstClient;
2462 host->FirstClient = client;
2464 CurrentConnections++; /* increment number of connections */
2466 rx_SetSpecific(tcon, rxcon_client_key, client);
2467 ReleaseWriteLock(&client->lock);
2471 } /*h_FindClient_r */
2474 h_ReleaseClient_r(struct client *client)
2476 assert(client->refCount > 0);
2483 * Sigh: this one is used to get the client AGAIN within the individual
2484 * server routines. This does not bother h_Holding the host, since
2485 * this is assumed already have been done by the server main loop.
2486 * It does check tokens, since only the server routines can return the
2487 * VICETOKENDEAD error code
2490 GetClient(struct rx_connection *tcon, struct client **cp)
2492 register struct client *client;
2497 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2498 if (client == NULL) {
2500 ("GetClient: no client in conn %x (host %s:%d), VBUSYING\n",
2501 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2502 ntohs(rxr_PortOf(tcon))));
2506 if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2508 ("GetClient: tcon %x tcon sid %d client sid %d\n",
2509 tcon, rxr_CidOf(tcon), client->sid));
2513 if (client && client->LastCall > client->expTime && client->expTime) {
2515 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2516 afs_inet_ntoa_r(client->host->host, hoststr),
2517 ntohs(client->host->port), client->expTime));
2519 return VICETOKENDEAD;
2529 PutClient(struct client **cp)
2535 h_ReleaseClient_r(*cp);
2542 /* Client user name for short term use. Note that this is NOT inexpensive */
2544 h_UserName(struct client *client)
2546 static char User[PR_MAXNAMELEN + 1];
2550 lids.idlist_len = 1;
2551 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2552 if (!lids.idlist_val) {
2553 ViceLog(0, ("Failed malloc in h_UserName\n"));
2556 lnames.namelist_len = 0;
2557 lnames.namelist_val = (prname *) 0;
2558 lids.idlist_val[0] = client->ViceId;
2559 if (hpr_IdToName(&lids, &lnames)) {
2560 /* We need to free id we alloced above! */
2561 free(lids.idlist_val);
2562 return "*UNKNOWN USER NAME*";
2564 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2565 free(lids.idlist_val);
2566 free(lnames.namelist_val);
2575 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2576 CEs, CEBlocks, HTs, HTBlocks));
2582 h_PrintClient(register struct host *host, int held, void *rock)
2584 StreamHandle_t *file = (StreamHandle_t *)rock;
2585 register struct client *client;
2590 time_t LastCall, expTime;
2593 LastCall = host->LastCall;
2594 if (host->hostFlags & HOSTDELETED) {
2598 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2599 "Host %s:%d down = %d, LastCall %s",
2600 afs_inet_ntoa_r(host->host, hoststr),
2601 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2602 afs_ctime(&LastCall, tbuffer,
2604 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2605 for (client = host->FirstClient; client; client = client->next) {
2606 if (!client->deleted) {
2607 expTime = client->expTime;
2608 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2609 " user id=%d, name=%s, sl=%s till %s",
2610 client->ViceId, h_UserName(client),
2612 authClass ? "Authenticated" :
2613 "Not authenticated",
2615 authClass ? afs_ctime(&expTime, tbuffer,
2618 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2619 (void)afs_snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2620 client->CPS.prlist_len);
2621 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2622 if (client->CPS.prlist_val) {
2623 for (i = 0; i > client->CPS.prlist_len; i++) {
2624 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2625 client->CPS.prlist_val[i]);
2626 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2629 sprintf(tmpStr, "]\n");
2630 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2636 } /*h_PrintClient */
2641 * Print a list of clients, with last security level and token value seen,
2645 h_PrintClients(void)
2651 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2655 ("Couldn't create client dump file %s\n",
2656 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2659 now = FT_ApproxTime();
2660 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
2661 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2662 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2663 h_Enumerate(h_PrintClient, (char *)file);
2664 STREAM_REALLYCLOSE(file);
2665 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2672 h_DumpHost(register struct host *host, int held, void *rock)
2674 StreamHandle_t *file = (StreamHandle_t *)rock;
2681 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2682 "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 [",
2683 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), host->index,
2684 host->cblist, CheckLock(&host->lock), host->LastCall,
2685 host->ActiveCall, (host->hostFlags & VENUSDOWN),
2686 host->hostFlags & HOSTDELETED, host->Console,
2687 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2689 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2690 if (host->hcps.prlist_val)
2691 for (i = 0; i < host->hcps.prlist_len; i++) {
2692 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2693 host->hcps.prlist_val[i]);
2694 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2696 sprintf(tmpStr, "] [");
2697 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2698 if (host->interface)
2699 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2701 sprintf(tmpStr, " %s:%d",
2702 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2703 ntohs(host->interface->interface[i].port));
2704 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2706 sprintf(tmpStr, "] holds: ");
2707 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2709 for (i = 0; i < h_maxSlots; i++) {
2710 sprintf(tmpStr, "%04x", host->holds[i]);
2711 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2713 sprintf(tmpStr, " slot/bit: %ld/%d\n", (long int) h_holdSlot(),
2715 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2727 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2733 ("Couldn't create host dump file %s\n",
2734 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2737 now = FT_ApproxTime();
2738 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
2739 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2740 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2741 h_Enumerate(h_DumpHost, (char *)file);
2742 STREAM_REALLYCLOSE(file);
2743 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2747 #ifdef AFS_DEMAND_ATTACH_FS
2750 * host state serialization
2752 static int h_stateFillHeader(struct host_state_header * hdr);
2753 static int h_stateCheckHeader(struct host_state_header * hdr);
2754 static int h_stateAllocMap(struct fs_dump_state * state);
2755 static int h_stateSaveHost(struct host * host, int held, void *rock);
2756 static int h_stateRestoreHost(struct fs_dump_state * state);
2757 static int h_stateRestoreIndex(struct host * h, int held, void *rock);
2758 static int h_stateVerifyHost(struct host * h, int held, void *rock);
2759 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port);
2760 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2761 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2762 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2765 /* this procedure saves all host state to disk for fast startup */
2767 h_stateSave(struct fs_dump_state * state)
2769 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2772 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2774 /* invalidate host state header */
2775 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2777 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2778 sizeof(struct host_state_header))) {
2783 fs_stateIncEOF(state, sizeof(struct host_state_header));
2785 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2790 h_stateFillHeader(state->h_hdr);
2792 /* write the real header to disk */
2793 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2794 sizeof(struct host_state_header));
2801 * host state serialization
2803 * this procedure restores all host state from a disk for fast startup
2806 h_stateRestore(struct fs_dump_state * state)
2810 /* seek to the right position and read in the host state header */
2811 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2812 sizeof(struct host_state_header))) {
2817 /* check the validity of the header */
2818 if (h_stateCheckHeader(state->h_hdr)) {
2823 records = state->h_hdr->records;
2825 if (h_stateAllocMap(state)) {
2830 /* iterate over records restoring host state */
2831 for (i=0; i < records; i++) {
2832 if (h_stateRestoreHost(state) != 0) {
2843 h_stateRestoreIndices(struct fs_dump_state * state)
2845 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
2850 h_stateRestoreIndex(struct host * h, int held, void *rock)
2852 struct fs_dump_state *state = (struct fs_dump_state *)rock;
2853 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
2854 return H_ENUMERATE_BAIL(held);
2860 h_stateVerify(struct fs_dump_state * state)
2862 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
2867 h_stateVerifyHost(struct host * h, int held, void* rock)
2869 struct fs_dump_state *state = (struct fs_dump_state *)rock;
2873 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
2874 return H_ENUMERATE_BAIL(held);
2878 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
2879 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
2880 h->interface->interface[i].port)) {
2884 if (h_stateVerifyUuidHash(state, h)) {
2887 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port)) {
2891 if (cb_stateVerifyHCBList(state, h)) {
2899 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port)
2901 int ret = 0, found = 0;
2902 struct host *host = NULL;
2903 struct h_AddrHashChain *chain;
2904 int index = h_HashIndex(addr);
2908 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
2909 host = chain->hostPtr;
2911 afs_inet_ntoa_r(addr, tmp);
2912 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
2916 if ((chain->addr == addr) && (chain->port == port)) {
2918 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry points to different host struct (%d, %d)\n",
2919 h->index, host->index));
2920 state->flags.warnings_generated = 1;
2925 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
2926 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2927 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
2935 afs_inet_ntoa_r(addr, tmp);
2936 if (state->mode == FS_STATE_LOAD_MODE) {
2937 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s not found in hash\n", tmp));
2941 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s not found in hash\n", tmp));
2942 state->flags.warnings_generated = 1;
2951 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
2953 int ret = 0, found = 0;
2954 struct host *host = NULL;
2955 struct h_UuidHashChain *chain;
2956 afsUUID * uuidp = &h->interface->uuid;
2957 int index = h_UuidHashIndex(uuidp);
2961 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
2962 host = chain->hostPtr;
2964 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2965 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
2969 if (host->interface &&
2970 afs_uuid_equal(&host->interface->uuid, uuidp)) {
2972 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
2973 h->index, host->index));
2974 state->flags.warnings_generated = 1;
2979 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
2980 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2981 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
2989 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2990 if (state->mode == FS_STATE_LOAD_MODE) {
2991 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
2995 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
2996 state->flags.warnings_generated = 1;
3004 /* create the host state header structure */
3006 h_stateFillHeader(struct host_state_header * hdr)
3008 hdr->stamp.magic = HOST_STATE_MAGIC;
3009 hdr->stamp.version = HOST_STATE_VERSION;
3013 /* check the contents of the host state header structure */
3015 h_stateCheckHeader(struct host_state_header * hdr)
3019 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3020 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3023 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3024 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3030 /* allocate the host id mapping table */
3032 h_stateAllocMap(struct fs_dump_state * state)
3034 state->h_map.len = state->h_hdr->index_max + 1;
3035 state->h_map.entries = (struct idx_map_entry_t *)
3036 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3037 return (state->h_map.entries != NULL) ? 0 : 1;
3040 /* function called by h_Enumerate to save a host to disk */
3042 h_stateSaveHost(struct host * host, int held, void* rock)
3044 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3045 int if_len=0, hcps_len=0;
3046 struct hostDiskEntry hdsk;
3047 struct host_state_entry_header hdr;
3048 struct Interface * ifp = NULL;
3049 afs_int32 * hcps = NULL;
3050 struct iovec iov[4];
3053 memset(&hdr, 0, sizeof(hdr));
3055 if (state->h_hdr->index_max < host->index) {
3056 state->h_hdr->index_max = host->index;
3059 h_hostToDiskEntry_r(host, &hdsk);
3060 if (host->interface) {
3061 if_len = sizeof(struct Interface) +
3062 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3063 ifp = (struct Interface *) malloc(if_len);
3064 assert(ifp != NULL);
3065 memcpy(ifp, host->interface, if_len);
3066 hdr.interfaces = host->interface->numberOfInterfaces;
3067 iov[iovcnt].iov_base = (char *) ifp;
3068 iov[iovcnt].iov_len = if_len;
3071 if (host->hcps.prlist_val) {
3072 hdr.hcps = host->hcps.prlist_len;
3073 hcps_len = hdr.hcps * sizeof(afs_int32);
3074 hcps = (afs_int32 *) malloc(hcps_len);
3075 assert(hcps != NULL);
3076 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3077 iov[iovcnt].iov_base = (char *) hcps;
3078 iov[iovcnt].iov_len = hcps_len;
3082 if (hdsk.index > state->h_hdr->index_max)
3083 state->h_hdr->index_max = hdsk.index;
3085 hdr.len = sizeof(struct host_state_entry_header) +
3086 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3087 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3089 iov[0].iov_base = (char *) &hdr;
3090 iov[0].iov_len = sizeof(hdr);
3091 iov[1].iov_base = (char *) &hdsk;
3092 iov[1].iov_len = sizeof(struct hostDiskEntry);
3094 if (fs_stateWriteV(state, iov, iovcnt)) {
3095 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3099 fs_stateIncEOF(state, hdr.len);
3101 state->h_hdr->records++;
3108 return H_ENUMERATE_BAIL(held);
3113 /* restores a host from disk */
3115 h_stateRestoreHost(struct fs_dump_state * state)
3117 int ifp_len=0, hcps_len=0, bail=0;
3118 struct host_state_entry_header hdr;
3119 struct hostDiskEntry hdsk;
3120 struct host *host = NULL;
3121 struct Interface *ifp = NULL;
3122 afs_int32 * hcps = NULL;
3123 struct iovec iov[3];
3126 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3127 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3133 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3134 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3140 iov[0].iov_base = (char *) &hdsk;
3141 iov[0].iov_len = sizeof(struct hostDiskEntry);
3143 if (hdr.interfaces) {
3144 ifp_len = sizeof(struct Interface) +
3145 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3146 ifp = (struct Interface *) malloc(ifp_len);
3147 assert(ifp != NULL);
3148 iov[iovcnt].iov_base = (char *) ifp;
3149 iov[iovcnt].iov_len = ifp_len;
3153 hcps_len = hdr.hcps * sizeof(afs_int32);
3154 hcps = (afs_int32 *) malloc(hcps_len);
3155 assert(hcps != NULL);
3156 iov[iovcnt].iov_base = (char *) hcps;
3157 iov[iovcnt].iov_len = hcps_len;
3161 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3162 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3167 if (fs_stateReadV(state, iov, iovcnt)) {
3168 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3173 if (!hdr.hcps && hdsk.hcps_valid) {
3174 /* valid, zero-length host cps ; does this ever happen? */
3175 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3176 assert(hcps != NULL);
3180 assert(host != NULL);
3183 host->interface = ifp;
3186 host->hcps.prlist_val = hcps;
3187 host->hcps.prlist_len = hdr.hcps;
3190 h_diskEntryToHost_r(&hdsk, host);
3191 h_SetupCallbackConn_r(host);
3193 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3196 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3197 if (ifp->interface[i].valid &&
3198 !(ifp->interface[i].addr == host->host &&
3199 ifp->interface[i].port == host->port)) {
3200 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3201 ifp->interface[i].port,
3205 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3207 h_InsertList_r(host);
3209 /* setup host id map entry */
3210 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3211 state->h_map.entries[hdsk.index].new_idx = host->index;
3223 /* serialize a host structure to disk */
3225 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3227 out->host = in->host;
3228 out->port = in->port;
3229 out->hostFlags = in->hostFlags;
3230 out->Console = in->Console;
3231 out->hcpsfailed = in->hcpsfailed;
3232 out->LastCall = in->LastCall;
3233 out->ActiveCall = in->ActiveCall;
3234 out->cpsCall = in->cpsCall;
3235 out->cblist = in->cblist;
3236 #ifdef FS_STATS_DETAILED
3237 out->InSameNetwork = in->InSameNetwork;
3240 /* special fields we save, but are not memcpy'd back on restore */
3241 out->index = in->index;
3242 out->hcps_len = in->hcps.prlist_len;
3243 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3246 /* restore a host structure from disk */
3248 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3250 out->host = in->host;
3251 out->port = in->port;
3252 out->hostFlags = in->hostFlags;
3253 out->Console = in->Console;
3254 out->hcpsfailed = in->hcpsfailed;
3255 out->LastCall = in->LastCall;
3256 out->ActiveCall = in->ActiveCall;
3257 out->cpsCall = in->cpsCall;
3258 out->cblist = in->cblist;
3259 #ifdef FS_STATS_DETAILED
3260 out->InSameNetwork = in->InSameNetwork;
3264 /* index translation routines */
3266 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3270 /* hosts use a zero-based index, so old==0 is valid */
3272 if (old >= state->h_map.len) {
3273 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3275 } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
3276 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3279 *new = state->h_map.entries[old].new_idx;
3284 #endif /* AFS_DEMAND_ATTACH_FS */
3288 * This counts the number of workstations, the number of active workstations,
3289 * and the number of workstations declared "down" (i.e. not heard from
3290 * recently). An active workstation has received a call since the cutoff
3291 * time argument passed.
3294 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3296 register struct host *host;
3297 register int num = 0, active = 0, del = 0;
3300 for (host = hostList; host; host = host->next) {
3301 if (!(host->hostFlags & HOSTDELETED)) {
3303 if (host->ActiveCall > cutofftime)
3305 if (host->hostFlags & VENUSDOWN)
3317 } /*h_GetWorkStats */
3320 /*------------------------------------------------------------------------
3321 * PRIVATE h_ClassifyAddress
3324 * Given a target IP address and a candidate IP address (both
3325 * in host byte order), classify the candidate into one of three
3326 * buckets in relation to the target by bumping the counters passed
3330 * a_targetAddr : Target address.
3331 * a_candAddr : Candidate address.
3332 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3333 * addresses are either in the same network
3334 * or the same subnet.
3335 * a_diffSubnetP : ...when the candidate is in a different
3337 * a_diffNetworkP : ...when the candidate is in a different
3344 * The target and candidate addresses are both in host byte
3345 * order, NOT network byte order, when passed in.
3349 *------------------------------------------------------------------------*/
3352 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3353 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3354 afs_int32 * a_diffNetworkP)
3355 { /*h_ClassifyAddress */
3357 afs_uint32 targetNet;
3358 afs_uint32 targetSubnet;
3360 afs_uint32 candSubnet;
3363 * Put bad values into the subnet info to start with.
3365 targetSubnet = (afs_uint32) 0;
3366 candSubnet = (afs_uint32) 0;
3369 * Pull out the network and subnetwork numbers from the target
3370 * and candidate addresses. We can short-circuit this whole
3371 * affair if the target and candidate addresses are not of the
3374 if (IN_CLASSA(a_targetAddr)) {
3375 if (!(IN_CLASSA(a_candAddr))) {
3376 (*a_diffNetworkP)++;
3379 targetNet = a_targetAddr & IN_CLASSA_NET;
3380 candNet = a_candAddr & IN_CLASSA_NET;
3381 if (IN_SUBNETA(a_targetAddr))
3382 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3383 if (IN_SUBNETA(a_candAddr))
3384 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3385 } else if (IN_CLASSB(a_targetAddr)) {
3386 if (!(IN_CLASSB(a_candAddr))) {
3387 (*a_diffNetworkP)++;
3390 targetNet = a_targetAddr & IN_CLASSB_NET;
3391 candNet = a_candAddr & IN_CLASSB_NET;
3392 if (IN_SUBNETB(a_targetAddr))
3393 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3394 if (IN_SUBNETB(a_candAddr))
3395 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3396 } /*Class B target */
3397 else if (IN_CLASSC(a_targetAddr)) {
3398 if (!(IN_CLASSC(a_candAddr))) {
3399 (*a_diffNetworkP)++;
3402 targetNet = a_targetAddr & IN_CLASSC_NET;
3403 candNet = a_candAddr & IN_CLASSC_NET;
3406 * Note that class C addresses can't have subnets,
3407 * so we leave the defaults untouched.
3409 } /*Class C target */
3411 targetNet = a_targetAddr;
3412 candNet = a_candAddr;
3413 } /*Class D address */
3416 * Now, simply compare the extracted net and subnet values for
3417 * the two addresses (which at this point are known to be of the
3420 if (targetNet == candNet) {
3421 if (targetSubnet == candSubnet)
3422 (*a_sameNetOrSubnetP)++;
3426 (*a_diffNetworkP)++;
3428 } /*h_ClassifyAddress */
3431 /*------------------------------------------------------------------------
3432 * EXPORTED h_GetHostNetStats
3435 * Iterate through the host table, and classify each (non-deleted)
3436 * host entry into ``proximity'' categories (same net or subnet,
3437 * different subnet, different network).
3440 * a_numHostsP : Set to total number of (non-deleted) hosts.
3441 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3442 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3443 * a_diffNetworkP : Set to # hosts on diff network as server.
3449 * We only count non-deleted hosts. The storage pointed to by our
3450 * parameters is zeroed upon entry.
3454 *------------------------------------------------------------------------*/
3457 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3458 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3459 { /*h_GetHostNetStats */
3461 register struct host *hostP; /*Ptr to current host entry */
3462 register afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3465 * Clear out the storage pointed to by our parameters.
3467 *a_numHostsP = (afs_int32) 0;
3468 *a_sameNetOrSubnetP = (afs_int32) 0;
3469 *a_diffSubnetP = (afs_int32) 0;
3470 *a_diffNetworkP = (afs_int32) 0;
3473 for (hostP = hostList; hostP; hostP = hostP->next) {
3474 if (!(hostP->hostFlags & HOSTDELETED)) {
3476 * Bump the number of undeleted host entries found.
3477 * In classifying the current entry's address, make
3478 * sure to first convert to host byte order.
3481 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3482 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3483 a_sameNetOrSubnetP, a_diffSubnetP,
3485 } /*Only look at non-deleted hosts */
3486 } /*For each host record hashed to this index */
3488 } /*h_GetHostNetStats */
3490 static afs_uint32 checktime;
3491 static afs_uint32 clientdeletetime;
3492 static struct AFSFid zerofid;
3496 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3497 * Since it can serialize them, and pile up, it should be a separate LWP
3498 * from other events.
3502 CheckHost(register struct host *host, int held, void *rock)
3504 register struct client *client;
3505 struct rx_connection *cb_conn = NULL;
3508 #ifdef AFS_DEMAND_ATTACH_FS
3509 /* kill the checkhost lwp ASAP during shutdown */
3511 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3513 return H_ENUMERATE_BAIL(held);
3518 /* Host is held by h_Enumerate */
3520 for (client = host->FirstClient; client; client = client->next) {
3521 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3522 client->deleted = 1;
3523 host->hostFlags |= CLIENTDELETED;
3526 if (host->LastCall < checktime) {
3528 host->hostFlags |= HWHO_INPROGRESS;
3529 if (!(host->hostFlags & HOSTDELETED)) {
3530 cb_conn = host->callback_rxcon;
3531 rx_GetConnection(cb_conn);
3532 if (host->LastCall < clientdeletetime) {
3533 host->hostFlags |= HOSTDELETED;
3534 if (!(host->hostFlags & VENUSDOWN)) {
3535 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3536 if (host->interface) {
3539 RXAFSCB_InitCallBackState3(cb_conn,
3545 RXAFSCB_InitCallBackState(cb_conn);
3548 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3551 (void)afs_inet_ntoa_r(host->host, hoststr);
3553 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3554 hoststr, ntohs(host->port)));
3555 host->hostFlags |= VENUSDOWN;
3557 /* Note: it's safe to delete hosts even if they have call
3558 * back state, because break delayed callbacks (called when a
3559 * message is received from the workstation) will always send a
3560 * break all call backs to the workstation if there is no
3565 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3567 (void)afs_inet_ntoa_r(host->host, hoststr);
3568 if (host->interface) {
3569 afsUUID uuid = host->interface->uuid;
3571 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3574 if (MultiProbeAlternateAddress_r(host)) {
3575 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3576 hoststr, ntohs(host->port), code));
3577 host->hostFlags |= VENUSDOWN;
3582 code = RXAFSCB_Probe(cb_conn);
3586 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3587 hoststr, ntohs(host->port), code));
3588 host->hostFlags |= VENUSDOWN;
3594 rx_PutConnection(cb_conn);
3598 host->hostFlags &= ~HWHO_INPROGRESS;
3608 CheckHost_r(register struct host *host, int held, void *dummy)
3610 register struct client *client;
3611 struct rx_connection *cb_conn = NULL;
3614 #ifdef AFS_DEMAND_ATTACH_FS
3615 /* kill the checkhost lwp ASAP during shutdown */
3617 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3619 return H_ENUMERATE_BAIL(held);
3624 /* Host is held by h_Enumerate_r */
3625 for (client = host->FirstClient; client; client = client->next) {
3626 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3627 client->deleted = 1;
3628 host->hostFlags |= CLIENTDELETED;
3631 if (host->LastCall < checktime) {
3633 if (!(host->hostFlags & HOSTDELETED)) {
3634 cb_conn = host->callback_rxcon;
3635 rx_GetConnection(cb_conn);
3636 if (host->LastCall < clientdeletetime) {
3637 host->hostFlags |= HOSTDELETED;
3638 if (!(host->hostFlags & VENUSDOWN)) {
3639 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3640 if (host->interface) {
3643 RXAFSCB_InitCallBackState3(cb_conn,
3649 RXAFSCB_InitCallBackState(cb_conn);
3652 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3655 (void)afs_inet_ntoa_r(host->host, hoststr);
3657 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3658 hoststr, ntohs(host->port)));
3659 host->hostFlags |= VENUSDOWN;
3661 /* Note: it's safe to delete hosts even if they have call
3662 * back state, because break delayed callbacks (called when a
3663 * message is received from the workstation) will always send a
3664 * break all call backs to the workstation if there is no
3669 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3671 (void)afs_inet_ntoa_r(host->host, hoststr);
3672 if (host->interface) {
3673 afsUUID uuid = host->interface->uuid;
3675 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3678 if (MultiProbeAlternateAddress_r(host)) {
3679 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3680 hoststr, ntohs(host->port), code));
3681 host->hostFlags |= VENUSDOWN;
3686 code = RXAFSCB_Probe(cb_conn);
3690 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3691 hoststr, ntohs(host->port), code));
3692 host->hostFlags |= VENUSDOWN;
3698 rx_PutConnection(cb_conn);
3710 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3711 * don't respond to a probe. Note that VenusDown can only be cleared if
3712 * a message is received from the host (see ServerLWP in file.c).
3713 * Delete hosts that have not had any calls in 1 hour, clients that
3714 * have not had any calls in 15 minutes.
3716 * This routine is called roughly every 5 minutes.
3721 afs_uint32 now = FT_ApproxTime();
3723 memset(&zerofid, 0, sizeof(zerofid));
3725 * Send a probe to the workstation if it hasn't been heard from in
3728 checktime = now - 15 * 60;
3729 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3732 h_Enumerate_r(CheckHost_r, hostList, NULL);
3737 * This is called with host locked and held. At this point, the
3738 * hostAddrHashTable has an entry for the primary addr/port inserted
3739 * by h_Alloc_r(). No other interfaces should be considered valid.
3741 * The addresses in the interfaceAddr list are in host byte order.
3744 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3751 struct Interface *interface;
3754 afs_uint16 port7001 = htons(7001);
3759 number = interf->numberOfInterfaces;
3760 myAddr = host->host; /* current interface address */
3761 myPort = host->port; /* current port */
3764 ("initInterfaceAddr : host %s:%d numAddr %d\n",
3765 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3767 /* validation checks */
3768 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3770 ("Invalid number of alternate addresses is %d\n", number));
3775 * The client's notion of its own IP addresses is not reliable.
3777 * 1. The client list might contain private address ranges which
3778 * are likely to be re-used by many clients allocated addresses
3781 * 2. The client list will not include any public addresses that
3782 * are hidden by a NAT.
3784 * 3. Private address ranges that are exposed to the server will
3785 * be obtained from the rx connections that use them.
3787 * 4. Lists provided by the client are not necessarily truthful.
3788 * Many existing clients (UNIX) do not refresh the IP address
3789 * list as the actual assigned addresses change. The end result
3790 * is that they report the initial address list for the lifetime
3791 * of the process. In other words, a client can report addresses
3792 * that they are in fact not using. Adding these addresses to
3793 * the host interface list without verification is not only
3794 * pointless, it is downright dangerous.
3796 * We therefore do not add alternate addresses to the addr hash table.
3797 * We only use them for multi-rx callback breaks.
3801 * Convert IP addresses to network byte order, and remove
3802 * duplicate IP addresses from the interface list, and
3803 * determine whether or not the incoming addr/port is
3804 * listed. Note that if the address matches it is not
3805 * truly a match because the port number for the entries
3806 * in the interface list are port 7001 and the port number
3807 * for this connection might not be 7001.
3809 for (i = 0, count = 0, found = 0; i < number; i++) {
3810 interf->addr_in[i] = htonl(interf->addr_in[i]);
3811 for (j = 0; j < count; j++) {
3812 if (interf->addr_in[j] == interf->addr_in[i])
3816 interf->addr_in[count] = interf->addr_in[i];
3817 if (interf->addr_in[count] == myAddr &&
3825 * Allocate and initialize an interface structure for this host.
3828 interface = (struct Interface *)
3829 malloc(sizeof(struct Interface) +
3830 (sizeof(struct AddrPort) * (count - 1)));
3832 ViceLog(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
3835 interface->numberOfInterfaces = count;
3837 interface = (struct Interface *)
3838 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
3840 ViceLog(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
3843 interface->numberOfInterfaces = count + 1;
3844 interface->interface[count].addr = myAddr;
3845 interface->interface[count].port = myPort;
3846 interface->interface[count].valid = 1;
3849 for (i = 0; i < count; i++) {
3851 interface->interface[i].addr = interf->addr_in[i];
3852 /* We store the port as 7001 because the addresses reported by
3853 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
3854 * are coming from fully connected hosts (no NAT/PATs)
3856 interface->interface[i].port = port7001;
3857 interface->interface[i].valid =
3858 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
3861 interface->uuid = interf->uuid;
3863 assert(!host->interface);
3864 host->interface = interface;
3866 if (LogLevel >= 125) {
3867 afsUUID_to_string(&interface->uuid, uuidstr, 127);
3869 ViceLog(125, ("--- uuid %s\n", uuidstr));
3870 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
3871 ViceLog(125, ("--- alt address %s:%d\n",
3872 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3873 ntohs(host->interface->interface[i].port)));
3880 /* deleted a HashChain structure for this address and host */
3881 /* returns 1 on success */
3883 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
3887 register struct h_AddrHashChain **hp, *th;
3889 if (addr == 0 && port == 0)
3892 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
3894 assert(th->hostPtr);
3895 if (th->hostPtr == host && th->addr == addr && th->port == port) {
3896 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
3897 host, afs_inet_ntoa_r(host->host, hoststr),
3898 ntohs(host->port)));
3905 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
3906 host, afs_inet_ntoa_r(host->host, hoststr),
3907 ntohs(host->port)));
3913 ** prints out all alternate interface address for the host. The 'level'
3914 ** parameter indicates what level of debugging sets this output
3917 printInterfaceAddr(struct host *host, int level)
3922 if (host->interface) {
3923 /* check alternate addresses */
3924 number = host->interface->numberOfInterfaces;
3926 ViceLog(level, ("no-addresses "));
3928 for (i = 0; i < number; i++)
3929 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3930 ntohs(host->interface->interface[i].port)));
3933 ViceLog(level, ("\n"));