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>
26 #include <netinet/in.h>
39 #include <afs/assert.h>
42 #include <afs/afsint.h>
43 #include <afs/rxgen_consts.h>
45 #include <afs/errors.h>
46 #include <afs/ihandle.h>
47 #include <afs/vnode.h>
48 #include <afs/volume.h>
49 #ifdef AFS_ATHENA_STDENV
53 #include <afs/ptclient.h>
54 #include <afs/ptuser.h>
55 #include <afs/prs_fs.h>
57 #include <afs/afsutil.h>
58 #include <afs/com_err.h>
60 #include <afs/cellconfig.h>
62 #include "viced_prototypes.h"
66 #ifdef AFS_DEMAND_ATTACH_FS
67 #include "../util/afsutil_prototypes.h"
68 #include "../tviced/serialize_state.h"
69 #endif /* AFS_DEMAND_ATTACH_FS */
71 #ifdef AFS_PTHREAD_ENV
72 pthread_mutex_t host_glock_mutex;
73 #endif /* AFS_PTHREAD_ENV */
76 extern int CurrentConnections;
78 extern int AnonymousID;
79 extern prlist AnonCPS;
81 extern struct afsconf_dir *confDir; /* config dir object */
82 extern int lwps; /* the max number of server threads */
83 extern afsUUID FS_HostUUID;
85 int CEs = 0; /* active clients */
86 int CEBlocks = 0; /* number of blocks of CEs */
87 struct client *CEFree = 0; /* first free client */
88 struct host *hostList = 0; /* linked list of all hosts */
89 int hostCount = 0; /* number of hosts in hostList */
93 static struct rx_securityClass *sc = NULL;
95 static void h_SetupCallbackConn_r(struct host * host);
96 static void h_AddHostToHashTable_r(afs_uint32 addr, afs_uint16 port, struct host * host);
97 static void h_AddHostToUuidHashTable_r(afsUUID * uuid, struct host * host);
98 static int h_DeleteHostFromHashTableByAddr_r(afs_uint32 addr, afs_uint16 port, struct host *host);
100 #define CESPERBLOCK 73
101 struct CEBlock { /* block of CESPERBLOCK file entries */
102 struct client entry[CESPERBLOCK];
105 static void h_TossStuff_r(register struct host *host);
106 static int hashDelete_r(afs_uint32 addr, afs_uint16 port, struct host *host);
109 * Make sure the subnet macros have been defined.
112 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
115 #ifndef IN_CLASSA_SUBNET
116 #define IN_CLASSA_SUBNET 0xffff0000
120 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
123 #ifndef IN_CLASSB_SUBNET
124 #define IN_CLASSB_SUBNET 0xffffff00
128 /* get a new block of CEs and chain it on CEFree */
132 register struct CEBlock *block;
135 block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
137 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
138 ShutDownAndCore(PANIC);
141 for (i = 0; i < (CESPERBLOCK - 1); i++) {
142 Lock_Init(&block->entry[i].lock);
143 block->entry[i].next = &(block->entry[i + 1]);
145 block->entry[CESPERBLOCK - 1].next = 0;
146 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
147 CEFree = (struct client *)block;
153 /* get the next available CE */
154 static struct client *
157 register struct client *entry;
162 ViceLog(0, ("CEFree NULL in GetCE\n"));
163 ShutDownAndCore(PANIC);
167 CEFree = entry->next;
169 memset((char *)entry, 0, CLIENT_TO_ZERO(entry));
175 /* return an entry to the free list */
177 FreeCE(register struct client *entry)
179 entry->VenusEpoch = 0;
181 entry->next = CEFree;
188 * The HTs and HTBlocks variables were formerly static, but they are
189 * now referenced elsewhere in the FileServer.
191 int HTs = 0; /* active file entries */
192 int HTBlocks = 0; /* number of blocks of HTs */
193 static struct host *HTFree = 0; /* first free file entry */
196 * Hash tables of host pointers. We need two tables, one
197 * to map IP addresses onto host pointers, and another
198 * to map host UUIDs onto host pointers.
200 static struct h_hashChain *hostHashTable[h_HASHENTRIES];
201 static struct h_hashChain *hostUuidHashTable[h_HASHENTRIES];
202 #define h_HashIndex(hostip) ((hostip) & (h_HASHENTRIES-1))
203 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
205 struct HTBlock { /* block of HTSPERBLOCK file entries */
206 struct host entry[h_HTSPERBLOCK];
210 /* get a new block of HTs and chain it on HTFree */
214 register struct HTBlock *block;
216 static int index = 0;
218 if (HTBlocks == h_MAXHOSTTABLES) {
219 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
220 ShutDownAndCore(PANIC);
223 block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
225 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
226 ShutDownAndCore(PANIC);
228 #ifdef AFS_PTHREAD_ENV
229 for (i = 0; i < (h_HTSPERBLOCK); i++)
230 assert(pthread_cond_init(&block->entry[i].cond, NULL) == 0);
231 #endif /* AFS_PTHREAD_ENV */
232 for (i = 0; i < (h_HTSPERBLOCK); i++)
233 Lock_Init(&block->entry[i].lock);
234 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
235 block->entry[i].next = &(block->entry[i + 1]);
236 for (i = 0; i < (h_HTSPERBLOCK); i++)
237 block->entry[i].index = index++;
238 block->entry[h_HTSPERBLOCK - 1].next = 0;
239 HTFree = (struct host *)block;
240 hosttableptrs[HTBlocks++] = block->entry;
245 /* get the next available HT */
249 register struct host *entry;
253 assert(HTFree != NULL);
255 HTFree = entry->next;
257 memset((char *)entry, 0, HOST_TO_ZERO(entry));
263 /* return an entry to the free list */
265 FreeHT(register struct host *entry)
267 entry->next = HTFree;
274 hpr_Initialize(struct ubik_client **uclient)
277 struct rx_connection *serverconns[MAXSERVERS];
278 struct rx_securityClass *sc[3];
279 struct afsconf_dir *tdir;
280 char tconfDir[100] = "";
282 struct ktc_token ttoken;
284 struct afsconf_cell info;
288 tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
290 ViceLog(0, ("hpr_Initialize: Could not open configuration directory: %s", AFSDIR_SERVER_ETC_DIRPATH));
294 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
296 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
301 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
303 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s", cellstr, confDir, AFSDIR_CELLSERVDB_FILE));
310 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
319 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
320 * to force use of the KeyFile. secLevel == 0 implies -noauth was
322 if ((afsconf_GetLatestKey(tdir, 0, 0) == 0)) {
323 code = afsconf_ClientAuthSecure(tdir, &sc[2], &scIndex);
325 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s (so trying noauth)", code, afs_error_message(code)));
327 scIndex = 0; /* use noauth */
329 /* if there was a problem, an unauthenticated conn is returned */
332 struct ktc_principal sname;
333 strcpy(sname.cell, info.name);
334 sname.instance[0] = 0;
335 strcpy(sname.name, "afs");
336 code = ktc_GetToken(&sname, &ttoken, sizeof(ttoken), NULL);
340 if (ttoken.kvno >= 0 && ttoken.kvno <= 256)
341 /* this is a kerberos ticket, set scIndex accordingly */
344 ViceLog(0, ("hpr_Initialize: funny kvno (%d) in ticket, proceeding", ttoken.kvno));
348 rxkad_NewClientSecurityObject(rxkad_clear, &ttoken.sessionKey,
349 ttoken.kvno, ttoken.ticketLen,
353 if ((scIndex == 0) && (sc[0] == 0))
354 sc[0] = rxnull_NewClientSecurityObject();
356 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, running unauthenticated. [%d]", code));
358 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
359 for (i = 0; i < info.numServers; i++) {
361 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
362 info.hostAddr[i].sin_port, PRSRV, sc[scIndex],
366 code = ubik_ClientInit(serverconns, uclient);
368 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
371 code = rxs_Release(sc[scIndex]);
376 hpr_End(struct ubik_client *uclient)
381 code = ubik_ClientDestroy(uclient);
387 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
389 #ifdef AFS_PTHREAD_ENV
390 register afs_int32 code;
392 struct ubik_client *uclient =
393 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
396 code = hpr_Initialize(&uclient);
397 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
401 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
402 if (code != PRSUCCESS)
405 /* do something about this, probably make a new call */
406 /* don't forget there's a hard limit in the interface */
408 "membership list for host id %d exceeds display limit\n",
413 return pr_GetHostCPS(host, CPS);
418 hpr_NameToId(namelist *names, idlist *ids)
420 #ifdef AFS_PTHREAD_ENV
421 register afs_int32 code;
422 register afs_int32 i;
423 struct ubik_client *uclient =
424 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
427 code = hpr_Initialize(&uclient);
428 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
431 for (i = 0; i < names->namelist_len; i++)
432 stolower(names->namelist_val[i]);
433 code = ubik_PR_NameToID(uclient, 0, names, ids);
436 return pr_NameToId(names, ids);
441 hpr_IdToName(idlist *ids, namelist *names)
443 #ifdef AFS_PTHREAD_ENV
444 register afs_int32 code;
445 struct ubik_client *uclient =
446 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
449 code = hpr_Initialize(&uclient);
450 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
453 code = ubik_PR_IDToName(uclient, 0, ids, names);
456 return pr_IdToName(ids, names);
461 hpr_GetCPS(afs_int32 id, prlist *CPS)
463 #ifdef AFS_PTHREAD_ENV
464 register afs_int32 code;
466 struct ubik_client *uclient =
467 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
470 code = hpr_Initialize(&uclient);
471 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
475 code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
476 if (code != PRSUCCESS)
479 /* do something about this, probably make a new call */
480 /* don't forget there's a hard limit in the interface */
481 fprintf(stderr, "membership list for id %d exceeds display limit\n",
486 return pr_GetCPS(id, CPS);
490 static short consolePort = 0;
493 h_Release(register struct host *host)
502 * If this thread does not have a hold on this host AND
503 * if other threads also dont have any holds on this host AND
504 * If either the HOSTDELETED or CLIENTDELETED flags are set
508 h_Release_r(register struct host *host)
511 if (!((host)->holds[h_holdSlot()] & ~h_holdbit())) {
512 if (!h_OtherHolds_r(host)) {
513 /* must avoid masking this until after h_OtherHolds_r runs
514 * but it should be run before h_TossStuff_r */
515 (host)->holds[h_holdSlot()] &= ~h_holdbit();
516 if ((host->hostFlags & HOSTDELETED)
517 || (host->hostFlags & CLIENTDELETED)) {
521 (host)->holds[h_holdSlot()] &= ~h_holdbit();
523 (host)->holds[h_holdSlot()] &= ~h_holdbit();
529 h_OtherHolds_r(register struct host *host)
531 register int i, bit, slot;
534 for (i = 0; i < h_maxSlots; i++) {
535 if (host->holds[i] != ((i == slot) ? bit : 0)) {
543 h_Lock_r(register struct host *host)
553 * returns 1 if already locked
554 * else returns locks and returns 0
558 h_NBLock_r(register struct host *host)
560 struct Lock *hostLock = &host->lock;
565 if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
566 hostLock->excl_locked = WRITE_LOCK;
570 LOCK_UNLOCK(hostLock);
579 #if FS_STATS_DETAILED
580 /*------------------------------------------------------------------------
581 * PRIVATE h_AddrInSameNetwork
584 * Given a target IP address and a candidate IP address (both
585 * in host byte order), return a non-zero value (1) if the
586 * candidate address is in a different network from the target
590 * a_targetAddr : Target address.
591 * a_candAddr : Candidate address.
594 * 1 if the candidate address is in the same net as the target,
598 * The target and candidate addresses are both in host byte
599 * order, NOT network byte order, when passed in. We return
600 * our value as a character, since that's the type of field in
601 * the host structure, where this info will be stored.
605 *------------------------------------------------------------------------*/
608 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
609 { /*h_AddrInSameNetwork */
611 afs_uint32 targetNet;
615 * Pull out the network and subnetwork numbers from the target
616 * and candidate addresses. We can short-circuit this whole
617 * affair if the target and candidate addresses are not of the
620 if (IN_CLASSA(a_targetAddr)) {
621 if (!(IN_CLASSA(a_candAddr))) {
624 targetNet = a_targetAddr & IN_CLASSA_NET;
625 candNet = a_candAddr & IN_CLASSA_NET;
626 } else if (IN_CLASSB(a_targetAddr)) {
627 if (!(IN_CLASSB(a_candAddr))) {
630 targetNet = a_targetAddr & IN_CLASSB_NET;
631 candNet = a_candAddr & IN_CLASSB_NET;
632 } /*Class B target */
633 else if (IN_CLASSC(a_targetAddr)) {
634 if (!(IN_CLASSC(a_candAddr))) {
637 targetNet = a_targetAddr & IN_CLASSC_NET;
638 candNet = a_candAddr & IN_CLASSC_NET;
639 } /*Class C target */
641 targetNet = a_targetAddr;
642 candNet = a_candAddr;
643 } /*Class D address */
646 * Now, simply compare the extracted net values for the two addresses
647 * (which at this point are known to be of the same class)
649 if (targetNet == candNet)
654 } /*h_AddrInSameNetwork */
655 #endif /* FS_STATS_DETAILED */
658 /* Assumptions: called with held host */
660 h_gethostcps_r(register struct host *host, register afs_int32 now)
665 /* wait if somebody else is already doing the getCPS call */
666 while (host->hostFlags & HCPS_INPROGRESS) {
667 slept = 1; /* I did sleep */
668 host->hostFlags |= HCPS_WAITING; /* I am sleeping now */
669 #ifdef AFS_PTHREAD_ENV
670 pthread_cond_wait(&host->cond, &host_glock_mutex);
671 #else /* AFS_PTHREAD_ENV */
672 if ((code = LWP_WaitProcess(&(host->hostFlags))) != LWP_SUCCESS)
673 ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
674 #endif /* AFS_PTHREAD_ENV */
678 host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
679 if (host->hcps.prlist_val)
680 free(host->hcps.prlist_val); /* this is for hostaclRefresh */
681 host->hcps.prlist_val = NULL;
682 host->hcps.prlist_len = 0;
683 host->cpsCall = slept ? (FT_ApproxTime()) : (now);
686 code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
690 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
691 * and reevaluates things if no sync server or quorum is found we could still end up
692 * with one of these errors. In such case we would like to reevaluate the rpc call to
693 * find if there's cps for this guy. We treat other errors (except network failures
694 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
695 * we could like to deal this problem the other way around (i.e. if code == NOCPS
696 * ignore else retry next time) but the problem is that there're other errors (i.e.
697 * EPERM) for which we don't want to retry and we don't know the whole code list!
699 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
701 * We would have preferred to use a while loop and try again since ops in protected
702 * acls for this host will fail now but they'll be reevaluated on any subsequent
703 * call. The attempt to wait for a quorum/sync site or network error won't work
704 * since this problems really should only occurs during a complete fileserver
705 * restart. Since the fileserver will start before the ptservers (and thus before
706 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
708 host->hcpsfailed = 1;
710 ("Warning: GetHostCPS failed (%d) for %x; will retry\n",
713 host->hcpsfailed = 0;
715 ("gethost: GetHostCPS failed (%d) for %x; ignored\n",
718 if (host->hcps.prlist_val)
719 free(host->hcps.prlist_val);
720 host->hcps.prlist_val = NULL;
721 host->hcps.prlist_len = 0; /* Make sure it's zero */
723 host->hcpsfailed = 0;
725 host->hostFlags &= ~HCPS_INPROGRESS;
726 /* signal all who are waiting */
727 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
728 host->hostFlags &= ~HCPS_WAITING;
729 #ifdef AFS_PTHREAD_ENV
730 assert(pthread_cond_broadcast(&host->cond) == 0);
731 #else /* AFS_PTHREAD_ENV */
732 if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
733 ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
734 #endif /* AFS_PTHREAD_ENV */
738 /* args in net byte order */
740 h_flushhostcps(register afs_uint32 hostaddr, register afs_uint16 hport)
742 register struct host *host;
746 host = h_Lookup_r(hostaddr, hport, &held);
748 host->hcpsfailed = 1;
758 * Allocate a host. It will be identified by the peer (ip,port) info in the
759 * rx connection provided. The host is returned held and locked
761 #define DEF_ROPCONS 2115
764 h_Alloc_r(register struct rx_connection *r_con)
766 struct servent *serverentry;
769 #if FS_STATS_DETAILED
770 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
771 #endif /* FS_STATS_DETAILED */
775 host->host = rxr_HostOf(r_con);
776 host->port = rxr_PortOf(r_con);
778 h_AddHostToHashTable_r(host->host, host->port, host);
780 if (consolePort == 0) { /* find the portal number for console */
781 #if defined(AFS_OSF_ENV)
782 serverentry = getservbyname("ropcons", "");
784 serverentry = getservbyname("ropcons", 0);
787 consolePort = serverentry->s_port;
789 consolePort = htons(DEF_ROPCONS); /* Use a default */
791 if (host->port == consolePort)
793 /* Make a callback channel even for the console, on the off chance that it
794 * makes a request that causes a break call back. It shouldn't. */
795 h_SetupCallbackConn_r(host);
796 now = host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
798 host->hcps.prlist_val = NULL;
799 host->hcps.prlist_len = 0;
800 host->interface = NULL;
802 host->hcpsfailed = 0; /* save cycles */
803 h_gethostcps(host); /* do this under host hold/lock */
805 host->FirstClient = NULL;
808 h_InsertList_r(host); /* update global host List */
809 #if FS_STATS_DETAILED
811 * Compare the new host's IP address (in host byte order) with ours
812 * (the File Server's), remembering if they are in the same network.
814 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
815 host->InSameNetwork =
816 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
817 #endif /* FS_STATS_DETAILED */
824 /* Make a callback channel even for the console, on the off chance that it
825 * makes a request that causes a break call back. It shouldn't. */
827 h_SetupCallbackConn_r(struct host * host)
830 sc = rxnull_NewClientSecurityObject();
831 host->callback_rxcon =
832 rx_NewConnection(host->host, host->port, 1, sc, 0);
833 rx_SetConnDeadTime(host->callback_rxcon, 50);
834 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
837 /* Lookup a host given an IP address and UDP port number. */
838 /* hostaddr and hport are in network order */
839 /* Note: host should be released by caller if 0 == *heldp and non-null */
840 /* hostaddr and hport are in network order */
842 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, int *heldp)
845 struct host *host = 0;
846 struct h_hashChain *chain;
847 int index = h_HashIndex(haddr);
848 extern int hostaclRefresh;
851 for (chain = hostHashTable[index]; chain; chain = chain->next) {
852 host = chain->hostPtr;
854 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
855 && chain->port == hport) {
856 *heldp = h_Held_r(host);
860 if (host->hostFlags & HOSTDELETED) {
867 now = FT_ApproxTime(); /* always evaluate "now" */
868 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
870 * Every hostaclRefresh period (def 2 hrs) get the new
871 * membership list for the host. Note this could be the
872 * first time that the host is added to a group. Also
873 * here we also retry on previous legitimate hcps failures.
875 * If we get here we still have a host hold.
877 h_gethostcps_r(host, now);
887 /* Lookup a host given its UUID. */
889 h_LookupUuid_r(afsUUID * uuidp)
891 struct host *host = 0;
892 struct h_hashChain *chain;
893 int index = h_UuidHashIndex(uuidp);
895 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
896 host = chain->hostPtr;
898 if (!(host->hostFlags & HOSTDELETED) && host->interface
899 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
910 * h_Hold_r: Establish a hold by the current LWP on this host--the host
911 * or its clients will not be physically deleted until all holds have
913 * NOTE: h_Hold_r is a macro defined in host.h.
916 /* h_TossStuff_r: Toss anything in the host structure (the host or
917 * clients marked for deletion. Called from h_Release_r ONLY.
918 * To be called, there must be no holds, and either host->deleted
919 * or host->clientDeleted must be set.
922 h_TossStuff_r(register struct host *host)
924 register struct client **cp, *client;
927 /* if somebody still has this host held */
928 for (i = 0; (i < h_maxSlots) && (!(host)->holds[i]); i++);
932 /* if somebody still has this host locked */
933 if (h_NBLock_r(host) != 0) {
936 ("Warning: h_TossStuff_r failed; Host %s:%d was locked.\n",
937 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
943 /* ASSUMPTION: rxi_FreeConnection() does not yield */
944 for (cp = &host->FirstClient; (client = *cp);) {
945 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
947 ObtainWriteLockNoBlock(&client->lock, code);
951 ("Warning: h_TossStuff_r failed: Host %s:%d client %x was locked.\n",
952 afs_inet_ntoa_r(host->host, hoststr),
953 ntohs(host->port), client));
957 if (client->refCount) {
960 ("Warning: h_TossStuff_r failed: Host %s:%d client %x refcount %d.\n",
961 afs_inet_ntoa_r(host->host, hoststr),
962 ntohs(host->port), client, client->refCount));
963 /* This is the same thing we do if the host is locked */
964 ReleaseWriteLock(&client->lock);
967 client->CPS.prlist_len = 0;
968 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
969 free(client->CPS.prlist_val);
970 client->CPS.prlist_val = NULL;
971 CurrentConnections--;
973 ReleaseWriteLock(&client->lock);
979 /* We've just cleaned out all the deleted clients; clear the flag */
980 host->hostFlags &= ~CLIENTDELETED;
982 if (host->hostFlags & HOSTDELETED) {
983 register struct h_hashChain **hp, *th;
984 register struct rx_connection *rxconn;
986 struct AddrPort hostAddrPort;
989 if (host->Console & 1)
991 if ((rxconn = host->callback_rxcon)) {
992 host->callback_rxcon = (struct rx_connection *)0;
993 rx_DestroyConnection(rxconn);
995 if (host->hcps.prlist_val)
996 free(host->hcps.prlist_val);
997 host->hcps.prlist_val = NULL;
998 host->hcps.prlist_len = 0;
999 DeleteAllCallBacks_r(host, 1);
1000 host->hostFlags &= ~RESETDONE; /* just to be safe */
1002 /* if alternate addresses do not exist */
1003 if (!(host->interface)) {
1004 for (hp = &hostHashTable[h_HashIndex(host->host)]; (th = *hp);
1006 assert(th->hostPtr);
1007 if (th->hostPtr == host) {
1009 h_DeleteList_r(host);
1016 /* delete all hash entries for the UUID */
1017 uuidp = &host->interface->uuid;
1018 for (hp = &hostUuidHashTable[h_UuidHashIndex(uuidp)]; (th = *hp);
1020 assert(th->hostPtr);
1021 if (th->hostPtr == host) {
1027 /* delete all hash entries for alternate addresses */
1028 assert(host->interface->numberOfInterfaces > 0);
1029 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
1030 hostAddrPort = host->interface->interface[i];
1032 for (hp = &hostHashTable[h_HashIndex(hostAddrPort.addr)]; (th = *hp);
1034 assert(th->hostPtr);
1035 if (th->hostPtr == host) {
1042 free(host->interface);
1043 host->interface = NULL;
1044 h_DeleteList_r(host); /* remove host from global host List */
1046 } /* if alternate address exists */
1048 } /*h_TossStuff_r */
1051 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
1052 * system at the start of the enumeration (perhaps more). Hosts may be deleted
1053 * (have delete flag set); ditto for clients. (*proc) is always called with
1054 * host h_held(). The hold state of the host with respect to this lwp is passed
1055 * to (*proc) as the param held. The proc should return 0 if the host should be
1056 * released, 1 if it should be held after enumeration.
1059 h_Enumerate(int (*proc) (), char *param)
1061 register struct host *host, **list;
1063 register int i, count;
1066 if (hostCount == 0) {
1070 list = (struct host **)malloc(hostCount * sizeof(struct host *));
1072 ViceLog(0, ("Failed malloc in h_Enumerate\n"));
1075 held = (int *)malloc(hostCount * sizeof(int));
1077 ViceLog(0, ("Failed malloc in h_Enumerate\n"));
1080 for (count = 0, host = hostList; host; host = host->next, count++) {
1082 if (!(held[count] = h_Held_r(host)))
1085 assert(count == hostCount);
1087 for (i = 0; i < count; i++) {
1088 held[i] = (*proc) (list[i], held[i], param);
1089 if (!H_ENUMERATE_ISSET_HELD(held[i]))
1090 h_Release(list[i]); /* this might free up the host */
1091 /* bail out of the enumeration early */
1092 if (H_ENUMERATE_ISSET_BAIL(held[i]))
1099 /* h_Enumerate_r (revised):
1100 * Calls (*proc)(host, held, param) for each host in hostList, starting
1102 * Hosts may be deleted (have delete flag set); ditto for clients.
1103 * (*proc) is always called with
1104 * host h_held() and the global host lock (H_LOCK) locked.The hold state of the
1105 * host with respect to this lwp is passed to (*proc) as the param held.
1106 * The proc should return 0 if the host should be released, 1 if it should
1107 * be held after enumeration.
1110 h_Enumerate_r(int (*proc) (), struct host *enumstart, char *param)
1112 register struct host *host, *next;
1113 register int held, nheld;
1115 if (hostCount == 0) {
1118 if (enumstart && !(held = h_Held_r(enumstart)))
1119 h_Hold_r(enumstart);
1120 for (host = enumstart; host; host = next, held = nheld) {
1122 if (next && !(nheld = h_Held_r(next)) && !H_ENUMERATE_ISSET_BAIL(held))
1124 held = (*proc) (host, held, param);
1125 if (!H_ENUMERATE_ISSET_HELD(held))
1126 h_Release_r(host); /* this might free up the host */
1127 if (H_ENUMERATE_ISSET_BAIL(held)) {
1128 if (!H_ENUMERATE_ISSET_HELD(nheld))
1129 h_Release_r(next); /* this might free up the host */
1133 } /*h_Enumerate_r */
1135 /* inserts a new HashChain structure corresponding to this UUID */
1137 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1140 struct h_hashChain *chain;
1142 /* hash into proper bucket */
1143 index = h_UuidHashIndex(uuid);
1145 /* insert into beginning of list for this bucket */
1146 chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
1148 ViceLog(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1152 chain->hostPtr = host;
1153 chain->next = hostUuidHashTable[index];
1154 hostUuidHashTable[index] = chain;
1158 /* inserts a new HashChain structure corresponding to this address */
1160 h_AddHostToHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1163 struct h_hashChain *chain;
1165 /* hash into proper bucket */
1166 index = h_HashIndex(addr);
1168 /* don't add the same entry multiple times */
1169 for (chain = hostHashTable[index]; chain; chain = chain->next) {
1170 if (chain->hostPtr == host && chain->addr == addr && chain->port == port)
1174 /* insert into beginning of list for this bucket */
1175 chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
1177 ViceLog(0, ("Failed malloc in h_AddHostToHashTable_r\n"));
1180 chain->hostPtr = host;
1181 chain->next = hostHashTable[index];
1184 hostHashTable[index] = chain;
1188 * This is called with host locked and held. At this point, the
1189 * hostHashTable should not be having entries for the alternate
1190 * interfaces. This function has to insert these entries in the
1193 * All addresses are in network byte order.
1196 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1201 struct Interface *interface;
1202 char hoststr[16], hoststr2[16];
1205 assert(host->interface);
1207 ViceLog(125, ("addInterfaceAddr : host %s:%d addr %s:%d\n",
1208 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1209 afs_inet_ntoa_r(addr, hoststr2), ntohs(port)));
1212 * Make sure this address is on the list of known addresses
1215 number = host->interface->numberOfInterfaces;
1216 for (i = 0, found = 0; i < number && !found; i++) {
1217 if (host->interface->interface[i].addr == addr &&
1218 host->interface->interface[i].port == port)
1222 interface = (struct Interface *)
1223 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1225 ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
1228 interface->numberOfInterfaces = number + 1;
1229 interface->uuid = host->interface->uuid;
1230 for (i = 0; i < number; i++)
1231 interface->interface[i] = host->interface->interface[i];
1232 interface->interface[number].addr = addr;
1233 interface->interface[number].port = port;
1234 free(host->interface);
1235 host->interface = interface;
1239 * Create a hash table entry for this address
1241 h_AddHostToHashTable_r(addr, port, host);
1248 * This is called with host locked and held. At this point, the
1249 * hostHashTable should not be having entries for the alternate
1250 * interfaces. This function has to insert these entries in the
1253 * All addresses are in network byte order.
1256 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1261 struct Interface *interface;
1262 char hoststr[16], hoststr2[16];
1265 assert(host->interface);
1267 ViceLog(125, ("removeInterfaceAddr : host %s:%d addr %s:%d\n",
1268 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1269 afs_inet_ntoa_r(addr, hoststr2), ntohs(port)));
1272 * Make sure this address is on the list of known addresses
1275 interface = host->interface;
1276 number = host->interface->numberOfInterfaces;
1277 for (i = 0, found = 0; i < number; i++) {
1278 if (interface->interface[i].addr == addr &&
1279 interface->interface[i].port == port) {
1286 for (; i < number; i++) {
1287 interface->interface[i].addr = interface->interface[i+1].addr;
1288 interface->interface[i].port = interface->interface[i+1].port;
1290 interface->numberOfInterfaces = number;
1294 * Remove the hash table entry for this address
1296 h_DeleteHostFromHashTableByAddr_r(addr, port, host);
1302 /* Host is returned held */
1304 h_GetHost_r(struct rx_connection *tcon)
1307 struct host *oldHost;
1310 struct interfaceAddr interf;
1311 int interfValid = 0;
1312 struct Identity *identP = NULL;
1315 char hoststr[16], hoststr2[16];
1317 struct rx_connection *cb_conn = NULL;
1319 caps.Capabilities_val = NULL;
1321 haddr = rxr_HostOf(tcon);
1322 hport = rxr_PortOf(tcon);
1324 if (caps.Capabilities_val)
1325 free(caps.Capabilities_val);
1326 caps.Capabilities_val = NULL;
1327 caps.Capabilities_len = 0;
1330 host = h_Lookup_r(haddr, hport, &held);
1331 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1332 if (host && !identP && !(host->Console & 1)) {
1333 /* This is a new connection, and we already have a host
1334 * structure for this address. Verify that the identity
1335 * of the caller matches the identity in the host structure.
1338 if (!(host->hostFlags & ALTADDR)) {
1339 /* Another thread is doing initialization */
1344 ("Host %s:%d starting h_Lookup again\n",
1345 afs_inet_ntoa_r(host->host, hoststr),
1346 ntohs(host->port)));
1349 host->hostFlags &= ~ALTADDR;
1350 cb_conn = host->callback_rxcon;
1351 rx_GetConnection(cb_conn);
1354 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1355 if (code == RXGEN_OPCODE)
1356 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1357 rx_PutConnection(cb_conn);
1360 if (code == RXGEN_OPCODE) {
1361 identP = (struct Identity *)malloc(sizeof(struct Identity));
1363 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1367 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1368 /* The host on this connection was unable to respond to
1369 * the WhoAreYou. We will treat this as a new connection
1370 * from the existing host. The worst that can happen is
1371 * that we maintain some extra callback state information */
1372 if (host->interface) {
1374 ("Host %s:%d used to support WhoAreYou, deleting.\n",
1375 afs_inet_ntoa_r(host->host, hoststr),
1376 ntohs(host->port)));
1377 host->hostFlags |= HOSTDELETED;
1384 } else if (code == 0) {
1386 identP = (struct Identity *)malloc(sizeof(struct Identity));
1388 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1392 identP->uuid = interf.uuid;
1393 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1394 /* Check whether the UUID on this connection matches
1395 * the UUID in the host structure. If they don't match
1396 * then this is not the same host as before. */
1397 if (!host->interface
1398 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1400 ("Host %s:%d has changed its identity, deleting.\n",
1401 afs_inet_ntoa_r(host->host, hoststr), host->port));
1402 host->hostFlags |= HOSTDELETED;
1410 afs_inet_ntoa_r(host->host, hoststr);
1412 ("CB: WhoAreYou failed for %s:%d, error %d\n", hoststr,
1413 ntohs(host->port), code));
1414 host->hostFlags |= VENUSDOWN;
1416 if (caps.Capabilities_val
1417 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1418 host->hostFlags |= HERRORTRANS;
1420 host->hostFlags &= ~(HERRORTRANS);
1421 host->hostFlags |= ALTADDR;
1424 if (!(host->hostFlags & ALTADDR)) {
1425 /* another thread is doing the initialisation */
1427 ("Host %s:%d waiting for host-init to complete\n",
1428 afs_inet_ntoa_r(host->host, hoststr),
1429 ntohs(host->port)));
1435 ("Host %s:%d starting h_Lookup again\n",
1436 afs_inet_ntoa_r(host->host, hoststr),
1437 ntohs(host->port)));
1440 /* We need to check whether the identity in the host structure
1441 * matches the identity on the connection. If they don't match
1442 * then treat this a new host. */
1443 if (!(host->Console & 1)
1444 && ((!identP->valid && host->interface)
1445 || (identP->valid && !host->interface)
1447 && !afs_uuid_equal(&identP->uuid,
1448 &host->interface->uuid)))) {
1449 char uuid1[128], uuid2[128];
1451 afsUUID_to_string(&identP->uuid, uuid1, 127);
1452 if (host->interface)
1453 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1455 ("CB: new identity for host %s:%d, deleting(%x %x %s %s)\n",
1456 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1457 identP->valid, host->interface,
1458 identP->valid ? uuid1 : "",
1459 host->interface ? uuid2 : ""));
1461 /* The host in the cache is not the host for this connection */
1462 host->hostFlags |= HOSTDELETED;
1469 host = h_Alloc_r(tcon); /* returned held and locked */
1470 h_gethostcps_r(host, FT_ApproxTime());
1471 if (!(host->Console & 1)) {
1473 cb_conn = host->callback_rxcon;
1474 rx_GetConnection(cb_conn);
1477 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1478 if (code == RXGEN_OPCODE)
1479 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1480 rx_PutConnection(cb_conn);
1483 if (code == RXGEN_OPCODE) {
1486 (struct Identity *)malloc(sizeof(struct Identity));
1491 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1496 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1498 ("Host %s:%d does not support WhoAreYou.\n",
1499 afs_inet_ntoa_r(host->host, hoststr),
1500 ntohs(host->port)));
1502 } else if (code == 0) {
1505 (struct Identity *)malloc(sizeof(struct Identity));
1510 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1515 identP->uuid = interf.uuid;
1517 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1519 ("WhoAreYou success on %s:%d\n",
1520 afs_inet_ntoa_r(host->host, hoststr),
1521 ntohs(host->port)));
1523 if (code == 0 && !identP->valid) {
1524 cb_conn = host->callback_rxcon;
1525 rx_GetConnection(cb_conn);
1527 code = RXAFSCB_InitCallBackState(cb_conn);
1528 rx_PutConnection(cb_conn);
1531 } else if (code == 0) {
1532 oldHost = h_LookupUuid_r(&identP->uuid);
1536 if (!(oheld = h_Held_r(oldHost)))
1540 if (oldHost->interface) {
1542 afsUUID uuid = oldHost->interface->uuid;
1543 cb_conn = oldHost->callback_rxcon;
1544 rx_GetConnection(cb_conn);
1545 rx_SetConnDeadTime(cb_conn, 2);
1546 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1548 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1550 rx_SetConnDeadTime(cb_conn, 50);
1551 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1552 rx_PutConnection(cb_conn);
1555 /* The primary address is either not responding or
1556 * is not the client we are looking for.
1557 * MultiProbeAlternateAddress_r() will remove the
1558 * alternate interfaces that do not have the same
1560 ViceLog(0,("CB: ProbeUuid for %s:%d failed %d\n",
1561 afs_inet_ntoa_r(oldHost->host, hoststr),
1562 ntohs(oldHost->port),code2));
1563 MultiProbeAlternateAddress_r(oldHost);
1570 /* This is a new address for an existing host. Update
1571 * the list of interfaces for the existing host and
1572 * delete the host structure we just allocated. */
1573 if (oldHost->host != haddr || oldHost->port != hport) {
1574 struct rx_connection *rxconn;
1577 ("CB: new addr %s:%d for old host %s:%d\n",
1578 afs_inet_ntoa_r(haddr, hoststr),
1580 afs_inet_ntoa_r(oldHost->host, hoststr2),
1581 ntohs(oldHost->port)));
1582 if (probefail || oldHost->host == haddr) {
1583 /* The probe failed which means that the old address is
1584 * either unreachable or is not the same host we were just
1585 * contacted by. We will also remove addresses if only
1586 * the port has changed because that indicates the client
1589 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
1592 struct Interface *interface = oldHost->interface;
1593 int number = oldHost->interface->numberOfInterfaces;
1594 for (i = 0, found = 0; i < number; i++) {
1595 if (interface->interface[i].addr == haddr &&
1596 interface->interface[i].port != hport) {
1602 /* We have just been contacted by a client that has been
1603 * seen from behind a NAT and at least one other address.
1605 removeInterfaceAddr_r(oldHost, haddr, interface->interface[i].port);
1608 addInterfaceAddr_r(oldHost, haddr, hport);
1609 oldHost->host = haddr;
1610 oldHost->port = hport;
1611 rxconn = oldHost->callback_rxcon;
1612 oldHost->callback_rxcon = host->callback_rxcon;
1613 host->callback_rxcon = NULL;
1616 struct client *client;
1618 * If rx_DestroyConnection calls h_FreeConnection we will
1619 * deadlock on the host_glock_mutex. Work around the problem
1620 * by unhooking the client from the connection before
1621 * destroying the connection.
1623 client = rx_GetSpecific(rxconn, rxcon_client_key);
1624 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1625 rx_DestroyConnection(rxconn);
1628 host->hostFlags |= HOSTDELETED;
1630 /* release host because it was allocated by h_Alloc_r */
1633 /* the new host is held and locked */
1635 /* This really is a new host */
1636 h_AddHostToUuidHashTable_r(&identP->uuid, host);
1637 cb_conn = host->callback_rxcon;
1638 rx_GetConnection(cb_conn);
1641 RXAFSCB_InitCallBackState3(cb_conn,
1643 rx_PutConnection(cb_conn);
1648 ("InitCallBackState3 success on %s:%d\n",
1649 afs_inet_ntoa_r(host->host, hoststr),
1650 ntohs(host->port)));
1651 assert(interfValid == 1);
1652 initInterfaceAddr_r(host, &interf);
1657 afs_inet_ntoa_r(host->host, hoststr);
1659 ("CB: RCallBackConnectBack failed for %s:%d\n",
1660 hoststr, ntohs(host->port)));
1661 host->hostFlags |= VENUSDOWN;
1664 ("CB: RCallBackConnectBack succeeded for %s:%d\n",
1665 hoststr, ntohs(host->port)));
1666 host->hostFlags |= RESETDONE;
1669 if (caps.Capabilities_val
1670 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1671 host->hostFlags |= HERRORTRANS;
1673 host->hostFlags &= ~(HERRORTRANS);
1674 host->hostFlags |= ALTADDR; /* host structure initialization complete */
1677 if (caps.Capabilities_val)
1678 free(caps.Capabilities_val);
1679 caps.Capabilities_val = NULL;
1680 caps.Capabilities_len = 0;
1686 static char localcellname[PR_MAXNAMELEN + 1];
1687 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
1688 int num_lrealms = -1;
1694 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
1695 if (num_lrealms == -1) {
1697 for (i=0; i<AFS_NUM_LREALMS; i++) {
1698 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
1704 ("afs_krb_get_lrealm failed, using %s.\n",
1706 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
1712 /* initialize the rest of the local realms to nullstring for debugging */
1713 for (; i<AFS_NUM_LREALMS; i++)
1714 local_realms[i][0] = '\0';
1716 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
1717 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
1718 #ifdef AFS_PTHREAD_ENV
1719 assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
1720 #endif /* AFS_PTHREAD_ENV */
1724 MapName_r(char *aname, char *acell, afs_int32 * aval)
1729 afs_int32 anamelen, cnamelen;
1733 anamelen = strlen(aname);
1734 if (anamelen >= PR_MAXNAMELEN)
1735 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
1737 lnames.namelist_len = 1;
1738 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
1739 lids.idlist_len = 0;
1740 lids.idlist_val = NULL;
1742 cnamelen = strlen(acell);
1744 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
1746 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
1747 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
1748 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
1750 ("MapName: Name too long, using AnonymousID for %s@%s\n",
1752 *aval = AnonymousID;
1755 foreign = 1; /* attempt cross-cell authentication */
1756 tname = (char *)malloc(PR_MAXNAMELEN);
1758 ViceLog(0, ("Failed malloc in MapName_r\n"));
1761 strcpy(tname, aname);
1762 tname[anamelen] = '@';
1763 strcpy(tname + anamelen + 1, acell);
1764 lnames.namelist_val = (prname *) tname;
1769 code = hpr_NameToId(&lnames, &lids);
1772 if (lids.idlist_val) {
1773 *aval = lids.idlist_val[0];
1774 if (*aval == AnonymousID) {
1776 ("MapName: NameToId on %s returns anonymousID\n",
1777 lnames.namelist_val));
1779 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
1782 ("MapName: NameToId on '%s' is unknown\n",
1783 lnames.namelist_val));
1789 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
1797 /* NOTE: this returns the client with a Write lock and a refCount */
1799 h_ID2Client(afs_int32 vid)
1801 register struct client *client;
1802 register struct host *host;
1805 for (host = hostList; host; host = host->next) {
1806 if (host->hostFlags & HOSTDELETED)
1808 for (client = host->FirstClient; client; client = client->next) {
1809 if (!client->deleted && client->ViceId == vid) {
1812 ObtainWriteLock(&client->lock);
1823 * Called by the server main loop. Returns a h_Held client, which must be
1824 * released later the main loop. Allocates a client if the matching one
1825 * isn't around. The client is returned with its reference count incremented
1826 * by one. The caller must call h_ReleaseClient_r when finished with
1829 * the client->host is returned held. h_ReleaseClient_r does not release
1830 * the hold on client->host.
1833 h_FindClient_r(struct rx_connection *tcon)
1835 register struct client *client;
1836 register struct host *host;
1837 struct client *oldClient;
1842 #if (64-MAXKTCNAMELEN)
1843 ticket name length != 64
1847 char uname[PR_MAXNAMELEN];
1848 char tcell[MAXKTCREALMLEN];
1852 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1853 if (client && client->sid == rxr_CidOf(tcon)
1854 && client->VenusEpoch == rxr_GetEpoch(tcon)) {
1856 h_Hold_r(client->host);
1857 if (!client->deleted && client->prfail != 2) {
1858 /* Could add shared lock on client here */
1859 /* note that we don't have to lock entry in this path to
1860 * ensure CPS is initialized, since we don't call rx_SetSpecific
1861 * until initialization is done, and we only get here if
1862 * rx_GetSpecific located the client structure.
1867 ObtainWriteLock(&client->lock); /* released at end */
1873 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
1875 ("FindClient: authenticating connection: authClass=%d\n",
1877 if (authClass == 1) {
1878 /* A bcrypt tickets, no longer supported */
1879 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
1880 viceid = AnonymousID;
1881 expTime = 0x7fffffff;
1882 } else if (authClass == 2) {
1885 /* kerberos ticket */
1886 code = rxkad_GetServerInfo(tcon, /*level */ 0, &expTime,
1887 tname, tinst, tcell, &kvno);
1889 ViceLog(1, ("Failed to get rxkad ticket info\n"));
1890 viceid = AnonymousID;
1891 expTime = 0x7fffffff;
1893 int ilen = strlen(tinst);
1895 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
1896 tname, tinst, tcell, expTime, kvno));
1897 strncpy(uname, tname, sizeof(uname));
1899 if (strlen(uname) + 1 + ilen >= sizeof(uname))
1902 strcat(uname, tinst);
1904 /* translate the name to a vice id */
1905 code = MapName_r(uname, tcell, &viceid);
1909 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
1912 viceid = AnonymousID;
1913 expTime = 0x7fffffff;
1917 viceid = AnonymousID; /* unknown security class */
1918 expTime = 0x7fffffff;
1921 if (!client) { /* loop */
1922 host = h_GetHost_r(tcon); /* Returns it h_Held */
1925 /* First try to find the client structure */
1926 for (client = host->FirstClient; client; client = client->next) {
1927 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
1928 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1931 ObtainWriteLock(&client->lock);
1937 /* Still no client structure - get one */
1940 /* Retry to find the client structure */
1941 for (client = host->FirstClient; client; client = client->next) {
1942 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
1943 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1945 goto retryfirstclient;
1950 ObtainWriteLock(&client->lock);
1951 client->refCount = 1;
1952 client->host = host;
1953 #if FS_STATS_DETAILED
1954 client->InSameNetwork = host->InSameNetwork;
1955 #endif /* FS_STATS_DETAILED */
1956 client->ViceId = viceid;
1957 client->expTime = expTime; /* rx only */
1958 client->authClass = authClass; /* rx only */
1959 client->sid = rxr_CidOf(tcon);
1960 client->VenusEpoch = rxr_GetEpoch(tcon);
1961 client->CPS.prlist_val = NULL;
1962 client->CPS.prlist_len = 0;
1966 client->prfail = fail;
1968 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
1969 client->CPS.prlist_len = 0;
1970 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
1971 free(client->CPS.prlist_val);
1972 client->CPS.prlist_val = NULL;
1973 client->ViceId = viceid;
1974 client->expTime = expTime;
1976 if (viceid == ANONYMOUSID) {
1977 client->CPS.prlist_len = AnonCPS.prlist_len;
1978 client->CPS.prlist_val = AnonCPS.prlist_val;
1981 code = hpr_GetCPS(viceid, &client->CPS);
1986 ("pr_GetCPS failed(%d) for user %d, host %s:%d\n",
1987 code, viceid, afs_inet_ntoa_r(client->host->host,
1989 ntohs(client->host->port)));
1991 /* Although ubik_Call (called by pr_GetCPS) traverses thru
1992 * all protection servers and reevaluates things if no
1993 * sync server or quorum is found we could still end up
1994 * with one of these errors. In such case we would like to
1995 * reevaluate the rpc call to find if there's cps for this
1996 * guy. We treat other errors (except network failures
1997 * ones - i.e. code < 0) as an indication that there is no
1998 * CPS for this host. Ideally we could like to deal this
1999 * problem the other way around (i.e. if code == NOCPS
2000 * ignore else retry next time) but the problem is that
2001 * there're other errors (i.e. EPERM) for which we don't
2002 * want to retry and we don't know the whole code list!
2004 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2008 /* the disabling of system:administrators is so iffy and has so many
2009 * possible failure modes that we will disable it again */
2010 /* Turn off System:Administrator for safety
2011 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2012 * assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2015 /* Now, tcon may already be set to a rock, since we blocked with no host
2016 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2017 * required). So, before setting the RPC's rock, we should disconnect
2018 * the RPC from the other client structure's rock.
2020 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2021 if (oldClient && oldClient != client && oldClient->sid == rxr_CidOf(tcon)
2022 && oldClient->VenusEpoch == rxr_GetEpoch(tcon)) {
2024 if (!oldClient->deleted) {
2025 /* if we didn't create it, it's not ours to put back */
2027 ViceLog(0, ("FindClient: stillborn client %x(%x); conn %x (host %s:%d) had client %x(%x)\n",
2028 client, client->sid, tcon,
2029 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2030 ntohs(rxr_PortOf(tcon)),
2031 oldClient, oldClient->sid));
2032 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2033 free(client->CPS.prlist_val);
2034 client->CPS.prlist_val = NULL;
2035 client->CPS.prlist_len = 0;
2037 /* We should perhaps check for 0 here */
2039 ReleaseWriteLock(&client->lock);
2044 oldClient->refCount++;
2046 ObtainWriteLock(&oldClient->lock);
2050 ViceLog(0, ("FindClient: deleted client %x(%x) already had conn %x (host %s:%d), stolen by client %x(%x)\n",
2051 oldClient, oldClient->sid, tcon,
2052 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2053 ntohs(rxr_PortOf(tcon)),
2054 client, client->sid));
2055 /* rx_SetSpecific will be done immediately below */
2058 /* Avoid chaining in more than once. */
2061 client->next = host->FirstClient;
2062 host->FirstClient = client;
2064 CurrentConnections++; /* increment number of connections */
2066 rx_SetSpecific(tcon, rxcon_client_key, client);
2067 ReleaseWriteLock(&client->lock);
2071 } /*h_FindClient_r */
2074 h_ReleaseClient_r(struct client *client)
2076 assert(client->refCount > 0);
2083 * Sigh: this one is used to get the client AGAIN within the individual
2084 * server routines. This does not bother h_Holding the host, since
2085 * this is assumed already have been done by the server main loop.
2086 * It does check tokens, since only the server routines can return the
2087 * VICETOKENDEAD error code
2090 GetClient(struct rx_connection *tcon, struct client **cp)
2092 register struct client *client;
2096 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2097 if (client == NULL) {
2099 ("GetClient: no client in conn %x (host %x:%d), VBUSYING\n",
2100 tcon, rxr_HostOf(tcon),ntohs(rxr_PortOf(tcon))));
2104 if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2106 ("GetClient: tcon %x tcon sid %d client sid %d\n",
2107 tcon, rxr_CidOf(tcon), client->sid));
2111 if (client && client->LastCall > client->expTime && client->expTime) {
2114 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2115 afs_inet_ntoa_r(client->host->host, hoststr),
2116 ntohs(client->host->port), client->expTime));
2118 return VICETOKENDEAD;
2128 PutClient(struct client **cp)
2134 h_ReleaseClient_r(*cp);
2141 /* Client user name for short term use. Note that this is NOT inexpensive */
2143 h_UserName(struct client *client)
2145 static char User[PR_MAXNAMELEN + 1];
2150 lids.idlist_len = 1;
2151 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2152 if (!lids.idlist_val) {
2153 ViceLog(0, ("Failed malloc in h_UserName\n"));
2156 lnames.namelist_len = 0;
2157 lnames.namelist_val = (prname *) 0;
2158 lids.idlist_val[0] = client->ViceId;
2159 if (hpr_IdToName(&lids, &lnames)) {
2160 /* We need to free id we alloced above! */
2161 free(lids.idlist_val);
2162 return "*UNKNOWN USER NAME*";
2164 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2165 free(lids.idlist_val);
2166 free(lnames.namelist_val);
2176 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2177 CEs, CEBlocks, HTs, HTBlocks));
2183 h_PrintClient(register struct host *host, int held, StreamHandle_t * file)
2185 register struct client *client;
2190 time_t LastCall, expTime;
2193 LastCall = host->LastCall;
2194 if (host->hostFlags & HOSTDELETED) {
2198 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2199 "Host %s:%d down = %d, LastCall %s",
2200 afs_inet_ntoa_r(host->host, hoststr),
2201 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2202 afs_ctime(&LastCall, tbuffer,
2204 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2205 for (client = host->FirstClient; client; client = client->next) {
2206 if (!client->deleted) {
2207 expTime = client->expTime;
2208 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2209 " user id=%d, name=%s, sl=%s till %s",
2210 client->ViceId, h_UserName(client),
2212 authClass ? "Authenticated" :
2213 "Not authenticated",
2215 authClass ? afs_ctime(&expTime, tbuffer,
2218 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2219 (void)afs_snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2220 client->CPS.prlist_len);
2221 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2222 if (client->CPS.prlist_val) {
2223 for (i = 0; i > client->CPS.prlist_len; i++) {
2224 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2225 client->CPS.prlist_val[i]);
2226 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2229 sprintf(tmpStr, "]\n");
2230 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2236 } /*h_PrintClient */
2241 * Print a list of clients, with last security level and token value seen,
2251 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2255 ("Couldn't create client dump file %s\n",
2256 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2259 now = FT_ApproxTime();
2260 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
2261 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2262 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2263 h_Enumerate(h_PrintClient, (char *)file);
2264 STREAM_REALLYCLOSE(file);
2265 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2272 h_DumpHost(register struct host *host, int held, StreamHandle_t * file)
2279 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2280 "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 [",
2281 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), host->index,
2282 host->cblist, CheckLock(&host->lock), host->LastCall,
2283 host->ActiveCall, (host->hostFlags & VENUSDOWN),
2284 host->hostFlags & HOSTDELETED, host->Console,
2285 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2287 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2288 if (host->hcps.prlist_val)
2289 for (i = 0; i < host->hcps.prlist_len; i++) {
2290 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2291 host->hcps.prlist_val[i]);
2292 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2294 sprintf(tmpStr, "] [");
2295 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2296 if (host->interface)
2297 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2299 sprintf(tmpStr, " %s:%d",
2300 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2301 ntohs(host->interface->interface[i].port));
2302 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2304 sprintf(tmpStr, "] holds: ");
2305 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2307 for (i = 0; i < h_maxSlots; i++) {
2308 sprintf(tmpStr, "%04x", host->holds[i]);
2309 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2311 sprintf(tmpStr, " slot/bit: %d/%d\n", h_holdSlot(), h_holdbit());
2312 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2324 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2330 ("Couldn't create host dump file %s\n",
2331 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2334 now = FT_ApproxTime();
2335 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
2336 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2337 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2338 h_Enumerate(h_DumpHost, (char *)file);
2339 STREAM_REALLYCLOSE(file);
2340 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2344 #ifdef AFS_DEMAND_ATTACH_FS
2347 * host state serialization
2349 static int h_stateFillHeader(struct host_state_header * hdr);
2350 static int h_stateCheckHeader(struct host_state_header * hdr);
2351 static int h_stateAllocMap(struct fs_dump_state * state);
2352 static int h_stateSaveHost(register struct host * host, int held, struct fs_dump_state * state);
2353 static int h_stateRestoreHost(struct fs_dump_state * state);
2354 static int h_stateRestoreIndex(struct host * h, int held, struct fs_dump_state * state);
2355 static int h_stateVerifyHost(struct host * h, int held, struct fs_dump_state * state);
2356 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port);
2357 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2358 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2359 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2362 /* this procedure saves all host state to disk for fast startup */
2364 h_stateSave(struct fs_dump_state * state)
2366 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2369 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2371 /* invalidate host state header */
2372 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2374 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2375 sizeof(struct host_state_header))) {
2380 fs_stateIncEOF(state, sizeof(struct host_state_header));
2382 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2387 h_stateFillHeader(state->h_hdr);
2389 /* write the real header to disk */
2390 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2391 sizeof(struct host_state_header));
2398 * host state serialization
2400 * this procedure restores all host state from a disk for fast startup
2403 h_stateRestore(struct fs_dump_state * state)
2407 /* seek to the right position and read in the host state header */
2408 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2409 sizeof(struct host_state_header))) {
2414 /* check the validity of the header */
2415 if (h_stateCheckHeader(state->h_hdr)) {
2420 records = state->h_hdr->records;
2422 if (h_stateAllocMap(state)) {
2427 /* iterate over records restoring host state */
2428 for (i=0; i < records; i++) {
2429 if (h_stateRestoreHost(state) != 0) {
2440 h_stateRestoreIndices(struct fs_dump_state * state)
2442 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
2447 h_stateRestoreIndex(struct host * h, int held, struct fs_dump_state * state)
2449 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
2450 return H_ENUMERATE_BAIL(held);
2456 h_stateVerify(struct fs_dump_state * state)
2458 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
2463 h_stateVerifyHost(struct host * h, int held, struct fs_dump_state * state)
2468 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
2469 return H_ENUMERATE_BAIL(held);
2473 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
2474 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
2475 h->interface->interface[i].port)) {
2479 if (h_stateVerifyUuidHash(state, h)) {
2482 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port)) {
2486 if (cb_stateVerifyHCBList(state, h)) {
2495 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port)
2497 int ret = 0, found = 0;
2498 struct host *host = NULL;
2499 struct h_hashChain *chain;
2500 int index = h_HashIndex(addr);
2504 for (chain = hostHashTable[index]; chain; chain = chain->next) {
2505 host = chain->hostPtr;
2507 afs_inet_ntoa_r(addr, tmp);
2508 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
2512 if ((chain->addr == addr) && (chain->port == port)) {
2514 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry points to different host struct (%d, %d)\n",
2515 h->index, host->index));
2516 state->flags.warnings_generated = 1;
2521 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
2522 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2523 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
2531 afs_inet_ntoa_r(addr, tmp);
2532 if (state->mode == FS_STATE_LOAD_MODE) {
2533 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s not found in hash\n", tmp));
2537 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s not found in hash\n", tmp));
2538 state->flags.warnings_generated = 1;
2547 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
2549 int ret = 0, found = 0;
2550 struct host *host = NULL;
2551 struct h_hashChain *chain;
2552 afsUUID * uuidp = &h->interface->uuid;
2553 int index = h_UuidHashIndex(uuidp);
2557 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
2558 host = chain->hostPtr;
2560 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2561 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
2565 if (host->interface &&
2566 afs_uuid_equal(&host->interface->uuid, uuidp)) {
2568 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
2569 h->index, host->index));
2570 state->flags.warnings_generated = 1;
2575 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
2576 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2577 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
2585 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2586 if (state->mode == FS_STATE_LOAD_MODE) {
2587 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
2591 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
2592 state->flags.warnings_generated = 1;
2600 /* create the host state header structure */
2602 h_stateFillHeader(struct host_state_header * hdr)
2604 hdr->stamp.magic = HOST_STATE_MAGIC;
2605 hdr->stamp.version = HOST_STATE_VERSION;
2608 /* check the contents of the host state header structure */
2610 h_stateCheckHeader(struct host_state_header * hdr)
2614 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
2615 ViceLog(0, ("check_host_state_header: invalid state header\n"));
2618 else if (hdr->stamp.version != HOST_STATE_VERSION) {
2619 ViceLog(0, ("check_host_state_header: unknown version number\n"));
2625 /* allocate the host id mapping table */
2627 h_stateAllocMap(struct fs_dump_state * state)
2629 state->h_map.len = state->h_hdr->index_max + 1;
2630 state->h_map.entries = (struct idx_map_entry_t *)
2631 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
2632 return (state->h_map.entries != NULL) ? 0 : 1;
2635 /* function called by h_Enumerate to save a host to disk */
2637 h_stateSaveHost(register struct host * host, int held, struct fs_dump_state * state)
2639 int i, if_len=0, hcps_len=0;
2640 struct hostDiskEntry hdsk;
2641 struct host_state_entry_header hdr;
2642 struct Interface * ifp = NULL;
2643 afs_int32 * hcps = NULL;
2644 struct iovec iov[4];
2647 memset(&hdr, 0, sizeof(hdr));
2649 if (state->h_hdr->index_max < host->index) {
2650 state->h_hdr->index_max = host->index;
2653 h_hostToDiskEntry_r(host, &hdsk);
2654 if (host->interface) {
2655 if_len = sizeof(struct Interface) +
2656 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
2657 ifp = (struct Interface *) malloc(if_len);
2658 assert(ifp != NULL);
2659 memcpy(ifp, host->interface, if_len);
2660 hdr.interfaces = host->interface->numberOfInterfaces;
2661 iov[iovcnt].iov_base = (char *) ifp;
2662 iov[iovcnt].iov_len = if_len;
2665 if (host->hcps.prlist_val) {
2666 hdr.hcps = host->hcps.prlist_len;
2667 hcps_len = hdr.hcps * sizeof(afs_int32);
2668 hcps = (afs_int32 *) malloc(hcps_len);
2669 assert(hcps != NULL);
2670 memcpy(hcps, host->hcps.prlist_val, hcps_len);
2671 iov[iovcnt].iov_base = (char *) hcps;
2672 iov[iovcnt].iov_len = hcps_len;
2676 if (hdsk.index > state->h_hdr->index_max)
2677 state->h_hdr->index_max = hdsk.index;
2679 hdr.len = sizeof(struct host_state_entry_header) +
2680 sizeof(struct hostDiskEntry) + if_len + hcps_len;
2681 hdr.magic = HOST_STATE_ENTRY_MAGIC;
2683 iov[0].iov_base = (char *) &hdr;
2684 iov[0].iov_len = sizeof(hdr);
2685 iov[1].iov_base = (char *) &hdsk;
2686 iov[1].iov_len = sizeof(struct hostDiskEntry);
2688 if (fs_stateWriteV(state, iov, iovcnt)) {
2689 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
2693 fs_stateIncEOF(state, hdr.len);
2695 state->h_hdr->records++;
2703 return H_ENUMERATE_BAIL(held);
2708 /* restores a host from disk */
2710 h_stateRestoreHost(struct fs_dump_state * state)
2712 int ifp_len=0, hcps_len=0, bail=0;
2713 struct host_state_entry_header hdr;
2714 struct hostDiskEntry hdsk;
2715 struct host *host = NULL;
2716 struct Interface *ifp = NULL;
2717 afs_int32 * hcps = NULL;
2718 struct iovec iov[3];
2721 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
2722 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
2728 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
2729 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
2735 iov[0].iov_base = (char *) &hdsk;
2736 iov[0].iov_len = sizeof(struct hostDiskEntry);
2738 if (hdr.interfaces) {
2739 ifp_len = sizeof(struct Interface) +
2740 ((hdr.interfaces-1) * sizeof(struct AddrPort));
2741 ifp = (struct Interface *) malloc(ifp_len);
2742 assert(ifp != NULL);
2743 iov[iovcnt].iov_base = (char *) ifp;
2744 iov[iovcnt].iov_len = ifp_len;
2748 hcps_len = hdr.hcps * sizeof(afs_int32);
2749 hcps = (afs_int32 *) malloc(hcps_len);
2750 assert(hcps != NULL);
2751 iov[iovcnt].iov_base = (char *) hcps;
2752 iov[iovcnt].iov_len = hcps_len;
2756 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
2757 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
2762 if (fs_stateReadV(state, iov, iovcnt)) {
2763 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
2768 if (!hdr.hcps && hdsk.hcps_valid) {
2769 /* valid, zero-length host cps ; does this ever happen? */
2770 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
2771 assert(hcps != NULL);
2775 assert(host != NULL);
2778 host->interface = ifp;
2781 host->hcps.prlist_val = hcps;
2782 host->hcps.prlist_len = hdr.hcps;
2785 h_diskEntryToHost_r(&hdsk, host);
2786 h_SetupCallbackConn_r(host);
2790 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
2791 h_AddHostToHashTable_r(ifp->interface[i].addr,
2792 ifp->interface[i].port, host);
2794 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
2796 h_AddHostToHashTable_r(host->host, host->port, host);
2798 h_InsertList_r(host);
2800 /* setup host id map entry */
2801 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
2802 state->h_map.entries[hdsk.index].new_idx = host->index;
2814 /* serialize a host structure to disk */
2816 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
2818 out->host = in->host;
2819 out->port = in->port;
2820 out->hostFlags = in->hostFlags;
2821 out->Console = in->Console;
2822 out->hcpsfailed = in->hcpsfailed;
2823 out->LastCall = in->LastCall;
2824 out->ActiveCall = in->ActiveCall;
2825 out->cpsCall = in->cpsCall;
2826 out->cblist = in->cblist;
2827 #ifdef FS_STATS_DETAILED
2828 out->InSameNetwork = in->InSameNetwork;
2831 /* special fields we save, but are not memcpy'd back on restore */
2832 out->index = in->index;
2833 out->hcps_len = in->hcps.prlist_len;
2834 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
2837 /* restore a host structure from disk */
2839 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
2841 out->host = in->host;
2842 out->port = in->port;
2843 out->hostFlags = in->hostFlags;
2844 out->Console = in->Console;
2845 out->hcpsfailed = in->hcpsfailed;
2846 out->LastCall = in->LastCall;
2847 out->ActiveCall = in->ActiveCall;
2848 out->cpsCall = in->cpsCall;
2849 out->cblist = in->cblist;
2850 #ifdef FS_STATS_DETAILED
2851 out->InSameNetwork = in->InSameNetwork;
2855 /* index translation routines */
2857 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
2861 /* hosts use a zero-based index, so old==0 is valid */
2863 if (old >= state->h_map.len) {
2864 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
2866 } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
2867 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
2870 *new = state->h_map.entries[old].new_idx;
2876 #endif /* AFS_DEMAND_ATTACH_FS */
2880 * This counts the number of workstations, the number of active workstations,
2881 * and the number of workstations declared "down" (i.e. not heard from
2882 * recently). An active workstation has received a call since the cutoff
2883 * time argument passed.
2886 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
2888 register struct host *host;
2889 register int num = 0, active = 0, del = 0;
2892 for (host = hostList; host; host = host->next) {
2893 if (!(host->hostFlags & HOSTDELETED)) {
2895 if (host->ActiveCall > cutofftime)
2897 if (host->hostFlags & VENUSDOWN)
2909 } /*h_GetWorkStats */
2912 /*------------------------------------------------------------------------
2913 * PRIVATE h_ClassifyAddress
2916 * Given a target IP address and a candidate IP address (both
2917 * in host byte order), classify the candidate into one of three
2918 * buckets in relation to the target by bumping the counters passed
2922 * a_targetAddr : Target address.
2923 * a_candAddr : Candidate address.
2924 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
2925 * addresses are either in the same network
2926 * or the same subnet.
2927 * a_diffSubnetP : ...when the candidate is in a different
2929 * a_diffNetworkP : ...when the candidate is in a different
2936 * The target and candidate addresses are both in host byte
2937 * order, NOT network byte order, when passed in.
2941 *------------------------------------------------------------------------*/
2944 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
2945 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
2946 afs_int32 * a_diffNetworkP)
2947 { /*h_ClassifyAddress */
2949 afs_uint32 targetNet;
2950 afs_uint32 targetSubnet;
2952 afs_uint32 candSubnet;
2955 * Put bad values into the subnet info to start with.
2957 targetSubnet = (afs_uint32) 0;
2958 candSubnet = (afs_uint32) 0;
2961 * Pull out the network and subnetwork numbers from the target
2962 * and candidate addresses. We can short-circuit this whole
2963 * affair if the target and candidate addresses are not of the
2966 if (IN_CLASSA(a_targetAddr)) {
2967 if (!(IN_CLASSA(a_candAddr))) {
2968 (*a_diffNetworkP)++;
2971 targetNet = a_targetAddr & IN_CLASSA_NET;
2972 candNet = a_candAddr & IN_CLASSA_NET;
2973 if (IN_SUBNETA(a_targetAddr))
2974 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
2975 if (IN_SUBNETA(a_candAddr))
2976 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
2977 } else if (IN_CLASSB(a_targetAddr)) {
2978 if (!(IN_CLASSB(a_candAddr))) {
2979 (*a_diffNetworkP)++;
2982 targetNet = a_targetAddr & IN_CLASSB_NET;
2983 candNet = a_candAddr & IN_CLASSB_NET;
2984 if (IN_SUBNETB(a_targetAddr))
2985 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
2986 if (IN_SUBNETB(a_candAddr))
2987 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
2988 } /*Class B target */
2989 else if (IN_CLASSC(a_targetAddr)) {
2990 if (!(IN_CLASSC(a_candAddr))) {
2991 (*a_diffNetworkP)++;
2994 targetNet = a_targetAddr & IN_CLASSC_NET;
2995 candNet = a_candAddr & IN_CLASSC_NET;
2998 * Note that class C addresses can't have subnets,
2999 * so we leave the defaults untouched.
3001 } /*Class C target */
3003 targetNet = a_targetAddr;
3004 candNet = a_candAddr;
3005 } /*Class D address */
3008 * Now, simply compare the extracted net and subnet values for
3009 * the two addresses (which at this point are known to be of the
3012 if (targetNet == candNet) {
3013 if (targetSubnet == candSubnet)
3014 (*a_sameNetOrSubnetP)++;
3018 (*a_diffNetworkP)++;
3020 } /*h_ClassifyAddress */
3023 /*------------------------------------------------------------------------
3024 * EXPORTED h_GetHostNetStats
3027 * Iterate through the host table, and classify each (non-deleted)
3028 * host entry into ``proximity'' categories (same net or subnet,
3029 * different subnet, different network).
3032 * a_numHostsP : Set to total number of (non-deleted) hosts.
3033 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3034 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3035 * a_diffNetworkP : Set to # hosts on diff network as server.
3041 * We only count non-deleted hosts. The storage pointed to by our
3042 * parameters is zeroed upon entry.
3046 *------------------------------------------------------------------------*/
3049 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3050 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3051 { /*h_GetHostNetStats */
3053 register struct host *hostP; /*Ptr to current host entry */
3054 register afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3057 * Clear out the storage pointed to by our parameters.
3059 *a_numHostsP = (afs_int32) 0;
3060 *a_sameNetOrSubnetP = (afs_int32) 0;
3061 *a_diffSubnetP = (afs_int32) 0;
3062 *a_diffNetworkP = (afs_int32) 0;
3065 for (hostP = hostList; hostP; hostP = hostP->next) {
3066 if (!(hostP->hostFlags & HOSTDELETED)) {
3068 * Bump the number of undeleted host entries found.
3069 * In classifying the current entry's address, make
3070 * sure to first convert to host byte order.
3073 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3074 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3075 a_sameNetOrSubnetP, a_diffSubnetP,
3077 } /*Only look at non-deleted hosts */
3078 } /*For each host record hashed to this index */
3080 } /*h_GetHostNetStats */
3082 static afs_uint32 checktime;
3083 static afs_uint32 clientdeletetime;
3084 static struct AFSFid zerofid;
3088 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3089 * Since it can serialize them, and pile up, it should be a separate LWP
3090 * from other events.
3093 CheckHost(register struct host *host, int held)
3095 register struct client *client;
3096 struct rx_connection *cb_conn = NULL;
3099 #ifdef AFS_DEMAND_ATTACH_FS
3100 /* kill the checkhost lwp ASAP during shutdown */
3102 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3104 return H_ENUMERATE_BAIL(held);
3109 /* Host is held by h_Enumerate */
3111 for (client = host->FirstClient; client; client = client->next) {
3112 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3113 client->deleted = 1;
3114 host->hostFlags |= CLIENTDELETED;
3117 if (host->LastCall < checktime) {
3119 if (!(host->hostFlags & HOSTDELETED)) {
3120 cb_conn = host->callback_rxcon;
3121 rx_GetConnection(cb_conn);
3122 if (host->LastCall < clientdeletetime) {
3123 host->hostFlags |= HOSTDELETED;
3124 if (!(host->hostFlags & VENUSDOWN)) {
3125 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3126 if (host->interface) {
3129 RXAFSCB_InitCallBackState3(cb_conn,
3135 RXAFSCB_InitCallBackState(cb_conn);
3138 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3141 (void)afs_inet_ntoa_r(host->host, hoststr);
3143 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3144 hoststr, ntohs(host->port)));
3145 host->hostFlags |= VENUSDOWN;
3147 /* Note: it's safe to delete hosts even if they have call
3148 * back state, because break delayed callbacks (called when a
3149 * message is received from the workstation) will always send a
3150 * break all call backs to the workstation if there is no
3155 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3157 (void)afs_inet_ntoa_r(host->host, hoststr);
3158 if (host->interface) {
3159 afsUUID uuid = host->interface->uuid;
3161 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3164 if (MultiProbeAlternateAddress_r(host)) {
3165 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3166 hoststr, ntohs(host->port), code));
3167 host->hostFlags |= VENUSDOWN;
3172 code = RXAFSCB_Probe(cb_conn);
3176 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3177 hoststr, ntohs(host->port), code));
3178 host->hostFlags |= VENUSDOWN;
3184 rx_PutConnection(cb_conn);
3197 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3198 * don't respond to a probe. Note that VenusDown can only be cleared if
3199 * a message is received from the host (see ServerLWP in file.c).
3200 * Delete hosts that have not had any calls in 1 hour, clients that
3201 * have not had any calls in 15 minutes.
3203 * This routine is called roughly every 5 minutes.
3208 afs_uint32 now = FT_ApproxTime();
3210 memset((char *)&zerofid, 0, sizeof(zerofid));
3212 * Send a probe to the workstation if it hasn't been heard from in
3215 checktime = now - 15 * 60;
3216 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3217 h_Enumerate(CheckHost, NULL);
3222 * This is called with host locked and held. At this point, the
3223 * hostHashTable should not have any entries for the alternate
3224 * interfaces. This function has to insert these entries in the
3227 * The addresses in the interfaceAddr list are in host byte order.
3230 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3237 struct Interface *interface;
3243 number = interf->numberOfInterfaces;
3244 myAddr = host->host; /* current interface address */
3245 myPort = host->port; /* current port */
3248 ("initInterfaceAddr : host %s:%d numAddr %d\n",
3249 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3251 /* validation checks */
3252 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3254 ("Invalid number of alternate addresses is %d\n", number));
3259 * Convert IP addresses to network byte order, and remove for
3260 * duplicate IP addresses from the interface list.
3262 for (i = 0, count = 0, found = 0; i < number; i++) {
3263 interf->addr_in[i] = htonl(interf->addr_in[i]);
3264 for (j = 0; j < count; j++) {
3265 if (interf->addr_in[j] == interf->addr_in[i])
3269 interf->addr_in[count] = interf->addr_in[i];
3270 if (interf->addr_in[count] == myAddr)
3277 * Allocate and initialize an interface structure for this host.
3280 interface = (struct Interface *)
3281 malloc(sizeof(struct Interface) +
3282 (sizeof(struct AddrPort) * (count - 1)));
3284 ViceLog(0, ("Failed malloc in initInterfaceAddr_r\n"));
3287 interface->numberOfInterfaces = count;
3289 interface = (struct Interface *)
3290 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
3292 interface->numberOfInterfaces = count + 1;
3293 interface->interface[count].addr = myAddr;
3294 interface->interface[count].port = myPort;
3296 interface->uuid = interf->uuid;
3297 for (i = 0; i < count; i++) {
3298 interface->interface[i].addr = interf->addr_in[i];
3299 /* We store the port as 7001 because the addresses reported by
3300 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
3301 * are coming from fully connected hosts (no NAT/PATs)
3303 interface->interface[i].port = htons(7001);
3306 assert(!host->interface);
3307 host->interface = interface;
3309 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
3310 ViceLog(125, ("--- alt address %s:%d\n",
3311 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3312 ntohs(host->interface->interface[i].port)));
3318 /* deleted a HashChain structure for this address and host */
3319 /* returns 1 on success */
3321 h_DeleteHostFromHashTableByAddr_r(afs_uint32 addr, afs_uint16 port, struct host *host)
3324 register struct h_hashChain **hp, *th;
3326 for (hp = &hostHashTable[h_HashIndex(addr)]; (th = *hp);) {
3327 assert(th->hostPtr);
3328 if (th->hostPtr == host && th->addr == addr && th->port == port) {
3342 ** prints out all alternate interface address for the host. The 'level'
3343 ** parameter indicates what level of debugging sets this output
3346 printInterfaceAddr(struct host *host, int level)
3351 if (host->interface) {
3352 /* check alternate addresses */
3353 number = host->interface->numberOfInterfaces;
3355 for (i = 0; i < number; i++)
3356 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3357 ntohs(host->interface->interface[i].port)));
3359 ViceLog(level, ("\n"));