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;
86 int CEs = 0; /* active clients */
87 int CEBlocks = 0; /* number of blocks of CEs */
88 struct client *CEFree = 0; /* first free client */
89 struct host *hostList = 0; /* linked list of all hosts */
90 int hostCount = 0; /* number of hosts in hostList */
94 static struct rx_securityClass *sc = NULL;
96 static void h_SetupCallbackConn_r(struct host * host);
97 static void h_AddHostToHashTable_r(afs_uint32 addr, afs_uint16 port, struct host * host);
98 static void h_AddHostToUuidHashTable_r(afsUUID * uuid, struct host * host);
99 static int h_DeleteHostFromHashTableByAddr_r(afs_uint32 addr, afs_uint16 port, struct host *host);
101 #define CESPERBLOCK 73
102 struct CEBlock { /* block of CESPERBLOCK file entries */
103 struct client entry[CESPERBLOCK];
106 static void h_TossStuff_r(register struct host *host);
107 static int hashDelete_r(afs_uint32 addr, afs_uint16 port, struct host *host);
110 * Make sure the subnet macros have been defined.
113 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
116 #ifndef IN_CLASSA_SUBNET
117 #define IN_CLASSA_SUBNET 0xffff0000
121 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
124 #ifndef IN_CLASSB_SUBNET
125 #define IN_CLASSB_SUBNET 0xffffff00
129 /* get a new block of CEs and chain it on CEFree */
133 register struct CEBlock *block;
136 block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
138 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
139 ShutDownAndCore(PANIC);
142 for (i = 0; i < (CESPERBLOCK - 1); i++) {
143 Lock_Init(&block->entry[i].lock);
144 block->entry[i].next = &(block->entry[i + 1]);
146 block->entry[CESPERBLOCK - 1].next = 0;
147 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
148 CEFree = (struct client *)block;
154 /* get the next available CE */
155 static struct client *
158 register struct client *entry;
163 ViceLog(0, ("CEFree NULL in GetCE\n"));
164 ShutDownAndCore(PANIC);
168 CEFree = entry->next;
170 memset((char *)entry, 0, CLIENT_TO_ZERO(entry));
176 /* return an entry to the free list */
178 FreeCE(register struct client *entry)
180 entry->VenusEpoch = 0;
182 entry->next = CEFree;
189 * The HTs and HTBlocks variables were formerly static, but they are
190 * now referenced elsewhere in the FileServer.
192 int HTs = 0; /* active file entries */
193 int HTBlocks = 0; /* number of blocks of HTs */
194 static struct host *HTFree = 0; /* first free file entry */
197 * Hash tables of host pointers. We need two tables, one
198 * to map IP addresses onto host pointers, and another
199 * to map host UUIDs onto host pointers.
201 static struct h_hashChain *hostHashTable[h_HASHENTRIES];
202 static struct h_hashChain *hostUuidHashTable[h_HASHENTRIES];
203 #define h_HashIndex(hostip) ((hostip) & (h_HASHENTRIES-1))
204 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
206 struct HTBlock { /* block of HTSPERBLOCK file entries */
207 struct host entry[h_HTSPERBLOCK];
211 /* get a new block of HTs and chain it on HTFree */
215 register struct HTBlock *block;
217 static int index = 0;
219 if (HTBlocks == h_MAXHOSTTABLES) {
220 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
221 ShutDownAndCore(PANIC);
224 block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
226 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
227 ShutDownAndCore(PANIC);
229 #ifdef AFS_PTHREAD_ENV
230 for (i = 0; i < (h_HTSPERBLOCK); i++)
231 assert(pthread_cond_init(&block->entry[i].cond, NULL) == 0);
232 #endif /* AFS_PTHREAD_ENV */
233 for (i = 0; i < (h_HTSPERBLOCK); i++)
234 Lock_Init(&block->entry[i].lock);
235 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
236 block->entry[i].next = &(block->entry[i + 1]);
237 for (i = 0; i < (h_HTSPERBLOCK); i++)
238 block->entry[i].index = index++;
239 block->entry[h_HTSPERBLOCK - 1].next = 0;
240 HTFree = (struct host *)block;
241 hosttableptrs[HTBlocks++] = block->entry;
246 /* get the next available HT */
250 register struct host *entry;
254 assert(HTFree != NULL);
256 HTFree = entry->next;
258 memset((char *)entry, 0, HOST_TO_ZERO(entry));
264 /* return an entry to the free list */
266 FreeHT(register struct host *entry)
268 entry->next = HTFree;
275 hpr_Initialize(struct ubik_client **uclient)
278 struct rx_connection *serverconns[MAXSERVERS];
279 struct rx_securityClass *sc[3];
280 struct afsconf_dir *tdir;
281 char tconfDir[100] = "";
283 struct ktc_token ttoken;
285 struct afsconf_cell info;
289 tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
291 ViceLog(0, ("hpr_Initialize: Could not open configuration directory: %s", AFSDIR_SERVER_ETC_DIRPATH));
295 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
297 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
302 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
304 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s", cellstr, confDir, AFSDIR_CELLSERVDB_FILE));
311 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
320 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
321 * to force use of the KeyFile. secLevel == 0 implies -noauth was
323 if ((afsconf_GetLatestKey(tdir, 0, 0) == 0)) {
324 code = afsconf_ClientAuthSecure(tdir, &sc[2], &scIndex);
326 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s (so trying noauth)", code, afs_error_message(code)));
328 scIndex = 0; /* use noauth */
330 /* if there was a problem, an unauthenticated conn is returned */
333 struct ktc_principal sname;
334 strcpy(sname.cell, info.name);
335 sname.instance[0] = 0;
336 strcpy(sname.name, "afs");
337 code = ktc_GetToken(&sname, &ttoken, sizeof(ttoken), NULL);
341 if (ttoken.kvno >= 0 && ttoken.kvno <= 256)
342 /* this is a kerberos ticket, set scIndex accordingly */
345 ViceLog(0, ("hpr_Initialize: funny kvno (%d) in ticket, proceeding", ttoken.kvno));
349 rxkad_NewClientSecurityObject(rxkad_clear, &ttoken.sessionKey,
350 ttoken.kvno, ttoken.ticketLen,
354 if ((scIndex == 0) && (sc[0] == 0))
355 sc[0] = rxnull_NewClientSecurityObject();
357 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, running unauthenticated. [%d]", code));
359 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
360 for (i = 0; i < info.numServers; i++) {
362 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
363 info.hostAddr[i].sin_port, PRSRV, sc[scIndex],
367 code = ubik_ClientInit(serverconns, uclient);
369 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
372 code = rxs_Release(sc[scIndex]);
377 hpr_End(struct ubik_client *uclient)
382 code = ubik_ClientDestroy(uclient);
388 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
390 #ifdef AFS_PTHREAD_ENV
391 register afs_int32 code;
393 struct ubik_client *uclient =
394 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
397 code = hpr_Initialize(&uclient);
398 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
402 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
403 if (code != PRSUCCESS)
406 /* do something about this, probably make a new call */
407 /* don't forget there's a hard limit in the interface */
409 "membership list for host id %d exceeds display limit\n",
414 return pr_GetHostCPS(host, CPS);
419 hpr_NameToId(namelist *names, idlist *ids)
421 #ifdef AFS_PTHREAD_ENV
422 register afs_int32 code;
423 register afs_int32 i;
424 struct ubik_client *uclient =
425 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
428 code = hpr_Initialize(&uclient);
429 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
432 for (i = 0; i < names->namelist_len; i++)
433 stolower(names->namelist_val[i]);
434 code = ubik_PR_NameToID(uclient, 0, names, ids);
437 return pr_NameToId(names, ids);
442 hpr_IdToName(idlist *ids, namelist *names)
444 #ifdef AFS_PTHREAD_ENV
445 register afs_int32 code;
446 struct ubik_client *uclient =
447 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
450 code = hpr_Initialize(&uclient);
451 assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
454 code = ubik_PR_IDToName(uclient, 0, ids, names);
457 return pr_IdToName(ids, names);
462 hpr_GetCPS(afs_int32 id, prlist *CPS)
464 #ifdef AFS_PTHREAD_ENV
465 register afs_int32 code;
467 struct ubik_client *uclient =
468 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
471 code = hpr_Initialize(&uclient);
472 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);
691 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
692 * and reevaluates things if no sync server or quorum is found we could still end up
693 * with one of these errors. In such case we would like to reevaluate the rpc call to
694 * find if there's cps for this guy. We treat other errors (except network failures
695 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
696 * we could like to deal this problem the other way around (i.e. if code == NOCPS
697 * ignore else retry next time) but the problem is that there're other errors (i.e.
698 * EPERM) for which we don't want to retry and we don't know the whole code list!
700 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
702 * We would have preferred to use a while loop and try again since ops in protected
703 * acls for this host will fail now but they'll be reevaluated on any subsequent
704 * call. The attempt to wait for a quorum/sync site or network error won't work
705 * since this problems really should only occurs during a complete fileserver
706 * restart. Since the fileserver will start before the ptservers (and thus before
707 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
709 host->hcpsfailed = 1;
711 ("Warning: GetHostCPS failed (%d) for %x; will retry\n",
714 host->hcpsfailed = 0;
716 ("gethost: GetHostCPS failed (%d) for %x; ignored\n",
719 if (host->hcps.prlist_val)
720 free(host->hcps.prlist_val);
721 host->hcps.prlist_val = NULL;
722 host->hcps.prlist_len = 0; /* Make sure it's zero */
724 host->hcpsfailed = 0;
726 host->hostFlags &= ~HCPS_INPROGRESS;
727 /* signal all who are waiting */
728 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
729 host->hostFlags &= ~HCPS_WAITING;
730 #ifdef AFS_PTHREAD_ENV
731 assert(pthread_cond_broadcast(&host->cond) == 0);
732 #else /* AFS_PTHREAD_ENV */
733 if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
734 ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
735 #endif /* AFS_PTHREAD_ENV */
739 /* args in net byte order */
741 h_flushhostcps(register afs_uint32 hostaddr, register afs_uint16 hport)
743 register struct host *host;
747 host = h_Lookup_r(hostaddr, hport, &held);
749 host->hcpsfailed = 1;
759 * Allocate a host. It will be identified by the peer (ip,port) info in the
760 * rx connection provided. The host is returned held and locked
762 #define DEF_ROPCONS 2115
765 h_Alloc_r(register struct rx_connection *r_con)
767 struct servent *serverentry;
770 #if FS_STATS_DETAILED
771 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
772 #endif /* FS_STATS_DETAILED */
776 host->host = rxr_HostOf(r_con);
777 host->port = rxr_PortOf(r_con);
779 h_AddHostToHashTable_r(host->host, host->port, host);
781 if (consolePort == 0) { /* find the portal number for console */
782 #if defined(AFS_OSF_ENV)
783 serverentry = getservbyname("ropcons", "");
785 serverentry = getservbyname("ropcons", 0);
788 consolePort = serverentry->s_port;
790 consolePort = htons(DEF_ROPCONS); /* Use a default */
792 if (host->port == consolePort)
794 /* Make a callback channel even for the console, on the off chance that it
795 * makes a request that causes a break call back. It shouldn't. */
796 h_SetupCallbackConn_r(host);
797 now = host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
799 host->hcps.prlist_val = NULL;
800 host->hcps.prlist_len = 0;
801 host->interface = NULL;
803 host->hcpsfailed = 0; /* save cycles */
804 h_gethostcps(host); /* do this under host hold/lock */
806 host->FirstClient = NULL;
809 h_InsertList_r(host); /* update global host List */
810 #if FS_STATS_DETAILED
812 * Compare the new host's IP address (in host byte order) with ours
813 * (the File Server's), remembering if they are in the same network.
815 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
816 host->InSameNetwork =
817 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
818 #endif /* FS_STATS_DETAILED */
825 /* Make a callback channel even for the console, on the off chance that it
826 * makes a request that causes a break call back. It shouldn't. */
828 h_SetupCallbackConn_r(struct host * host)
831 sc = rxnull_NewClientSecurityObject();
832 host->callback_rxcon =
833 rx_NewConnection(host->host, host->port, 1, sc, 0);
834 rx_SetConnDeadTime(host->callback_rxcon, 50);
835 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
838 /* Lookup a host given an IP address and UDP port number. */
839 /* hostaddr and hport are in network order */
840 /* Note: host should be released by caller if 0 == *heldp and non-null */
841 /* hostaddr and hport are in network order */
843 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, int *heldp)
846 struct host *host = 0;
847 struct h_hashChain *chain;
848 int index = h_HashIndex(haddr);
849 extern int hostaclRefresh;
852 for (chain = hostHashTable[index]; chain; chain = chain->next) {
853 host = chain->hostPtr;
855 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
856 && chain->port == hport) {
857 *heldp = h_Held_r(host);
861 if (host->hostFlags & HOSTDELETED) {
868 now = FT_ApproxTime(); /* always evaluate "now" */
869 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
871 * Every hostaclRefresh period (def 2 hrs) get the new
872 * membership list for the host. Note this could be the
873 * first time that the host is added to a group. Also
874 * here we also retry on previous legitimate hcps failures.
876 * If we get here we still have a host hold.
878 h_gethostcps_r(host, now);
888 /* Lookup a host given its UUID. */
890 h_LookupUuid_r(afsUUID * uuidp)
892 struct host *host = 0;
893 struct h_hashChain *chain;
894 int index = h_UuidHashIndex(uuidp);
896 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
897 host = chain->hostPtr;
899 if (!(host->hostFlags & HOSTDELETED) && host->interface
900 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
911 * h_Hold_r: Establish a hold by the current LWP on this host--the host
912 * or its clients will not be physically deleted until all holds have
914 * NOTE: h_Hold_r is a macro defined in host.h.
917 /* h_TossStuff_r: Toss anything in the host structure (the host or
918 * clients marked for deletion. Called from h_Release_r ONLY.
919 * To be called, there must be no holds, and either host->deleted
920 * or host->clientDeleted must be set.
923 h_TossStuff_r(register struct host *host)
925 register struct client **cp, *client;
928 /* if somebody still has this host held */
929 for (i = 0; (i < h_maxSlots) && (!(host)->holds[i]); i++);
933 /* if somebody still has this host locked */
934 if (h_NBLock_r(host) != 0) {
937 ("Warning: h_TossStuff_r failed; Host %s:%d was locked.\n",
938 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
944 /* ASSUMPTION: rxi_FreeConnection() does not yield */
945 for (cp = &host->FirstClient; (client = *cp);) {
946 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
948 ObtainWriteLockNoBlock(&client->lock, code);
952 ("Warning: h_TossStuff_r failed: Host %s:%d client %x was locked.\n",
953 afs_inet_ntoa_r(host->host, hoststr),
954 ntohs(host->port), client));
958 if (client->refCount) {
961 ("Warning: h_TossStuff_r failed: Host %s:%d client %x refcount %d.\n",
962 afs_inet_ntoa_r(host->host, hoststr),
963 ntohs(host->port), client, client->refCount));
964 /* This is the same thing we do if the host is locked */
965 ReleaseWriteLock(&client->lock);
968 client->CPS.prlist_len = 0;
969 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
970 free(client->CPS.prlist_val);
971 client->CPS.prlist_val = NULL;
972 CurrentConnections--;
974 ReleaseWriteLock(&client->lock);
980 /* We've just cleaned out all the deleted clients; clear the flag */
981 host->hostFlags &= ~CLIENTDELETED;
983 if (host->hostFlags & HOSTDELETED) {
984 register struct h_hashChain **hp, *th;
985 register struct rx_connection *rxconn;
987 struct AddrPort hostAddrPort;
990 if (host->Console & 1)
992 if ((rxconn = host->callback_rxcon)) {
993 host->callback_rxcon = (struct rx_connection *)0;
994 rx_DestroyConnection(rxconn);
996 if (host->hcps.prlist_val)
997 free(host->hcps.prlist_val);
998 host->hcps.prlist_val = NULL;
999 host->hcps.prlist_len = 0;
1000 DeleteAllCallBacks_r(host, 1);
1001 host->hostFlags &= ~RESETDONE; /* just to be safe */
1003 /* if alternate addresses do not exist */
1004 if (!(host->interface)) {
1005 for (hp = &hostHashTable[h_HashIndex(host->host)]; (th = *hp);
1007 assert(th->hostPtr);
1008 if (th->hostPtr == host) {
1010 h_DeleteList_r(host);
1017 /* delete all hash entries for the UUID */
1018 uuidp = &host->interface->uuid;
1019 for (hp = &hostUuidHashTable[h_UuidHashIndex(uuidp)]; (th = *hp);
1021 assert(th->hostPtr);
1022 if (th->hostPtr == host) {
1028 /* delete all hash entries for alternate addresses */
1029 assert(host->interface->numberOfInterfaces > 0);
1030 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
1031 hostAddrPort = host->interface->interface[i];
1033 for (hp = &hostHashTable[h_HashIndex(hostAddrPort.addr)]; (th = *hp);
1035 assert(th->hostPtr);
1036 if (th->hostPtr == host) {
1043 free(host->interface);
1044 host->interface = NULL;
1045 h_DeleteList_r(host); /* remove host from global host List */
1047 } /* if alternate address exists */
1049 } /*h_TossStuff_r */
1052 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
1053 * system at the start of the enumeration (perhaps more). Hosts may be deleted
1054 * (have delete flag set); ditto for clients. (*proc) is always called with
1055 * host h_held(). The hold state of the host with respect to this lwp is passed
1056 * to (*proc) as the param held. The proc should return 0 if the host should be
1057 * released, 1 if it should be held after enumeration.
1060 h_Enumerate(int (*proc) (), char *param)
1062 register struct host *host, **list;
1064 register int i, count;
1067 if (hostCount == 0) {
1071 list = (struct host **)malloc(hostCount * sizeof(struct host *));
1073 ViceLog(0, ("Failed malloc in h_Enumerate\n"));
1076 held = (int *)malloc(hostCount * sizeof(int));
1078 ViceLog(0, ("Failed malloc in h_Enumerate\n"));
1081 for (count = 0, host = hostList; host; host = host->next, count++) {
1083 if (!(held[count] = h_Held_r(host)))
1086 assert(count == hostCount);
1088 for (i = 0; i < count; i++) {
1089 held[i] = (*proc) (list[i], held[i], param);
1090 if (!H_ENUMERATE_ISSET_HELD(held[i]))
1091 h_Release(list[i]); /* this might free up the host */
1092 /* bail out of the enumeration early */
1093 if (H_ENUMERATE_ISSET_BAIL(held[i]))
1100 /* h_Enumerate_r (revised):
1101 * Calls (*proc)(host, held, param) for each host in hostList, starting
1103 * Hosts may be deleted (have delete flag set); ditto for clients.
1104 * (*proc) is always called with
1105 * host h_held() and the global host lock (H_LOCK) locked.The hold state of the
1106 * host with respect to this lwp is passed to (*proc) as the param held.
1107 * The proc should return 0 if the host should be released, 1 if it should
1108 * be held after enumeration.
1111 h_Enumerate_r(int (*proc) (), struct host *enumstart, char *param)
1113 register struct host *host, *next;
1114 register int held, nheld;
1116 if (hostCount == 0) {
1119 if (enumstart && !(held = h_Held_r(enumstart)))
1120 h_Hold_r(enumstart);
1121 for (host = enumstart; host; host = next, held = nheld) {
1123 if (next && !(nheld = h_Held_r(next)) && !H_ENUMERATE_ISSET_BAIL(held))
1125 held = (*proc) (host, held, param);
1126 if (!H_ENUMERATE_ISSET_HELD(held))
1127 h_Release_r(host); /* this might free up the host */
1128 if (H_ENUMERATE_ISSET_BAIL(held)) {
1129 if (!H_ENUMERATE_ISSET_HELD(nheld))
1130 h_Release_r(next); /* this might free up the host */
1134 } /*h_Enumerate_r */
1136 /* inserts a new HashChain structure corresponding to this UUID */
1138 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1141 struct h_hashChain *chain;
1143 /* hash into proper bucket */
1144 index = h_UuidHashIndex(uuid);
1146 /* insert into beginning of list for this bucket */
1147 chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
1149 ViceLog(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1153 chain->hostPtr = host;
1154 chain->next = hostUuidHashTable[index];
1155 hostUuidHashTable[index] = chain;
1159 /* inserts a new HashChain structure corresponding to this address */
1161 h_AddHostToHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1164 struct h_hashChain *chain;
1166 /* hash into proper bucket */
1167 index = h_HashIndex(addr);
1169 /* don't add the same entry multiple times */
1170 for (chain = hostHashTable[index]; chain; chain = chain->next) {
1171 if (chain->hostPtr == host && chain->addr == addr && chain->port == port)
1175 /* insert into beginning of list for this bucket */
1176 chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
1178 ViceLog(0, ("Failed malloc in h_AddHostToHashTable_r\n"));
1181 chain->hostPtr = host;
1182 chain->next = hostHashTable[index];
1185 hostHashTable[index] = chain;
1189 * This is called with host locked and held. At this point, the
1190 * hostHashTable should not be having entries for the alternate
1191 * interfaces. This function has to insert these entries in the
1194 * All addresses are in network byte order.
1197 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1202 struct Interface *interface;
1203 char hoststr[16], hoststr2[16];
1206 assert(host->interface);
1208 ViceLog(125, ("addInterfaceAddr : host %s:%d addr %s:%d\n",
1209 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1210 afs_inet_ntoa_r(addr, hoststr2), ntohs(port)));
1213 * Make sure this address is on the list of known addresses
1216 number = host->interface->numberOfInterfaces;
1217 for (i = 0, found = 0; i < number && !found; i++) {
1218 if (host->interface->interface[i].addr == addr &&
1219 host->interface->interface[i].port == port)
1223 interface = (struct Interface *)
1224 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1226 ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
1229 interface->numberOfInterfaces = number + 1;
1230 interface->uuid = host->interface->uuid;
1231 for (i = 0; i < number; i++)
1232 interface->interface[i] = host->interface->interface[i];
1233 interface->interface[number].addr = addr;
1234 interface->interface[number].port = port;
1235 free(host->interface);
1236 host->interface = interface;
1240 * Create a hash table entry for this address
1242 h_AddHostToHashTable_r(addr, port, host);
1249 * This is called with host locked and held. At this point, the
1250 * hostHashTable should not be having entries for the alternate
1251 * interfaces. This function has to insert these entries in the
1254 * All addresses are in network byte order.
1257 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1262 struct Interface *interface;
1263 char hoststr[16], hoststr2[16];
1266 assert(host->interface);
1268 ViceLog(125, ("removeInterfaceAddr : host %s:%d addr %s:%d\n",
1269 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1270 afs_inet_ntoa_r(addr, hoststr2), ntohs(port)));
1273 * Make sure this address is on the list of known addresses
1276 interface = host->interface;
1277 number = host->interface->numberOfInterfaces;
1278 for (i = 0, found = 0; i < number; i++) {
1279 if (interface->interface[i].addr == addr &&
1280 interface->interface[i].port == port) {
1287 for (; i < number; i++) {
1288 interface->interface[i].addr = interface->interface[i+1].addr;
1289 interface->interface[i].port = interface->interface[i+1].port;
1291 interface->numberOfInterfaces = number;
1295 * Remove the hash table entry for this address
1297 h_DeleteHostFromHashTableByAddr_r(addr, port, host);
1303 /* Host is returned held */
1305 h_GetHost_r(struct rx_connection *tcon)
1308 struct host *oldHost;
1311 struct interfaceAddr interf;
1312 int interfValid = 0;
1313 struct Identity *identP = NULL;
1316 char hoststr[16], hoststr2[16];
1318 struct rx_connection *cb_conn = NULL;
1320 caps.Capabilities_val = NULL;
1322 haddr = rxr_HostOf(tcon);
1323 hport = rxr_PortOf(tcon);
1325 if (caps.Capabilities_val)
1326 free(caps.Capabilities_val);
1327 caps.Capabilities_val = NULL;
1328 caps.Capabilities_len = 0;
1331 host = h_Lookup_r(haddr, hport, &held);
1332 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1333 if (host && !identP && !(host->Console & 1)) {
1334 /* This is a new connection, and we already have a host
1335 * structure for this address. Verify that the identity
1336 * of the caller matches the identity in the host structure.
1339 if (!(host->hostFlags & ALTADDR)) {
1340 /* Another thread is doing initialization */
1345 ("Host %s:%d starting h_Lookup again\n",
1346 afs_inet_ntoa_r(host->host, hoststr),
1347 ntohs(host->port)));
1350 host->hostFlags &= ~ALTADDR;
1351 cb_conn = host->callback_rxcon;
1352 rx_GetConnection(cb_conn);
1355 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1356 if (code == RXGEN_OPCODE)
1357 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1358 rx_PutConnection(cb_conn);
1361 if ((code == RXGEN_OPCODE) ||
1362 (afs_uuid_equal(&interf.uuid, &nulluuid))) {
1363 identP = (struct Identity *)malloc(sizeof(struct Identity));
1365 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1369 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1370 /* The host on this connection was unable to respond to
1371 * the WhoAreYou. We will treat this as a new connection
1372 * from the existing host. The worst that can happen is
1373 * that we maintain some extra callback state information */
1374 if (host->interface) {
1376 ("Host %s:%d used to support WhoAreYou, deleting.\n",
1377 afs_inet_ntoa_r(host->host, hoststr),
1378 ntohs(host->port)));
1379 host->hostFlags |= HOSTDELETED;
1386 } else if (code == 0) {
1388 identP = (struct Identity *)malloc(sizeof(struct Identity));
1390 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1394 identP->uuid = interf.uuid;
1395 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1396 /* Check whether the UUID on this connection matches
1397 * the UUID in the host structure. If they don't match
1398 * then this is not the same host as before. */
1399 if (!host->interface
1400 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1402 ("Host %s:%d has changed its identity, deleting.\n",
1403 afs_inet_ntoa_r(host->host, hoststr), host->port));
1404 host->hostFlags |= HOSTDELETED;
1412 afs_inet_ntoa_r(host->host, hoststr);
1414 ("CB: WhoAreYou failed for %s:%d, error %d\n", hoststr,
1415 ntohs(host->port), code));
1416 host->hostFlags |= VENUSDOWN;
1418 if (caps.Capabilities_val
1419 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1420 host->hostFlags |= HERRORTRANS;
1422 host->hostFlags &= ~(HERRORTRANS);
1423 host->hostFlags |= ALTADDR;
1426 if (!(host->hostFlags & ALTADDR)) {
1427 /* another thread is doing the initialisation */
1429 ("Host %s:%d waiting for host-init to complete\n",
1430 afs_inet_ntoa_r(host->host, hoststr),
1431 ntohs(host->port)));
1437 ("Host %s:%d starting h_Lookup again\n",
1438 afs_inet_ntoa_r(host->host, hoststr),
1439 ntohs(host->port)));
1442 /* We need to check whether the identity in the host structure
1443 * matches the identity on the connection. If they don't match
1444 * then treat this a new host. */
1445 if (!(host->Console & 1)
1446 && ((!identP->valid && host->interface)
1447 || (identP->valid && !host->interface)
1449 && !afs_uuid_equal(&identP->uuid,
1450 &host->interface->uuid)))) {
1451 char uuid1[128], uuid2[128];
1453 afsUUID_to_string(&identP->uuid, uuid1, 127);
1454 if (host->interface)
1455 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1457 ("CB: new identity for host %s:%d, deleting(%x %x %s %s)\n",
1458 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1459 identP->valid, host->interface,
1460 identP->valid ? uuid1 : "",
1461 host->interface ? uuid2 : ""));
1463 /* The host in the cache is not the host for this connection */
1464 host->hostFlags |= HOSTDELETED;
1471 host = h_Alloc_r(tcon); /* returned held and locked */
1472 h_gethostcps_r(host, FT_ApproxTime());
1473 if (!(host->Console & 1)) {
1475 cb_conn = host->callback_rxcon;
1476 rx_GetConnection(cb_conn);
1479 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1480 if (code == RXGEN_OPCODE)
1481 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1482 rx_PutConnection(cb_conn);
1485 if ((code == RXGEN_OPCODE) ||
1486 afs_uuid_equal(&interf.uuid, &nulluuid)) {
1489 (struct Identity *)malloc(sizeof(struct Identity));
1494 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1499 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1501 ("Host %s:%d does not support WhoAreYou.\n",
1502 afs_inet_ntoa_r(host->host, hoststr),
1503 ntohs(host->port)));
1505 } else if (code == 0) {
1508 (struct Identity *)malloc(sizeof(struct Identity));
1513 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1518 identP->uuid = interf.uuid;
1520 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1522 ("WhoAreYou success on %s:%d\n",
1523 afs_inet_ntoa_r(host->host, hoststr),
1524 ntohs(host->port)));
1526 if (code == 0 && !identP->valid) {
1527 cb_conn = host->callback_rxcon;
1528 rx_GetConnection(cb_conn);
1530 code = RXAFSCB_InitCallBackState(cb_conn);
1531 rx_PutConnection(cb_conn);
1534 } else if (code == 0) {
1535 oldHost = h_LookupUuid_r(&identP->uuid);
1539 if (!(oheld = h_Held_r(oldHost)))
1543 if (oldHost->interface) {
1545 afsUUID uuid = oldHost->interface->uuid;
1546 cb_conn = oldHost->callback_rxcon;
1547 rx_GetConnection(cb_conn);
1548 rx_SetConnDeadTime(cb_conn, 2);
1549 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1551 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1553 rx_SetConnDeadTime(cb_conn, 50);
1554 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1555 rx_PutConnection(cb_conn);
1558 /* The primary address is either not responding or
1559 * is not the client we are looking for.
1560 * MultiProbeAlternateAddress_r() will remove the
1561 * alternate interfaces that do not have the same
1563 ViceLog(0,("CB: ProbeUuid for %s:%d failed %d\n",
1564 afs_inet_ntoa_r(oldHost->host, hoststr),
1565 ntohs(oldHost->port),code2));
1566 MultiProbeAlternateAddress_r(oldHost);
1573 /* This is a new address for an existing host. Update
1574 * the list of interfaces for the existing host and
1575 * delete the host structure we just allocated. */
1576 if (oldHost->host != haddr || oldHost->port != hport) {
1577 struct rx_connection *rxconn;
1580 ("CB: new addr %s:%d for old host %s:%d\n",
1581 afs_inet_ntoa_r(haddr, hoststr),
1583 afs_inet_ntoa_r(oldHost->host, hoststr2),
1584 ntohs(oldHost->port)));
1585 if (probefail || oldHost->host == haddr) {
1586 /* The probe failed which means that the old address is
1587 * either unreachable or is not the same host we were just
1588 * contacted by. We will also remove addresses if only
1589 * the port has changed because that indicates the client
1592 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
1595 struct Interface *interface = oldHost->interface;
1596 int number = oldHost->interface->numberOfInterfaces;
1597 for (i = 0, found = 0; i < number; i++) {
1598 if (interface->interface[i].addr == haddr &&
1599 interface->interface[i].port != hport) {
1605 /* We have just been contacted by a client that has been
1606 * seen from behind a NAT and at least one other address.
1608 removeInterfaceAddr_r(oldHost, haddr, interface->interface[i].port);
1611 addInterfaceAddr_r(oldHost, haddr, hport);
1612 oldHost->host = haddr;
1613 oldHost->port = hport;
1614 rxconn = oldHost->callback_rxcon;
1615 oldHost->callback_rxcon = host->callback_rxcon;
1616 host->callback_rxcon = NULL;
1619 struct client *client;
1621 * If rx_DestroyConnection calls h_FreeConnection we will
1622 * deadlock on the host_glock_mutex. Work around the problem
1623 * by unhooking the client from the connection before
1624 * destroying the connection.
1626 client = rx_GetSpecific(rxconn, rxcon_client_key);
1627 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1628 rx_DestroyConnection(rxconn);
1631 host->hostFlags |= HOSTDELETED;
1633 /* release host because it was allocated by h_Alloc_r */
1636 /* the new host is held and locked */
1638 /* This really is a new host */
1639 h_AddHostToUuidHashTable_r(&identP->uuid, host);
1640 cb_conn = host->callback_rxcon;
1641 rx_GetConnection(cb_conn);
1644 RXAFSCB_InitCallBackState3(cb_conn,
1646 rx_PutConnection(cb_conn);
1651 ("InitCallBackState3 success on %s:%d\n",
1652 afs_inet_ntoa_r(host->host, hoststr),
1653 ntohs(host->port)));
1654 assert(interfValid == 1);
1655 initInterfaceAddr_r(host, &interf);
1660 afs_inet_ntoa_r(host->host, hoststr);
1662 ("CB: RCallBackConnectBack failed for %s:%d\n",
1663 hoststr, ntohs(host->port)));
1664 host->hostFlags |= VENUSDOWN;
1667 ("CB: RCallBackConnectBack succeeded for %s:%d\n",
1668 hoststr, ntohs(host->port)));
1669 host->hostFlags |= RESETDONE;
1672 if (caps.Capabilities_val
1673 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1674 host->hostFlags |= HERRORTRANS;
1676 host->hostFlags &= ~(HERRORTRANS);
1677 host->hostFlags |= ALTADDR; /* host structure initialization complete */
1680 if (caps.Capabilities_val)
1681 free(caps.Capabilities_val);
1682 caps.Capabilities_val = NULL;
1683 caps.Capabilities_len = 0;
1689 static char localcellname[PR_MAXNAMELEN + 1];
1690 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
1691 int num_lrealms = -1;
1697 memset(&nulluuid, 0, sizeof(afsUUID));
1698 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
1699 if (num_lrealms == -1) {
1701 for (i=0; i<AFS_NUM_LREALMS; i++) {
1702 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
1708 ("afs_krb_get_lrealm failed, using %s.\n",
1710 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
1716 /* initialize the rest of the local realms to nullstring for debugging */
1717 for (; i<AFS_NUM_LREALMS; i++)
1718 local_realms[i][0] = '\0';
1720 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
1721 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
1722 #ifdef AFS_PTHREAD_ENV
1723 assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
1724 #endif /* AFS_PTHREAD_ENV */
1728 MapName_r(char *aname, char *acell, afs_int32 * aval)
1733 afs_int32 anamelen, cnamelen;
1737 anamelen = strlen(aname);
1738 if (anamelen >= PR_MAXNAMELEN)
1739 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
1741 lnames.namelist_len = 1;
1742 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
1743 lids.idlist_len = 0;
1744 lids.idlist_val = NULL;
1746 cnamelen = strlen(acell);
1748 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
1750 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
1751 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
1752 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
1754 ("MapName: Name too long, using AnonymousID for %s@%s\n",
1756 *aval = AnonymousID;
1759 foreign = 1; /* attempt cross-cell authentication */
1760 tname = (char *)malloc(PR_MAXNAMELEN);
1762 ViceLog(0, ("Failed malloc in MapName_r\n"));
1765 strcpy(tname, aname);
1766 tname[anamelen] = '@';
1767 strcpy(tname + anamelen + 1, acell);
1768 lnames.namelist_val = (prname *) tname;
1773 code = hpr_NameToId(&lnames, &lids);
1776 if (lids.idlist_val) {
1777 *aval = lids.idlist_val[0];
1778 if (*aval == AnonymousID) {
1780 ("MapName: NameToId on %s returns anonymousID\n",
1781 lnames.namelist_val));
1783 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
1786 ("MapName: NameToId on '%s' is unknown\n",
1787 lnames.namelist_val));
1793 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
1801 /* NOTE: this returns the client with a Write lock and a refCount */
1803 h_ID2Client(afs_int32 vid)
1805 register struct client *client;
1806 register struct host *host;
1809 for (host = hostList; host; host = host->next) {
1810 if (host->hostFlags & HOSTDELETED)
1812 for (client = host->FirstClient; client; client = client->next) {
1813 if (!client->deleted && client->ViceId == vid) {
1816 ObtainWriteLock(&client->lock);
1827 * Called by the server main loop. Returns a h_Held client, which must be
1828 * released later the main loop. Allocates a client if the matching one
1829 * isn't around. The client is returned with its reference count incremented
1830 * by one. The caller must call h_ReleaseClient_r when finished with
1833 * the client->host is returned held. h_ReleaseClient_r does not release
1834 * the hold on client->host.
1837 h_FindClient_r(struct rx_connection *tcon)
1839 register struct client *client;
1840 register struct host *host;
1841 struct client *oldClient;
1846 #if (64-MAXKTCNAMELEN)
1847 ticket name length != 64
1851 char uname[PR_MAXNAMELEN];
1852 char tcell[MAXKTCREALMLEN];
1856 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1857 if (client && client->sid == rxr_CidOf(tcon)
1858 && client->VenusEpoch == rxr_GetEpoch(tcon)) {
1860 h_Hold_r(client->host);
1861 if (!client->deleted && client->prfail != 2) {
1862 /* Could add shared lock on client here */
1863 /* note that we don't have to lock entry in this path to
1864 * ensure CPS is initialized, since we don't call rx_SetSpecific
1865 * until initialization is done, and we only get here if
1866 * rx_GetSpecific located the client structure.
1871 ObtainWriteLock(&client->lock); /* released at end */
1877 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
1879 ("FindClient: authenticating connection: authClass=%d\n",
1881 if (authClass == 1) {
1882 /* A bcrypt tickets, no longer supported */
1883 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
1884 viceid = AnonymousID;
1885 expTime = 0x7fffffff;
1886 } else if (authClass == 2) {
1889 /* kerberos ticket */
1890 code = rxkad_GetServerInfo(tcon, /*level */ 0, &expTime,
1891 tname, tinst, tcell, &kvno);
1893 ViceLog(1, ("Failed to get rxkad ticket info\n"));
1894 viceid = AnonymousID;
1895 expTime = 0x7fffffff;
1897 int ilen = strlen(tinst);
1899 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
1900 tname, tinst, tcell, expTime, kvno));
1901 strncpy(uname, tname, sizeof(uname));
1903 if (strlen(uname) + 1 + ilen >= sizeof(uname))
1906 strcat(uname, tinst);
1908 /* translate the name to a vice id */
1909 code = MapName_r(uname, tcell, &viceid);
1913 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
1916 viceid = AnonymousID;
1917 expTime = 0x7fffffff;
1921 viceid = AnonymousID; /* unknown security class */
1922 expTime = 0x7fffffff;
1925 if (!client) { /* loop */
1926 host = h_GetHost_r(tcon); /* Returns it h_Held */
1929 /* First try to find the client structure */
1930 for (client = host->FirstClient; client; client = client->next) {
1931 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
1932 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1935 ObtainWriteLock(&client->lock);
1941 /* Still no client structure - get one */
1944 /* Retry to find the client structure */
1945 for (client = host->FirstClient; client; client = client->next) {
1946 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
1947 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1949 goto retryfirstclient;
1954 ObtainWriteLock(&client->lock);
1955 client->refCount = 1;
1956 client->host = host;
1957 #if FS_STATS_DETAILED
1958 client->InSameNetwork = host->InSameNetwork;
1959 #endif /* FS_STATS_DETAILED */
1960 client->ViceId = viceid;
1961 client->expTime = expTime; /* rx only */
1962 client->authClass = authClass; /* rx only */
1963 client->sid = rxr_CidOf(tcon);
1964 client->VenusEpoch = rxr_GetEpoch(tcon);
1965 client->CPS.prlist_val = NULL;
1966 client->CPS.prlist_len = 0;
1970 client->prfail = fail;
1972 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
1973 client->CPS.prlist_len = 0;
1974 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
1975 free(client->CPS.prlist_val);
1976 client->CPS.prlist_val = NULL;
1977 client->ViceId = viceid;
1978 client->expTime = expTime;
1980 if (viceid == ANONYMOUSID) {
1981 client->CPS.prlist_len = AnonCPS.prlist_len;
1982 client->CPS.prlist_val = AnonCPS.prlist_val;
1985 code = hpr_GetCPS(viceid, &client->CPS);
1990 ("pr_GetCPS failed(%d) for user %d, host %s:%d\n",
1991 code, viceid, afs_inet_ntoa_r(client->host->host,
1993 ntohs(client->host->port)));
1995 /* Although ubik_Call (called by pr_GetCPS) traverses thru
1996 * all protection servers and reevaluates things if no
1997 * sync server or quorum is found we could still end up
1998 * with one of these errors. In such case we would like to
1999 * reevaluate the rpc call to find if there's cps for this
2000 * guy. We treat other errors (except network failures
2001 * ones - i.e. code < 0) as an indication that there is no
2002 * CPS for this host. Ideally we could like to deal this
2003 * problem the other way around (i.e. if code == NOCPS
2004 * ignore else retry next time) but the problem is that
2005 * there're other errors (i.e. EPERM) for which we don't
2006 * want to retry and we don't know the whole code list!
2008 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2012 /* the disabling of system:administrators is so iffy and has so many
2013 * possible failure modes that we will disable it again */
2014 /* Turn off System:Administrator for safety
2015 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2016 * assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2019 /* Now, tcon may already be set to a rock, since we blocked with no host
2020 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2021 * required). So, before setting the RPC's rock, we should disconnect
2022 * the RPC from the other client structure's rock.
2024 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2025 if (oldClient && oldClient != client && oldClient->sid == rxr_CidOf(tcon)
2026 && oldClient->VenusEpoch == rxr_GetEpoch(tcon)) {
2028 if (!oldClient->deleted) {
2029 /* if we didn't create it, it's not ours to put back */
2031 ViceLog(0, ("FindClient: stillborn client %x(%x); conn %x (host %s:%d) had client %x(%x)\n",
2032 client, client->sid, tcon,
2033 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2034 ntohs(rxr_PortOf(tcon)),
2035 oldClient, oldClient->sid));
2036 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2037 free(client->CPS.prlist_val);
2038 client->CPS.prlist_val = NULL;
2039 client->CPS.prlist_len = 0;
2041 /* We should perhaps check for 0 here */
2043 ReleaseWriteLock(&client->lock);
2048 oldClient->refCount++;
2050 ObtainWriteLock(&oldClient->lock);
2054 ViceLog(0, ("FindClient: deleted client %x(%x) already had conn %x (host %s:%d), stolen by client %x(%x)\n",
2055 oldClient, oldClient->sid, tcon,
2056 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2057 ntohs(rxr_PortOf(tcon)),
2058 client, client->sid));
2059 /* rx_SetSpecific will be done immediately below */
2062 /* Avoid chaining in more than once. */
2065 client->next = host->FirstClient;
2066 host->FirstClient = client;
2068 CurrentConnections++; /* increment number of connections */
2070 rx_SetSpecific(tcon, rxcon_client_key, client);
2071 ReleaseWriteLock(&client->lock);
2075 } /*h_FindClient_r */
2078 h_ReleaseClient_r(struct client *client)
2080 assert(client->refCount > 0);
2087 * Sigh: this one is used to get the client AGAIN within the individual
2088 * server routines. This does not bother h_Holding the host, since
2089 * this is assumed already have been done by the server main loop.
2090 * It does check tokens, since only the server routines can return the
2091 * VICETOKENDEAD error code
2094 GetClient(struct rx_connection *tcon, struct client **cp)
2096 register struct client *client;
2100 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2101 if (client == NULL) {
2103 ("GetClient: no client in conn %x (host %x:%d), VBUSYING\n",
2104 tcon, rxr_HostOf(tcon),ntohs(rxr_PortOf(tcon))));
2108 if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2110 ("GetClient: tcon %x tcon sid %d client sid %d\n",
2111 tcon, rxr_CidOf(tcon), client->sid));
2115 if (client && client->LastCall > client->expTime && client->expTime) {
2118 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2119 afs_inet_ntoa_r(client->host->host, hoststr),
2120 ntohs(client->host->port), client->expTime));
2122 return VICETOKENDEAD;
2132 PutClient(struct client **cp)
2138 h_ReleaseClient_r(*cp);
2145 /* Client user name for short term use. Note that this is NOT inexpensive */
2147 h_UserName(struct client *client)
2149 static char User[PR_MAXNAMELEN + 1];
2154 lids.idlist_len = 1;
2155 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2156 if (!lids.idlist_val) {
2157 ViceLog(0, ("Failed malloc in h_UserName\n"));
2160 lnames.namelist_len = 0;
2161 lnames.namelist_val = (prname *) 0;
2162 lids.idlist_val[0] = client->ViceId;
2163 if (hpr_IdToName(&lids, &lnames)) {
2164 /* We need to free id we alloced above! */
2165 free(lids.idlist_val);
2166 return "*UNKNOWN USER NAME*";
2168 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2169 free(lids.idlist_val);
2170 free(lnames.namelist_val);
2180 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2181 CEs, CEBlocks, HTs, HTBlocks));
2187 h_PrintClient(register struct host *host, int held, StreamHandle_t * file)
2189 register struct client *client;
2194 time_t LastCall, expTime;
2197 LastCall = host->LastCall;
2198 if (host->hostFlags & HOSTDELETED) {
2202 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2203 "Host %s:%d down = %d, LastCall %s",
2204 afs_inet_ntoa_r(host->host, hoststr),
2205 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2206 afs_ctime(&LastCall, tbuffer,
2208 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2209 for (client = host->FirstClient; client; client = client->next) {
2210 if (!client->deleted) {
2211 expTime = client->expTime;
2212 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2213 " user id=%d, name=%s, sl=%s till %s",
2214 client->ViceId, h_UserName(client),
2216 authClass ? "Authenticated" :
2217 "Not authenticated",
2219 authClass ? afs_ctime(&expTime, tbuffer,
2222 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2223 (void)afs_snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2224 client->CPS.prlist_len);
2225 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2226 if (client->CPS.prlist_val) {
2227 for (i = 0; i > client->CPS.prlist_len; i++) {
2228 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2229 client->CPS.prlist_val[i]);
2230 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2233 sprintf(tmpStr, "]\n");
2234 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2240 } /*h_PrintClient */
2245 * Print a list of clients, with last security level and token value seen,
2255 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2259 ("Couldn't create client dump file %s\n",
2260 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2263 now = FT_ApproxTime();
2264 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
2265 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2266 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2267 h_Enumerate(h_PrintClient, (char *)file);
2268 STREAM_REALLYCLOSE(file);
2269 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2276 h_DumpHost(register struct host *host, int held, StreamHandle_t * file)
2283 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2284 "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 [",
2285 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), host->index,
2286 host->cblist, CheckLock(&host->lock), host->LastCall,
2287 host->ActiveCall, (host->hostFlags & VENUSDOWN),
2288 host->hostFlags & HOSTDELETED, host->Console,
2289 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2291 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2292 if (host->hcps.prlist_val)
2293 for (i = 0; i < host->hcps.prlist_len; i++) {
2294 (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2295 host->hcps.prlist_val[i]);
2296 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2298 sprintf(tmpStr, "] [");
2299 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2300 if (host->interface)
2301 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2303 sprintf(tmpStr, " %s:%d",
2304 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2305 ntohs(host->interface->interface[i].port));
2306 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2308 sprintf(tmpStr, "] holds: ");
2309 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2311 for (i = 0; i < h_maxSlots; i++) {
2312 sprintf(tmpStr, "%04x", host->holds[i]);
2313 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2315 sprintf(tmpStr, " slot/bit: %d/%d\n", h_holdSlot(), h_holdbit());
2316 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2328 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2334 ("Couldn't create host dump file %s\n",
2335 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2338 now = FT_ApproxTime();
2339 (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
2340 afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2341 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2342 h_Enumerate(h_DumpHost, (char *)file);
2343 STREAM_REALLYCLOSE(file);
2344 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2348 #ifdef AFS_DEMAND_ATTACH_FS
2351 * host state serialization
2353 static int h_stateFillHeader(struct host_state_header * hdr);
2354 static int h_stateCheckHeader(struct host_state_header * hdr);
2355 static int h_stateAllocMap(struct fs_dump_state * state);
2356 static int h_stateSaveHost(register struct host * host, int held, struct fs_dump_state * state);
2357 static int h_stateRestoreHost(struct fs_dump_state * state);
2358 static int h_stateRestoreIndex(struct host * h, int held, struct fs_dump_state * state);
2359 static int h_stateVerifyHost(struct host * h, int held, struct fs_dump_state * state);
2360 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port);
2361 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2362 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2363 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2366 /* this procedure saves all host state to disk for fast startup */
2368 h_stateSave(struct fs_dump_state * state)
2370 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2373 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2375 /* invalidate host state header */
2376 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2378 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2379 sizeof(struct host_state_header))) {
2384 fs_stateIncEOF(state, sizeof(struct host_state_header));
2386 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2391 h_stateFillHeader(state->h_hdr);
2393 /* write the real header to disk */
2394 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2395 sizeof(struct host_state_header));
2402 * host state serialization
2404 * this procedure restores all host state from a disk for fast startup
2407 h_stateRestore(struct fs_dump_state * state)
2411 /* seek to the right position and read in the host state header */
2412 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2413 sizeof(struct host_state_header))) {
2418 /* check the validity of the header */
2419 if (h_stateCheckHeader(state->h_hdr)) {
2424 records = state->h_hdr->records;
2426 if (h_stateAllocMap(state)) {
2431 /* iterate over records restoring host state */
2432 for (i=0; i < records; i++) {
2433 if (h_stateRestoreHost(state) != 0) {
2444 h_stateRestoreIndices(struct fs_dump_state * state)
2446 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
2451 h_stateRestoreIndex(struct host * h, int held, struct fs_dump_state * state)
2453 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
2454 return H_ENUMERATE_BAIL(held);
2460 h_stateVerify(struct fs_dump_state * state)
2462 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
2467 h_stateVerifyHost(struct host * h, int held, struct fs_dump_state * state)
2472 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
2473 return H_ENUMERATE_BAIL(held);
2477 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
2478 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
2479 h->interface->interface[i].port)) {
2483 if (h_stateVerifyUuidHash(state, h)) {
2486 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port)) {
2490 if (cb_stateVerifyHCBList(state, h)) {
2499 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port)
2501 int ret = 0, found = 0;
2502 struct host *host = NULL;
2503 struct h_hashChain *chain;
2504 int index = h_HashIndex(addr);
2508 for (chain = hostHashTable[index]; chain; chain = chain->next) {
2509 host = chain->hostPtr;
2511 afs_inet_ntoa_r(addr, tmp);
2512 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
2516 if ((chain->addr == addr) && (chain->port == port)) {
2518 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry points to different host struct (%d, %d)\n",
2519 h->index, host->index));
2520 state->flags.warnings_generated = 1;
2525 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
2526 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2527 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
2535 afs_inet_ntoa_r(addr, tmp);
2536 if (state->mode == FS_STATE_LOAD_MODE) {
2537 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s not found in hash\n", tmp));
2541 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s not found in hash\n", tmp));
2542 state->flags.warnings_generated = 1;
2551 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
2553 int ret = 0, found = 0;
2554 struct host *host = NULL;
2555 struct h_hashChain *chain;
2556 afsUUID * uuidp = &h->interface->uuid;
2557 int index = h_UuidHashIndex(uuidp);
2561 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
2562 host = chain->hostPtr;
2564 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2565 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
2569 if (host->interface &&
2570 afs_uuid_equal(&host->interface->uuid, uuidp)) {
2572 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
2573 h->index, host->index));
2574 state->flags.warnings_generated = 1;
2579 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
2580 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2581 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
2589 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2590 if (state->mode == FS_STATE_LOAD_MODE) {
2591 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
2595 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
2596 state->flags.warnings_generated = 1;
2604 /* create the host state header structure */
2606 h_stateFillHeader(struct host_state_header * hdr)
2608 hdr->stamp.magic = HOST_STATE_MAGIC;
2609 hdr->stamp.version = HOST_STATE_VERSION;
2612 /* check the contents of the host state header structure */
2614 h_stateCheckHeader(struct host_state_header * hdr)
2618 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
2619 ViceLog(0, ("check_host_state_header: invalid state header\n"));
2622 else if (hdr->stamp.version != HOST_STATE_VERSION) {
2623 ViceLog(0, ("check_host_state_header: unknown version number\n"));
2629 /* allocate the host id mapping table */
2631 h_stateAllocMap(struct fs_dump_state * state)
2633 state->h_map.len = state->h_hdr->index_max + 1;
2634 state->h_map.entries = (struct idx_map_entry_t *)
2635 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
2636 return (state->h_map.entries != NULL) ? 0 : 1;
2639 /* function called by h_Enumerate to save a host to disk */
2641 h_stateSaveHost(register struct host * host, int held, struct fs_dump_state * state)
2643 int i, if_len=0, hcps_len=0;
2644 struct hostDiskEntry hdsk;
2645 struct host_state_entry_header hdr;
2646 struct Interface * ifp = NULL;
2647 afs_int32 * hcps = NULL;
2648 struct iovec iov[4];
2651 memset(&hdr, 0, sizeof(hdr));
2653 if (state->h_hdr->index_max < host->index) {
2654 state->h_hdr->index_max = host->index;
2657 h_hostToDiskEntry_r(host, &hdsk);
2658 if (host->interface) {
2659 if_len = sizeof(struct Interface) +
2660 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
2661 ifp = (struct Interface *) malloc(if_len);
2662 assert(ifp != NULL);
2663 memcpy(ifp, host->interface, if_len);
2664 hdr.interfaces = host->interface->numberOfInterfaces;
2665 iov[iovcnt].iov_base = (char *) ifp;
2666 iov[iovcnt].iov_len = if_len;
2669 if (host->hcps.prlist_val) {
2670 hdr.hcps = host->hcps.prlist_len;
2671 hcps_len = hdr.hcps * sizeof(afs_int32);
2672 hcps = (afs_int32 *) malloc(hcps_len);
2673 assert(hcps != NULL);
2674 memcpy(hcps, host->hcps.prlist_val, hcps_len);
2675 iov[iovcnt].iov_base = (char *) hcps;
2676 iov[iovcnt].iov_len = hcps_len;
2680 if (hdsk.index > state->h_hdr->index_max)
2681 state->h_hdr->index_max = hdsk.index;
2683 hdr.len = sizeof(struct host_state_entry_header) +
2684 sizeof(struct hostDiskEntry) + if_len + hcps_len;
2685 hdr.magic = HOST_STATE_ENTRY_MAGIC;
2687 iov[0].iov_base = (char *) &hdr;
2688 iov[0].iov_len = sizeof(hdr);
2689 iov[1].iov_base = (char *) &hdsk;
2690 iov[1].iov_len = sizeof(struct hostDiskEntry);
2692 if (fs_stateWriteV(state, iov, iovcnt)) {
2693 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
2697 fs_stateIncEOF(state, hdr.len);
2699 state->h_hdr->records++;
2707 return H_ENUMERATE_BAIL(held);
2712 /* restores a host from disk */
2714 h_stateRestoreHost(struct fs_dump_state * state)
2716 int ifp_len=0, hcps_len=0, bail=0;
2717 struct host_state_entry_header hdr;
2718 struct hostDiskEntry hdsk;
2719 struct host *host = NULL;
2720 struct Interface *ifp = NULL;
2721 afs_int32 * hcps = NULL;
2722 struct iovec iov[3];
2725 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
2726 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
2732 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
2733 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
2739 iov[0].iov_base = (char *) &hdsk;
2740 iov[0].iov_len = sizeof(struct hostDiskEntry);
2742 if (hdr.interfaces) {
2743 ifp_len = sizeof(struct Interface) +
2744 ((hdr.interfaces-1) * sizeof(struct AddrPort));
2745 ifp = (struct Interface *) malloc(ifp_len);
2746 assert(ifp != NULL);
2747 iov[iovcnt].iov_base = (char *) ifp;
2748 iov[iovcnt].iov_len = ifp_len;
2752 hcps_len = hdr.hcps * sizeof(afs_int32);
2753 hcps = (afs_int32 *) malloc(hcps_len);
2754 assert(hcps != NULL);
2755 iov[iovcnt].iov_base = (char *) hcps;
2756 iov[iovcnt].iov_len = hcps_len;
2760 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
2761 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
2766 if (fs_stateReadV(state, iov, iovcnt)) {
2767 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
2772 if (!hdr.hcps && hdsk.hcps_valid) {
2773 /* valid, zero-length host cps ; does this ever happen? */
2774 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
2775 assert(hcps != NULL);
2779 assert(host != NULL);
2782 host->interface = ifp;
2785 host->hcps.prlist_val = hcps;
2786 host->hcps.prlist_len = hdr.hcps;
2789 h_diskEntryToHost_r(&hdsk, host);
2790 h_SetupCallbackConn_r(host);
2794 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
2795 h_AddHostToHashTable_r(ifp->interface[i].addr,
2796 ifp->interface[i].port, host);
2798 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
2800 h_AddHostToHashTable_r(host->host, host->port, host);
2802 h_InsertList_r(host);
2804 /* setup host id map entry */
2805 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
2806 state->h_map.entries[hdsk.index].new_idx = host->index;
2818 /* serialize a host structure to disk */
2820 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
2822 out->host = in->host;
2823 out->port = in->port;
2824 out->hostFlags = in->hostFlags;
2825 out->Console = in->Console;
2826 out->hcpsfailed = in->hcpsfailed;
2827 out->LastCall = in->LastCall;
2828 out->ActiveCall = in->ActiveCall;
2829 out->cpsCall = in->cpsCall;
2830 out->cblist = in->cblist;
2831 #ifdef FS_STATS_DETAILED
2832 out->InSameNetwork = in->InSameNetwork;
2835 /* special fields we save, but are not memcpy'd back on restore */
2836 out->index = in->index;
2837 out->hcps_len = in->hcps.prlist_len;
2838 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
2841 /* restore a host structure from disk */
2843 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
2845 out->host = in->host;
2846 out->port = in->port;
2847 out->hostFlags = in->hostFlags;
2848 out->Console = in->Console;
2849 out->hcpsfailed = in->hcpsfailed;
2850 out->LastCall = in->LastCall;
2851 out->ActiveCall = in->ActiveCall;
2852 out->cpsCall = in->cpsCall;
2853 out->cblist = in->cblist;
2854 #ifdef FS_STATS_DETAILED
2855 out->InSameNetwork = in->InSameNetwork;
2859 /* index translation routines */
2861 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
2865 /* hosts use a zero-based index, so old==0 is valid */
2867 if (old >= state->h_map.len) {
2868 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
2870 } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
2871 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
2874 *new = state->h_map.entries[old].new_idx;
2880 #endif /* AFS_DEMAND_ATTACH_FS */
2884 * This counts the number of workstations, the number of active workstations,
2885 * and the number of workstations declared "down" (i.e. not heard from
2886 * recently). An active workstation has received a call since the cutoff
2887 * time argument passed.
2890 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
2892 register struct host *host;
2893 register int num = 0, active = 0, del = 0;
2896 for (host = hostList; host; host = host->next) {
2897 if (!(host->hostFlags & HOSTDELETED)) {
2899 if (host->ActiveCall > cutofftime)
2901 if (host->hostFlags & VENUSDOWN)
2913 } /*h_GetWorkStats */
2916 /*------------------------------------------------------------------------
2917 * PRIVATE h_ClassifyAddress
2920 * Given a target IP address and a candidate IP address (both
2921 * in host byte order), classify the candidate into one of three
2922 * buckets in relation to the target by bumping the counters passed
2926 * a_targetAddr : Target address.
2927 * a_candAddr : Candidate address.
2928 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
2929 * addresses are either in the same network
2930 * or the same subnet.
2931 * a_diffSubnetP : ...when the candidate is in a different
2933 * a_diffNetworkP : ...when the candidate is in a different
2940 * The target and candidate addresses are both in host byte
2941 * order, NOT network byte order, when passed in.
2945 *------------------------------------------------------------------------*/
2948 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
2949 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
2950 afs_int32 * a_diffNetworkP)
2951 { /*h_ClassifyAddress */
2953 afs_uint32 targetNet;
2954 afs_uint32 targetSubnet;
2956 afs_uint32 candSubnet;
2959 * Put bad values into the subnet info to start with.
2961 targetSubnet = (afs_uint32) 0;
2962 candSubnet = (afs_uint32) 0;
2965 * Pull out the network and subnetwork numbers from the target
2966 * and candidate addresses. We can short-circuit this whole
2967 * affair if the target and candidate addresses are not of the
2970 if (IN_CLASSA(a_targetAddr)) {
2971 if (!(IN_CLASSA(a_candAddr))) {
2972 (*a_diffNetworkP)++;
2975 targetNet = a_targetAddr & IN_CLASSA_NET;
2976 candNet = a_candAddr & IN_CLASSA_NET;
2977 if (IN_SUBNETA(a_targetAddr))
2978 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
2979 if (IN_SUBNETA(a_candAddr))
2980 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
2981 } else if (IN_CLASSB(a_targetAddr)) {
2982 if (!(IN_CLASSB(a_candAddr))) {
2983 (*a_diffNetworkP)++;
2986 targetNet = a_targetAddr & IN_CLASSB_NET;
2987 candNet = a_candAddr & IN_CLASSB_NET;
2988 if (IN_SUBNETB(a_targetAddr))
2989 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
2990 if (IN_SUBNETB(a_candAddr))
2991 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
2992 } /*Class B target */
2993 else if (IN_CLASSC(a_targetAddr)) {
2994 if (!(IN_CLASSC(a_candAddr))) {
2995 (*a_diffNetworkP)++;
2998 targetNet = a_targetAddr & IN_CLASSC_NET;
2999 candNet = a_candAddr & IN_CLASSC_NET;
3002 * Note that class C addresses can't have subnets,
3003 * so we leave the defaults untouched.
3005 } /*Class C target */
3007 targetNet = a_targetAddr;
3008 candNet = a_candAddr;
3009 } /*Class D address */
3012 * Now, simply compare the extracted net and subnet values for
3013 * the two addresses (which at this point are known to be of the
3016 if (targetNet == candNet) {
3017 if (targetSubnet == candSubnet)
3018 (*a_sameNetOrSubnetP)++;
3022 (*a_diffNetworkP)++;
3024 } /*h_ClassifyAddress */
3027 /*------------------------------------------------------------------------
3028 * EXPORTED h_GetHostNetStats
3031 * Iterate through the host table, and classify each (non-deleted)
3032 * host entry into ``proximity'' categories (same net or subnet,
3033 * different subnet, different network).
3036 * a_numHostsP : Set to total number of (non-deleted) hosts.
3037 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3038 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3039 * a_diffNetworkP : Set to # hosts on diff network as server.
3045 * We only count non-deleted hosts. The storage pointed to by our
3046 * parameters is zeroed upon entry.
3050 *------------------------------------------------------------------------*/
3053 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3054 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3055 { /*h_GetHostNetStats */
3057 register struct host *hostP; /*Ptr to current host entry */
3058 register afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3061 * Clear out the storage pointed to by our parameters.
3063 *a_numHostsP = (afs_int32) 0;
3064 *a_sameNetOrSubnetP = (afs_int32) 0;
3065 *a_diffSubnetP = (afs_int32) 0;
3066 *a_diffNetworkP = (afs_int32) 0;
3069 for (hostP = hostList; hostP; hostP = hostP->next) {
3070 if (!(hostP->hostFlags & HOSTDELETED)) {
3072 * Bump the number of undeleted host entries found.
3073 * In classifying the current entry's address, make
3074 * sure to first convert to host byte order.
3077 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3078 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3079 a_sameNetOrSubnetP, a_diffSubnetP,
3081 } /*Only look at non-deleted hosts */
3082 } /*For each host record hashed to this index */
3084 } /*h_GetHostNetStats */
3086 static afs_uint32 checktime;
3087 static afs_uint32 clientdeletetime;
3088 static struct AFSFid zerofid;
3092 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3093 * Since it can serialize them, and pile up, it should be a separate LWP
3094 * from other events.
3097 CheckHost(register struct host *host, int held)
3099 register struct client *client;
3100 struct rx_connection *cb_conn = NULL;
3103 #ifdef AFS_DEMAND_ATTACH_FS
3104 /* kill the checkhost lwp ASAP during shutdown */
3106 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3108 return H_ENUMERATE_BAIL(held);
3113 /* Host is held by h_Enumerate */
3115 for (client = host->FirstClient; client; client = client->next) {
3116 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3117 client->deleted = 1;
3118 host->hostFlags |= CLIENTDELETED;
3121 if (host->LastCall < checktime) {
3123 if (!(host->hostFlags & HOSTDELETED)) {
3124 cb_conn = host->callback_rxcon;
3125 rx_GetConnection(cb_conn);
3126 if (host->LastCall < clientdeletetime) {
3127 host->hostFlags |= HOSTDELETED;
3128 if (!(host->hostFlags & VENUSDOWN)) {
3129 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3130 if (host->interface) {
3133 RXAFSCB_InitCallBackState3(cb_conn,
3139 RXAFSCB_InitCallBackState(cb_conn);
3142 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3145 (void)afs_inet_ntoa_r(host->host, hoststr);
3147 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3148 hoststr, ntohs(host->port)));
3149 host->hostFlags |= VENUSDOWN;
3151 /* Note: it's safe to delete hosts even if they have call
3152 * back state, because break delayed callbacks (called when a
3153 * message is received from the workstation) will always send a
3154 * break all call backs to the workstation if there is no
3159 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3161 (void)afs_inet_ntoa_r(host->host, hoststr);
3162 if (host->interface) {
3163 afsUUID uuid = host->interface->uuid;
3165 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3168 if (MultiProbeAlternateAddress_r(host)) {
3169 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3170 hoststr, ntohs(host->port), code));
3171 host->hostFlags |= VENUSDOWN;
3176 code = RXAFSCB_Probe(cb_conn);
3180 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3181 hoststr, ntohs(host->port), code));
3182 host->hostFlags |= VENUSDOWN;
3188 rx_PutConnection(cb_conn);
3201 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3202 * don't respond to a probe. Note that VenusDown can only be cleared if
3203 * a message is received from the host (see ServerLWP in file.c).
3204 * Delete hosts that have not had any calls in 1 hour, clients that
3205 * have not had any calls in 15 minutes.
3207 * This routine is called roughly every 5 minutes.
3212 afs_uint32 now = FT_ApproxTime();
3214 memset((char *)&zerofid, 0, sizeof(zerofid));
3216 * Send a probe to the workstation if it hasn't been heard from in
3219 checktime = now - 15 * 60;
3220 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3221 h_Enumerate(CheckHost, NULL);
3226 * This is called with host locked and held. At this point, the
3227 * hostHashTable should not have any entries for the alternate
3228 * interfaces. This function has to insert these entries in the
3231 * The addresses in the interfaceAddr list are in host byte order.
3234 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3241 struct Interface *interface;
3247 number = interf->numberOfInterfaces;
3248 myAddr = host->host; /* current interface address */
3249 myPort = host->port; /* current port */
3252 ("initInterfaceAddr : host %s:%d numAddr %d\n",
3253 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3255 /* validation checks */
3256 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3258 ("Invalid number of alternate addresses is %d\n", number));
3263 * Convert IP addresses to network byte order, and remove for
3264 * duplicate IP addresses from the interface list.
3266 for (i = 0, count = 0, found = 0; i < number; i++) {
3267 interf->addr_in[i] = htonl(interf->addr_in[i]);
3268 for (j = 0; j < count; j++) {
3269 if (interf->addr_in[j] == interf->addr_in[i])
3273 interf->addr_in[count] = interf->addr_in[i];
3274 if (interf->addr_in[count] == myAddr)
3281 * Allocate and initialize an interface structure for this host.
3284 interface = (struct Interface *)
3285 malloc(sizeof(struct Interface) +
3286 (sizeof(struct AddrPort) * (count - 1)));
3288 ViceLog(0, ("Failed malloc in initInterfaceAddr_r\n"));
3291 interface->numberOfInterfaces = count;
3293 interface = (struct Interface *)
3294 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
3296 interface->numberOfInterfaces = count + 1;
3297 interface->interface[count].addr = myAddr;
3298 interface->interface[count].port = myPort;
3300 interface->uuid = interf->uuid;
3301 for (i = 0; i < count; i++) {
3302 interface->interface[i].addr = interf->addr_in[i];
3303 /* We store the port as 7001 because the addresses reported by
3304 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
3305 * are coming from fully connected hosts (no NAT/PATs)
3307 interface->interface[i].port = htons(7001);
3310 assert(!host->interface);
3311 host->interface = interface;
3313 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
3314 ViceLog(125, ("--- alt address %s:%d\n",
3315 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3316 ntohs(host->interface->interface[i].port)));
3322 /* deleted a HashChain structure for this address and host */
3323 /* returns 1 on success */
3325 h_DeleteHostFromHashTableByAddr_r(afs_uint32 addr, afs_uint16 port, struct host *host)
3328 register struct h_hashChain **hp, *th;
3330 for (hp = &hostHashTable[h_HashIndex(addr)]; (th = *hp);) {
3331 assert(th->hostPtr);
3332 if (th->hostPtr == host && th->addr == addr && th->port == port) {
3346 ** prints out all alternate interface address for the host. The 'level'
3347 ** parameter indicates what level of debugging sets this output
3350 printInterfaceAddr(struct host *host, int level)
3355 if (host->interface) {
3356 /* check alternate addresses */
3357 number = host->interface->numberOfInterfaces;
3359 for (i = 0; i < number; i++)
3360 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3361 ntohs(host->interface->interface[i].port)));
3363 ViceLog(level, ("\n"));