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 for (i=0; i < host->interface->numberOfInterfaces; i++) {
1448 if (host->interface->interface[i].valid) {
1450 ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
1451 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1452 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
1453 ntohs(host->interface->interface[i].port)));
1454 host->host = host->interface->interface[i].addr;
1455 host->port = host->interface->interface[i].port;
1456 h_AddHostToAddrHashTable_r(host->host, host->port, host);
1461 if (i == host->interface->numberOfInterfaces) {
1463 ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
1464 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1465 host->hostFlags |= HOSTDELETED;
1466 /* addr/port was removed from the hash table */
1470 rxconn = host->callback_rxcon;
1471 host->callback_rxcon = NULL;
1474 rx_DestroyConnection(rxconn);
1479 sc = rxnull_NewClientSecurityObject();
1480 host->callback_rxcon =
1481 rx_NewConnection(host->host, host->port, 1, sc, 0);
1482 rx_SetConnDeadTime(host->callback_rxcon, 50);
1483 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
1486 /* not the primary addr/port, just invalidate it */
1487 invalidateInterfaceAddr_r(host, addr, port);
1494 h_threadquota(int waiting)
1499 } else if (lwps > 32) {
1502 } else if (lwps > 16) {
1512 /* Host is returned held */
1514 h_GetHost_r(struct rx_connection *tcon)
1517 struct host *oldHost;
1520 struct interfaceAddr interf;
1521 int interfValid = 0;
1522 struct Identity *identP = NULL;
1525 char hoststr[16], hoststr2[16];
1527 struct rx_connection *cb_conn = NULL;
1528 struct rx_connection *cb_in = NULL;
1530 caps.Capabilities_val = NULL;
1532 haddr = rxr_HostOf(tcon);
1533 hport = rxr_PortOf(tcon);
1536 rx_DestroyConnection(cb_in);
1539 if (caps.Capabilities_val)
1540 free(caps.Capabilities_val);
1541 caps.Capabilities_val = NULL;
1542 caps.Capabilities_len = 0;
1545 if (h_Lookup_r(haddr, hport, &held, &host))
1547 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1548 if (host && !identP && !(host->Console & 1)) {
1549 /* This is a new connection, and we already have a host
1550 * structure for this address. Verify that the identity
1551 * of the caller matches the identity in the host structure.
1553 if ((host->hostFlags & HWHO_INPROGRESS) &&
1554 h_threadquota(host->lock.num_waiting)) {
1561 if (!(host->hostFlags & ALTADDR)) {
1562 /* Another thread is doing initialization */
1567 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1568 host, afs_inet_ntoa_r(host->host, hoststr),
1569 ntohs(host->port)));
1572 host->hostFlags |= HWHO_INPROGRESS;
1573 host->hostFlags &= ~ALTADDR;
1575 /* We received a new connection from an IP address/port
1576 * that is associated with 'host' but the address/port of
1577 * the callback connection does not have to match it.
1578 * If there is a match, we can use the existing callback
1579 * connection to verify the UUID. If they do not match
1580 * we need to use a new callback connection to verify the
1581 * UUID of the incoming caller and perhaps use the old
1582 * callback connection to verify that the old address/port
1586 cb_conn = host->callback_rxcon;
1587 rx_GetConnection(cb_conn);
1589 if (haddr == host->host && hport == host->port) {
1590 /* The existing callback connection matches the
1591 * incoming connection so just use it.
1594 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1595 if (code == RXGEN_OPCODE)
1596 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1598 /* We do not have a match. Create a new connection
1599 * for the new addr/port and use multi_Rx to probe
1600 * both of them simultaneously.
1603 sc = rxnull_NewClientSecurityObject();
1604 cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1605 rx_SetConnDeadTime(cb_in, 50);
1606 rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1609 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1610 if (code == RXGEN_OPCODE)
1611 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1613 rx_PutConnection(cb_conn);
1616 if ((code == RXGEN_OPCODE) ||
1617 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1618 identP = (struct Identity *)malloc(sizeof(struct Identity));
1620 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1624 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1625 if (cb_in == NULL) {
1626 /* The host on this connection was unable to respond to
1627 * the WhoAreYou. We will treat this as a new connection
1628 * from the existing host. The worst that can happen is
1629 * that we maintain some extra callback state information */
1630 if (host->interface) {
1632 ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1634 afs_inet_ntoa_r(host->host, hoststr),
1635 ntohs(host->port)));
1636 host->hostFlags |= HOSTDELETED;
1637 host->hostFlags &= ~HWHO_INPROGRESS;
1645 /* The incoming connection does not support WhoAreYou but
1646 * the original one might have. Use removeAddress_r() to
1647 * remove this addr/port from the host that was found.
1648 * If there are no more addresses left for the host it
1649 * will be deleted. Then we retry.
1651 removeAddress_r(host, haddr, hport);
1652 host->hostFlags &= ~HWHO_INPROGRESS;
1653 host->hostFlags |= ALTADDR;
1660 } else if (code == 0) {
1662 identP = (struct Identity *)malloc(sizeof(struct Identity));
1664 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1668 identP->uuid = interf.uuid;
1669 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1670 /* Check whether the UUID on this connection matches
1671 * the UUID in the host structure. If they don't match
1672 * then this is not the same host as before. */
1673 if (!host->interface
1674 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1677 ("Uuid doesn't match connection (%s:%d).\n",
1678 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1680 removeAddress_r(host, haddr, hport);
1683 ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1684 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1686 removeAddress_r(host, host->host, host->port);
1688 host->hostFlags &= ~HWHO_INPROGRESS;
1689 host->hostFlags |= ALTADDR;
1696 /* the UUID matched the client at the incoming addr/port
1697 * but this is not the address of the active callback
1698 * connection. Try that connection and see if the client
1699 * is still there and if the reported UUID is the same.
1702 afsUUID uuid = host->interface->uuid;
1703 cb_conn = host->callback_rxcon;
1704 rx_GetConnection(cb_conn);
1705 rx_SetConnDeadTime(cb_conn, 2);
1706 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1708 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1710 rx_SetConnDeadTime(cb_conn, 50);
1711 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1712 rx_PutConnection(cb_conn);
1715 /* The primary address is either not responding or
1716 * is not the client we are looking for. Need to
1717 * remove the primary address and add swap in the new
1718 * callback connection, and destroy the old one.
1720 struct rx_connection *rxconn;
1721 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1723 afs_inet_ntoa_r(host->host, hoststr),
1724 ntohs(host->port),code2));
1727 * make sure we add and then remove. otherwise, we
1728 * might end up with no valid interfaces after the
1729 * remove and the host will have been marked deleted.
1731 addInterfaceAddr_r(host, haddr, hport);
1732 removeInterfaceAddr_r(host, host->host, host->port);
1735 rxconn = host->callback_rxcon;
1736 host->callback_rxcon = cb_in;
1740 struct client *client;
1742 * If rx_DestroyConnection calls h_FreeConnection we will
1743 * deadlock on the host_glock_mutex. Work around the problem
1744 * by unhooking the client from the connection before
1745 * destroying the connection.
1747 client = rx_GetSpecific(rxconn, rxcon_client_key);
1748 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1749 rx_DestroyConnection(rxconn);
1755 /* A callback to the incoming connection address is failing.
1756 * Assume that the addr/port is no longer associated with the host
1757 * returned by h_Lookup_r.
1760 ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1761 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1762 removeAddress_r(host, haddr, hport);
1763 host->hostFlags &= ~HWHO_INPROGRESS;
1764 host->hostFlags |= ALTADDR;
1769 rx_DestroyConnection(cb_in);
1774 ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1775 host, afs_inet_ntoa_r(host->host, hoststr),
1776 ntohs(host->port), code));
1777 host->hostFlags |= VENUSDOWN;
1780 if (caps.Capabilities_val
1781 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1782 host->hostFlags |= HERRORTRANS;
1784 host->hostFlags &= ~(HERRORTRANS);
1785 host->hostFlags |= ALTADDR;
1786 host->hostFlags &= ~HWHO_INPROGRESS;
1789 if (!(host->hostFlags & ALTADDR)) {
1790 /* another thread is doing the initialisation */
1792 ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1793 host, afs_inet_ntoa_r(host->host, hoststr),
1794 ntohs(host->port)));
1800 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1801 host, afs_inet_ntoa_r(host->host, hoststr),
1802 ntohs(host->port)));
1805 /* We need to check whether the identity in the host structure
1806 * matches the identity on the connection. If they don't match
1807 * then treat this a new host. */
1808 if (!(host->Console & 1)
1809 && ((!identP->valid && host->interface)
1810 || (identP->valid && !host->interface)
1812 && !afs_uuid_equal(&identP->uuid,
1813 &host->interface->uuid)))) {
1814 char uuid1[128], uuid2[128];
1816 afsUUID_to_string(&identP->uuid, uuid1, 127);
1817 if (host->interface)
1818 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1820 ("CB: new identity for host %" AFS_PTR_FMT " (%s:%d), deleting(%x %x %s %s)\n",
1821 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1822 identP->valid, host->interface,
1823 identP->valid ? uuid1 : "no_uuid",
1824 host->interface ? uuid2 : "no_uuid"));
1826 /* The host in the cache is not the host for this connection */
1828 host->hostFlags |= HOSTDELETED;
1835 host = h_Alloc_r(tcon); /* returned held and locked */
1836 h_gethostcps_r(host, FT_ApproxTime());
1837 if (!(host->Console & 1)) {
1839 cb_conn = host->callback_rxcon;
1840 rx_GetConnection(cb_conn);
1841 host->hostFlags |= HWHO_INPROGRESS;
1844 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1845 if (code == RXGEN_OPCODE)
1846 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1847 rx_PutConnection(cb_conn);
1850 if ((code == RXGEN_OPCODE) ||
1851 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1854 (struct Identity *)malloc(sizeof(struct Identity));
1859 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1864 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1866 ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1867 host, afs_inet_ntoa_r(host->host, hoststr),
1868 ntohs(host->port)));
1870 } else if (code == 0) {
1873 (struct Identity *)malloc(sizeof(struct Identity));
1878 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1883 identP->uuid = interf.uuid;
1885 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1887 ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
1888 host, afs_inet_ntoa_r(host->host, hoststr),
1889 ntohs(host->port)));
1891 if (code == 0 && !identP->valid) {
1892 cb_conn = host->callback_rxcon;
1893 rx_GetConnection(cb_conn);
1895 code = RXAFSCB_InitCallBackState(cb_conn);
1896 rx_PutConnection(cb_conn);
1899 } else if (code == 0) {
1900 oldHost = h_LookupUuid_r(&identP->uuid);
1904 if (!h_Held_r(oldHost))
1907 oldHost->hostFlags |= HWHO_INPROGRESS;
1909 if (oldHost->interface) {
1911 afsUUID uuid = oldHost->interface->uuid;
1912 cb_conn = oldHost->callback_rxcon;
1913 rx_GetConnection(cb_conn);
1914 rx_SetConnDeadTime(cb_conn, 2);
1915 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1917 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1919 rx_SetConnDeadTime(cb_conn, 50);
1920 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1921 rx_PutConnection(cb_conn);
1924 /* The primary address is either not responding or
1925 * is not the client we are looking for.
1926 * MultiProbeAlternateAddress_r() will remove the
1927 * alternate interfaces that do not have the same
1929 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1931 afs_inet_ntoa_r(oldHost->host, hoststr),
1932 ntohs(oldHost->port),code2));
1933 MultiProbeAlternateAddress_r(oldHost);
1940 /* This is a new address for an existing host. Update
1941 * the list of interfaces for the existing host and
1942 * delete the host structure we just allocated. */
1944 /* prevent warnings while manipulating interface lists */
1945 host->hostFlags |= HOSTDELETED;
1947 if (oldHost->host != haddr || oldHost->port != hport) {
1948 struct rx_connection *rxconn;
1951 ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
1953 afs_inet_ntoa_r(oldHost->host, hoststr2),
1954 ntohs(oldHost->port),
1955 afs_inet_ntoa_r(haddr, hoststr),
1958 * add then remove. otherwise the host may get marked
1959 * deleted if we removed the only valid address.
1961 addInterfaceAddr_r(oldHost, haddr, hport);
1962 if (probefail || oldHost->host == haddr) {
1964 * The probe failed which means that the old
1965 * address is either unreachable or is not the
1966 * same host we were just contacted by. We will
1967 * also remove addresses if only the port has
1968 * changed because that indicates the client
1971 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
1974 struct Interface *interface = oldHost->interface;
1975 int number = oldHost->interface->numberOfInterfaces;
1976 for (i = 0; i < number; i++) {
1977 if (interface->interface[i].addr == haddr &&
1978 interface->interface[i].port != hport) {
1980 * We have just been contacted by a client
1981 * that has been seen from behind a NAT
1982 * and at least one other address.
1984 removeInterfaceAddr_r(oldHost, haddr,
1985 interface->interface[i].port);
1990 h_AddHostToAddrHashTable_r(haddr, hport, oldHost);
1991 oldHost->host = haddr;
1992 oldHost->port = hport;
1993 rxconn = oldHost->callback_rxcon;
1994 oldHost->callback_rxcon = host->callback_rxcon;
1995 host->callback_rxcon = rxconn;
1997 /* don't destroy rxconn here; let h_TossStuff_r
1998 * take care of that via h_Release_r below */
2000 host->hostFlags &= ~HWHO_INPROGRESS;
2002 /* release host because it was allocated by h_Alloc_r */
2005 /* the new host is held and locked */
2007 /* This really is a new host */
2008 h_AddHostToUuidHashTable_r(&identP->uuid, host);
2009 cb_conn = host->callback_rxcon;
2010 rx_GetConnection(cb_conn);
2013 RXAFSCB_InitCallBackState3(cb_conn,
2015 rx_PutConnection(cb_conn);
2020 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2021 host, afs_inet_ntoa_r(host->host, hoststr),
2022 ntohs(host->port)));
2023 assert(interfValid == 1);
2024 initInterfaceAddr_r(host, &interf);
2030 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2031 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2032 host->hostFlags |= VENUSDOWN;
2035 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2036 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2037 host->hostFlags |= RESETDONE;
2040 if (caps.Capabilities_val
2041 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2042 host->hostFlags |= HERRORTRANS;
2044 host->hostFlags &= ~(HERRORTRANS);
2045 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2046 host->hostFlags &= ~HWHO_INPROGRESS;
2051 if (caps.Capabilities_val)
2052 free(caps.Capabilities_val);
2053 caps.Capabilities_val = NULL;
2054 caps.Capabilities_len = 0;
2056 rx_DestroyConnection(cb_in);
2064 static char localcellname[PR_MAXNAMELEN + 1];
2065 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
2066 int num_lrealms = -1;
2070 h_InitHostPackage(void)
2072 memset(&nulluuid, 0, sizeof(afsUUID));
2073 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
2074 if (num_lrealms == -1) {
2076 for (i=0; i<AFS_NUM_LREALMS; i++) {
2077 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
2083 ("afs_krb_get_lrealm failed, using %s.\n",
2085 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
2091 /* initialize the rest of the local realms to nullstring for debugging */
2092 for (; i<AFS_NUM_LREALMS; i++)
2093 local_realms[i][0] = '\0';
2095 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2096 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2097 #ifdef AFS_PTHREAD_ENV
2098 assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
2099 #endif /* AFS_PTHREAD_ENV */
2103 MapName_r(char *aname, char *acell, afs_int32 * aval)
2108 afs_int32 anamelen, cnamelen;
2112 anamelen = strlen(aname);
2113 if (anamelen >= PR_MAXNAMELEN)
2114 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
2116 lnames.namelist_len = 1;
2117 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
2118 lids.idlist_len = 0;
2119 lids.idlist_val = NULL;
2121 cnamelen = strlen(acell);
2123 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2125 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2126 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2127 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2129 ("MapName: Name too long, using AnonymousID for %s@%s\n",
2131 *aval = AnonymousID;
2134 foreign = 1; /* attempt cross-cell authentication */
2135 tname = (char *)malloc(PR_MAXNAMELEN);
2137 ViceLog(0, ("Failed malloc in MapName_r\n"));
2140 strcpy(tname, aname);
2141 tname[anamelen] = '@';
2142 strcpy(tname + anamelen + 1, acell);
2143 lnames.namelist_val = (prname *) tname;
2148 code = hpr_NameToId(&lnames, &lids);
2151 if (lids.idlist_val) {
2152 *aval = lids.idlist_val[0];
2153 if (*aval == AnonymousID) {
2155 ("MapName: NameToId on %s returns anonymousID\n",
2156 lnames.namelist_val));
2158 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2161 ("MapName: NameToId on '%s' is unknown\n",
2162 lnames.namelist_val));
2168 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
2176 /* NOTE: this returns the client with a Write lock and a refCount */
2178 h_ID2Client(afs_int32 vid)
2180 register struct client *client;
2181 register struct host *host;
2184 for (host = hostList; host; host = host->next) {
2185 if (host->hostFlags & HOSTDELETED)
2187 for (client = host->FirstClient; client; client = client->next) {
2188 if (!client->deleted && client->ViceId == vid) {
2191 ObtainWriteLock(&client->lock);
2202 * Called by the server main loop. Returns a h_Held client, which must be
2203 * released later the main loop. Allocates a client if the matching one
2204 * isn't around. The client is returned with its reference count incremented
2205 * by one. The caller must call h_ReleaseClient_r when finished with
2208 * the client->host is returned held. h_ReleaseClient_r does not release
2209 * the hold on client->host.
2212 h_FindClient_r(struct rx_connection *tcon)
2214 register struct client *client;
2215 struct host *host = NULL;
2216 struct client *oldClient;
2217 afs_int32 viceid = 0;
2221 #if (64-MAXKTCNAMELEN)
2222 ticket name length != 64
2226 char uname[PR_MAXNAMELEN];
2227 char tcell[MAXKTCREALMLEN];
2231 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2232 if (client && client->sid == rxr_CidOf(tcon)
2233 && client->VenusEpoch == rxr_GetEpoch(tcon)) {
2235 h_Hold_r(client->host);
2236 if (!client->deleted && client->prfail != 2) {
2237 /* Could add shared lock on client here */
2238 /* note that we don't have to lock entry in this path to
2239 * ensure CPS is initialized, since we don't call rx_SetSpecific
2240 * until initialization is done, and we only get here if
2241 * rx_GetSpecific located the client structure.
2246 ObtainWriteLock(&client->lock); /* released at end */
2252 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2254 ("FindClient: authenticating connection: authClass=%d\n",
2256 if (authClass == 1) {
2257 /* A bcrypt tickets, no longer supported */
2258 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2259 viceid = AnonymousID;
2260 expTime = 0x7fffffff;
2261 } else if (authClass == 2) {
2264 /* kerberos ticket */
2265 code = rxkad_GetServerInfo(tcon, /*level */ 0, (afs_uint32 *)&expTime,
2266 tname, tinst, tcell, &kvno);
2268 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2269 viceid = AnonymousID;
2270 expTime = 0x7fffffff;
2272 int ilen = strlen(tinst);
2274 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2275 tname, tinst, tcell, expTime, kvno));
2276 strncpy(uname, tname, sizeof(uname));
2278 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2281 strcat(uname, tinst);
2283 /* translate the name to a vice id */
2284 code = MapName_r(uname, tcell, &viceid);
2288 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2291 viceid = AnonymousID;
2292 expTime = 0x7fffffff;
2296 viceid = AnonymousID; /* unknown security class */
2297 expTime = 0x7fffffff;
2300 if (!client) { /* loop */
2301 host = h_GetHost_r(tcon); /* Returns it h_Held */
2307 /* First try to find the client structure */
2308 for (client = host->FirstClient; client; client = client->next) {
2309 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2310 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2313 ObtainWriteLock(&client->lock);
2319 /* Still no client structure - get one */
2322 /* Retry to find the client structure */
2323 for (client = host->FirstClient; client; client = client->next) {
2324 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2325 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2327 goto retryfirstclient;
2332 ObtainWriteLock(&client->lock);
2333 client->refCount = 1;
2334 client->host = host;
2335 #if FS_STATS_DETAILED
2336 client->InSameNetwork = host->InSameNetwork;
2337 #endif /* FS_STATS_DETAILED */
2338 client->ViceId = viceid;
2339 client->expTime = expTime; /* rx only */
2340 client->authClass = authClass; /* rx only */
2341 client->sid = rxr_CidOf(tcon);
2342 client->VenusEpoch = rxr_GetEpoch(tcon);
2343 client->CPS.prlist_val = NULL;
2344 client->CPS.prlist_len = 0;
2348 client->prfail = fail;
2350 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2351 client->CPS.prlist_len = 0;
2352 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2353 free(client->CPS.prlist_val);
2354 client->CPS.prlist_val = NULL;
2355 client->ViceId = viceid;
2356 client->expTime = expTime;
2358 if (viceid == ANONYMOUSID) {
2359 client->CPS.prlist_len = AnonCPS.prlist_len;
2360 client->CPS.prlist_val = AnonCPS.prlist_val;
2363 code = hpr_GetCPS(viceid, &client->CPS);
2368 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2369 code, viceid, client->host,
2370 afs_inet_ntoa_r(client->host->host,hoststr),
2371 ntohs(client->host->port)));
2373 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2374 * all protection servers and reevaluates things if no
2375 * sync server or quorum is found we could still end up
2376 * with one of these errors. In such case we would like to
2377 * reevaluate the rpc call to find if there's cps for this
2378 * guy. We treat other errors (except network failures
2379 * ones - i.e. code < 0) as an indication that there is no
2380 * CPS for this host. Ideally we could like to deal this
2381 * problem the other way around (i.e. if code == NOCPS
2382 * ignore else retry next time) but the problem is that
2383 * there're other errors (i.e. EPERM) for which we don't
2384 * want to retry and we don't know the whole code list!
2386 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2390 /* the disabling of system:administrators is so iffy and has so many
2391 * possible failure modes that we will disable it again */
2392 /* Turn off System:Administrator for safety
2393 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2394 * assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2397 /* Now, tcon may already be set to a rock, since we blocked with no host
2398 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2399 * required). So, before setting the RPC's rock, we should disconnect
2400 * the RPC from the other client structure's rock.
2402 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2403 if (oldClient && oldClient != client && oldClient->sid == rxr_CidOf(tcon)
2404 && oldClient->VenusEpoch == rxr_GetEpoch(tcon)) {
2406 if (!oldClient->deleted) {
2407 /* if we didn't create it, it's not ours to put back */
2409 ViceLog(0, ("FindClient: stillborn client %x(%x); conn %x (host %s:%d) had client %x(%x)\n",
2410 client, client->sid, tcon,
2411 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2412 ntohs(rxr_PortOf(tcon)),
2413 oldClient, oldClient->sid));
2414 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2415 free(client->CPS.prlist_val);
2416 client->CPS.prlist_val = NULL;
2417 client->CPS.prlist_len = 0;
2419 /* We should perhaps check for 0 here */
2421 ReleaseWriteLock(&client->lock);
2426 oldClient->refCount++;
2428 ObtainWriteLock(&oldClient->lock);
2432 ViceLog(0, ("FindClient: deleted client %x(%x) already had conn %x (host %s:%d), stolen by client %x(%x)\n",
2433 oldClient, oldClient->sid, tcon,
2434 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2435 ntohs(rxr_PortOf(tcon)),
2436 client, client->sid));
2437 /* rx_SetSpecific will be done immediately below */
2440 /* Avoid chaining in more than once. */
2443 client->next = host->FirstClient;
2444 host->FirstClient = client;
2446 CurrentConnections++; /* increment number of connections */
2448 rx_SetSpecific(tcon, rxcon_client_key, client);
2449 ReleaseWriteLock(&client->lock);
2453 } /*h_FindClient_r */
2456 h_ReleaseClient_r(struct client *client)
2458 assert(client->refCount > 0);
2465 * Sigh: this one is used to get the client AGAIN within the individual
2466 * server routines. This does not bother h_Holding the host, since
2467 * this is assumed already have been done by the server main loop.
2468 * It does check tokens, since only the server routines can return the
2469 * VICETOKENDEAD error code
2472 GetClient(struct rx_connection *tcon, struct client **cp)
2474 register struct client *client;
2479 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2480 if (client == NULL) {
2482 ("GetClient: no client in conn %x (host %s:%d), VBUSYING\n",
2483 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2484 ntohs(rxr_PortOf(tcon))));
2488 if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2490 ("GetClient: tcon %x tcon sid %d client sid %d\n",
2491 tcon, rxr_CidOf(tcon), client->sid));
2495 if (client && client->LastCall > client->expTime && client->expTime) {
2497 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2498 afs_inet_ntoa_r(client->host->host, hoststr),
2499 ntohs(client->host->port), client->expTime));
2501 return VICETOKENDEAD;
2511 PutClient(struct client **cp)
2517 h_ReleaseClient_r(*cp);
2524 /* Client user name for short term use. Note that this is NOT inexpensive */
2526 h_UserName(struct client *client)
2528 static char User[PR_MAXNAMELEN + 1];
2532 lids.idlist_len = 1;
2533 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2534 if (!lids.idlist_val) {
2535 ViceLog(0, ("Failed malloc in h_UserName\n"));
2538 lnames.namelist_len = 0;
2539 lnames.namelist_val = (prname *) 0;
2540 lids.idlist_val[0] = client->ViceId;
2541 if (hpr_IdToName(&lids, &lnames)) {
2542 /* We need to free id we alloced above! */
2543 free(lids.idlist_val);
2544 return "*UNKNOWN USER NAME*";
2546 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2547 free(lids.idlist_val);
2548 free(lnames.namelist_val);
2557 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2558 CEs, CEBlocks, HTs, HTBlocks));
2564 h_PrintClient(register struct host *host, int held, void *rock)
2566 StreamHandle_t *file = (StreamHandle_t *)rock;
2567 register struct client *client;
2572 time_t LastCall, expTime;
2575 LastCall = host->LastCall;
2576 if (host->hostFlags & HOSTDELETED) {
2580 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2581 "Host %s:%d down = %d, LastCall %s",
2582 afs_inet_ntoa_r(host->host, hoststr),
2583 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2584 afs_ctime(&LastCall, tbuffer,
2586 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2587 for (client = host->FirstClient; client; client = client->next) {
2588 if (!client->deleted) {
2589 expTime = client->expTime;
2590 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2591 " user id=%d, name=%s, sl=%s till %s",
2592 client->ViceId, h_UserName(client),
2594 authClass ? "Authenticated" :
2595 "Not authenticated",
2597 authClass ? afs_ctime(&expTime, tbuffer,
2600 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2601 (void)afs_snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2602 client->CPS.prlist_len);
2603 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2604 if (client->CPS.prlist_val) {
2605 for (i = 0; i > client->CPS.prlist_len; i++) {
2606 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2607 client->CPS.prlist_val[i]);
2608 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2611 sprintf(tmpStr, "]\n");
2612 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2618 } /*h_PrintClient */
2623 * Print a list of clients, with last security level and token value seen,
2627 h_PrintClients(void)
2633 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2637 ("Couldn't create client dump file %s\n",
2638 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2641 now = FT_ApproxTime();
2642 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
2643 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2644 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2645 h_Enumerate(h_PrintClient, (char *)file);
2646 STREAM_REALLYCLOSE(file);
2647 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2654 h_DumpHost(register struct host *host, int held, void *rock)
2656 StreamHandle_t *file = (StreamHandle_t *)rock;
2663 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2664 "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 [",
2665 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), host->index,
2666 host->cblist, CheckLock(&host->lock), host->LastCall,
2667 host->ActiveCall, (host->hostFlags & VENUSDOWN),
2668 host->hostFlags & HOSTDELETED, host->Console,
2669 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2671 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2672 if (host->hcps.prlist_val)
2673 for (i = 0; i < host->hcps.prlist_len; i++) {
2674 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2675 host->hcps.prlist_val[i]);
2676 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2678 sprintf(tmpStr, "] [");
2679 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2680 if (host->interface)
2681 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2683 sprintf(tmpStr, " %s:%d",
2684 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2685 ntohs(host->interface->interface[i].port));
2686 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2688 sprintf(tmpStr, "] holds: ");
2689 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2691 for (i = 0; i < h_maxSlots; i++) {
2692 sprintf(tmpStr, "%04x", host->holds[i]);
2693 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2695 sprintf(tmpStr, " slot/bit: %ld/%d\n", (long int) h_holdSlot(),
2697 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2709 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2715 ("Couldn't create host dump file %s\n",
2716 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2719 now = FT_ApproxTime();
2720 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
2721 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2722 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2723 h_Enumerate(h_DumpHost, (char *)file);
2724 STREAM_REALLYCLOSE(file);
2725 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2729 #ifdef AFS_DEMAND_ATTACH_FS
2732 * host state serialization
2734 static int h_stateFillHeader(struct host_state_header * hdr);
2735 static int h_stateCheckHeader(struct host_state_header * hdr);
2736 static int h_stateAllocMap(struct fs_dump_state * state);
2737 static int h_stateSaveHost(struct host * host, int held, void *rock);
2738 static int h_stateRestoreHost(struct fs_dump_state * state);
2739 static int h_stateRestoreIndex(struct host * h, int held, void *rock);
2740 static int h_stateVerifyHost(struct host * h, int held, void *rock);
2741 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port);
2742 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2743 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2744 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2747 /* this procedure saves all host state to disk for fast startup */
2749 h_stateSave(struct fs_dump_state * state)
2751 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2754 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2756 /* invalidate host state header */
2757 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2759 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2760 sizeof(struct host_state_header))) {
2765 fs_stateIncEOF(state, sizeof(struct host_state_header));
2767 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2772 h_stateFillHeader(state->h_hdr);
2774 /* write the real header to disk */
2775 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2776 sizeof(struct host_state_header));
2783 * host state serialization
2785 * this procedure restores all host state from a disk for fast startup
2788 h_stateRestore(struct fs_dump_state * state)
2792 /* seek to the right position and read in the host state header */
2793 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2794 sizeof(struct host_state_header))) {
2799 /* check the validity of the header */
2800 if (h_stateCheckHeader(state->h_hdr)) {
2805 records = state->h_hdr->records;
2807 if (h_stateAllocMap(state)) {
2812 /* iterate over records restoring host state */
2813 for (i=0; i < records; i++) {
2814 if (h_stateRestoreHost(state) != 0) {
2825 h_stateRestoreIndices(struct fs_dump_state * state)
2827 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
2832 h_stateRestoreIndex(struct host * h, int held, void *rock)
2834 struct fs_dump_state *state = (struct fs_dump_state *)rock;
2835 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
2836 return H_ENUMERATE_BAIL(held);
2842 h_stateVerify(struct fs_dump_state * state)
2844 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
2849 h_stateVerifyHost(struct host * h, int held, void* rock)
2851 struct fs_dump_state *state = (struct fs_dump_state *)rock;
2855 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
2856 return H_ENUMERATE_BAIL(held);
2860 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
2861 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
2862 h->interface->interface[i].port)) {
2866 if (h_stateVerifyUuidHash(state, h)) {
2869 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port)) {
2873 if (cb_stateVerifyHCBList(state, h)) {
2881 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port)
2883 int ret = 0, found = 0;
2884 struct host *host = NULL;
2885 struct h_AddrHashChain *chain;
2886 int index = h_HashIndex(addr);
2890 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
2891 host = chain->hostPtr;
2893 afs_inet_ntoa_r(addr, tmp);
2894 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
2898 if ((chain->addr == addr) && (chain->port == port)) {
2900 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry points to different host struct (%d, %d)\n",
2901 h->index, host->index));
2902 state->flags.warnings_generated = 1;
2907 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
2908 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2909 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
2917 afs_inet_ntoa_r(addr, tmp);
2918 if (state->mode == FS_STATE_LOAD_MODE) {
2919 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s not found in hash\n", tmp));
2923 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s not found in hash\n", tmp));
2924 state->flags.warnings_generated = 1;
2933 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
2935 int ret = 0, found = 0;
2936 struct host *host = NULL;
2937 struct h_UuidHashChain *chain;
2938 afsUUID * uuidp = &h->interface->uuid;
2939 int index = h_UuidHashIndex(uuidp);
2943 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
2944 host = chain->hostPtr;
2946 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2947 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
2951 if (host->interface &&
2952 afs_uuid_equal(&host->interface->uuid, uuidp)) {
2954 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
2955 h->index, host->index));
2956 state->flags.warnings_generated = 1;
2961 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
2962 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2963 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
2971 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2972 if (state->mode == FS_STATE_LOAD_MODE) {
2973 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
2977 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
2978 state->flags.warnings_generated = 1;
2986 /* create the host state header structure */
2988 h_stateFillHeader(struct host_state_header * hdr)
2990 hdr->stamp.magic = HOST_STATE_MAGIC;
2991 hdr->stamp.version = HOST_STATE_VERSION;
2995 /* check the contents of the host state header structure */
2997 h_stateCheckHeader(struct host_state_header * hdr)
3001 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3002 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3005 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3006 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3012 /* allocate the host id mapping table */
3014 h_stateAllocMap(struct fs_dump_state * state)
3016 state->h_map.len = state->h_hdr->index_max + 1;
3017 state->h_map.entries = (struct idx_map_entry_t *)
3018 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3019 return (state->h_map.entries != NULL) ? 0 : 1;
3022 /* function called by h_Enumerate to save a host to disk */
3024 h_stateSaveHost(struct host * host, int held, void* rock)
3026 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3027 int if_len=0, hcps_len=0;
3028 struct hostDiskEntry hdsk;
3029 struct host_state_entry_header hdr;
3030 struct Interface * ifp = NULL;
3031 afs_int32 * hcps = NULL;
3032 struct iovec iov[4];
3035 memset(&hdr, 0, sizeof(hdr));
3037 if (state->h_hdr->index_max < host->index) {
3038 state->h_hdr->index_max = host->index;
3041 h_hostToDiskEntry_r(host, &hdsk);
3042 if (host->interface) {
3043 if_len = sizeof(struct Interface) +
3044 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3045 ifp = (struct Interface *) malloc(if_len);
3046 assert(ifp != NULL);
3047 memcpy(ifp, host->interface, if_len);
3048 hdr.interfaces = host->interface->numberOfInterfaces;
3049 iov[iovcnt].iov_base = (char *) ifp;
3050 iov[iovcnt].iov_len = if_len;
3053 if (host->hcps.prlist_val) {
3054 hdr.hcps = host->hcps.prlist_len;
3055 hcps_len = hdr.hcps * sizeof(afs_int32);
3056 hcps = (afs_int32 *) malloc(hcps_len);
3057 assert(hcps != NULL);
3058 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3059 iov[iovcnt].iov_base = (char *) hcps;
3060 iov[iovcnt].iov_len = hcps_len;
3064 if (hdsk.index > state->h_hdr->index_max)
3065 state->h_hdr->index_max = hdsk.index;
3067 hdr.len = sizeof(struct host_state_entry_header) +
3068 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3069 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3071 iov[0].iov_base = (char *) &hdr;
3072 iov[0].iov_len = sizeof(hdr);
3073 iov[1].iov_base = (char *) &hdsk;
3074 iov[1].iov_len = sizeof(struct hostDiskEntry);
3076 if (fs_stateWriteV(state, iov, iovcnt)) {
3077 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3081 fs_stateIncEOF(state, hdr.len);
3083 state->h_hdr->records++;
3090 return H_ENUMERATE_BAIL(held);
3095 /* restores a host from disk */
3097 h_stateRestoreHost(struct fs_dump_state * state)
3099 int ifp_len=0, hcps_len=0, bail=0;
3100 struct host_state_entry_header hdr;
3101 struct hostDiskEntry hdsk;
3102 struct host *host = NULL;
3103 struct Interface *ifp = NULL;
3104 afs_int32 * hcps = NULL;
3105 struct iovec iov[3];
3108 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3109 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3115 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3116 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3122 iov[0].iov_base = (char *) &hdsk;
3123 iov[0].iov_len = sizeof(struct hostDiskEntry);
3125 if (hdr.interfaces) {
3126 ifp_len = sizeof(struct Interface) +
3127 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3128 ifp = (struct Interface *) malloc(ifp_len);
3129 assert(ifp != NULL);
3130 iov[iovcnt].iov_base = (char *) ifp;
3131 iov[iovcnt].iov_len = ifp_len;
3135 hcps_len = hdr.hcps * sizeof(afs_int32);
3136 hcps = (afs_int32 *) malloc(hcps_len);
3137 assert(hcps != NULL);
3138 iov[iovcnt].iov_base = (char *) hcps;
3139 iov[iovcnt].iov_len = hcps_len;
3143 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3144 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3149 if (fs_stateReadV(state, iov, iovcnt)) {
3150 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3155 if (!hdr.hcps && hdsk.hcps_valid) {
3156 /* valid, zero-length host cps ; does this ever happen? */
3157 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3158 assert(hcps != NULL);
3162 assert(host != NULL);
3165 host->interface = ifp;
3168 host->hcps.prlist_val = hcps;
3169 host->hcps.prlist_len = hdr.hcps;
3172 h_diskEntryToHost_r(&hdsk, host);
3173 h_SetupCallbackConn_r(host);
3175 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3178 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3179 if (ifp->interface[i].valid &&
3180 !(ifp->interface[i].addr == host->host &&
3181 ifp->interface[i].port == host->port)) {
3182 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3183 ifp->interface[i].port,
3187 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3189 h_InsertList_r(host);
3191 /* setup host id map entry */
3192 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3193 state->h_map.entries[hdsk.index].new_idx = host->index;
3205 /* serialize a host structure to disk */
3207 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3209 out->host = in->host;
3210 out->port = in->port;
3211 out->hostFlags = in->hostFlags;
3212 out->Console = in->Console;
3213 out->hcpsfailed = in->hcpsfailed;
3214 out->LastCall = in->LastCall;
3215 out->ActiveCall = in->ActiveCall;
3216 out->cpsCall = in->cpsCall;
3217 out->cblist = in->cblist;
3218 #ifdef FS_STATS_DETAILED
3219 out->InSameNetwork = in->InSameNetwork;
3222 /* special fields we save, but are not memcpy'd back on restore */
3223 out->index = in->index;
3224 out->hcps_len = in->hcps.prlist_len;
3225 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3228 /* restore a host structure from disk */
3230 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3232 out->host = in->host;
3233 out->port = in->port;
3234 out->hostFlags = in->hostFlags;
3235 out->Console = in->Console;
3236 out->hcpsfailed = in->hcpsfailed;
3237 out->LastCall = in->LastCall;
3238 out->ActiveCall = in->ActiveCall;
3239 out->cpsCall = in->cpsCall;
3240 out->cblist = in->cblist;
3241 #ifdef FS_STATS_DETAILED
3242 out->InSameNetwork = in->InSameNetwork;
3246 /* index translation routines */
3248 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3252 /* hosts use a zero-based index, so old==0 is valid */
3254 if (old >= state->h_map.len) {
3255 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3257 } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
3258 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3261 *new = state->h_map.entries[old].new_idx;
3266 #endif /* AFS_DEMAND_ATTACH_FS */
3270 * This counts the number of workstations, the number of active workstations,
3271 * and the number of workstations declared "down" (i.e. not heard from
3272 * recently). An active workstation has received a call since the cutoff
3273 * time argument passed.
3276 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3278 register struct host *host;
3279 register int num = 0, active = 0, del = 0;
3282 for (host = hostList; host; host = host->next) {
3283 if (!(host->hostFlags & HOSTDELETED)) {
3285 if (host->ActiveCall > cutofftime)
3287 if (host->hostFlags & VENUSDOWN)
3299 } /*h_GetWorkStats */
3302 /*------------------------------------------------------------------------
3303 * PRIVATE h_ClassifyAddress
3306 * Given a target IP address and a candidate IP address (both
3307 * in host byte order), classify the candidate into one of three
3308 * buckets in relation to the target by bumping the counters passed
3312 * a_targetAddr : Target address.
3313 * a_candAddr : Candidate address.
3314 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3315 * addresses are either in the same network
3316 * or the same subnet.
3317 * a_diffSubnetP : ...when the candidate is in a different
3319 * a_diffNetworkP : ...when the candidate is in a different
3326 * The target and candidate addresses are both in host byte
3327 * order, NOT network byte order, when passed in.
3331 *------------------------------------------------------------------------*/
3334 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3335 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3336 afs_int32 * a_diffNetworkP)
3337 { /*h_ClassifyAddress */
3339 afs_uint32 targetNet;
3340 afs_uint32 targetSubnet;
3342 afs_uint32 candSubnet;
3345 * Put bad values into the subnet info to start with.
3347 targetSubnet = (afs_uint32) 0;
3348 candSubnet = (afs_uint32) 0;
3351 * Pull out the network and subnetwork numbers from the target
3352 * and candidate addresses. We can short-circuit this whole
3353 * affair if the target and candidate addresses are not of the
3356 if (IN_CLASSA(a_targetAddr)) {
3357 if (!(IN_CLASSA(a_candAddr))) {
3358 (*a_diffNetworkP)++;
3361 targetNet = a_targetAddr & IN_CLASSA_NET;
3362 candNet = a_candAddr & IN_CLASSA_NET;
3363 if (IN_SUBNETA(a_targetAddr))
3364 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3365 if (IN_SUBNETA(a_candAddr))
3366 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3367 } else if (IN_CLASSB(a_targetAddr)) {
3368 if (!(IN_CLASSB(a_candAddr))) {
3369 (*a_diffNetworkP)++;
3372 targetNet = a_targetAddr & IN_CLASSB_NET;
3373 candNet = a_candAddr & IN_CLASSB_NET;
3374 if (IN_SUBNETB(a_targetAddr))
3375 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3376 if (IN_SUBNETB(a_candAddr))
3377 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3378 } /*Class B target */
3379 else if (IN_CLASSC(a_targetAddr)) {
3380 if (!(IN_CLASSC(a_candAddr))) {
3381 (*a_diffNetworkP)++;
3384 targetNet = a_targetAddr & IN_CLASSC_NET;
3385 candNet = a_candAddr & IN_CLASSC_NET;
3388 * Note that class C addresses can't have subnets,
3389 * so we leave the defaults untouched.
3391 } /*Class C target */
3393 targetNet = a_targetAddr;
3394 candNet = a_candAddr;
3395 } /*Class D address */
3398 * Now, simply compare the extracted net and subnet values for
3399 * the two addresses (which at this point are known to be of the
3402 if (targetNet == candNet) {
3403 if (targetSubnet == candSubnet)
3404 (*a_sameNetOrSubnetP)++;
3408 (*a_diffNetworkP)++;
3410 } /*h_ClassifyAddress */
3413 /*------------------------------------------------------------------------
3414 * EXPORTED h_GetHostNetStats
3417 * Iterate through the host table, and classify each (non-deleted)
3418 * host entry into ``proximity'' categories (same net or subnet,
3419 * different subnet, different network).
3422 * a_numHostsP : Set to total number of (non-deleted) hosts.
3423 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3424 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3425 * a_diffNetworkP : Set to # hosts on diff network as server.
3431 * We only count non-deleted hosts. The storage pointed to by our
3432 * parameters is zeroed upon entry.
3436 *------------------------------------------------------------------------*/
3439 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3440 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3441 { /*h_GetHostNetStats */
3443 register struct host *hostP; /*Ptr to current host entry */
3444 register afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3447 * Clear out the storage pointed to by our parameters.
3449 *a_numHostsP = (afs_int32) 0;
3450 *a_sameNetOrSubnetP = (afs_int32) 0;
3451 *a_diffSubnetP = (afs_int32) 0;
3452 *a_diffNetworkP = (afs_int32) 0;
3455 for (hostP = hostList; hostP; hostP = hostP->next) {
3456 if (!(hostP->hostFlags & HOSTDELETED)) {
3458 * Bump the number of undeleted host entries found.
3459 * In classifying the current entry's address, make
3460 * sure to first convert to host byte order.
3463 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3464 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3465 a_sameNetOrSubnetP, a_diffSubnetP,
3467 } /*Only look at non-deleted hosts */
3468 } /*For each host record hashed to this index */
3470 } /*h_GetHostNetStats */
3472 static afs_uint32 checktime;
3473 static afs_uint32 clientdeletetime;
3474 static struct AFSFid zerofid;
3478 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3479 * Since it can serialize them, and pile up, it should be a separate LWP
3480 * from other events.
3484 CheckHost(register struct host *host, int held, void *rock)
3486 register struct client *client;
3487 struct rx_connection *cb_conn = NULL;
3490 #ifdef AFS_DEMAND_ATTACH_FS
3491 /* kill the checkhost lwp ASAP during shutdown */
3493 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3495 return H_ENUMERATE_BAIL(held);
3500 /* Host is held by h_Enumerate */
3502 for (client = host->FirstClient; client; client = client->next) {
3503 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3504 client->deleted = 1;
3505 host->hostFlags |= CLIENTDELETED;
3508 if (host->LastCall < checktime) {
3510 host->hostFlags |= HWHO_INPROGRESS;
3511 if (!(host->hostFlags & HOSTDELETED)) {
3512 cb_conn = host->callback_rxcon;
3513 rx_GetConnection(cb_conn);
3514 if (host->LastCall < clientdeletetime) {
3515 host->hostFlags |= HOSTDELETED;
3516 if (!(host->hostFlags & VENUSDOWN)) {
3517 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3518 if (host->interface) {
3521 RXAFSCB_InitCallBackState3(cb_conn,
3527 RXAFSCB_InitCallBackState(cb_conn);
3530 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3533 (void)afs_inet_ntoa_r(host->host, hoststr);
3535 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3536 hoststr, ntohs(host->port)));
3537 host->hostFlags |= VENUSDOWN;
3539 /* Note: it's safe to delete hosts even if they have call
3540 * back state, because break delayed callbacks (called when a
3541 * message is received from the workstation) will always send a
3542 * break all call backs to the workstation if there is no
3547 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3549 (void)afs_inet_ntoa_r(host->host, hoststr);
3550 if (host->interface) {
3551 afsUUID uuid = host->interface->uuid;
3553 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3556 if (MultiProbeAlternateAddress_r(host)) {
3557 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3558 hoststr, ntohs(host->port), code));
3559 host->hostFlags |= VENUSDOWN;
3564 code = RXAFSCB_Probe(cb_conn);
3568 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3569 hoststr, ntohs(host->port), code));
3570 host->hostFlags |= VENUSDOWN;
3576 rx_PutConnection(cb_conn);
3580 host->hostFlags &= ~HWHO_INPROGRESS;
3590 CheckHost_r(register struct host *host, int held, void *dummy)
3592 register struct client *client;
3593 struct rx_connection *cb_conn = NULL;
3596 #ifdef AFS_DEMAND_ATTACH_FS
3597 /* kill the checkhost lwp ASAP during shutdown */
3599 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3601 return H_ENUMERATE_BAIL(held);
3606 /* Host is held by h_Enumerate_r */
3607 for (client = host->FirstClient; client; client = client->next) {
3608 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3609 client->deleted = 1;
3610 host->hostFlags |= CLIENTDELETED;
3613 if (host->LastCall < checktime) {
3615 if (!(host->hostFlags & HOSTDELETED)) {
3616 cb_conn = host->callback_rxcon;
3617 rx_GetConnection(cb_conn);
3618 if (host->LastCall < clientdeletetime) {
3619 host->hostFlags |= HOSTDELETED;
3620 if (!(host->hostFlags & VENUSDOWN)) {
3621 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3622 if (host->interface) {
3625 RXAFSCB_InitCallBackState3(cb_conn,
3631 RXAFSCB_InitCallBackState(cb_conn);
3634 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3637 (void)afs_inet_ntoa_r(host->host, hoststr);
3639 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3640 hoststr, ntohs(host->port)));
3641 host->hostFlags |= VENUSDOWN;
3643 /* Note: it's safe to delete hosts even if they have call
3644 * back state, because break delayed callbacks (called when a
3645 * message is received from the workstation) will always send a
3646 * break all call backs to the workstation if there is no
3651 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3653 (void)afs_inet_ntoa_r(host->host, hoststr);
3654 if (host->interface) {
3655 afsUUID uuid = host->interface->uuid;
3657 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3660 if (MultiProbeAlternateAddress_r(host)) {
3661 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3662 hoststr, ntohs(host->port), code));
3663 host->hostFlags |= VENUSDOWN;
3668 code = RXAFSCB_Probe(cb_conn);
3672 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3673 hoststr, ntohs(host->port), code));
3674 host->hostFlags |= VENUSDOWN;
3680 rx_PutConnection(cb_conn);
3692 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3693 * don't respond to a probe. Note that VenusDown can only be cleared if
3694 * a message is received from the host (see ServerLWP in file.c).
3695 * Delete hosts that have not had any calls in 1 hour, clients that
3696 * have not had any calls in 15 minutes.
3698 * This routine is called roughly every 5 minutes.
3703 afs_uint32 now = FT_ApproxTime();
3705 memset(&zerofid, 0, sizeof(zerofid));
3707 * Send a probe to the workstation if it hasn't been heard from in
3710 checktime = now - 15 * 60;
3711 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3714 h_Enumerate_r(CheckHost_r, hostList, NULL);
3719 * This is called with host locked and held. At this point, the
3720 * hostAddrHashTable has an entry for the primary addr/port inserted
3721 * by h_Alloc_r(). No other interfaces should be considered valid.
3723 * The addresses in the interfaceAddr list are in host byte order.
3726 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3733 struct Interface *interface;
3736 afs_uint16 port7001 = htons(7001);
3741 number = interf->numberOfInterfaces;
3742 myAddr = host->host; /* current interface address */
3743 myPort = host->port; /* current port */
3746 ("initInterfaceAddr : host %s:%d numAddr %d\n",
3747 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3749 /* validation checks */
3750 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3752 ("Invalid number of alternate addresses is %d\n", number));
3757 * The client's notion of its own IP addresses is not reliable.
3759 * 1. The client list might contain private address ranges which
3760 * are likely to be re-used by many clients allocated addresses
3763 * 2. The client list will not include any public addresses that
3764 * are hidden by a NAT.
3766 * 3. Private address ranges that are exposed to the server will
3767 * be obtained from the rx connections that use them.
3769 * 4. Lists provided by the client are not necessarily truthful.
3770 * Many existing clients (UNIX) do not refresh the IP address
3771 * list as the actual assigned addresses change. The end result
3772 * is that they report the initial address list for the lifetime
3773 * of the process. In other words, a client can report addresses
3774 * that they are in fact not using. Adding these addresses to
3775 * the host interface list without verification is not only
3776 * pointless, it is downright dangerous.
3778 * We therefore do not add alternate addresses to the addr hash table.
3779 * We only use them for multi-rx callback breaks.
3783 * Convert IP addresses to network byte order, and remove
3784 * duplicate IP addresses from the interface list, and
3785 * determine whether or not the incoming addr/port is
3786 * listed. Note that if the address matches it is not
3787 * truly a match because the port number for the entries
3788 * in the interface list are port 7001 and the port number
3789 * for this connection might not be 7001.
3791 for (i = 0, count = 0, found = 0; i < number; i++) {
3792 interf->addr_in[i] = htonl(interf->addr_in[i]);
3793 for (j = 0; j < count; j++) {
3794 if (interf->addr_in[j] == interf->addr_in[i])
3798 interf->addr_in[count] = interf->addr_in[i];
3799 if (interf->addr_in[count] == myAddr &&
3807 * Allocate and initialize an interface structure for this host.
3810 interface = (struct Interface *)
3811 malloc(sizeof(struct Interface) +
3812 (sizeof(struct AddrPort) * (count - 1)));
3814 ViceLog(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
3817 interface->numberOfInterfaces = count;
3819 interface = (struct Interface *)
3820 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
3822 ViceLog(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
3825 interface->numberOfInterfaces = count + 1;
3826 interface->interface[count].addr = myAddr;
3827 interface->interface[count].port = myPort;
3828 interface->interface[count].valid = 1;
3831 for (i = 0; i < count; i++) {
3833 interface->interface[i].addr = interf->addr_in[i];
3834 /* We store the port as 7001 because the addresses reported by
3835 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
3836 * are coming from fully connected hosts (no NAT/PATs)
3838 interface->interface[i].port = port7001;
3839 interface->interface[i].valid =
3840 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
3843 interface->uuid = interf->uuid;
3845 assert(!host->interface);
3846 host->interface = interface;
3848 if (LogLevel >= 125) {
3849 afsUUID_to_string(&interface->uuid, uuidstr, 127);
3851 ViceLog(125, ("--- uuid %s\n", uuidstr));
3852 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
3853 ViceLog(125, ("--- alt address %s:%d\n",
3854 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3855 ntohs(host->interface->interface[i].port)));
3862 /* deleted a HashChain structure for this address and host */
3863 /* returns 1 on success */
3865 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
3869 register struct h_AddrHashChain **hp, *th;
3871 if (addr == 0 && port == 0)
3874 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
3876 assert(th->hostPtr);
3877 if (th->hostPtr == host && th->addr == addr && th->port == port) {
3878 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
3879 host, afs_inet_ntoa_r(host->host, hoststr),
3880 ntohs(host->port)));
3887 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
3888 host, afs_inet_ntoa_r(host->host, hoststr),
3889 ntohs(host->port)));
3895 ** prints out all alternate interface address for the host. The 'level'
3896 ** parameter indicates what level of debugging sets this output
3899 printInterfaceAddr(struct host *host, int level)
3904 if (host->interface) {
3905 /* check alternate addresses */
3906 number = host->interface->numberOfInterfaces;
3908 ViceLog(level, ("no-addresses "));
3910 for (i = 0; i < number; i++)
3911 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3912 ntohs(host->interface->interface[i].port)));
3915 ViceLog(level, ("\n"));