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>
18 #ifdef HAVE_SYS_FILE_H
23 #include <afs/afs_assert.h>
26 #include <afs/afsint.h>
27 #define FSINT_COMMON_XG
28 #include <afs/afscbint.h>
29 #include <afs/rxgen_consts.h>
31 #include <afs/errors.h>
32 #include <afs/ihandle.h>
33 #include <afs/vnode.h>
34 #include <afs/volume.h>
35 #ifdef AFS_ATHENA_STDENV
39 #include <afs/ptclient.h>
40 #include <afs/ptuser.h>
41 #include <afs/prs_fs.h>
43 #include <afs/afsutil.h>
44 #include <afs/com_err.h>
46 #include <afs/cellconfig.h>
47 #include "viced_prototypes.h"
51 #ifdef AFS_DEMAND_ATTACH_FS
52 #include "../util/afsutil_prototypes.h"
53 #include "../tviced/serialize_state.h"
54 #endif /* AFS_DEMAND_ATTACH_FS */
56 #ifdef AFS_PTHREAD_ENV
57 pthread_mutex_t host_glock_mutex;
58 #endif /* AFS_PTHREAD_ENV */
61 extern int CurrentConnections;
63 extern int AnonymousID;
64 extern prlist AnonCPS;
66 extern struct afsconf_dir *confDir; /* config dir object */
67 extern int lwps; /* the max number of server threads */
68 extern afsUUID FS_HostUUID;
71 int CEs = 0; /* active clients */
72 int CEBlocks = 0; /* number of blocks of CEs */
73 struct client *CEFree = 0; /* first free client */
74 struct host *hostList = 0; /* linked list of all hosts */
75 int hostCount = 0; /* number of hosts in hostList */
79 static struct rx_securityClass *sc = NULL;
81 static void h_SetupCallbackConn_r(struct host * host);
82 static int h_threadquota(int);
84 #define CESPERBLOCK 73
85 struct CEBlock { /* block of CESPERBLOCK file entries */
86 struct client entry[CESPERBLOCK];
89 void h_TossStuff_r(struct host *host);
92 * Make sure the subnet macros have been defined.
95 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
98 #ifndef IN_CLASSA_SUBNET
99 #define IN_CLASSA_SUBNET 0xffff0000
103 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
106 #ifndef IN_CLASSB_SUBNET
107 #define IN_CLASSB_SUBNET 0xffffff00
111 /* get a new block of CEs and chain it on CEFree */
115 struct CEBlock *block;
118 block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
120 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
121 ShutDownAndCore(PANIC);
124 for (i = 0; i < (CESPERBLOCK - 1); i++) {
125 Lock_Init(&block->entry[i].lock);
126 block->entry[i].next = &(block->entry[i + 1]);
128 block->entry[CESPERBLOCK - 1].next = 0;
129 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
130 CEFree = (struct client *)block;
136 /* get the next available CE */
137 static struct client *
140 struct client *entry;
145 ViceLog(0, ("CEFree NULL in GetCE\n"));
146 ShutDownAndCore(PANIC);
150 CEFree = entry->next;
152 memset(entry, 0, CLIENT_TO_ZERO(entry));
158 /* return an entry to the free list */
160 FreeCE(struct client *entry)
162 entry->VenusEpoch = 0;
164 entry->next = CEFree;
171 * The HTs and HTBlocks variables were formerly static, but they are
172 * now referenced elsewhere in the FileServer.
174 int HTs = 0; /* active file entries */
175 int HTBlocks = 0; /* number of blocks of HTs */
176 static struct host *HTFree = 0; /* first free file entry */
179 * Hash tables of host pointers. We need two tables, one
180 * to map IP addresses onto host pointers, and another
181 * to map host UUIDs onto host pointers.
183 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
184 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
185 #define h_HashIndex(hostip) (ntohl(hostip) & (h_HASHENTRIES-1))
186 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
188 struct HTBlock { /* block of HTSPERBLOCK file entries */
189 struct host entry[h_HTSPERBLOCK];
193 /* get a new block of HTs and chain it on HTFree */
197 struct HTBlock *block;
199 static int index = 0;
201 if (HTBlocks == h_MAXHOSTTABLES) {
202 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
203 ShutDownAndCore(PANIC);
206 block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
208 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
209 ShutDownAndCore(PANIC);
211 #ifdef AFS_PTHREAD_ENV
212 for (i = 0; i < (h_HTSPERBLOCK); i++)
213 CV_INIT(&block->entry[i].cond, "block entry", CV_DEFAULT, 0);
214 #endif /* AFS_PTHREAD_ENV */
215 for (i = 0; i < (h_HTSPERBLOCK); i++)
216 Lock_Init(&block->entry[i].lock);
217 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
218 block->entry[i].next = &(block->entry[i + 1]);
219 for (i = 0; i < (h_HTSPERBLOCK); i++)
220 block->entry[i].index = index++;
221 block->entry[h_HTSPERBLOCK - 1].next = 0;
222 HTFree = (struct host *)block;
223 hosttableptrs[HTBlocks++] = block->entry;
228 /* get the next available HT */
236 osi_Assert(HTFree != NULL);
238 HTFree = entry->next;
240 memset(entry, 0, HOST_TO_ZERO(entry));
246 /* return an entry to the free list */
248 FreeHT(struct host *entry)
250 entry->next = HTFree;
257 hpr_Initialize(struct ubik_client **uclient)
260 struct rx_connection *serverconns[MAXSERVERS];
261 struct rx_securityClass *sc;
262 struct afsconf_dir *tdir;
264 struct afsconf_cell info;
268 tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
270 ViceLog(0, ("hpr_Initialize: Could not open configuration directory: %s", AFSDIR_SERVER_ETC_DIRPATH));
274 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
276 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
281 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
283 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s",
284 cellstr, confDir->name, AFSDIR_CELLSERVDB_FILE));
291 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
296 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
297 * to force use of the KeyFile. secLevel == 0 implies -noauth was
299 code = afsconf_ClientAuthSecure(tdir, &sc, &scIndex);
301 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s "
302 "(so trying noauth)", code, afs_error_message(code)));
303 scIndex = RX_SECIDX_NULL;
304 sc = rxnull_NewClientSecurityObject();
307 if (scIndex == RX_SECIDX_NULL)
308 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, "
309 "running unauthenticated. [%d]", code));
311 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
312 for (i = 0; i < info.numServers; i++) {
314 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
315 info.hostAddr[i].sin_port, PRSRV,
319 code = ubik_ClientInit(serverconns, uclient);
321 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
324 code = rxs_Release(sc);
329 hpr_End(struct ubik_client *uclient)
334 code = ubik_ClientDestroy(uclient);
340 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
342 #ifdef AFS_PTHREAD_ENV
345 struct ubik_client *uclient =
346 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
349 code = hpr_Initialize(&uclient);
351 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
357 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
358 if (code != PRSUCCESS)
361 /* do something about this, probably make a new call */
362 /* don't forget there's a hard limit in the interface */
364 "membership list for host id %d exceeds display limit\n",
369 return pr_GetHostCPS(host, CPS);
374 hpr_NameToId(namelist *names, idlist *ids)
376 #ifdef AFS_PTHREAD_ENV
379 struct ubik_client *uclient =
380 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
383 code = hpr_Initialize(&uclient);
385 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
390 for (i = 0; i < names->namelist_len; i++)
391 stolower(names->namelist_val[i]);
392 code = ubik_PR_NameToID(uclient, 0, names, ids);
395 return pr_NameToId(names, ids);
400 hpr_IdToName(idlist *ids, namelist *names)
402 #ifdef AFS_PTHREAD_ENV
404 struct ubik_client *uclient =
405 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
408 code = hpr_Initialize(&uclient);
410 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
415 code = ubik_PR_IDToName(uclient, 0, ids, names);
418 return pr_IdToName(ids, names);
423 hpr_GetCPS(afs_int32 id, prlist *CPS)
425 #ifdef AFS_PTHREAD_ENV
428 struct ubik_client *uclient =
429 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
432 code = hpr_Initialize(&uclient);
434 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
440 code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
441 if (code != PRSUCCESS)
444 /* do something about this, probably make a new call */
445 /* don't forget there's a hard limit in the interface */
446 fprintf(stderr, "membership list for id %d exceeds display limit\n",
451 return pr_GetCPS(id, CPS);
455 static short consolePort = 0;
458 h_Lock_r(struct host *host)
468 * returns 1 if already locked
469 * else returns locks and returns 0
473 h_NBLock_r(struct host *host)
475 struct Lock *hostLock = &host->lock;
480 if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
481 hostLock->excl_locked = WRITE_LOCK;
485 LOCK_UNLOCK(hostLock);
494 #if FS_STATS_DETAILED
495 /*------------------------------------------------------------------------
496 * PRIVATE h_AddrInSameNetwork
499 * Given a target IP address and a candidate IP address (both
500 * in host byte order), return a non-zero value (1) if the
501 * candidate address is in a different network from the target
505 * a_targetAddr : Target address.
506 * a_candAddr : Candidate address.
509 * 1 if the candidate address is in the same net as the target,
513 * The target and candidate addresses are both in host byte
514 * order, NOT network byte order, when passed in. We return
515 * our value as a character, since that's the type of field in
516 * the host structure, where this info will be stored.
520 *------------------------------------------------------------------------*/
523 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
524 { /*h_AddrInSameNetwork */
526 afs_uint32 targetNet;
530 * Pull out the network and subnetwork numbers from the target
531 * and candidate addresses. We can short-circuit this whole
532 * affair if the target and candidate addresses are not of the
535 if (IN_CLASSA(a_targetAddr)) {
536 if (!(IN_CLASSA(a_candAddr))) {
539 targetNet = a_targetAddr & IN_CLASSA_NET;
540 candNet = a_candAddr & IN_CLASSA_NET;
541 } else if (IN_CLASSB(a_targetAddr)) {
542 if (!(IN_CLASSB(a_candAddr))) {
545 targetNet = a_targetAddr & IN_CLASSB_NET;
546 candNet = a_candAddr & IN_CLASSB_NET;
547 } /*Class B target */
548 else if (IN_CLASSC(a_targetAddr)) {
549 if (!(IN_CLASSC(a_candAddr))) {
552 targetNet = a_targetAddr & IN_CLASSC_NET;
553 candNet = a_candAddr & IN_CLASSC_NET;
554 } /*Class C target */
556 targetNet = a_targetAddr;
557 candNet = a_candAddr;
558 } /*Class D address */
561 * Now, simply compare the extracted net values for the two addresses
562 * (which at this point are known to be of the same class)
564 if (targetNet == candNet)
569 } /*h_AddrInSameNetwork */
570 #endif /* FS_STATS_DETAILED */
573 /* Assumptions: called with held host */
575 h_gethostcps_r(struct host *host, afs_int32 now)
580 /* wait if somebody else is already doing the getCPS call */
581 while (host->hostFlags & HCPS_INPROGRESS) {
582 slept = 1; /* I did sleep */
583 host->hostFlags |= HCPS_WAITING; /* I am sleeping now */
584 #ifdef AFS_PTHREAD_ENV
585 CV_WAIT(&host->cond, &host_glock_mutex);
586 #else /* AFS_PTHREAD_ENV */
587 if ((code = LWP_WaitProcess(&(host->hostFlags))) != LWP_SUCCESS)
588 ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
589 #endif /* AFS_PTHREAD_ENV */
593 host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
594 if (host->hcps.prlist_val)
595 free(host->hcps.prlist_val); /* this is for hostaclRefresh */
596 host->hcps.prlist_val = NULL;
597 host->hcps.prlist_len = 0;
598 host->cpsCall = slept ? (FT_ApproxTime()) : (now);
601 code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
606 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
607 * and reevaluates things if no sync server or quorum is found we could still end up
608 * with one of these errors. In such case we would like to reevaluate the rpc call to
609 * find if there's cps for this guy. We treat other errors (except network failures
610 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
611 * we could like to deal this problem the other way around (i.e. if code == NOCPS
612 * ignore else retry next time) but the problem is that there're other errors (i.e.
613 * EPERM) for which we don't want to retry and we don't know the whole code list!
615 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
617 * We would have preferred to use a while loop and try again since ops in protected
618 * acls for this host will fail now but they'll be reevaluated on any subsequent
619 * call. The attempt to wait for a quorum/sync site or network error won't work
620 * since this problems really should only occurs during a complete fileserver
621 * restart. Since the fileserver will start before the ptservers (and thus before
622 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
624 host->hcpsfailed = 1;
626 ("Warning: GetHostCPS failed (%d) for %p (%s:%d); will retry\n",
627 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
629 host->hcpsfailed = 0;
631 ("gethost: GetHostCPS failed (%d) for %p (%s:%d); ignored\n",
632 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
634 if (host->hcps.prlist_val)
635 free(host->hcps.prlist_val);
636 host->hcps.prlist_val = NULL;
637 host->hcps.prlist_len = 0; /* Make sure it's zero */
639 host->hcpsfailed = 0;
641 host->hostFlags &= ~HCPS_INPROGRESS;
642 /* signal all who are waiting */
643 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
644 host->hostFlags &= ~HCPS_WAITING;
645 #ifdef AFS_PTHREAD_ENV
646 CV_BROADCAST(&host->cond);
647 #else /* AFS_PTHREAD_ENV */
648 if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
649 ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
650 #endif /* AFS_PTHREAD_ENV */
654 /* args in net byte order */
656 h_flushhostcps(afs_uint32 hostaddr, afs_uint16 hport)
661 h_Lookup_r(hostaddr, hport, &host);
663 host->hcpsfailed = 1;
672 * Allocate a host. It will be identified by the peer (ip,port) info in the
673 * rx connection provided. The host is returned held and locked
675 #define DEF_ROPCONS 2115
678 h_Alloc_r(struct rx_connection *r_con)
680 struct servent *serverentry;
682 #if FS_STATS_DETAILED
683 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
684 #endif /* FS_STATS_DETAILED */
688 host->host = rxr_HostOf(r_con);
689 host->port = rxr_PortOf(r_con);
691 h_AddHostToAddrHashTable_r(host->host, host->port, host);
693 if (consolePort == 0) { /* find the portal number for console */
694 #if defined(AFS_OSF_ENV)
695 serverentry = getservbyname("ropcons", "");
697 serverentry = getservbyname("ropcons", 0);
700 consolePort = serverentry->s_port;
702 consolePort = htons(DEF_ROPCONS); /* Use a default */
704 if (host->port == consolePort)
706 /* Make a callback channel even for the console, on the off chance that it
707 * makes a request that causes a break call back. It shouldn't. */
708 h_SetupCallbackConn_r(host);
709 host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
711 host->hcps.prlist_val = NULL;
712 host->hcps.prlist_len = 0;
713 host->interface = NULL;
715 host->hcpsfailed = 0; /* save cycles */
716 h_gethostcps(host); /* do this under host hold/lock */
718 host->FirstClient = NULL;
721 h_InsertList_r(host); /* update global host List */
722 #if FS_STATS_DETAILED
724 * Compare the new host's IP address (in host byte order) with ours
725 * (the File Server's), remembering if they are in the same network.
727 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
728 host->InSameNetwork =
729 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
730 #endif /* FS_STATS_DETAILED */
737 /* Make a callback channel even for the console, on the off chance that it
738 * makes a request that causes a break call back. It shouldn't. */
740 h_SetupCallbackConn_r(struct host * host)
743 sc = rxnull_NewClientSecurityObject();
744 host->callback_rxcon =
745 rx_NewConnection(host->host, host->port, 1, sc, 0);
746 rx_SetConnDeadTime(host->callback_rxcon, 50);
747 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
748 rx_SetConnSecondsUntilNatPing(host->callback_rxcon, 20);
752 * Lookup a host given an IP address and UDP port number.
753 * hostaddr and hport are in network order
754 * hostaddr and hport are in network order
755 * On return, refCount is incremented.
758 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, struct host **hostp)
761 struct host *host = NULL;
762 struct h_AddrHashChain *chain;
763 int index = h_HashIndex(haddr);
764 extern int hostaclRefresh;
767 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
768 host = chain->hostPtr;
770 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
771 && chain->port == hport) {
772 if ((host->hostFlags & HWHO_INPROGRESS) &&
773 h_threadquota(host->lock.num_waiting)) {
779 if (host->hostFlags & HOSTDELETED) {
786 now = FT_ApproxTime(); /* always evaluate "now" */
787 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
789 * Every hostaclRefresh period (def 2 hrs) get the new
790 * membership list for the host. Note this could be the
791 * first time that the host is added to a group. Also
792 * here we also retry on previous legitimate hcps failures.
794 * If we get here refCount is elevated.
796 h_gethostcps_r(host, now);
806 /* Lookup a host given its UUID. */
808 h_LookupUuid_r(afsUUID * uuidp)
810 struct host *host = 0;
811 struct h_UuidHashChain *chain;
812 int index = h_UuidHashIndex(uuidp);
814 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
815 host = chain->hostPtr;
817 if (!(host->hostFlags & HOSTDELETED) && host->interface
818 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
826 /* h_TossStuff_r: Toss anything in the host structure (the host or
827 * clients marked for deletion. Called from h_Release_r ONLY.
828 * To be called, there must be no holds, and either host->deleted
829 * or host->clientDeleted must be set.
832 h_TossStuff_r(struct host *host)
834 struct client **cp, *client;
837 /* make sure host doesn't go away over h_NBLock_r */
840 code = h_NBLock_r(host);
842 /* don't use h_Release_r, since that may call h_TossStuff_r again */
845 /* if somebody still has this host locked */
849 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was locked.\n",
850 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
856 /* if somebody still has this host held */
857 /* we must check this _after_ h_NBLock_r, since h_NBLock_r can drop and
858 * reacquire H_LOCK */
859 if (host->refCount > 0) {
862 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was held.\n",
863 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
867 /* ASSUMPTION: rxi_FreeConnection() does not yield */
868 for (cp = &host->FirstClient; (client = *cp);) {
869 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
871 ObtainWriteLockNoBlock(&client->lock, code);
875 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
876 "client %p was locked.\n",
877 host, afs_inet_ntoa_r(host->host, hoststr),
878 ntohs(host->port), client));
882 if (client->refCount) {
885 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
886 "client %p refcount %d.\n",
887 host, afs_inet_ntoa_r(host->host, hoststr),
888 ntohs(host->port), client, client->refCount));
889 /* This is the same thing we do if the host is locked */
890 ReleaseWriteLock(&client->lock);
893 client->CPS.prlist_len = 0;
894 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
895 free(client->CPS.prlist_val);
896 client->CPS.prlist_val = NULL;
897 CurrentConnections--;
899 ReleaseWriteLock(&client->lock);
905 /* We've just cleaned out all the deleted clients; clear the flag */
906 host->hostFlags &= ~CLIENTDELETED;
908 if (host->hostFlags & HOSTDELETED) {
909 struct rx_connection *rxconn;
910 struct AddrPort hostAddrPort;
913 if (host->Console & 1)
915 if ((rxconn = host->callback_rxcon)) {
916 host->callback_rxcon = (struct rx_connection *)0;
917 rx_DestroyConnection(rxconn);
919 if (host->hcps.prlist_val)
920 free(host->hcps.prlist_val);
921 host->hcps.prlist_val = NULL;
922 host->hcps.prlist_len = 0;
923 DeleteAllCallBacks_r(host, 1);
924 host->hostFlags &= ~RESETDONE; /* just to be safe */
926 /* if alternate addresses do not exist */
927 if (!(host->interface)) {
928 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
930 h_DeleteHostFromUuidHashTable_r(host);
931 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
932 /* delete the hash entry for each valid alternate addresses */
933 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
934 hostAddrPort = host->interface->interface[i];
936 * if the interface addr/port is the primary, we already
937 * removed it. If the addr/port is not valid, its not
940 if (hostAddrPort.valid &&
941 (host->host != hostAddrPort.addr ||
942 host->port != hostAddrPort.port))
943 h_DeleteHostFromAddrHashTable_r(hostAddrPort.addr, hostAddrPort.port, host);
945 free(host->interface);
946 host->interface = NULL;
947 } /* if alternate address exists */
949 h_DeleteList_r(host); /* remove host from global host List */
956 /* h_Enumerate: Calls (*proc)(host, param) for at least each host in the
957 * system at the start of the enumeration (perhaps more). Hosts may be deleted
958 * (have delete flag set); ditto for clients. refCount is always incremented
959 * before (*proc) is called.
961 * The return value of the proc is a set of flags. The proc should set
962 * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
965 h_Enumerate(int (*proc) (struct host*, void *), void *param)
967 struct host *host, **list;
972 if (hostCount == 0) {
976 list = (struct host **)malloc(hostCount * sizeof(struct host *));
978 ViceLogThenPanic(0, ("Failed malloc in h_Enumerate (list)\n"));
980 for (totalCount = count = 0, host = hostList;
981 host && totalCount < hostCount;
982 host = host->next, totalCount++) {
984 if (!(host->hostFlags & HOSTDELETED)) {
990 if (totalCount != hostCount) {
991 ViceLog(0, ("h_Enumerate found %d of %d hosts\n", totalCount, hostCount));
992 } else if (host != NULL) {
993 ViceLog(0, ("h_Enumerate found more than %d hosts\n", hostCount));
994 ShutDownAndCore(PANIC);
997 for (i = 0; i < count; i++) {
999 flags = (*proc) (list[i], param);
1001 h_Release_r(list[i]);
1003 /* bail out of the enumeration early */
1004 if (H_ENUMERATE_ISSET_BAIL(flags)) {
1007 ViceLog(0, ("h_Enumerate got back invalid return value %d\n", flags));
1008 ShutDownAndCore(PANIC);
1012 /* we bailed out of enumerating hosts early; we still have holds on
1013 * some of the hosts in 'list', so release them */
1016 for ( ; i < count; i++) {
1017 h_Release_r(list[i]);
1025 /* h_Enumerate_r (revised):
1026 * Calls (*proc)(host, param) for each host in hostList, starting
1027 * at enumstart. Called only under H_LOCK. Hosts may be deleted (have
1028 * delete flag set); ditto for clients. refCount is always incremented
1029 * before (*proc) is called.
1031 * @note Assumes that hostList is only prepended to, that a host is never
1032 * inserted into the middle. Otherwise this would not be guaranteed to
1035 * The return value of the proc is a set of flags. The proc should set
1036 * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
1039 h_Enumerate_r(int (*proc) (struct host *, void *),
1040 struct host *enumstart, void *param)
1042 struct host *host, *next;
1046 if (hostCount == 0) {
1053 /* find the first non-deleted host, so we know where to actually start
1055 for (count = 0; host && count < hostCount; count++) {
1056 if (!(host->hostFlags & HOSTDELETED)) {
1063 /* we didn't find a non-deleted host... */
1065 if (host && count >= hostCount) {
1066 /* ...because we found a loop */
1067 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", hostCount));
1068 ShutDownAndCore(PANIC);
1071 /* ...because the hostList is full of deleted hosts */
1075 h_Hold_r(enumstart);
1077 /* remember hostCount, lest it change over the potential H_LOCK drop in
1079 origHostCount = hostCount;
1081 for (count = 0, host = enumstart; host && count < origHostCount; host = next, count++) {
1084 /* find the next non-deleted host */
1085 while (next && (next->hostFlags & HOSTDELETED)) {
1087 /* inc count for the skipped-over host */
1088 if (++count > origHostCount) {
1089 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1090 ShutDownAndCore(PANIC);
1096 if (!(host->hostFlags & HOSTDELETED)) {
1098 flags = (*proc) (host, param);
1099 if (H_ENUMERATE_ISSET_BAIL(flags)) {
1100 h_Release_r(host); /* this might free up the host */
1106 ViceLog(0, ("h_Enumerate_r got back invalid return value %d\n", flags));
1107 ShutDownAndCore(PANIC);
1110 h_Release_r(host); /* this might free up the host */
1112 if (host != NULL && count >= origHostCount) {
1113 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1114 ShutDownAndCore(PANIC);
1116 } /*h_Enumerate_r */
1119 /* inserts a new HashChain structure corresponding to this UUID */
1121 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1124 struct h_UuidHashChain *chain;
1125 char uuid1[128], uuid2[128];
1128 /* hash into proper bucket */
1129 index = h_UuidHashIndex(uuid);
1131 /* don't add the same entry multiple times */
1132 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1133 if (!chain->hostPtr)
1136 if (chain->hostPtr->interface &&
1137 afs_uuid_equal(&chain->hostPtr->interface->uuid, uuid)) {
1138 if (LogLevel >= 125) {
1139 afsUUID_to_string(&chain->hostPtr->interface->uuid, uuid1,
1141 afsUUID_to_string(uuid, uuid2, 127);
1142 ViceLog(125, ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s) exists as %s:%d (uuid %s)\n",
1144 afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1145 ntohs(chain->hostPtr->port), uuid2));
1151 /* insert into beginning of list for this bucket */
1152 chain = (struct h_UuidHashChain *)malloc(sizeof(struct h_UuidHashChain));
1154 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1156 chain->hostPtr = host;
1157 chain->next = hostUuidHashTable[index];
1158 hostUuidHashTable[index] = chain;
1161 afsUUID_to_string(uuid, uuid2, 127);
1163 ("h_AddHostToUuidHashTable_r: host %p (%s:%d) added as uuid %s\n",
1164 host, afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1165 ntohs(chain->hostPtr->port), uuid2));
1168 /* deletes a HashChain structure corresponding to this host */
1170 h_DeleteHostFromUuidHashTable_r(struct host *host)
1173 struct h_UuidHashChain **uhp, *uth;
1177 if (!host->interface)
1180 /* hash into proper bucket */
1181 index = h_UuidHashIndex(&host->interface->uuid);
1183 if (LogLevel >= 125)
1184 afsUUID_to_string(&host->interface->uuid, uuid1, 127);
1185 for (uhp = &hostUuidHashTable[index]; (uth = *uhp); uhp = &uth->next) {
1186 osi_Assert(uth->hostPtr);
1187 if (uth->hostPtr == host) {
1189 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d)\n",
1190 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1191 ntohs(host->port)));
1198 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d) not found\n",
1199 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1200 ntohs(host->port)));
1205 * This is called with host locked and held.
1207 * All addresses are in network byte order.
1210 invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1214 struct Interface *interface;
1215 char hoststr[16], hoststr2[16];
1218 osi_Assert(host->interface);
1220 ViceLog(125, ("invalidateInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1221 host, afs_inet_ntoa_r(host->host, hoststr),
1222 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1226 * Make sure this address is on the list of known addresses
1229 interface = host->interface;
1230 number = host->interface->numberOfInterfaces;
1231 for (i = 0; i < number; i++) {
1232 if (interface->interface[i].addr == addr &&
1233 interface->interface[i].port == port) {
1234 if (interface->interface[i].valid) {
1235 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1236 interface->interface[i].valid = 0;
1247 * This is called with host locked and held. This function differs
1248 * from removeInterfaceAddr_r in that it is called when the address
1249 * is being removed from the host regardless of whether or not there
1250 * is an interface list for the host. This function will delete the
1251 * host if there are no addresses left on it.
1253 * All addresses are in network byte order.
1256 removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1259 char hoststr[16], hoststr2[16];
1260 struct rx_connection *rxconn;
1262 if (!host->interface || host->interface->numberOfInterfaces == 1) {
1263 if (host->host == addr && host->port == port) {
1265 ("Removing only address for host %" AFS_PTR_FMT " (%s:%d), deleting host.\n",
1266 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1267 host->hostFlags |= HOSTDELETED;
1269 * Do not remove the primary addr/port from the hash table.
1270 * It will be ignored due to the HOSTDELETED flag and will
1271 * be removed when h_TossStuff_r() cleans up the HOSTDELETED
1272 * host. Removing it here will only result in a search for
1273 * the host/addr/port in the hash chain which will fail.
1277 ("Removing address that does not belong to host %" AFS_PTR_FMT " (%s:%d).\n",
1278 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1281 if (host->host == addr && host->port == port) {
1282 removeInterfaceAddr_r(host, addr, port);
1284 for (i=0; i < host->interface->numberOfInterfaces; i++) {
1285 if (host->interface->interface[i].valid) {
1287 ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
1288 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1289 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
1290 ntohs(host->interface->interface[i].port)));
1291 host->host = host->interface->interface[i].addr;
1292 host->port = host->interface->interface[i].port;
1293 h_AddHostToAddrHashTable_r(host->host, host->port, host);
1298 if (i == host->interface->numberOfInterfaces) {
1300 ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
1301 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1302 host->hostFlags |= HOSTDELETED;
1303 /* addr/port was removed from the hash table */
1307 rxconn = host->callback_rxcon;
1308 host->callback_rxcon = NULL;
1311 rx_DestroyConnection(rxconn);
1315 h_SetupCallbackConn_r(host);
1318 /* not the primary addr/port, just invalidate it */
1319 invalidateInterfaceAddr_r(host, addr, port);
1327 createHostAddrHashChain_r(int index, afs_uint32 addr, afs_uint16 port, struct host *host)
1329 struct h_AddrHashChain *chain;
1332 /* insert into beginning of list for this bucket */
1333 chain = (struct h_AddrHashChain *)malloc(sizeof(struct h_AddrHashChain));
1335 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToAddrHashTable_r\n"));
1337 chain->hostPtr = host;
1338 chain->next = hostAddrHashTable[index];
1341 hostAddrHashTable[index] = chain;
1342 ViceLog(125, ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " added as %s:%d\n",
1343 host, afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1347 * Resolve host address conflicts when hashing by address.
1349 * @param[in] addr an ip address of the interface
1350 * @param[in] port the port of the interface
1351 * @param[in] newHost the host being added with this address
1352 * @param[in] oldHost the host previously added with this address
1355 reconcileHosts_r(afs_uint32 addr, afs_uint16 port, struct host *newHost,
1356 struct host *oldHost)
1358 struct rx_connection *cb = NULL;
1360 struct interfaceAddr interf;
1362 afsUUID *newHostUuid = &nulluuid;
1363 afsUUID *oldHostUuid = &nulluuid;
1367 ("reconcileHosts_r: addr %s:%d newHost %" AFS_PTR_FMT " oldHost %"
1368 AFS_PTR_FMT, afs_inet_ntoa_r(addr, hoststr), ntohs(port),
1371 osi_Assert(oldHost != newHost);
1372 caps.Capabilities_val = NULL;
1375 sc = rxnull_NewClientSecurityObject();
1378 cb = rx_NewConnection(addr, port, 1, sc, 0);
1379 rx_SetConnDeadTime(cb, 50);
1380 rx_SetConnHardDeadTime(cb, AFS_HARDDEADTIME);
1385 code = RXAFSCB_TellMeAboutYourself(cb, &interf, &caps);
1386 if (code == RXGEN_OPCODE) {
1387 code = RXAFSCB_WhoAreYou(cb, &interf);
1391 if (code == RXGEN_OPCODE ||
1392 (code == 0 && afs_uuid_equal(&interf.uuid, &nulluuid))) {
1394 ("reconcileHosts_r: WhoAreYou not supported for connection (%s:%d), error %d\n",
1395 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1400 ("reconcileHosts_r: WhoAreYou failed for connection (%s:%d), error %d\n",
1401 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1405 /* Since lock was dropped, the hosts may have been deleted during the rpcs. */
1406 if ((newHost->hostFlags & HOSTDELETED)
1407 && (oldHost->hostFlags & HOSTDELETED)) {
1409 ("reconcileHosts_r: new and old hosts were deleted during probe.\n"));
1413 /* A check can be done if at least one of the hosts has a uuid. It
1414 * is an error if the hosts have the same (not null) uuid. */
1415 if ((!(newHost->hostFlags & HOSTDELETED)) && newHost->interface) {
1416 newHostUuid = &(newHost->interface->uuid);
1418 if ((!(oldHost->hostFlags & HOSTDELETED)) && oldHost->interface) {
1419 oldHostUuid = &(oldHost->interface->uuid);
1421 if (afs_uuid_equal(newHostUuid, &nulluuid) &&
1422 afs_uuid_equal(oldHostUuid, &nulluuid)) {
1424 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), no uuids\n",
1425 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1428 if (afs_uuid_equal(newHostUuid, oldHostUuid)) {
1430 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), same uuids\n",
1431 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1435 /* Determine which host should be hashed */
1436 if ((!(newHost->hostFlags & HOSTDELETED))
1437 && afs_uuid_equal(newHostUuid, &(interf.uuid))) {
1438 /* Install the new host into the hash before removing the stale
1439 * addresses. Walk the hash chain again since the hash table may have
1440 * been changed when the host lock was dropped to get the uuid. */
1441 struct h_AddrHashChain *chain;
1442 int index = h_HashIndex(addr);
1443 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1444 if (chain->addr == addr && chain->port == port) {
1445 chain->hostPtr = newHost;
1446 removeAddress_r(oldHost, addr, port);
1450 createHostAddrHashChain_r(index, addr, port, newHost);
1451 removeAddress_r(oldHost, addr, port);
1454 if ((!(oldHost->hostFlags & HOSTDELETED))
1455 && afs_uuid_equal(oldHostUuid, &(interf.uuid))) {
1456 removeAddress_r(newHost, addr, port);
1461 if (!(newHost->hostFlags & HOSTDELETED)) {
1462 removeAddress_r(newHost, addr, port);
1464 if (!(oldHost->hostFlags & HOSTDELETED)) {
1465 removeAddress_r(oldHost, addr, port);
1469 h_Release_r(newHost);
1470 h_Release_r(oldHost);
1471 rx_DestroyConnection(cb);
1475 /* inserts a new HashChain structure corresponding to this address */
1477 h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1480 struct h_AddrHashChain *chain;
1483 /* hash into proper bucket */
1484 index = h_HashIndex(addr);
1486 /* don't add the same address:port pair entry multiple times */
1487 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1488 if (chain->addr == addr && chain->port == port) {
1489 if (chain->hostPtr == host) {
1491 ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
1492 host, afs_inet_ntoa_r(chain->addr, hoststr),
1493 ntohs(chain->port)));
1496 if (!(chain->hostPtr->hostFlags & HOSTDELETED)) {
1497 /* attempt to resolve host address collision */
1498 reconcileHosts_r(addr, port, host, chain->hostPtr);
1503 createHostAddrHashChain_r(index, addr, port, host);
1507 * This is called with host locked and held.
1508 * It is called to either validate or add an additional interface
1509 * address/port on the specified host.
1511 * All addresses are in network byte order.
1514 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1518 struct Interface *interface;
1519 char hoststr[16], hoststr2[16];
1522 osi_Assert(host->interface);
1525 * Make sure this address is on the list of known addresses
1528 number = host->interface->numberOfInterfaces;
1529 for (i = 0; i < number; i++) {
1530 if (host->interface->interface[i].addr == addr &&
1531 host->interface->interface[i].port == port) {
1533 ("addInterfaceAddr : found host %" AFS_PTR_FMT " (%s:%d) adding %s:%d%s\n",
1534 host, afs_inet_ntoa_r(host->host, hoststr),
1535 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1536 ntohs(port), host->interface->interface[i].valid ? "" :
1539 if (host->interface->interface[i].valid == 0) {
1540 host->interface->interface[i].valid = 1;
1541 h_AddHostToAddrHashTable_r(addr, port, host);
1547 ViceLog(125, ("addInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) adding %s:%d\n",
1548 host, afs_inet_ntoa_r(host->host, hoststr),
1549 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1552 interface = (struct Interface *)
1553 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1555 ViceLogThenPanic(0, ("Failed malloc in addInterfaceAddr_r\n"));
1557 interface->numberOfInterfaces = number + 1;
1558 interface->uuid = host->interface->uuid;
1559 for (i = 0; i < number; i++)
1560 interface->interface[i] = host->interface->interface[i];
1562 /* Add the new valid interface */
1563 interface->interface[number].addr = addr;
1564 interface->interface[number].port = port;
1565 interface->interface[number].valid = 1;
1566 h_AddHostToAddrHashTable_r(addr, port, host);
1567 free(host->interface);
1568 host->interface = interface;
1575 * This is called with host locked and held.
1577 * All addresses are in network byte order.
1580 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1584 struct Interface *interface;
1585 char hoststr[16], hoststr2[16];
1588 osi_Assert(host->interface);
1590 ViceLog(125, ("removeInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1591 host, afs_inet_ntoa_r(host->host, hoststr),
1592 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1596 * Make sure this address is on the list of known addresses
1599 interface = host->interface;
1600 number = host->interface->numberOfInterfaces;
1601 for (i = 0; i < number; i++) {
1602 if (interface->interface[i].addr == addr &&
1603 interface->interface[i].port == port) {
1604 if (interface->interface[i].valid)
1605 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1607 for (; i < number; i++) {
1608 interface->interface[i] = interface->interface[i+1];
1610 interface->numberOfInterfaces = number;
1621 h_threadquota(int waiting)
1626 } else if (lwps > 32) {
1629 } else if (lwps > 16) {
1639 /* If found, host is returned with refCount incremented */
1641 h_GetHost_r(struct rx_connection *tcon)
1644 struct host *oldHost;
1646 struct interfaceAddr interf;
1647 int interfValid = 0;
1648 struct Identity *identP = NULL;
1651 char hoststr[16], hoststr2[16];
1653 struct rx_connection *cb_conn = NULL;
1654 struct rx_connection *cb_in = NULL;
1656 caps.Capabilities_val = NULL;
1658 haddr = rxr_HostOf(tcon);
1659 hport = rxr_PortOf(tcon);
1662 rx_DestroyConnection(cb_in);
1665 if (caps.Capabilities_val)
1666 free(caps.Capabilities_val);
1667 caps.Capabilities_val = NULL;
1668 caps.Capabilities_len = 0;
1671 if (h_Lookup_r(haddr, hport, &host))
1673 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1674 if (host && !identP && !(host->Console & 1)) {
1675 /* This is a new connection, and we already have a host
1676 * structure for this address. Verify that the identity
1677 * of the caller matches the identity in the host structure.
1679 if ((host->hostFlags & HWHO_INPROGRESS) &&
1680 h_threadquota(host->lock.num_waiting)) {
1686 if (!(host->hostFlags & ALTADDR) ||
1687 (host->hostFlags & HOSTDELETED)) {
1688 /* Another thread is doing initialization
1689 * or this host was deleted while we
1690 * waited for the lock. */
1693 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1694 host, afs_inet_ntoa_r(host->host, hoststr),
1695 ntohs(host->port)));
1699 host->hostFlags |= HWHO_INPROGRESS;
1700 host->hostFlags &= ~ALTADDR;
1702 /* We received a new connection from an IP address/port
1703 * that is associated with 'host' but the address/port of
1704 * the callback connection does not have to match it.
1705 * If there is a match, we can use the existing callback
1706 * connection to verify the UUID. If they do not match
1707 * we need to use a new callback connection to verify the
1708 * UUID of the incoming caller and perhaps use the old
1709 * callback connection to verify that the old address/port
1713 cb_conn = host->callback_rxcon;
1714 rx_GetConnection(cb_conn);
1716 if (haddr == host->host && hport == host->port) {
1717 /* The existing callback connection matches the
1718 * incoming connection so just use it.
1721 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1722 if (code == RXGEN_OPCODE)
1723 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1725 /* We do not have a match. Create a new connection
1726 * for the new addr/port and use multi_Rx to probe
1727 * both of them simultaneously.
1730 sc = rxnull_NewClientSecurityObject();
1731 cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1732 rx_SetConnDeadTime(cb_in, 50);
1733 rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1734 rx_SetConnSecondsUntilNatPing(cb_in, 20);
1737 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1738 if (code == RXGEN_OPCODE)
1739 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1741 rx_PutConnection(cb_conn);
1744 if ((code == RXGEN_OPCODE) ||
1745 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1746 identP = (struct Identity *)malloc(sizeof(struct Identity));
1748 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1751 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1752 if (cb_in == NULL) {
1753 /* The host on this connection was unable to respond to
1754 * the WhoAreYou. We will treat this as a new connection
1755 * from the existing host. The worst that can happen is
1756 * that we maintain some extra callback state information */
1757 if (host->interface) {
1759 ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1761 afs_inet_ntoa_r(host->host, hoststr),
1762 ntohs(host->port)));
1763 host->hostFlags |= HOSTDELETED;
1764 host->hostFlags &= ~HWHO_INPROGRESS;
1771 /* The incoming connection does not support WhoAreYou but
1772 * the original one might have. Use removeAddress_r() to
1773 * remove this addr/port from the host that was found.
1774 * If there are no more addresses left for the host it
1775 * will be deleted. Then we retry.
1777 removeAddress_r(host, haddr, hport);
1778 host->hostFlags &= ~HWHO_INPROGRESS;
1779 host->hostFlags |= ALTADDR;
1785 } else if (code == 0) {
1787 identP = (struct Identity *)malloc(sizeof(struct Identity));
1789 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1792 identP->uuid = interf.uuid;
1793 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1794 /* Check whether the UUID on this connection matches
1795 * the UUID in the host structure. If they don't match
1796 * then this is not the same host as before. */
1797 if (!host->interface
1798 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1801 ("Uuid doesn't match connection (%s:%d).\n",
1802 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1803 removeAddress_r(host, haddr, hport);
1806 ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1807 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1809 removeAddress_r(host, host->host, host->port);
1811 host->hostFlags &= ~HWHO_INPROGRESS;
1812 host->hostFlags |= ALTADDR;
1818 /* the UUID matched the client at the incoming addr/port
1819 * but this is not the address of the active callback
1820 * connection. Try that connection and see if the client
1821 * is still there and if the reported UUID is the same.
1824 afsUUID uuid = host->interface->uuid;
1825 cb_conn = host->callback_rxcon;
1826 rx_GetConnection(cb_conn);
1827 rx_SetConnDeadTime(cb_conn, 2);
1828 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1830 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1832 rx_SetConnDeadTime(cb_conn, 50);
1833 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1834 rx_PutConnection(cb_conn);
1837 /* The primary address is either not responding or
1838 * is not the client we are looking for. Need to
1839 * remove the primary address and add swap in the new
1840 * callback connection, and destroy the old one.
1842 struct rx_connection *rxconn;
1843 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1845 afs_inet_ntoa_r(host->host, hoststr),
1846 ntohs(host->port),code2));
1849 * make sure we add and then remove. otherwise, we
1850 * might end up with no valid interfaces after the
1851 * remove and the host will have been marked deleted.
1853 addInterfaceAddr_r(host, haddr, hport);
1854 removeInterfaceAddr_r(host, host->host, host->port);
1857 rxconn = host->callback_rxcon;
1858 host->callback_rxcon = cb_in;
1863 * If rx_DestroyConnection calls h_FreeConnection we
1864 * will deadlock on the host_glock_mutex. Work around
1865 * the problem by unhooking the client from the
1866 * connection before destroying the connection.
1868 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1869 rx_DestroyConnection(rxconn);
1875 /* A callback to the incoming connection address is failing.
1876 * Assume that the addr/port is no longer associated with the host
1877 * returned by h_Lookup_r.
1880 ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1881 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1882 removeAddress_r(host, haddr, hport);
1883 host->hostFlags &= ~HWHO_INPROGRESS;
1884 host->hostFlags |= ALTADDR;
1888 rx_DestroyConnection(cb_in);
1893 ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1894 host, afs_inet_ntoa_r(host->host, hoststr),
1895 ntohs(host->port), code));
1896 host->hostFlags |= VENUSDOWN;
1899 if (caps.Capabilities_val
1900 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1901 host->hostFlags |= HERRORTRANS;
1903 host->hostFlags &= ~(HERRORTRANS);
1904 host->hostFlags |= ALTADDR;
1905 host->hostFlags &= ~HWHO_INPROGRESS;
1908 if (!(host->hostFlags & ALTADDR)) {
1909 /* another thread is doing the initialisation */
1911 ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1912 host, afs_inet_ntoa_r(host->host, hoststr),
1913 ntohs(host->port)));
1917 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1918 host, afs_inet_ntoa_r(host->host, hoststr),
1919 ntohs(host->port)));
1923 /* We need to check whether the identity in the host structure
1924 * matches the identity on the connection. If they don't match
1925 * then treat this a new host. */
1926 if (!(host->Console & 1)
1927 && ((!identP->valid && host->interface)
1928 || (identP->valid && !host->interface)
1930 && !afs_uuid_equal(&identP->uuid,
1931 &host->interface->uuid)))) {
1932 char uuid1[128], uuid2[128];
1934 afsUUID_to_string(&identP->uuid, uuid1, 127);
1935 if (host->interface)
1936 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1938 ("CB: new identity for host %p (%s:%d), "
1939 "deleting(%x %p %s %s)\n",
1940 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1941 identP->valid, host->interface,
1942 identP->valid ? uuid1 : "no_uuid",
1943 host->interface ? uuid2 : "no_uuid"));
1945 /* The host in the cache is not the host for this connection */
1947 host->hostFlags |= HOSTDELETED;
1953 host = h_Alloc_r(tcon); /* returned held and locked */
1954 h_gethostcps_r(host, FT_ApproxTime());
1955 if (!(host->Console & 1)) {
1957 cb_conn = host->callback_rxcon;
1958 rx_GetConnection(cb_conn);
1959 host->hostFlags |= HWHO_INPROGRESS;
1962 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1963 if (code == RXGEN_OPCODE)
1964 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1965 rx_PutConnection(cb_conn);
1968 if ((code == RXGEN_OPCODE) ||
1969 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1972 (struct Identity *)malloc(sizeof(struct Identity));
1977 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1981 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1983 ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1984 host, afs_inet_ntoa_r(host->host, hoststr),
1985 ntohs(host->port)));
1987 } else if (code == 0) {
1990 (struct Identity *)malloc(sizeof(struct Identity));
1995 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1999 identP->uuid = interf.uuid;
2001 rx_SetSpecific(tcon, rxcon_ident_key, identP);
2003 ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
2004 host, afs_inet_ntoa_r(host->host, hoststr),
2005 ntohs(host->port)));
2007 if (code == 0 && !identP->valid) {
2008 cb_conn = host->callback_rxcon;
2009 rx_GetConnection(cb_conn);
2011 code = RXAFSCB_InitCallBackState(cb_conn);
2012 rx_PutConnection(cb_conn);
2015 } else if (code == 0) {
2016 oldHost = h_LookupUuid_r(&identP->uuid);
2021 if (oldHost->hostFlags & HOSTDELETED) {
2022 h_Unlock_r(oldHost);
2023 h_Release_r(oldHost);
2031 oldHost->hostFlags |= HWHO_INPROGRESS;
2033 if (oldHost->interface) {
2035 afsUUID uuid = oldHost->interface->uuid;
2036 cb_conn = oldHost->callback_rxcon;
2037 rx_GetConnection(cb_conn);
2038 rx_SetConnDeadTime(cb_conn, 2);
2039 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2041 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2043 rx_SetConnDeadTime(cb_conn, 50);
2044 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2045 rx_PutConnection(cb_conn);
2048 /* The primary address is either not responding or
2049 * is not the client we are looking for.
2050 * MultiProbeAlternateAddress_r() will remove the
2051 * alternate interfaces that do not have the same
2053 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
2055 afs_inet_ntoa_r(oldHost->host, hoststr),
2056 ntohs(oldHost->port),code2));
2057 MultiProbeAlternateAddress_r(oldHost);
2064 /* This is a new address for an existing host. Update
2065 * the list of interfaces for the existing host and
2066 * delete the host structure we just allocated. */
2068 /* prevent warnings while manipulating interface lists */
2069 host->hostFlags |= HOSTDELETED;
2071 if (oldHost->host != haddr || oldHost->port != hport) {
2072 struct rx_connection *rxconn;
2075 ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
2077 afs_inet_ntoa_r(oldHost->host, hoststr2),
2078 ntohs(oldHost->port),
2079 afs_inet_ntoa_r(haddr, hoststr),
2082 * add then remove. otherwise the host may get marked
2083 * deleted if we removed the only valid address.
2085 addInterfaceAddr_r(oldHost, haddr, hport);
2086 if (probefail || oldHost->host == haddr) {
2088 * The probe failed which means that the old
2089 * address is either unreachable or is not the
2090 * same host we were just contacted by. We will
2091 * also remove addresses if only the port has
2092 * changed because that indicates the client
2095 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
2098 struct Interface *interface = oldHost->interface;
2099 int number = oldHost->interface->numberOfInterfaces;
2100 for (i = 0; i < number; i++) {
2101 if (interface->interface[i].addr == haddr &&
2102 interface->interface[i].port != hport) {
2104 * We have just been contacted by a client
2105 * that has been seen from behind a NAT
2106 * and at least one other address.
2108 removeInterfaceAddr_r(oldHost, haddr,
2109 interface->interface[i].port);
2114 h_AddHostToAddrHashTable_r(haddr, hport, oldHost);
2115 oldHost->host = haddr;
2116 oldHost->port = hport;
2117 rxconn = oldHost->callback_rxcon;
2118 oldHost->callback_rxcon = host->callback_rxcon;
2119 host->callback_rxcon = rxconn;
2121 /* don't destroy rxconn here; let h_TossStuff_r
2122 * take care of that via h_Release_r below */
2124 host->hostFlags &= ~HWHO_INPROGRESS;
2126 /* release host because it was allocated by h_Alloc_r */
2129 /* the new host is held and locked */
2131 /* This really is a new host */
2132 h_AddHostToUuidHashTable_r(&identP->uuid, host);
2133 cb_conn = host->callback_rxcon;
2134 rx_GetConnection(cb_conn);
2137 RXAFSCB_InitCallBackState3(cb_conn,
2139 rx_PutConnection(cb_conn);
2144 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2145 host, afs_inet_ntoa_r(host->host, hoststr),
2146 ntohs(host->port)));
2147 osi_Assert(interfValid == 1);
2148 initInterfaceAddr_r(host, &interf);
2154 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2155 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2156 host->hostFlags |= VENUSDOWN;
2159 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2160 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2161 host->hostFlags |= RESETDONE;
2164 if (caps.Capabilities_val
2165 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2166 host->hostFlags |= HERRORTRANS;
2168 host->hostFlags &= ~(HERRORTRANS);
2169 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2170 host->hostFlags &= ~HWHO_INPROGRESS;
2175 if (caps.Capabilities_val)
2176 free(caps.Capabilities_val);
2177 caps.Capabilities_val = NULL;
2178 caps.Capabilities_len = 0;
2180 rx_DestroyConnection(cb_in);
2188 static char localcellname[PR_MAXNAMELEN + 1];
2189 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
2190 int num_lrealms = -1;
2194 h_InitHostPackage(void)
2196 memset(&nulluuid, 0, sizeof(afsUUID));
2197 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
2198 if (num_lrealms == -1) {
2200 for (i=0; i<AFS_NUM_LREALMS; i++) {
2201 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
2207 ("afs_krb_get_lrealm failed, using %s.\n",
2209 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
2215 /* initialize the rest of the local realms to nullstring for debugging */
2216 for (; i<AFS_NUM_LREALMS; i++)
2217 local_realms[i][0] = '\0';
2219 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2220 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2221 MUTEX_INIT(&host_glock_mutex, "host glock", MUTEX_DEFAULT, 0);
2225 MapName_r(char *aname, char *acell, afs_int32 * aval)
2230 afs_int32 anamelen, cnamelen;
2234 anamelen = strlen(aname);
2235 if (anamelen >= PR_MAXNAMELEN)
2236 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
2238 lnames.namelist_len = 1;
2239 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
2240 lids.idlist_len = 0;
2241 lids.idlist_val = NULL;
2243 cnamelen = strlen(acell);
2245 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2247 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2248 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2249 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2251 ("MapName: Name too long, using AnonymousID for %s@%s\n",
2253 *aval = AnonymousID;
2256 foreign = 1; /* attempt cross-cell authentication */
2257 tname = (char *)malloc(PR_MAXNAMELEN);
2259 ViceLogThenPanic(0, ("Failed malloc in MapName_r\n"));
2261 strcpy(tname, aname);
2262 tname[anamelen] = '@';
2263 strcpy(tname + anamelen + 1, acell);
2264 lnames.namelist_val = (prname *) tname;
2269 code = hpr_NameToId(&lnames, &lids);
2272 if (lids.idlist_val) {
2273 *aval = lids.idlist_val[0];
2274 if (*aval == AnonymousID) {
2276 ("MapName: NameToId on %s returns anonymousID\n",
2277 lnames.namelist_val[0]));
2279 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2282 ("MapName: NameToId on '%s' is unknown\n",
2283 lnames.namelist_val[0]));
2289 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
2297 /* NOTE: this returns the client with a Write lock and a refCount */
2299 h_ID2Client(afs_int32 vid)
2301 struct client *client;
2306 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
2307 if (host->hostFlags & HOSTDELETED)
2309 for (client = host->FirstClient; client; client = client->next) {
2310 if (!client->deleted && client->ViceId == vid) {
2313 ObtainWriteLock(&client->lock);
2318 if (count != hostCount) {
2319 ViceLog(0, ("h_ID2Client found %d of %d hosts\n", count, hostCount));
2320 } else if (host != NULL) {
2321 ViceLog(0, ("h_ID2Client found more than %d hosts\n", hostCount));
2322 ShutDownAndCore(PANIC);
2330 * Called by the server main loop. Returns a h_Held client, which must be
2331 * released later the main loop. Allocates a client if the matching one
2332 * isn't around. The client is returned with its reference count incremented
2333 * by one. The caller must call h_ReleaseClient_r when finished with
2336 * The refCount on client->host is returned incremented. h_ReleaseClient_r
2337 * does not decrement the refCount on client->host.
2340 h_FindClient_r(struct rx_connection *tcon)
2342 struct client *client;
2343 struct host *host = NULL;
2344 struct client *oldClient;
2345 afs_int32 viceid = 0;
2349 #if (64-MAXKTCNAMELEN)
2350 ticket name length != 64
2354 char uname[PR_MAXNAMELEN];
2355 char tcell[MAXKTCREALMLEN];
2359 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2360 if (client && client->sid == rxr_CidOf(tcon)
2361 && client->VenusEpoch == rxr_GetEpoch(tcon)
2362 && !(client->host->hostFlags & HOSTDELETED)
2363 && !client->deleted) {
2366 h_Hold_r(client->host);
2367 if (client->prfail != 2) {
2368 /* Could add shared lock on client here */
2369 /* note that we don't have to lock entry in this path to
2370 * ensure CPS is initialized, since we don't call rx_SetSpecific
2371 * until initialization is done, and we only get here if
2372 * rx_GetSpecific located the client structure.
2377 ObtainWriteLock(&client->lock); /* released at end */
2383 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2385 ("FindClient: authenticating connection: authClass=%d\n",
2387 if (authClass == 1) {
2388 /* A bcrypt tickets, no longer supported */
2389 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2390 viceid = AnonymousID;
2391 expTime = 0x7fffffff;
2392 } else if (authClass == 2) {
2395 /* kerberos ticket */
2396 code = rxkad_GetServerInfo(tcon, /*level */ 0, (afs_uint32 *)&expTime,
2397 tname, tinst, tcell, &kvno);
2399 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2400 viceid = AnonymousID;
2401 expTime = 0x7fffffff;
2403 int ilen = strlen(tinst);
2405 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2406 tname, tinst, tcell, expTime, kvno));
2407 strncpy(uname, tname, sizeof(uname));
2409 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2412 strcat(uname, tinst);
2414 /* translate the name to a vice id */
2415 code = MapName_r(uname, tcell, &viceid);
2419 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2422 viceid = AnonymousID;
2423 expTime = 0x7fffffff;
2427 viceid = AnonymousID; /* unknown security class */
2428 expTime = 0x7fffffff;
2431 if (!client) { /* loop */
2432 host = h_GetHost_r(tcon); /* Returns with incremented refCount */
2438 /* First try to find the client structure */
2439 for (client = host->FirstClient; client; client = client->next) {
2440 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2441 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2444 ObtainWriteLock(&client->lock);
2450 /* Still no client structure - get one */
2453 if (host->hostFlags & HOSTDELETED) {
2458 /* Retry to find the client structure */
2459 for (client = host->FirstClient; client; client = client->next) {
2460 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2461 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2463 goto retryfirstclient;
2468 ObtainWriteLock(&client->lock);
2469 client->refCount = 1;
2470 client->host = host;
2471 #if FS_STATS_DETAILED
2472 client->InSameNetwork = host->InSameNetwork;
2473 #endif /* FS_STATS_DETAILED */
2474 client->ViceId = viceid;
2475 client->expTime = expTime; /* rx only */
2476 client->authClass = authClass; /* rx only */
2477 client->sid = rxr_CidOf(tcon);
2478 client->VenusEpoch = rxr_GetEpoch(tcon);
2479 client->CPS.prlist_val = NULL;
2480 client->CPS.prlist_len = 0;
2484 client->prfail = fail;
2486 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2487 client->CPS.prlist_len = 0;
2488 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2489 free(client->CPS.prlist_val);
2490 client->CPS.prlist_val = NULL;
2491 client->ViceId = viceid;
2492 client->expTime = expTime;
2494 if (viceid == ANONYMOUSID) {
2495 client->CPS.prlist_len = AnonCPS.prlist_len;
2496 client->CPS.prlist_val = AnonCPS.prlist_val;
2499 code = hpr_GetCPS(viceid, &client->CPS);
2504 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2505 code, viceid, client->host,
2506 afs_inet_ntoa_r(client->host->host,hoststr),
2507 ntohs(client->host->port)));
2509 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2510 * all protection servers and reevaluates things if no
2511 * sync server or quorum is found we could still end up
2512 * with one of these errors. In such case we would like to
2513 * reevaluate the rpc call to find if there's cps for this
2514 * guy. We treat other errors (except network failures
2515 * ones - i.e. code < 0) as an indication that there is no
2516 * CPS for this host. Ideally we could like to deal this
2517 * problem the other way around (i.e. if code == NOCPS
2518 * ignore else retry next time) but the problem is that
2519 * there're other errors (i.e. EPERM) for which we don't
2520 * want to retry and we don't know the whole code list!
2522 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2526 /* the disabling of system:administrators is so iffy and has so many
2527 * possible failure modes that we will disable it again */
2528 /* Turn off System:Administrator for safety
2529 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2530 * osi_Assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2533 /* Now, tcon may already be set to a rock, since we blocked with no host
2534 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2535 * required). So, before setting the RPC's rock, we should disconnect
2536 * the RPC from the other client structure's rock.
2538 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2539 if (oldClient && oldClient != client && oldClient->sid == rxr_CidOf(tcon)
2540 && oldClient->VenusEpoch == rxr_GetEpoch(tcon)) {
2542 if (!oldClient->deleted) {
2543 /* if we didn't create it, it's not ours to put back */
2545 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2546 "conn %p (host %s:%d) had client %p(%x)\n",
2547 client, client->sid, tcon,
2548 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2549 ntohs(rxr_PortOf(tcon)),
2550 oldClient, oldClient->sid));
2551 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2552 free(client->CPS.prlist_val);
2553 client->CPS.prlist_val = NULL;
2554 client->CPS.prlist_len = 0;
2556 /* We should perhaps check for 0 here */
2558 ReleaseWriteLock(&client->lock);
2563 oldClient->refCount++;
2565 h_Hold_r(oldClient->host);
2566 h_Release_r(client->host);
2569 ObtainWriteLock(&oldClient->lock);
2572 host = oldClient->host;
2574 ViceLog(0, ("FindClient: deleted client %p(%x ref %d host %p href "
2575 "%d) already had conn %p (host %s:%d, cid %x), stolen "
2576 "by client %p(%x, ref %d host %p href %d)\n",
2577 oldClient, oldClient->sid, oldClient->refCount,
2578 oldClient->host, oldClient->host->refCount, tcon,
2579 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2580 ntohs(rxr_PortOf(tcon)), rxr_CidOf(tcon),
2581 client, client->sid, client->refCount,
2582 client->host, client->host->refCount));
2583 /* rx_SetSpecific will be done immediately below */
2586 /* Avoid chaining in more than once. */
2590 if (host->hostFlags & HOSTDELETED) {
2595 client->host = NULL;
2597 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2598 free(client->CPS.prlist_val);
2599 client->CPS.prlist_val = NULL;
2600 client->CPS.prlist_len = 0;
2603 ReleaseWriteLock(&client->lock);
2608 client->next = host->FirstClient;
2609 host->FirstClient = client;
2611 CurrentConnections++; /* increment number of connections */
2613 rx_SetSpecific(tcon, rxcon_client_key, client);
2614 ReleaseWriteLock(&client->lock);
2618 } /*h_FindClient_r */
2621 h_ReleaseClient_r(struct client *client)
2623 osi_Assert(client->refCount > 0);
2630 * Sigh: this one is used to get the client AGAIN within the individual
2631 * server routines. This does not bother h_Holding the host, since
2632 * this is assumed already have been done by the server main loop.
2633 * It does check tokens, since only the server routines can return the
2634 * VICETOKENDEAD error code
2637 GetClient(struct rx_connection *tcon, struct client **cp)
2639 struct client *client;
2644 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2645 if (client == NULL) {
2647 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2648 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2649 ntohs(rxr_PortOf(tcon))));
2653 if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2655 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2656 tcon, rxr_CidOf(tcon), client->sid));
2660 if (client && client->LastCall > client->expTime && client->expTime) {
2662 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2663 afs_inet_ntoa_r(client->host->host, hoststr),
2664 ntohs(client->host->port), client->expTime));
2666 return VICETOKENDEAD;
2668 if (client->deleted) {
2669 ViceLog(0, ("GetClient: got deleted client, connection will appear "
2670 "anonymous; tcon %p cid %x client %p ref %d host %p "
2671 "(%s:%d) href %d ViceId %d\n",
2672 tcon, rxr_CidOf(tcon), client, client->refCount,
2674 afs_inet_ntoa_r(client->host->host, hoststr),
2675 (int)ntohs(client->host->port), client->host->refCount,
2676 (int)client->ViceId));
2686 PutClient(struct client **cp)
2692 h_ReleaseClient_r(*cp);
2699 /* Client user name for short term use. Note that this is NOT inexpensive */
2701 h_UserName(struct client *client)
2703 static char User[PR_MAXNAMELEN + 1];
2707 lids.idlist_len = 1;
2708 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2709 if (!lids.idlist_val) {
2710 ViceLogThenPanic(0, ("Failed malloc in h_UserName\n"));
2712 lnames.namelist_len = 0;
2713 lnames.namelist_val = (prname *) 0;
2714 lids.idlist_val[0] = client->ViceId;
2715 if (hpr_IdToName(&lids, &lnames)) {
2716 /* We need to free id we alloced above! */
2717 free(lids.idlist_val);
2718 return "*UNKNOWN USER NAME*";
2720 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2721 free(lids.idlist_val);
2722 free(lnames.namelist_val);
2731 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2732 CEs, CEBlocks, HTs, HTBlocks));
2738 h_PrintClient(struct host *host, void *rock)
2740 StreamHandle_t *file = (StreamHandle_t *)rock;
2741 struct client *client;
2746 time_t LastCall, expTime;
2750 LastCall = host->LastCall;
2751 if (host->hostFlags & HOSTDELETED) {
2755 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %T %Y",
2756 localtime_r(&LastCall, &tm));
2757 snprintf(tmpStr, sizeof tmpStr, "Host %s:%d down = %d, LastCall %s\n",
2758 afs_inet_ntoa_r(host->host, hoststr),
2759 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2761 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2762 for (client = host->FirstClient; client; client = client->next) {
2763 if (!client->deleted) {
2764 expTime = client->expTime;
2765 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %T %Y",
2766 localtime_r(&expTime, &tm));
2767 snprintf(tmpStr, sizeof tmpStr,
2768 " user id=%d, name=%s, sl=%s till %s\n",
2769 client->ViceId, h_UserName(client),
2770 client->authClass ? "Authenticated"
2771 : "Not authenticated",
2772 client->authClass ? tbuffer : "No Limit");
2773 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2774 snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2775 client->CPS.prlist_len);
2776 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2777 if (client->CPS.prlist_val) {
2778 for (i = 0; i < client->CPS.prlist_len; i++) {
2779 snprintf(tmpStr, sizeof tmpStr, " %d",
2780 client->CPS.prlist_val[i]);
2781 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2784 sprintf(tmpStr, "]\n");
2785 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2791 } /*h_PrintClient */
2796 * Print a list of clients, with last security level and token value seen,
2800 h_PrintClients(void)
2807 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2811 ("Couldn't create client dump file %s\n",
2812 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2815 now = FT_ApproxTime();
2816 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %T %Y",
2817 localtime_r(&now, &tm));
2818 snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n\n",
2820 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2821 h_Enumerate(h_PrintClient, (char *)file);
2822 STREAM_REALLYCLOSE(file);
2823 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2830 h_DumpHost(struct host *host, void *rock)
2832 StreamHandle_t *file = (StreamHandle_t *)rock;
2839 snprintf(tmpStr, sizeof tmpStr,
2840 "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u "
2841 "down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u "
2843 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
2844 host->index, host->cblist, CheckLock(&host->lock),
2845 host->LastCall, host->ActiveCall, (host->hostFlags & VENUSDOWN),
2846 host->hostFlags & HOSTDELETED, host->Console,
2847 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2849 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2850 if (host->hcps.prlist_val)
2851 for (i = 0; i < host->hcps.prlist_len; i++) {
2852 snprintf(tmpStr, sizeof tmpStr, " %d", host->hcps.prlist_val[i]);
2853 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2855 sprintf(tmpStr, "] [");
2856 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2857 if (host->interface)
2858 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2860 sprintf(tmpStr, " %s:%d",
2861 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2862 ntohs(host->interface->interface[i].port));
2863 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2865 sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2866 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2878 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2885 ("Couldn't create host dump file %s\n",
2886 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2889 now = FT_ApproxTime();
2890 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %T %Y",
2891 localtime_r(&now, &tm));
2892 snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n\n", tbuffer);
2893 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2894 h_Enumerate(h_DumpHost, (char *)file);
2895 STREAM_REALLYCLOSE(file);
2896 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2900 #ifdef AFS_DEMAND_ATTACH_FS
2903 * host state serialization
2905 static int h_stateFillHeader(struct host_state_header * hdr);
2906 static int h_stateCheckHeader(struct host_state_header * hdr);
2907 static int h_stateAllocMap(struct fs_dump_state * state);
2908 static int h_stateSaveHost(struct host * host, void *rock);
2909 static int h_stateRestoreHost(struct fs_dump_state * state);
2910 static int h_stateRestoreIndex(struct host * h, void *rock);
2911 static int h_stateVerifyHost(struct host * h, void *rock);
2912 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
2913 afs_uint32 addr, afs_uint16 port, int valid);
2914 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2915 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2916 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2919 /* this procedure saves all host state to disk for fast startup */
2921 h_stateSave(struct fs_dump_state * state)
2923 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2926 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2928 /* invalidate host state header */
2929 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2931 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2932 sizeof(struct host_state_header))) {
2937 fs_stateIncEOF(state, sizeof(struct host_state_header));
2939 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2944 h_stateFillHeader(state->h_hdr);
2946 /* write the real header to disk */
2947 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2948 sizeof(struct host_state_header));
2955 * host state serialization
2957 * this procedure restores all host state from a disk for fast startup
2960 h_stateRestore(struct fs_dump_state * state)
2964 /* seek to the right position and read in the host state header */
2965 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2966 sizeof(struct host_state_header))) {
2971 /* check the validity of the header */
2972 if (h_stateCheckHeader(state->h_hdr)) {
2977 records = state->h_hdr->records;
2979 if (h_stateAllocMap(state)) {
2984 /* iterate over records restoring host state */
2985 for (i=0; i < records; i++) {
2986 if (h_stateRestoreHost(state) != 0) {
2997 h_stateRestoreIndices(struct fs_dump_state * state)
2999 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
3004 h_stateRestoreIndex(struct host * h, void *rock)
3006 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3007 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
3008 return H_ENUMERATE_BAIL(0);
3014 h_stateVerify(struct fs_dump_state * state)
3016 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
3021 h_stateVerifyHost(struct host * h, void* rock)
3023 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3027 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3028 return H_ENUMERATE_BAIL(0);
3032 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
3033 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
3034 h->interface->interface[i].port,
3035 h->interface->interface[i].valid)) {
3039 if (h_stateVerifyUuidHash(state, h)) {
3042 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
3046 if (cb_stateVerifyHCBList(state, h)) {
3054 * verify a host is either in, or absent from, the addr hash table.
3056 * @param[in] state fs dump state
3057 * @param[in] h host we're dealing with
3058 * @param[in] addr addr to look for (NBO)
3059 * @param[in] port port to look for (NBO)
3060 * @param[in] valid 1 if we're verifying that the specified addr and port
3061 * in the hash table point to the specified host. 0 if we're
3062 * verifying that the specified addr and port do NOT point
3063 * to the specified host
3065 * @return operation status
3066 * @retval 1 failed to verify, bail out
3067 * @retval 0 verified successfully, all is well
3070 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3071 afs_uint32 addr, afs_uint16 port, int valid)
3073 int ret = 0, found = 0;
3074 struct host *host = NULL;
3075 struct h_AddrHashChain *chain;
3076 int index = h_HashIndex(addr);
3080 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3081 host = chain->hostPtr;
3083 afs_inet_ntoa_r(addr, tmp);
3084 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3088 if ((chain->addr == addr) && (chain->port == port)) {
3091 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3092 "points to different host struct (%d, %d)\n",
3093 h->index, host->index));
3094 state->flags.warnings_generated = 1;
3098 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3099 "marked invalid, but points to the containing "
3100 "host\n", afs_inet_ntoa_r(addr, tmp),
3101 (unsigned)htons(port)));
3109 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3110 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3111 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3118 if (!found && valid) {
3119 afs_inet_ntoa_r(addr, tmp);
3120 if (state->mode == FS_STATE_LOAD_MODE) {
3121 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3122 tmp, (unsigned)htons(port)));
3126 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3127 tmp, (unsigned)htons(port)));
3128 state->flags.warnings_generated = 1;
3137 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3139 int ret = 0, found = 0;
3140 struct host *host = NULL;
3141 struct h_UuidHashChain *chain;
3142 afsUUID * uuidp = &h->interface->uuid;
3143 int index = h_UuidHashIndex(uuidp);
3147 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3148 host = chain->hostPtr;
3150 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3151 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3155 if (host->interface &&
3156 afs_uuid_equal(&host->interface->uuid, uuidp)) {
3158 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3159 h->index, host->index));
3160 state->flags.warnings_generated = 1;
3165 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3166 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3167 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3175 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3176 if (state->mode == FS_STATE_LOAD_MODE) {
3177 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3181 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3182 state->flags.warnings_generated = 1;
3190 /* create the host state header structure */
3192 h_stateFillHeader(struct host_state_header * hdr)
3194 hdr->stamp.magic = HOST_STATE_MAGIC;
3195 hdr->stamp.version = HOST_STATE_VERSION;
3199 /* check the contents of the host state header structure */
3201 h_stateCheckHeader(struct host_state_header * hdr)
3205 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3206 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3209 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3210 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3216 /* allocate the host id mapping table */
3218 h_stateAllocMap(struct fs_dump_state * state)
3220 state->h_map.len = state->h_hdr->index_max + 1;
3221 state->h_map.entries = (struct idx_map_entry_t *)
3222 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3223 return (state->h_map.entries != NULL) ? 0 : 1;
3226 /* function called by h_Enumerate to save a host to disk */
3228 h_stateSaveHost(struct host * host, void* rock)
3230 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3231 int if_len=0, hcps_len=0;
3232 struct hostDiskEntry hdsk;
3233 struct host_state_entry_header hdr;
3234 struct Interface * ifp = NULL;
3235 afs_int32 * hcps = NULL;
3236 struct iovec iov[4];
3239 memset(&hdr, 0, sizeof(hdr));
3241 if (state->h_hdr->index_max < host->index) {
3242 state->h_hdr->index_max = host->index;
3245 h_hostToDiskEntry_r(host, &hdsk);
3246 if (host->interface) {
3247 if_len = sizeof(struct Interface) +
3248 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3249 ifp = (struct Interface *) malloc(if_len);
3250 osi_Assert(ifp != NULL);
3251 memcpy(ifp, host->interface, if_len);
3252 hdr.interfaces = host->interface->numberOfInterfaces;
3253 iov[iovcnt].iov_base = (char *) ifp;
3254 iov[iovcnt].iov_len = if_len;
3257 if (host->hcps.prlist_val) {
3258 hdr.hcps = host->hcps.prlist_len;
3259 hcps_len = hdr.hcps * sizeof(afs_int32);
3260 hcps = (afs_int32 *) malloc(hcps_len);
3261 osi_Assert(hcps != NULL);
3262 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3263 iov[iovcnt].iov_base = (char *) hcps;
3264 iov[iovcnt].iov_len = hcps_len;
3268 if (hdsk.index > state->h_hdr->index_max)
3269 state->h_hdr->index_max = hdsk.index;
3271 hdr.len = sizeof(struct host_state_entry_header) +
3272 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3273 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3275 iov[0].iov_base = (char *) &hdr;
3276 iov[0].iov_len = sizeof(hdr);
3277 iov[1].iov_base = (char *) &hdsk;
3278 iov[1].iov_len = sizeof(struct hostDiskEntry);
3280 if (fs_stateWriteV(state, iov, iovcnt)) {
3281 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3285 fs_stateIncEOF(state, hdr.len);
3287 state->h_hdr->records++;
3294 return H_ENUMERATE_BAIL(0);
3299 /* restores a host from disk */
3301 h_stateRestoreHost(struct fs_dump_state * state)
3303 int ifp_len=0, hcps_len=0, bail=0;
3304 struct host_state_entry_header hdr;
3305 struct hostDiskEntry hdsk;
3306 struct host *host = NULL;
3307 struct Interface *ifp = NULL;
3308 afs_int32 * hcps = NULL;
3309 struct iovec iov[3];
3312 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3313 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3319 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3320 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3326 iov[0].iov_base = (char *) &hdsk;
3327 iov[0].iov_len = sizeof(struct hostDiskEntry);
3329 if (hdr.interfaces) {
3330 ifp_len = sizeof(struct Interface) +
3331 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3332 ifp = (struct Interface *) malloc(ifp_len);
3333 osi_Assert(ifp != NULL);
3334 iov[iovcnt].iov_base = (char *) ifp;
3335 iov[iovcnt].iov_len = ifp_len;
3339 hcps_len = hdr.hcps * sizeof(afs_int32);
3340 hcps = (afs_int32 *) malloc(hcps_len);
3341 osi_Assert(hcps != NULL);
3342 iov[iovcnt].iov_base = (char *) hcps;
3343 iov[iovcnt].iov_len = hcps_len;
3347 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3348 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3353 if (fs_stateReadV(state, iov, iovcnt)) {
3354 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3359 if (!hdr.hcps && hdsk.hcps_valid) {
3360 /* valid, zero-length host cps ; does this ever happen? */
3361 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3362 osi_Assert(hcps != NULL);
3366 osi_Assert(host != NULL);
3369 host->interface = ifp;
3372 host->hcps.prlist_val = hcps;
3373 host->hcps.prlist_len = hdr.hcps;
3376 h_diskEntryToHost_r(&hdsk, host);
3377 h_SetupCallbackConn_r(host);
3379 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3382 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3383 if (ifp->interface[i].valid &&
3384 !(ifp->interface[i].addr == host->host &&
3385 ifp->interface[i].port == host->port)) {
3386 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3387 ifp->interface[i].port,
3391 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3393 h_InsertList_r(host);
3395 /* setup host id map entry */
3396 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3397 state->h_map.entries[hdsk.index].new_idx = host->index;
3409 /* serialize a host structure to disk */
3411 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3413 out->host = in->host;
3414 out->port = in->port;
3415 out->hostFlags = in->hostFlags;
3416 out->Console = in->Console;
3417 out->hcpsfailed = in->hcpsfailed;
3418 out->LastCall = in->LastCall;
3419 out->ActiveCall = in->ActiveCall;
3420 out->cpsCall = in->cpsCall;
3421 out->cblist = in->cblist;
3422 #ifdef FS_STATS_DETAILED
3423 out->InSameNetwork = in->InSameNetwork;
3426 /* special fields we save, but are not memcpy'd back on restore */
3427 out->index = in->index;
3428 out->hcps_len = in->hcps.prlist_len;
3429 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3432 /* restore a host structure from disk */
3434 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3436 out->host = in->host;
3437 out->port = in->port;
3438 out->hostFlags = in->hostFlags;
3439 out->Console = in->Console;
3440 out->hcpsfailed = in->hcpsfailed;
3441 out->LastCall = in->LastCall;
3442 out->ActiveCall = in->ActiveCall;
3443 out->cpsCall = in->cpsCall;
3444 out->cblist = in->cblist;
3445 #ifdef FS_STATS_DETAILED
3446 out->InSameNetwork = in->InSameNetwork;
3450 /* index translation routines */
3452 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3456 /* hosts use a zero-based index, so old==0 is valid */
3458 if (old >= state->h_map.len) {
3459 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3461 } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
3462 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3465 *new = state->h_map.entries[old].new_idx;
3470 #endif /* AFS_DEMAND_ATTACH_FS */
3474 * This counts the number of workstations, the number of active workstations,
3475 * and the number of workstations declared "down" (i.e. not heard from
3476 * recently). An active workstation has received a call since the cutoff
3477 * time argument passed.
3480 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3483 int num = 0, active = 0, del = 0;
3487 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3488 if (!(host->hostFlags & HOSTDELETED)) {
3490 if (host->ActiveCall > cutofftime)
3492 if (host->hostFlags & VENUSDOWN)
3496 if (count != hostCount) {
3497 ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3498 } else if (host != NULL) {
3499 ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3500 ShutDownAndCore(PANIC);
3510 } /*h_GetWorkStats */
3513 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp,
3514 afs_int32 cutofftime)
3516 int num, active, del;
3517 h_GetWorkStats(&num, &active, &del, cutofftime);
3526 /*------------------------------------------------------------------------
3527 * PRIVATE h_ClassifyAddress
3530 * Given a target IP address and a candidate IP address (both
3531 * in host byte order), classify the candidate into one of three
3532 * buckets in relation to the target by bumping the counters passed
3536 * a_targetAddr : Target address.
3537 * a_candAddr : Candidate address.
3538 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3539 * addresses are either in the same network
3540 * or the same subnet.
3541 * a_diffSubnetP : ...when the candidate is in a different
3543 * a_diffNetworkP : ...when the candidate is in a different
3550 * The target and candidate addresses are both in host byte
3551 * order, NOT network byte order, when passed in.
3555 *------------------------------------------------------------------------*/
3558 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3559 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3560 afs_int32 * a_diffNetworkP)
3561 { /*h_ClassifyAddress */
3563 afs_uint32 targetNet;
3564 afs_uint32 targetSubnet;
3566 afs_uint32 candSubnet;
3569 * Put bad values into the subnet info to start with.
3571 targetSubnet = (afs_uint32) 0;
3572 candSubnet = (afs_uint32) 0;
3575 * Pull out the network and subnetwork numbers from the target
3576 * and candidate addresses. We can short-circuit this whole
3577 * affair if the target and candidate addresses are not of the
3580 if (IN_CLASSA(a_targetAddr)) {
3581 if (!(IN_CLASSA(a_candAddr))) {
3582 (*a_diffNetworkP)++;
3585 targetNet = a_targetAddr & IN_CLASSA_NET;
3586 candNet = a_candAddr & IN_CLASSA_NET;
3587 if (IN_SUBNETA(a_targetAddr))
3588 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3589 if (IN_SUBNETA(a_candAddr))
3590 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3591 } else if (IN_CLASSB(a_targetAddr)) {
3592 if (!(IN_CLASSB(a_candAddr))) {
3593 (*a_diffNetworkP)++;
3596 targetNet = a_targetAddr & IN_CLASSB_NET;
3597 candNet = a_candAddr & IN_CLASSB_NET;
3598 if (IN_SUBNETB(a_targetAddr))
3599 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3600 if (IN_SUBNETB(a_candAddr))
3601 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3602 } /*Class B target */
3603 else if (IN_CLASSC(a_targetAddr)) {
3604 if (!(IN_CLASSC(a_candAddr))) {
3605 (*a_diffNetworkP)++;
3608 targetNet = a_targetAddr & IN_CLASSC_NET;
3609 candNet = a_candAddr & IN_CLASSC_NET;
3612 * Note that class C addresses can't have subnets,
3613 * so we leave the defaults untouched.
3615 } /*Class C target */
3617 targetNet = a_targetAddr;
3618 candNet = a_candAddr;
3619 } /*Class D address */
3622 * Now, simply compare the extracted net and subnet values for
3623 * the two addresses (which at this point are known to be of the
3626 if (targetNet == candNet) {
3627 if (targetSubnet == candSubnet)
3628 (*a_sameNetOrSubnetP)++;
3632 (*a_diffNetworkP)++;
3634 } /*h_ClassifyAddress */
3637 /*------------------------------------------------------------------------
3638 * EXPORTED h_GetHostNetStats
3641 * Iterate through the host table, and classify each (non-deleted)
3642 * host entry into ``proximity'' categories (same net or subnet,
3643 * different subnet, different network).
3646 * a_numHostsP : Set to total number of (non-deleted) hosts.
3647 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3648 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3649 * a_diffNetworkP : Set to # hosts on diff network as server.
3655 * We only count non-deleted hosts. The storage pointed to by our
3656 * parameters is zeroed upon entry.
3660 *------------------------------------------------------------------------*/
3663 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3664 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3665 { /*h_GetHostNetStats */
3667 struct host *hostP; /*Ptr to current host entry */
3668 afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3672 * Clear out the storage pointed to by our parameters.
3674 *a_numHostsP = (afs_int32) 0;
3675 *a_sameNetOrSubnetP = (afs_int32) 0;
3676 *a_diffSubnetP = (afs_int32) 0;
3677 *a_diffNetworkP = (afs_int32) 0;
3680 for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3681 if (!(hostP->hostFlags & HOSTDELETED)) {
3683 * Bump the number of undeleted host entries found.
3684 * In classifying the current entry's address, make
3685 * sure to first convert to host byte order.
3688 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3689 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3690 a_sameNetOrSubnetP, a_diffSubnetP,
3692 } /*Only look at non-deleted hosts */
3693 } /*For each host record hashed to this index */
3694 if (count != hostCount) {
3695 ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3696 } else if (hostP != NULL) {
3697 ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3698 ShutDownAndCore(PANIC);
3701 } /*h_GetHostNetStats */
3703 static afs_uint32 checktime;
3704 static afs_uint32 clientdeletetime;
3705 static struct AFSFid zerofid;
3709 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3710 * Since it can serialize them, and pile up, it should be a separate LWP
3711 * from other events.
3715 CheckHost(struct host *host, int flags, void *rock)
3717 struct client *client;
3718 struct rx_connection *cb_conn = NULL;
3721 #ifdef AFS_DEMAND_ATTACH_FS
3722 /* kill the checkhost lwp ASAP during shutdown */
3724 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3726 return H_ENUMERATE_BAIL(flags);
3731 /* Host is held by h_Enumerate */
3733 for (client = host->FirstClient; client; client = client->next) {
3734 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3735 client->deleted = 1;
3736 host->hostFlags |= CLIENTDELETED;
3739 if (host->LastCall < checktime) {
3741 if (!(host->hostFlags & HOSTDELETED)) {
3742 host->hostFlags |= HWHO_INPROGRESS;
3743 cb_conn = host->callback_rxcon;
3744 rx_GetConnection(cb_conn);
3745 if (host->LastCall < clientdeletetime) {
3746 host->hostFlags |= HOSTDELETED;
3747 if (!(host->hostFlags & VENUSDOWN)) {
3748 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3749 if (host->interface) {
3752 RXAFSCB_InitCallBackState3(cb_conn,
3758 RXAFSCB_InitCallBackState(cb_conn);
3761 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3764 (void)afs_inet_ntoa_r(host->host, hoststr);
3766 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3767 hoststr, ntohs(host->port)));
3768 host->hostFlags |= VENUSDOWN;
3770 /* Note: it's safe to delete hosts even if they have call
3771 * back state, because break delayed callbacks (called when a
3772 * message is received from the workstation) will always send a
3773 * break all call backs to the workstation if there is no
3778 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3780 (void)afs_inet_ntoa_r(host->host, hoststr);
3781 if (host->interface) {
3782 afsUUID uuid = host->interface->uuid;
3784 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3787 if (MultiProbeAlternateAddress_r(host)) {
3788 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3789 hoststr, ntohs(host->port), code));
3790 host->hostFlags |= VENUSDOWN;
3795 code = RXAFSCB_Probe(cb_conn);
3799 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3800 hoststr, ntohs(host->port), code));
3801 host->hostFlags |= VENUSDOWN;
3807 rx_PutConnection(cb_conn);
3810 host->hostFlags &= ~HWHO_INPROGRESS;
3821 CheckHost_r(struct host *host, void *dummy)
3823 struct client *client;
3824 struct rx_connection *cb_conn = NULL;
3827 #ifdef AFS_DEMAND_ATTACH_FS
3828 /* kill the checkhost lwp ASAP during shutdown */
3830 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3832 return H_ENUMERATE_BAIL(0);
3837 /* Host is held by h_Enumerate_r */
3838 for (client = host->FirstClient; client; client = client->next) {
3839 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3840 client->deleted = 1;
3841 host->hostFlags |= CLIENTDELETED;
3844 if (host->LastCall < checktime) {
3846 if (!(host->hostFlags & HOSTDELETED)) {
3847 host->hostFlags |= HWHO_INPROGRESS;
3848 cb_conn = host->callback_rxcon;
3849 rx_GetConnection(cb_conn);
3850 if (host->LastCall < clientdeletetime) {
3851 host->hostFlags |= HOSTDELETED;
3852 if (!(host->hostFlags & VENUSDOWN)) {
3853 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3854 if (host->interface) {
3857 RXAFSCB_InitCallBackState3(cb_conn,
3863 RXAFSCB_InitCallBackState(cb_conn);
3866 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3869 (void)afs_inet_ntoa_r(host->host, hoststr);
3871 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3872 hoststr, ntohs(host->port)));
3873 host->hostFlags |= VENUSDOWN;
3875 /* Note: it's safe to delete hosts even if they have call
3876 * back state, because break delayed callbacks (called when a
3877 * message is received from the workstation) will always send a
3878 * break all call backs to the workstation if there is no
3883 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3885 (void)afs_inet_ntoa_r(host->host, hoststr);
3886 if (host->interface) {
3887 afsUUID uuid = host->interface->uuid;
3889 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3892 if (MultiProbeAlternateAddress_r(host)) {
3893 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3894 hoststr, ntohs(host->port), code));
3895 host->hostFlags |= VENUSDOWN;
3900 code = RXAFSCB_Probe(cb_conn);
3904 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3905 hoststr, ntohs(host->port), code));
3906 host->hostFlags |= VENUSDOWN;
3912 rx_PutConnection(cb_conn);
3915 host->hostFlags &= ~HWHO_INPROGRESS;
3925 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3926 * don't respond to a probe. Note that VenusDown can only be cleared if
3927 * a message is received from the host (see ServerLWP in file.c).
3928 * Delete hosts that have not had any calls in 1 hour, clients that
3929 * have not had any calls in 15 minutes.
3931 * This routine is called roughly every 5 minutes.
3936 afs_uint32 now = FT_ApproxTime();
3938 memset(&zerofid, 0, sizeof(zerofid));
3940 * Send a probe to the workstation if it hasn't been heard from in
3943 checktime = now - 15 * 60;
3944 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3947 h_Enumerate_r(CheckHost_r, hostList, NULL);
3952 * This is called with host locked and held. At this point, the
3953 * hostAddrHashTable has an entry for the primary addr/port inserted
3954 * by h_Alloc_r(). No other interfaces should be considered valid.
3956 * The addresses in the interfaceAddr list are in host byte order.
3959 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3966 struct Interface *interface;
3969 afs_uint16 port7001 = htons(7001);
3974 number = interf->numberOfInterfaces;
3975 myAddr = host->host; /* current interface address */
3976 myPort = host->port; /* current port */
3979 ("initInterfaceAddr : host %s:%d numAddr %d\n",
3980 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3982 /* validation checks */
3983 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3985 ("Invalid number of alternate addresses is %d\n", number));
3990 * The client's notion of its own IP addresses is not reliable.
3992 * 1. The client list might contain private address ranges which
3993 * are likely to be re-used by many clients allocated addresses
3996 * 2. The client list will not include any public addresses that
3997 * are hidden by a NAT.
3999 * 3. Private address ranges that are exposed to the server will
4000 * be obtained from the rx connections that use them.
4002 * 4. Lists provided by the client are not necessarily truthful.
4003 * Many existing clients (UNIX) do not refresh the IP address
4004 * list as the actual assigned addresses change. The end result
4005 * is that they report the initial address list for the lifetime
4006 * of the process. In other words, a client can report addresses
4007 * that they are in fact not using. Adding these addresses to
4008 * the host interface list without verification is not only
4009 * pointless, it is downright dangerous.
4011 * We therefore do not add alternate addresses to the addr hash table.
4012 * We only use them for multi-rx callback breaks.
4016 * Convert IP addresses to network byte order, and remove
4017 * duplicate IP addresses from the interface list, and
4018 * determine whether or not the incoming addr/port is
4019 * listed. Note that if the address matches it is not
4020 * truly a match because the port number for the entries
4021 * in the interface list are port 7001 and the port number
4022 * for this connection might not be 7001.
4024 for (i = 0, count = 0, found = 0; i < number; i++) {
4025 interf->addr_in[i] = htonl(interf->addr_in[i]);
4026 for (j = 0; j < count; j++) {
4027 if (interf->addr_in[j] == interf->addr_in[i])
4031 interf->addr_in[count] = interf->addr_in[i];
4032 if (interf->addr_in[count] == myAddr &&
4040 * Allocate and initialize an interface structure for this host.
4043 interface = (struct Interface *)
4044 malloc(sizeof(struct Interface) +
4045 (sizeof(struct AddrPort) * (count - 1)));
4047 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
4049 interface->numberOfInterfaces = count;
4051 interface = (struct Interface *)
4052 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
4054 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4056 interface->numberOfInterfaces = count + 1;
4057 interface->interface[count].addr = myAddr;
4058 interface->interface[count].port = myPort;
4059 interface->interface[count].valid = 1;
4062 for (i = 0; i < count; i++) {
4064 interface->interface[i].addr = interf->addr_in[i];
4065 /* We store the port as 7001 because the addresses reported by
4066 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4067 * are coming from fully connected hosts (no NAT/PATs)
4069 interface->interface[i].port = port7001;
4070 interface->interface[i].valid =
4071 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4074 interface->uuid = interf->uuid;
4076 osi_Assert(!host->interface);
4077 host->interface = interface;
4079 if (LogLevel >= 125) {
4080 afsUUID_to_string(&interface->uuid, uuidstr, 127);
4082 ViceLog(125, ("--- uuid %s\n", uuidstr));
4083 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
4084 ViceLog(125, ("--- alt address %s:%d\n",
4085 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4086 ntohs(host->interface->interface[i].port)));
4093 /* deleted a HashChain structure for this address and host */
4094 /* returns 1 on success */
4096 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4100 struct h_AddrHashChain **hp, *th;
4102 if (addr == 0 && port == 0)
4105 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4107 osi_Assert(th->hostPtr);
4108 if (th->hostPtr == host && th->addr == addr && th->port == port) {
4109 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4110 host, afs_inet_ntoa_r(host->host, hoststr),
4111 ntohs(host->port)));
4118 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4119 host, afs_inet_ntoa_r(host->host, hoststr),
4120 ntohs(host->port)));
4126 ** prints out all alternate interface address for the host. The 'level'
4127 ** parameter indicates what level of debugging sets this output
4130 printInterfaceAddr(struct host *host, int level)
4135 if (host->interface) {
4136 /* check alternate addresses */
4137 number = host->interface->numberOfInterfaces;
4139 ViceLog(level, ("no-addresses "));
4141 for (i = 0; i < number; i++)
4142 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4143 ntohs(host->interface->interface[i].port)));
4146 ViceLog(level, ("\n"));