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>
19 #ifdef HAVE_SYS_FILE_H
24 #include <afs/afs_assert.h>
27 #include <afs/afsint.h>
28 #define FSINT_COMMON_XG
29 #include <afs/afscbint.h>
30 #include <afs/rxgen_consts.h>
32 #include <afs/errors.h>
33 #include <afs/ihandle.h>
34 #include <afs/vnode.h>
35 #include <afs/volume.h>
36 #ifdef AFS_ATHENA_STDENV
40 #include <afs/ptclient.h>
41 #include <afs/ptuser.h>
42 #include <afs/prs_fs.h>
44 #include <afs/afsutil.h>
45 #include <afs/com_err.h>
47 #include <afs/cellconfig.h>
48 #include "viced_prototypes.h"
52 #ifdef AFS_DEMAND_ATTACH_FS
53 #include "../util/afsutil_prototypes.h"
54 #include "../tviced/serialize_state.h"
55 #endif /* AFS_DEMAND_ATTACH_FS */
57 #ifdef AFS_PTHREAD_ENV
58 pthread_mutex_t host_glock_mutex;
59 #endif /* AFS_PTHREAD_ENV */
62 extern int CurrentConnections;
64 extern int AnonymousID;
65 extern prlist AnonCPS;
67 extern struct afsconf_dir *confDir; /* config dir object */
68 extern int lwps; /* the max number of server threads */
69 extern afsUUID FS_HostUUID;
72 int CEs = 0; /* active clients */
73 int CEBlocks = 0; /* number of blocks of CEs */
74 struct client *CEFree = 0; /* first free client */
75 struct host *hostList = 0; /* linked list of all hosts */
76 int hostCount = 0; /* number of hosts in hostList */
80 static struct rx_securityClass *sc = NULL;
82 static void h_SetupCallbackConn_r(struct host * host);
83 static int h_threadquota(int);
85 #define CESPERBLOCK 73
86 struct CEBlock { /* block of CESPERBLOCK file entries */
87 struct client entry[CESPERBLOCK];
90 void h_TossStuff_r(struct host *host);
93 * Make sure the subnet macros have been defined.
96 #define IN_SUBNETA(i) ((((afs_int32)(i))&0x80800000)==0x00800000)
99 #ifndef IN_CLASSA_SUBNET
100 #define IN_CLASSA_SUBNET 0xffff0000
104 #define IN_SUBNETB(i) ((((afs_int32)(i))&0xc0008000)==0x80008000)
107 #ifndef IN_CLASSB_SUBNET
108 #define IN_CLASSB_SUBNET 0xffffff00
112 /* get a new block of CEs and chain it on CEFree */
116 struct CEBlock *block;
119 block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
121 ViceLog(0, ("Failed malloc in GetCEBlock\n"));
122 ShutDownAndCore(PANIC);
125 for (i = 0; i < (CESPERBLOCK - 1); i++) {
126 Lock_Init(&block->entry[i].lock);
127 block->entry[i].next = &(block->entry[i + 1]);
129 block->entry[CESPERBLOCK - 1].next = 0;
130 Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
131 CEFree = (struct client *)block;
137 /* get the next available CE */
138 static struct client *
141 struct client *entry;
146 ViceLog(0, ("CEFree NULL in GetCE\n"));
147 ShutDownAndCore(PANIC);
151 CEFree = entry->next;
153 memset(entry, 0, CLIENT_TO_ZERO(entry));
159 /* return an entry to the free list */
161 FreeCE(struct client *entry)
163 entry->VenusEpoch = 0;
165 entry->next = CEFree;
172 * The HTs and HTBlocks variables were formerly static, but they are
173 * now referenced elsewhere in the FileServer.
175 int HTs = 0; /* active file entries */
176 int HTBlocks = 0; /* number of blocks of HTs */
177 static struct host *HTFree = 0; /* first free file entry */
180 * Hash tables of host pointers. We need two tables, one
181 * to map IP addresses onto host pointers, and another
182 * to map host UUIDs onto host pointers.
184 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
185 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
186 #define h_HashIndex(hostip) (ntohl(hostip) & (h_HASHENTRIES-1))
187 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
189 struct HTBlock { /* block of HTSPERBLOCK file entries */
190 struct host entry[h_HTSPERBLOCK];
194 /* get a new block of HTs and chain it on HTFree */
198 struct HTBlock *block;
200 static int index = 0;
202 if (HTBlocks == h_MAXHOSTTABLES) {
203 ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
207 block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
209 ViceLog(0, ("Failed malloc in GetHTBlock\n"));
210 ShutDownAndCore(PANIC);
212 #ifdef AFS_PTHREAD_ENV
213 for (i = 0; i < (h_HTSPERBLOCK); i++)
214 CV_INIT(&block->entry[i].cond, "block entry", CV_DEFAULT, 0);
215 #endif /* AFS_PTHREAD_ENV */
216 for (i = 0; i < (h_HTSPERBLOCK); i++)
217 Lock_Init(&block->entry[i].lock);
218 for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
219 block->entry[i].next = &(block->entry[i + 1]);
220 for (i = 0; i < (h_HTSPERBLOCK); i++)
221 block->entry[i].index = index++;
222 block->entry[h_HTSPERBLOCK - 1].next = 0;
223 HTFree = (struct host *)block;
224 hosttableptrs[HTBlocks++] = block->entry;
229 /* get the next available HT */
240 HTFree = entry->next;
242 memset(entry, 0, HOST_TO_ZERO(entry));
248 /* return an entry to the free list */
250 FreeHT(struct host *entry)
252 entry->next = HTFree;
259 hpr_Initialize(struct ubik_client **uclient)
262 struct rx_connection *serverconns[MAXSERVERS];
263 struct rx_securityClass *sc;
264 struct afsconf_dir *tdir;
266 struct afsconf_cell info;
270 tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
272 ViceLog(0, ("hpr_Initialize: Could not open configuration directory: %s", AFSDIR_SERVER_ETC_DIRPATH));
276 code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
278 ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
283 code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
285 ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s",
286 cellstr, confDir->name, AFSDIR_CELLSERVDB_FILE));
293 ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
298 /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
299 * to force use of the KeyFile. secLevel == 0 implies -noauth was
301 code = afsconf_ClientAuthSecure(tdir, &sc, &scIndex);
303 ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s "
304 "(so trying noauth)", code, afs_error_message(code)));
305 scIndex = RX_SECIDX_NULL;
306 sc = rxnull_NewClientSecurityObject();
309 if (scIndex == RX_SECIDX_NULL)
310 ViceLog(0, ("hpr_Initialize: Could not get afs tokens, "
311 "running unauthenticated. [%d]", code));
313 memset(serverconns, 0, sizeof(serverconns)); /* terminate list!!! */
314 for (i = 0; i < info.numServers; i++) {
316 rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
317 info.hostAddr[i].sin_port, PRSRV,
321 code = ubik_ClientInit(serverconns, uclient);
323 ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
326 code = rxs_Release(sc);
331 hpr_End(struct ubik_client *uclient)
336 code = ubik_ClientDestroy(uclient);
342 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
344 #ifdef AFS_PTHREAD_ENV
347 struct ubik_client *uclient =
348 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
351 code = hpr_Initialize(&uclient);
353 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
359 code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
360 if (code != PRSUCCESS)
363 /* do something about this, probably make a new call */
364 /* don't forget there's a hard limit in the interface */
366 "membership list for host id %d exceeds display limit\n",
371 return pr_GetHostCPS(host, CPS);
376 hpr_NameToId(namelist *names, idlist *ids)
378 #ifdef AFS_PTHREAD_ENV
381 struct ubik_client *uclient =
382 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
385 code = hpr_Initialize(&uclient);
387 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
392 for (i = 0; i < names->namelist_len; i++)
393 stolower(names->namelist_val[i]);
394 code = ubik_PR_NameToID(uclient, 0, names, ids);
397 return pr_NameToId(names, ids);
402 hpr_IdToName(idlist *ids, namelist *names)
404 #ifdef AFS_PTHREAD_ENV
406 struct ubik_client *uclient =
407 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
410 code = hpr_Initialize(&uclient);
412 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
417 code = ubik_PR_IDToName(uclient, 0, ids, names);
420 return pr_IdToName(ids, names);
425 hpr_GetCPS(afs_int32 id, prlist *CPS)
427 #ifdef AFS_PTHREAD_ENV
430 struct ubik_client *uclient =
431 (struct ubik_client *)pthread_getspecific(viced_uclient_key);
434 code = hpr_Initialize(&uclient);
436 osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
442 code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
443 if (code != PRSUCCESS)
446 /* do something about this, probably make a new call */
447 /* don't forget there's a hard limit in the interface */
448 fprintf(stderr, "membership list for id %d exceeds display limit\n",
453 return pr_GetCPS(id, CPS);
457 static short consolePort = 0;
460 h_Lock_r(struct host *host)
470 * returns 1 if already locked
471 * else returns locks and returns 0
475 h_NBLock_r(struct host *host)
477 struct Lock *hostLock = &host->lock;
482 if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
483 hostLock->excl_locked = WRITE_LOCK;
487 LOCK_UNLOCK(hostLock);
496 #if FS_STATS_DETAILED
497 /*------------------------------------------------------------------------
498 * PRIVATE h_AddrInSameNetwork
501 * Given a target IP address and a candidate IP address (both
502 * in host byte order), return a non-zero value (1) if the
503 * candidate address is in a different network from the target
507 * a_targetAddr : Target address.
508 * a_candAddr : Candidate address.
511 * 1 if the candidate address is in the same net as the target,
515 * The target and candidate addresses are both in host byte
516 * order, NOT network byte order, when passed in. We return
517 * our value as a character, since that's the type of field in
518 * the host structure, where this info will be stored.
522 *------------------------------------------------------------------------*/
525 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
526 { /*h_AddrInSameNetwork */
528 afs_uint32 targetNet;
532 * Pull out the network and subnetwork numbers from the target
533 * and candidate addresses. We can short-circuit this whole
534 * affair if the target and candidate addresses are not of the
537 if (IN_CLASSA(a_targetAddr)) {
538 if (!(IN_CLASSA(a_candAddr))) {
541 targetNet = a_targetAddr & IN_CLASSA_NET;
542 candNet = a_candAddr & IN_CLASSA_NET;
543 } else if (IN_CLASSB(a_targetAddr)) {
544 if (!(IN_CLASSB(a_candAddr))) {
547 targetNet = a_targetAddr & IN_CLASSB_NET;
548 candNet = a_candAddr & IN_CLASSB_NET;
549 } /*Class B target */
550 else if (IN_CLASSC(a_targetAddr)) {
551 if (!(IN_CLASSC(a_candAddr))) {
554 targetNet = a_targetAddr & IN_CLASSC_NET;
555 candNet = a_candAddr & IN_CLASSC_NET;
556 } /*Class C target */
558 targetNet = a_targetAddr;
559 candNet = a_candAddr;
560 } /*Class D address */
563 * Now, simply compare the extracted net values for the two addresses
564 * (which at this point are known to be of the same class)
566 if (targetNet == candNet)
571 } /*h_AddrInSameNetwork */
572 #endif /* FS_STATS_DETAILED */
575 /* Assumptions: called with held host */
577 h_gethostcps_r(struct host *host, afs_int32 now)
582 /* wait if somebody else is already doing the getCPS call */
583 while (host->hostFlags & HCPS_INPROGRESS) {
584 slept = 1; /* I did sleep */
585 host->hostFlags |= HCPS_WAITING; /* I am sleeping now */
586 #ifdef AFS_PTHREAD_ENV
587 CV_WAIT(&host->cond, &host_glock_mutex);
588 #else /* AFS_PTHREAD_ENV */
589 if ((code = LWP_WaitProcess(&(host->hostFlags))) != LWP_SUCCESS)
590 ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
591 #endif /* AFS_PTHREAD_ENV */
595 host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
596 if (host->hcps.prlist_val)
597 free(host->hcps.prlist_val); /* this is for hostaclRefresh */
598 host->hcps.prlist_val = NULL;
599 host->hcps.prlist_len = 0;
600 host->cpsCall = slept ? (FT_ApproxTime()) : (now);
603 code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
608 * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
609 * and reevaluates things if no sync server or quorum is found we could still end up
610 * with one of these errors. In such case we would like to reevaluate the rpc call to
611 * find if there's cps for this guy. We treat other errors (except network failures
612 * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
613 * we could like to deal this problem the other way around (i.e. if code == NOCPS
614 * ignore else retry next time) but the problem is that there're other errors (i.e.
615 * EPERM) for which we don't want to retry and we don't know the whole code list!
617 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
619 * We would have preferred to use a while loop and try again since ops in protected
620 * acls for this host will fail now but they'll be reevaluated on any subsequent
621 * call. The attempt to wait for a quorum/sync site or network error won't work
622 * since this problems really should only occurs during a complete fileserver
623 * restart. Since the fileserver will start before the ptservers (and thus before
624 * quorums are complete) clients will be utilizing all the fileserver's lwps!!
626 host->hcpsfailed = 1;
628 ("Warning: GetHostCPS failed (%d) for %p (%s:%d); will retry\n",
629 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
631 host->hcpsfailed = 0;
633 ("gethost: GetHostCPS failed (%d) for %p (%s:%d); ignored\n",
634 code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
636 if (host->hcps.prlist_val)
637 free(host->hcps.prlist_val);
638 host->hcps.prlist_val = NULL;
639 host->hcps.prlist_len = 0; /* Make sure it's zero */
641 host->hcpsfailed = 0;
643 host->hostFlags &= ~HCPS_INPROGRESS;
644 /* signal all who are waiting */
645 if (host->hostFlags & HCPS_WAITING) { /* somebody is waiting */
646 host->hostFlags &= ~HCPS_WAITING;
647 #ifdef AFS_PTHREAD_ENV
648 CV_BROADCAST(&host->cond);
649 #else /* AFS_PTHREAD_ENV */
650 if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
651 ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
652 #endif /* AFS_PTHREAD_ENV */
656 /* args in net byte order */
658 h_flushhostcps(afs_uint32 hostaddr, afs_uint16 hport)
663 h_Lookup_r(hostaddr, hport, &host);
665 host->hcpsfailed = 1;
674 * Allocate a host. It will be identified by the peer (ip,port) info in the
675 * rx connection provided. The host is returned held and locked
677 #define DEF_ROPCONS 2115
680 h_Alloc_r(struct rx_connection *r_con)
682 struct servent *serverentry;
684 #if FS_STATS_DETAILED
685 afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
686 #endif /* FS_STATS_DETAILED */
692 host->host = rxr_HostOf(r_con);
693 host->port = rxr_PortOf(r_con);
695 h_AddHostToAddrHashTable_r(host->host, host->port, host);
697 if (consolePort == 0) { /* find the portal number for console */
698 #if defined(AFS_OSF_ENV)
699 serverentry = getservbyname("ropcons", "");
701 serverentry = getservbyname("ropcons", 0);
704 consolePort = serverentry->s_port;
706 consolePort = htons(DEF_ROPCONS); /* Use a default */
708 if (host->port == consolePort)
710 /* Make a callback channel even for the console, on the off chance that it
711 * makes a request that causes a break call back. It shouldn't. */
712 h_SetupCallbackConn_r(host);
713 host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
715 host->hcps.prlist_val = NULL;
716 host->hcps.prlist_len = 0;
717 host->interface = NULL;
719 host->hcpsfailed = 0; /* save cycles */
720 h_gethostcps(host); /* do this under host hold/lock */
722 host->FirstClient = NULL;
725 h_InsertList_r(host); /* update global host List */
726 #if FS_STATS_DETAILED
728 * Compare the new host's IP address (in host byte order) with ours
729 * (the File Server's), remembering if they are in the same network.
731 newHostAddr_HBO = (afs_uint32) ntohl(host->host);
732 host->InSameNetwork =
733 h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
734 #endif /* FS_STATS_DETAILED */
741 /* Make a callback channel even for the console, on the off chance that it
742 * makes a request that causes a break call back. It shouldn't. */
744 h_SetupCallbackConn_r(struct host * host)
747 sc = rxnull_NewClientSecurityObject();
748 host->callback_rxcon =
749 rx_NewConnection(host->host, host->port, 1, sc, 0);
750 rx_SetConnDeadTime(host->callback_rxcon, 50);
751 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
752 rx_SetConnSecondsUntilNatPing(host->callback_rxcon, 20);
756 * Lookup a host given an IP address and UDP port number.
757 * hostaddr and hport are in network order
758 * hostaddr and hport are in network order
759 * On return, refCount is incremented.
762 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, struct host **hostp)
765 struct host *host = NULL;
766 struct h_AddrHashChain *chain;
767 int index = h_HashIndex(haddr);
768 extern int hostaclRefresh;
771 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
772 host = chain->hostPtr;
774 if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
775 && chain->port == hport) {
776 if ((host->hostFlags & HWHO_INPROGRESS) &&
777 h_threadquota(host->lock.num_waiting)) {
783 if (host->hostFlags & HOSTDELETED) {
790 now = FT_ApproxTime(); /* always evaluate "now" */
791 if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
793 * Every hostaclRefresh period (def 2 hrs) get the new
794 * membership list for the host. Note this could be the
795 * first time that the host is added to a group. Also
796 * here we also retry on previous legitimate hcps failures.
798 * If we get here refCount is elevated.
800 h_gethostcps_r(host, now);
810 /* Lookup a host given its UUID. */
812 h_LookupUuid_r(afsUUID * uuidp)
814 struct host *host = 0;
815 struct h_UuidHashChain *chain;
816 int index = h_UuidHashIndex(uuidp);
818 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
819 host = chain->hostPtr;
821 if (!(host->hostFlags & HOSTDELETED) && host->interface
822 && afs_uuid_equal(&host->interface->uuid, uuidp)) {
830 /* h_TossStuff_r: Toss anything in the host structure (the host or
831 * clients marked for deletion. Called from h_Release_r ONLY.
832 * To be called, there must be no holds, and either host->deleted
833 * or host->clientDeleted must be set.
836 h_TossStuff_r(struct host *host)
838 struct client **cp, *client;
841 /* make sure host doesn't go away over h_NBLock_r */
844 code = h_NBLock_r(host);
846 /* don't use h_Release_r, since that may call h_TossStuff_r again */
849 /* if somebody still has this host locked */
853 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was locked.\n",
854 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
860 /* if somebody still has this host held */
861 /* we must check this _after_ h_NBLock_r, since h_NBLock_r can drop and
862 * reacquire H_LOCK */
863 if (host->refCount > 0) {
866 ("Warning: h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was held.\n",
867 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
871 /* ASSUMPTION: rxi_FreeConnection() does not yield */
872 for (cp = &host->FirstClient; (client = *cp);) {
873 if ((host->hostFlags & HOSTDELETED) || client->deleted) {
875 ObtainWriteLockNoBlock(&client->lock, code);
879 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
880 "client %p was locked.\n",
881 host, afs_inet_ntoa_r(host->host, hoststr),
882 ntohs(host->port), client));
886 if (client->refCount) {
889 ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
890 "client %p refcount %d.\n",
891 host, afs_inet_ntoa_r(host->host, hoststr),
892 ntohs(host->port), client, client->refCount));
893 /* This is the same thing we do if the host is locked */
894 ReleaseWriteLock(&client->lock);
897 client->CPS.prlist_len = 0;
898 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
899 free(client->CPS.prlist_val);
900 client->CPS.prlist_val = NULL;
901 CurrentConnections--;
903 ReleaseWriteLock(&client->lock);
909 /* We've just cleaned out all the deleted clients; clear the flag */
910 host->hostFlags &= ~CLIENTDELETED;
912 if (host->hostFlags & HOSTDELETED) {
913 struct rx_connection *rxconn;
914 struct AddrPort hostAddrPort;
917 if (host->Console & 1)
919 if ((rxconn = host->callback_rxcon)) {
920 host->callback_rxcon = (struct rx_connection *)0;
921 rx_DestroyConnection(rxconn);
923 if (host->hcps.prlist_val)
924 free(host->hcps.prlist_val);
925 host->hcps.prlist_val = NULL;
926 host->hcps.prlist_len = 0;
927 DeleteAllCallBacks_r(host, 1);
928 host->hostFlags &= ~RESETDONE; /* just to be safe */
930 /* if alternate addresses do not exist */
931 if (!(host->interface)) {
932 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
934 h_DeleteHostFromUuidHashTable_r(host);
935 h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
936 /* delete the hash entry for each valid alternate addresses */
937 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
938 hostAddrPort = host->interface->interface[i];
940 * if the interface addr/port is the primary, we already
941 * removed it. If the addr/port is not valid, its not
944 if (hostAddrPort.valid &&
945 (host->host != hostAddrPort.addr ||
946 host->port != hostAddrPort.port))
947 h_DeleteHostFromAddrHashTable_r(hostAddrPort.addr, hostAddrPort.port, host);
949 free(host->interface);
950 host->interface = NULL;
951 } /* if alternate address exists */
953 h_DeleteList_r(host); /* remove host from global host List */
960 /* h_Enumerate: Calls (*proc)(host, param) for at least each host in the
961 * system at the start of the enumeration (perhaps more). Hosts may be deleted
962 * (have delete flag set); ditto for clients. refCount is always incremented
963 * before (*proc) is called.
965 * The return value of the proc is a set of flags. The proc should set
966 * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
969 h_Enumerate(int (*proc) (struct host*, void *), void *param)
971 struct host *host, **list;
976 if (hostCount == 0) {
980 list = (struct host **)malloc(hostCount * sizeof(struct host *));
982 ViceLogThenPanic(0, ("Failed malloc in h_Enumerate (list)\n"));
984 for (totalCount = count = 0, host = hostList;
985 host && totalCount < hostCount;
986 host = host->next, totalCount++) {
988 if (!(host->hostFlags & HOSTDELETED)) {
994 if (totalCount != hostCount) {
995 ViceLog(0, ("h_Enumerate found %d of %d hosts\n", totalCount, hostCount));
996 } else if (host != NULL) {
997 ViceLog(0, ("h_Enumerate found more than %d hosts\n", hostCount));
998 ShutDownAndCore(PANIC);
1001 for (i = 0; i < count; i++) {
1003 flags = (*proc) (list[i], param);
1005 h_Release_r(list[i]);
1007 /* bail out of the enumeration early */
1008 if (H_ENUMERATE_ISSET_BAIL(flags)) {
1011 ViceLog(0, ("h_Enumerate got back invalid return value %d\n", flags));
1012 ShutDownAndCore(PANIC);
1016 /* we bailed out of enumerating hosts early; we still have holds on
1017 * some of the hosts in 'list', so release them */
1020 for ( ; i < count; i++) {
1021 h_Release_r(list[i]);
1029 /* h_Enumerate_r (revised):
1030 * Calls (*proc)(host, param) for each host in hostList, starting
1031 * at enumstart. Called only under H_LOCK. Hosts may be deleted (have
1032 * delete flag set); ditto for clients. refCount is always incremented
1033 * before (*proc) is called.
1035 * @note Assumes that hostList is only prepended to, that a host is never
1036 * inserted into the middle. Otherwise this would not be guaranteed to
1039 * The return value of the proc is a set of flags. The proc should set
1040 * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
1043 h_Enumerate_r(int (*proc) (struct host *, void *),
1044 struct host *enumstart, void *param)
1046 struct host *host, *next;
1050 if (hostCount == 0) {
1057 /* find the first non-deleted host, so we know where to actually start
1059 for (count = 0; host && count < hostCount; count++) {
1060 if (!(host->hostFlags & HOSTDELETED)) {
1067 /* we didn't find a non-deleted host... */
1069 if (host && count >= hostCount) {
1070 /* ...because we found a loop */
1071 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", hostCount));
1072 ShutDownAndCore(PANIC);
1075 /* ...because the hostList is full of deleted hosts */
1079 h_Hold_r(enumstart);
1081 /* remember hostCount, lest it change over the potential H_LOCK drop in
1083 origHostCount = hostCount;
1085 for (count = 0, host = enumstart; host && count < origHostCount; host = next, count++) {
1088 /* find the next non-deleted host */
1089 while (next && (next->hostFlags & HOSTDELETED)) {
1091 /* inc count for the skipped-over host */
1092 if (++count > origHostCount) {
1093 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1094 ShutDownAndCore(PANIC);
1100 if (!(host->hostFlags & HOSTDELETED)) {
1102 flags = (*proc) (host, param);
1103 if (H_ENUMERATE_ISSET_BAIL(flags)) {
1104 h_Release_r(host); /* this might free up the host */
1110 ViceLog(0, ("h_Enumerate_r got back invalid return value %d\n", flags));
1111 ShutDownAndCore(PANIC);
1114 h_Release_r(host); /* this might free up the host */
1116 if (host != NULL && count >= origHostCount) {
1117 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1118 ShutDownAndCore(PANIC);
1120 } /*h_Enumerate_r */
1123 /* inserts a new HashChain structure corresponding to this UUID */
1125 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1128 struct h_UuidHashChain *chain;
1129 char uuid1[128], uuid2[128];
1132 /* hash into proper bucket */
1133 index = h_UuidHashIndex(uuid);
1135 /* don't add the same entry multiple times */
1136 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1137 if (!chain->hostPtr)
1140 if (chain->hostPtr->interface &&
1141 afs_uuid_equal(&chain->hostPtr->interface->uuid, uuid)) {
1142 if (LogLevel >= 125) {
1143 afsUUID_to_string(&chain->hostPtr->interface->uuid, uuid1,
1145 afsUUID_to_string(uuid, uuid2, 127);
1146 ViceLog(125, ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s) exists as %s:%d (uuid %s)\n",
1148 afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1149 ntohs(chain->hostPtr->port), uuid2));
1155 /* insert into beginning of list for this bucket */
1156 chain = (struct h_UuidHashChain *)malloc(sizeof(struct h_UuidHashChain));
1158 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1160 chain->hostPtr = host;
1161 chain->next = hostUuidHashTable[index];
1162 hostUuidHashTable[index] = chain;
1165 afsUUID_to_string(uuid, uuid2, 127);
1167 ("h_AddHostToUuidHashTable_r: host %p (%s:%d) added as uuid %s\n",
1168 host, afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1169 ntohs(chain->hostPtr->port), uuid2));
1172 /* deletes a HashChain structure corresponding to this host */
1174 h_DeleteHostFromUuidHashTable_r(struct host *host)
1177 struct h_UuidHashChain **uhp, *uth;
1181 if (!host->interface)
1184 /* hash into proper bucket */
1185 index = h_UuidHashIndex(&host->interface->uuid);
1187 if (LogLevel >= 125)
1188 afsUUID_to_string(&host->interface->uuid, uuid1, 127);
1189 for (uhp = &hostUuidHashTable[index]; (uth = *uhp); uhp = &uth->next) {
1190 osi_Assert(uth->hostPtr);
1191 if (uth->hostPtr == host) {
1193 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d)\n",
1194 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1195 ntohs(host->port)));
1202 ("h_DeleteHostFromUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s %s:%d) not found\n",
1203 host, uuid1, afs_inet_ntoa_r(host->host, hoststr),
1204 ntohs(host->port)));
1209 * This is called with host locked and held.
1211 * All addresses are in network byte order.
1214 invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1218 struct Interface *interface;
1219 char hoststr[16], hoststr2[16];
1222 osi_Assert(host->interface);
1224 ViceLog(125, ("invalidateInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1225 host, afs_inet_ntoa_r(host->host, hoststr),
1226 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1230 * Make sure this address is on the list of known addresses
1233 interface = host->interface;
1234 number = host->interface->numberOfInterfaces;
1235 for (i = 0; i < number; i++) {
1236 if (interface->interface[i].addr == addr &&
1237 interface->interface[i].port == port) {
1238 if (interface->interface[i].valid) {
1239 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1240 interface->interface[i].valid = 0;
1251 * This is called with host locked and held. This function differs
1252 * from removeInterfaceAddr_r in that it is called when the address
1253 * is being removed from the host regardless of whether or not there
1254 * is an interface list for the host. This function will delete the
1255 * host if there are no addresses left on it.
1257 * All addresses are in network byte order.
1260 removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1263 char hoststr[16], hoststr2[16];
1264 struct rx_connection *rxconn;
1266 if (!host->interface || host->interface->numberOfInterfaces == 1) {
1267 if (host->host == addr && host->port == port) {
1269 ("Removing only address for host %" AFS_PTR_FMT " (%s:%d), deleting host.\n",
1270 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1271 host->hostFlags |= HOSTDELETED;
1273 * Do not remove the primary addr/port from the hash table.
1274 * It will be ignored due to the HOSTDELETED flag and will
1275 * be removed when h_TossStuff_r() cleans up the HOSTDELETED
1276 * host. Removing it here will only result in a search for
1277 * the host/addr/port in the hash chain which will fail.
1281 ("Removing address that does not belong to host %" AFS_PTR_FMT " (%s:%d).\n",
1282 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1285 if (host->host == addr && host->port == port) {
1286 removeInterfaceAddr_r(host, addr, port);
1288 for (i=0; i < host->interface->numberOfInterfaces; i++) {
1289 if (host->interface->interface[i].valid) {
1291 ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
1292 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1293 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2),
1294 ntohs(host->interface->interface[i].port)));
1295 host->host = host->interface->interface[i].addr;
1296 host->port = host->interface->interface[i].port;
1297 h_AddHostToAddrHashTable_r(host->host, host->port, host);
1302 if (i == host->interface->numberOfInterfaces) {
1304 ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
1305 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1306 host->hostFlags |= HOSTDELETED;
1307 /* addr/port was removed from the hash table */
1311 rxconn = host->callback_rxcon;
1312 host->callback_rxcon = NULL;
1315 rx_DestroyConnection(rxconn);
1319 h_SetupCallbackConn_r(host);
1322 /* not the primary addr/port, just invalidate it */
1323 invalidateInterfaceAddr_r(host, addr, port);
1331 createHostAddrHashChain_r(int index, afs_uint32 addr, afs_uint16 port, struct host *host)
1333 struct h_AddrHashChain *chain;
1336 /* insert into beginning of list for this bucket */
1337 chain = (struct h_AddrHashChain *)malloc(sizeof(struct h_AddrHashChain));
1339 ViceLogThenPanic(0, ("Failed malloc in h_AddHostToAddrHashTable_r\n"));
1341 chain->hostPtr = host;
1342 chain->next = hostAddrHashTable[index];
1345 hostAddrHashTable[index] = chain;
1346 ViceLog(125, ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " added as %s:%d\n",
1347 host, afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1351 * Resolve host address conflicts when hashing by address.
1353 * @param[in] addr an ip address of the interface
1354 * @param[in] port the port of the interface
1355 * @param[in] newHost the host being added with this address
1356 * @param[in] oldHost the host previously added with this address
1359 reconcileHosts_r(afs_uint32 addr, afs_uint16 port, struct host *newHost,
1360 struct host *oldHost)
1362 struct rx_connection *cb = NULL;
1364 struct interfaceAddr interf;
1366 afsUUID *newHostUuid = &nulluuid;
1367 afsUUID *oldHostUuid = &nulluuid;
1371 ("reconcileHosts_r: addr %s:%d newHost %" AFS_PTR_FMT " oldHost %"
1372 AFS_PTR_FMT, afs_inet_ntoa_r(addr, hoststr), ntohs(port),
1375 osi_Assert(oldHost != newHost);
1376 caps.Capabilities_val = NULL;
1379 sc = rxnull_NewClientSecurityObject();
1382 cb = rx_NewConnection(addr, port, 1, sc, 0);
1383 rx_SetConnDeadTime(cb, 50);
1384 rx_SetConnHardDeadTime(cb, AFS_HARDDEADTIME);
1389 code = RXAFSCB_TellMeAboutYourself(cb, &interf, &caps);
1390 if (code == RXGEN_OPCODE) {
1391 code = RXAFSCB_WhoAreYou(cb, &interf);
1395 if (code == RXGEN_OPCODE ||
1396 (code == 0 && afs_uuid_equal(&interf.uuid, &nulluuid))) {
1398 ("reconcileHosts_r: WhoAreYou not supported for connection (%s:%d), error %d\n",
1399 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1404 ("reconcileHosts_r: WhoAreYou failed for connection (%s:%d), error %d\n",
1405 afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1409 /* Since lock was dropped, the hosts may have been deleted during the rpcs. */
1410 if ((newHost->hostFlags & HOSTDELETED)
1411 && (oldHost->hostFlags & HOSTDELETED)) {
1413 ("reconcileHosts_r: new and old hosts were deleted during probe.\n"));
1417 /* A check can be done if at least one of the hosts has a uuid. It
1418 * is an error if the hosts have the same (not null) uuid. */
1419 if ((!(newHost->hostFlags & HOSTDELETED)) && newHost->interface) {
1420 newHostUuid = &(newHost->interface->uuid);
1422 if ((!(oldHost->hostFlags & HOSTDELETED)) && oldHost->interface) {
1423 oldHostUuid = &(oldHost->interface->uuid);
1425 if (afs_uuid_equal(newHostUuid, &nulluuid) &&
1426 afs_uuid_equal(oldHostUuid, &nulluuid)) {
1428 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), no uuids\n",
1429 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1432 if (afs_uuid_equal(newHostUuid, oldHostUuid)) {
1434 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), same uuids\n",
1435 afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1439 /* Determine which host should be hashed */
1440 if ((!(newHost->hostFlags & HOSTDELETED))
1441 && afs_uuid_equal(newHostUuid, &(interf.uuid))) {
1442 /* Install the new host into the hash before removing the stale
1443 * addresses. Walk the hash chain again since the hash table may have
1444 * been changed when the host lock was dropped to get the uuid. */
1445 struct h_AddrHashChain *chain;
1446 int index = h_HashIndex(addr);
1447 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1448 if (chain->addr == addr && chain->port == port) {
1449 chain->hostPtr = newHost;
1450 removeAddress_r(oldHost, addr, port);
1454 createHostAddrHashChain_r(index, addr, port, newHost);
1455 removeAddress_r(oldHost, addr, port);
1458 if ((!(oldHost->hostFlags & HOSTDELETED))
1459 && afs_uuid_equal(oldHostUuid, &(interf.uuid))) {
1460 removeAddress_r(newHost, addr, port);
1465 if (!(newHost->hostFlags & HOSTDELETED)) {
1466 removeAddress_r(newHost, addr, port);
1468 if (!(oldHost->hostFlags & HOSTDELETED)) {
1469 removeAddress_r(oldHost, addr, port);
1473 h_Release_r(newHost);
1474 h_Release_r(oldHost);
1475 rx_DestroyConnection(cb);
1479 /* inserts a new HashChain structure corresponding to this address */
1481 h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1484 struct h_AddrHashChain *chain;
1487 /* hash into proper bucket */
1488 index = h_HashIndex(addr);
1490 /* don't add the same address:port pair entry multiple times */
1491 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1492 if (chain->addr == addr && chain->port == port) {
1493 if (chain->hostPtr == host) {
1495 ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
1496 host, afs_inet_ntoa_r(chain->addr, hoststr),
1497 ntohs(chain->port)));
1500 if (!(chain->hostPtr->hostFlags & HOSTDELETED)) {
1501 /* attempt to resolve host address collision */
1502 reconcileHosts_r(addr, port, host, chain->hostPtr);
1507 createHostAddrHashChain_r(index, addr, port, host);
1511 * This is called with host locked and held.
1512 * It is called to either validate or add an additional interface
1513 * address/port on the specified host.
1515 * All addresses are in network byte order.
1518 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1522 struct Interface *interface;
1523 char hoststr[16], hoststr2[16];
1526 osi_Assert(host->interface);
1529 * Make sure this address is on the list of known addresses
1532 number = host->interface->numberOfInterfaces;
1533 for (i = 0; i < number; i++) {
1534 if (host->interface->interface[i].addr == addr &&
1535 host->interface->interface[i].port == port) {
1537 ("addInterfaceAddr : found host %" AFS_PTR_FMT " (%s:%d) adding %s:%d%s\n",
1538 host, afs_inet_ntoa_r(host->host, hoststr),
1539 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1540 ntohs(port), host->interface->interface[i].valid ? "" :
1543 if (host->interface->interface[i].valid == 0) {
1544 host->interface->interface[i].valid = 1;
1545 h_AddHostToAddrHashTable_r(addr, port, host);
1551 ViceLog(125, ("addInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) adding %s:%d\n",
1552 host, afs_inet_ntoa_r(host->host, hoststr),
1553 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1556 interface = (struct Interface *)
1557 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1559 ViceLogThenPanic(0, ("Failed malloc in addInterfaceAddr_r\n"));
1561 interface->numberOfInterfaces = number + 1;
1562 interface->uuid = host->interface->uuid;
1563 for (i = 0; i < number; i++)
1564 interface->interface[i] = host->interface->interface[i];
1566 /* Add the new valid interface */
1567 interface->interface[number].addr = addr;
1568 interface->interface[number].port = port;
1569 interface->interface[number].valid = 1;
1570 h_AddHostToAddrHashTable_r(addr, port, host);
1571 free(host->interface);
1572 host->interface = interface;
1579 * This is called with host locked and held.
1581 * All addresses are in network byte order.
1584 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1588 struct Interface *interface;
1589 char hoststr[16], hoststr2[16];
1592 osi_Assert(host->interface);
1594 ViceLog(125, ("removeInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1595 host, afs_inet_ntoa_r(host->host, hoststr),
1596 ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1600 * Make sure this address is on the list of known addresses
1603 interface = host->interface;
1604 number = host->interface->numberOfInterfaces;
1605 for (i = 0; i < number; i++) {
1606 if (interface->interface[i].addr == addr &&
1607 interface->interface[i].port == port) {
1608 if (interface->interface[i].valid)
1609 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1611 for (; i < number; i++) {
1612 interface->interface[i] = interface->interface[i+1];
1614 interface->numberOfInterfaces = number;
1625 h_threadquota(int waiting)
1630 } else if (lwps > 32) {
1633 } else if (lwps > 16) {
1643 /* If found, host is returned with refCount incremented */
1645 h_GetHost_r(struct rx_connection *tcon)
1648 struct host *oldHost;
1650 struct interfaceAddr interf;
1651 int interfValid = 0;
1652 struct Identity *identP = NULL;
1655 char hoststr[16], hoststr2[16];
1657 struct rx_connection *cb_conn = NULL;
1658 struct rx_connection *cb_in = NULL;
1660 caps.Capabilities_val = NULL;
1662 haddr = rxr_HostOf(tcon);
1663 hport = rxr_PortOf(tcon);
1666 rx_DestroyConnection(cb_in);
1669 if (caps.Capabilities_val)
1670 free(caps.Capabilities_val);
1671 caps.Capabilities_val = NULL;
1672 caps.Capabilities_len = 0;
1675 if (h_Lookup_r(haddr, hport, &host))
1677 identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1678 if (host && !identP && !(host->Console & 1)) {
1679 /* This is a new connection, and we already have a host
1680 * structure for this address. Verify that the identity
1681 * of the caller matches the identity in the host structure.
1683 if ((host->hostFlags & HWHO_INPROGRESS) &&
1684 h_threadquota(host->lock.num_waiting)) {
1690 if (!(host->hostFlags & ALTADDR) ||
1691 (host->hostFlags & HOSTDELETED)) {
1692 /* Another thread is doing initialization
1693 * or this host was deleted while we
1694 * waited for the lock. */
1697 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1698 host, afs_inet_ntoa_r(host->host, hoststr),
1699 ntohs(host->port)));
1703 host->hostFlags |= HWHO_INPROGRESS;
1704 host->hostFlags &= ~ALTADDR;
1706 /* We received a new connection from an IP address/port
1707 * that is associated with 'host' but the address/port of
1708 * the callback connection does not have to match it.
1709 * If there is a match, we can use the existing callback
1710 * connection to verify the UUID. If they do not match
1711 * we need to use a new callback connection to verify the
1712 * UUID of the incoming caller and perhaps use the old
1713 * callback connection to verify that the old address/port
1717 cb_conn = host->callback_rxcon;
1718 rx_GetConnection(cb_conn);
1720 if (haddr == host->host && hport == host->port) {
1721 /* The existing callback connection matches the
1722 * incoming connection so just use it.
1725 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1726 if (code == RXGEN_OPCODE)
1727 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1729 /* We do not have a match. Create a new connection
1730 * for the new addr/port and use multi_Rx to probe
1731 * both of them simultaneously.
1734 sc = rxnull_NewClientSecurityObject();
1735 cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1736 rx_SetConnDeadTime(cb_in, 50);
1737 rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1738 rx_SetConnSecondsUntilNatPing(cb_in, 20);
1741 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1742 if (code == RXGEN_OPCODE)
1743 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1745 rx_PutConnection(cb_conn);
1748 if ((code == RXGEN_OPCODE) ||
1749 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1750 identP = (struct Identity *)malloc(sizeof(struct Identity));
1752 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1755 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1756 if (cb_in == NULL) {
1757 /* The host on this connection was unable to respond to
1758 * the WhoAreYou. We will treat this as a new connection
1759 * from the existing host. The worst that can happen is
1760 * that we maintain some extra callback state information */
1761 if (host->interface) {
1763 ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1765 afs_inet_ntoa_r(host->host, hoststr),
1766 ntohs(host->port)));
1767 host->hostFlags |= HOSTDELETED;
1768 host->hostFlags &= ~HWHO_INPROGRESS;
1775 /* The incoming connection does not support WhoAreYou but
1776 * the original one might have. Use removeAddress_r() to
1777 * remove this addr/port from the host that was found.
1778 * If there are no more addresses left for the host it
1779 * will be deleted. Then we retry.
1781 removeAddress_r(host, haddr, hport);
1782 host->hostFlags &= ~HWHO_INPROGRESS;
1783 host->hostFlags |= ALTADDR;
1789 } else if (code == 0) {
1791 identP = (struct Identity *)malloc(sizeof(struct Identity));
1793 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1796 identP->uuid = interf.uuid;
1797 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1798 /* Check whether the UUID on this connection matches
1799 * the UUID in the host structure. If they don't match
1800 * then this is not the same host as before. */
1801 if (!host->interface
1802 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1805 ("Uuid doesn't match connection (%s:%d).\n",
1806 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1807 removeAddress_r(host, haddr, hport);
1810 ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1811 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1813 removeAddress_r(host, host->host, host->port);
1815 host->hostFlags &= ~HWHO_INPROGRESS;
1816 host->hostFlags |= ALTADDR;
1822 /* the UUID matched the client at the incoming addr/port
1823 * but this is not the address of the active callback
1824 * connection. Try that connection and see if the client
1825 * is still there and if the reported UUID is the same.
1828 afsUUID uuid = host->interface->uuid;
1829 cb_conn = host->callback_rxcon;
1830 rx_GetConnection(cb_conn);
1831 rx_SetConnDeadTime(cb_conn, 2);
1832 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1834 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1836 rx_SetConnDeadTime(cb_conn, 50);
1837 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1838 rx_PutConnection(cb_conn);
1841 /* The primary address is either not responding or
1842 * is not the client we are looking for. Need to
1843 * remove the primary address and add swap in the new
1844 * callback connection, and destroy the old one.
1846 struct rx_connection *rxconn;
1847 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1849 afs_inet_ntoa_r(host->host, hoststr),
1850 ntohs(host->port),code2));
1853 * make sure we add and then remove. otherwise, we
1854 * might end up with no valid interfaces after the
1855 * remove and the host will have been marked deleted.
1857 addInterfaceAddr_r(host, haddr, hport);
1858 removeInterfaceAddr_r(host, host->host, host->port);
1861 rxconn = host->callback_rxcon;
1862 host->callback_rxcon = cb_in;
1867 * If rx_DestroyConnection calls h_FreeConnection we
1868 * will deadlock on the host_glock_mutex. Work around
1869 * the problem by unhooking the client from the
1870 * connection before destroying the connection.
1872 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1873 rx_DestroyConnection(rxconn);
1879 /* A callback to the incoming connection address is failing.
1880 * Assume that the addr/port is no longer associated with the host
1881 * returned by h_Lookup_r.
1884 ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1885 afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1886 removeAddress_r(host, haddr, hport);
1887 host->hostFlags &= ~HWHO_INPROGRESS;
1888 host->hostFlags |= ALTADDR;
1892 rx_DestroyConnection(cb_in);
1897 ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1898 host, afs_inet_ntoa_r(host->host, hoststr),
1899 ntohs(host->port), code));
1900 host->hostFlags |= VENUSDOWN;
1903 if (caps.Capabilities_val
1904 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1905 host->hostFlags |= HERRORTRANS;
1907 host->hostFlags &= ~(HERRORTRANS);
1908 host->hostFlags |= ALTADDR;
1909 host->hostFlags &= ~HWHO_INPROGRESS;
1912 if (!(host->hostFlags & ALTADDR)) {
1913 /* another thread is doing the initialisation */
1915 ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1916 host, afs_inet_ntoa_r(host->host, hoststr),
1917 ntohs(host->port)));
1921 ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1922 host, afs_inet_ntoa_r(host->host, hoststr),
1923 ntohs(host->port)));
1927 /* We need to check whether the identity in the host structure
1928 * matches the identity on the connection. If they don't match
1929 * then treat this a new host. */
1930 if (!(host->Console & 1)
1931 && ((!identP->valid && host->interface)
1932 || (identP->valid && !host->interface)
1934 && !afs_uuid_equal(&identP->uuid,
1935 &host->interface->uuid)))) {
1936 char uuid1[128], uuid2[128];
1938 afsUUID_to_string(&identP->uuid, uuid1, 127);
1939 if (host->interface)
1940 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1942 ("CB: new identity for host %p (%s:%d), "
1943 "deleting(%x %p %s %s)\n",
1944 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1945 identP->valid, host->interface,
1946 identP->valid ? uuid1 : "no_uuid",
1947 host->interface ? uuid2 : "no_uuid"));
1949 /* The host in the cache is not the host for this connection */
1951 host->hostFlags |= HOSTDELETED;
1957 host = h_Alloc_r(tcon); /* returned held and locked */
1960 h_gethostcps_r(host, FT_ApproxTime());
1961 if (!(host->Console & 1)) {
1963 cb_conn = host->callback_rxcon;
1964 rx_GetConnection(cb_conn);
1965 host->hostFlags |= HWHO_INPROGRESS;
1968 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1969 if (code == RXGEN_OPCODE)
1970 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1971 rx_PutConnection(cb_conn);
1974 if ((code == RXGEN_OPCODE) ||
1975 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1978 (struct Identity *)malloc(sizeof(struct Identity));
1983 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
1987 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1989 ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1990 host, afs_inet_ntoa_r(host->host, hoststr),
1991 ntohs(host->port)));
1993 } else if (code == 0) {
1996 (struct Identity *)malloc(sizeof(struct Identity));
2001 ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
2005 identP->uuid = interf.uuid;
2007 rx_SetSpecific(tcon, rxcon_ident_key, identP);
2009 ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
2010 host, afs_inet_ntoa_r(host->host, hoststr),
2011 ntohs(host->port)));
2013 if (code == 0 && !identP->valid) {
2014 cb_conn = host->callback_rxcon;
2015 rx_GetConnection(cb_conn);
2017 code = RXAFSCB_InitCallBackState(cb_conn);
2018 rx_PutConnection(cb_conn);
2021 } else if (code == 0) {
2022 oldHost = h_LookupUuid_r(&identP->uuid);
2027 if (oldHost->hostFlags & HOSTDELETED) {
2028 h_Unlock_r(oldHost);
2029 h_Release_r(oldHost);
2037 oldHost->hostFlags |= HWHO_INPROGRESS;
2039 if (oldHost->interface) {
2041 afsUUID uuid = oldHost->interface->uuid;
2042 cb_conn = oldHost->callback_rxcon;
2043 rx_GetConnection(cb_conn);
2044 rx_SetConnDeadTime(cb_conn, 2);
2045 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2047 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2049 rx_SetConnDeadTime(cb_conn, 50);
2050 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2051 rx_PutConnection(cb_conn);
2054 /* The primary address is either not responding or
2055 * is not the client we are looking for.
2056 * MultiProbeAlternateAddress_r() will remove the
2057 * alternate interfaces that do not have the same
2059 ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
2061 afs_inet_ntoa_r(oldHost->host, hoststr),
2062 ntohs(oldHost->port),code2));
2063 MultiProbeAlternateAddress_r(oldHost);
2070 /* This is a new address for an existing host. Update
2071 * the list of interfaces for the existing host and
2072 * delete the host structure we just allocated. */
2074 /* prevent warnings while manipulating interface lists */
2075 host->hostFlags |= HOSTDELETED;
2077 if (oldHost->host != haddr || oldHost->port != hport) {
2078 struct rx_connection *rxconn;
2081 ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
2083 afs_inet_ntoa_r(oldHost->host, hoststr2),
2084 ntohs(oldHost->port),
2085 afs_inet_ntoa_r(haddr, hoststr),
2088 * add then remove. otherwise the host may get marked
2089 * deleted if we removed the only valid address.
2091 addInterfaceAddr_r(oldHost, haddr, hport);
2092 if (probefail || oldHost->host == haddr) {
2094 * The probe failed which means that the old
2095 * address is either unreachable or is not the
2096 * same host we were just contacted by. We will
2097 * also remove addresses if only the port has
2098 * changed because that indicates the client
2101 removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
2104 struct Interface *interface = oldHost->interface;
2105 int number = oldHost->interface->numberOfInterfaces;
2106 for (i = 0; i < number; i++) {
2107 if (interface->interface[i].addr == haddr &&
2108 interface->interface[i].port != hport) {
2110 * We have just been contacted by a client
2111 * that has been seen from behind a NAT
2112 * and at least one other address.
2114 removeInterfaceAddr_r(oldHost, haddr,
2115 interface->interface[i].port);
2120 h_AddHostToAddrHashTable_r(haddr, hport, oldHost);
2121 oldHost->host = haddr;
2122 oldHost->port = hport;
2123 rxconn = oldHost->callback_rxcon;
2124 oldHost->callback_rxcon = host->callback_rxcon;
2125 host->callback_rxcon = rxconn;
2127 /* don't destroy rxconn here; let h_TossStuff_r
2128 * take care of that via h_Release_r below */
2130 host->hostFlags &= ~HWHO_INPROGRESS;
2132 /* release host because it was allocated by h_Alloc_r */
2135 /* the new host is held and locked */
2137 /* This really is a new host */
2138 h_AddHostToUuidHashTable_r(&identP->uuid, host);
2139 cb_conn = host->callback_rxcon;
2140 rx_GetConnection(cb_conn);
2143 RXAFSCB_InitCallBackState3(cb_conn,
2145 rx_PutConnection(cb_conn);
2150 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2151 host, afs_inet_ntoa_r(host->host, hoststr),
2152 ntohs(host->port)));
2153 osi_Assert(interfValid == 1);
2154 initInterfaceAddr_r(host, &interf);
2160 ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2161 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2162 host->hostFlags |= VENUSDOWN;
2165 ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2166 host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2167 host->hostFlags |= RESETDONE;
2170 if (caps.Capabilities_val
2171 && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2172 host->hostFlags |= HERRORTRANS;
2174 host->hostFlags &= ~(HERRORTRANS);
2175 host->hostFlags |= ALTADDR; /* host structure initialization complete */
2176 host->hostFlags &= ~HWHO_INPROGRESS;
2181 if (caps.Capabilities_val)
2182 free(caps.Capabilities_val);
2183 caps.Capabilities_val = NULL;
2184 caps.Capabilities_len = 0;
2186 rx_DestroyConnection(cb_in);
2194 static char localcellname[PR_MAXNAMELEN + 1];
2195 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
2196 int num_lrealms = -1;
2200 h_InitHostPackage(void)
2202 memset(&nulluuid, 0, sizeof(afsUUID));
2203 afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
2204 if (num_lrealms == -1) {
2206 for (i=0; i<AFS_NUM_LREALMS; i++) {
2207 if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
2213 ("afs_krb_get_lrealm failed, using %s.\n",
2215 strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
2221 /* initialize the rest of the local realms to nullstring for debugging */
2222 for (; i<AFS_NUM_LREALMS; i++)
2223 local_realms[i][0] = '\0';
2225 rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2226 rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2227 MUTEX_INIT(&host_glock_mutex, "host glock", MUTEX_DEFAULT, 0);
2231 MapName_r(char *aname, char *acell, afs_int32 * aval)
2236 afs_int32 anamelen, cnamelen;
2240 anamelen = strlen(aname);
2241 if (anamelen >= PR_MAXNAMELEN)
2242 return -1; /* bad name -- caller interprets this as anonymous, but retries later */
2244 lnames.namelist_len = 1;
2245 lnames.namelist_val = (prname *) aname; /* don't malloc in the common case */
2246 lids.idlist_len = 0;
2247 lids.idlist_val = NULL;
2249 cnamelen = strlen(acell);
2251 if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2253 ("MapName: cell is foreign. cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2254 acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2255 if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2257 ("MapName: Name too long, using AnonymousID for %s@%s\n",
2259 *aval = AnonymousID;
2262 foreign = 1; /* attempt cross-cell authentication */
2263 tname = (char *)malloc(PR_MAXNAMELEN);
2265 ViceLogThenPanic(0, ("Failed malloc in MapName_r\n"));
2267 strcpy(tname, aname);
2268 tname[anamelen] = '@';
2269 strcpy(tname + anamelen + 1, acell);
2270 lnames.namelist_val = (prname *) tname;
2275 code = hpr_NameToId(&lnames, &lids);
2278 if (lids.idlist_val) {
2279 *aval = lids.idlist_val[0];
2280 if (*aval == AnonymousID) {
2282 ("MapName: NameToId on %s returns anonymousID\n",
2283 lnames.namelist_val[0]));
2285 free(lids.idlist_val); /* return parms are not malloced in stub if server proc aborts */
2288 ("MapName: NameToId on '%s' is unknown\n",
2289 lnames.namelist_val[0]));
2295 free(lnames.namelist_val); /* We allocated this above, so we must free it now. */
2303 /* NOTE: this returns the client with a Write lock and a refCount */
2305 h_ID2Client(afs_int32 vid)
2307 struct client *client;
2312 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
2313 if (host->hostFlags & HOSTDELETED)
2315 for (client = host->FirstClient; client; client = client->next) {
2316 if (!client->deleted && client->ViceId == vid) {
2319 ObtainWriteLock(&client->lock);
2324 if (count != hostCount) {
2325 ViceLog(0, ("h_ID2Client found %d of %d hosts\n", count, hostCount));
2326 } else if (host != NULL) {
2327 ViceLog(0, ("h_ID2Client found more than %d hosts\n", hostCount));
2328 ShutDownAndCore(PANIC);
2336 * Called by the server main loop. Returns a h_Held client, which must be
2337 * released later the main loop. Allocates a client if the matching one
2338 * isn't around. The client is returned with its reference count incremented
2339 * by one. The caller must call h_ReleaseClient_r when finished with
2342 * The refCount on client->host is returned incremented. h_ReleaseClient_r
2343 * does not decrement the refCount on client->host.
2346 h_FindClient_r(struct rx_connection *tcon)
2348 struct client *client;
2349 struct host *host = NULL;
2350 struct client *oldClient;
2351 afs_int32 viceid = 0;
2355 #if (64-MAXKTCNAMELEN)
2356 ticket name length != 64
2360 char uname[PR_MAXNAMELEN];
2361 char tcell[MAXKTCREALMLEN];
2365 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2366 if (client && client->sid == rxr_CidOf(tcon)
2367 && client->VenusEpoch == rxr_GetEpoch(tcon)
2368 && !(client->host->hostFlags & HOSTDELETED)
2369 && !client->deleted) {
2372 h_Hold_r(client->host);
2373 if (client->prfail != 2) {
2374 /* Could add shared lock on client here */
2375 /* note that we don't have to lock entry in this path to
2376 * ensure CPS is initialized, since we don't call rx_SetSpecific
2377 * until initialization is done, and we only get here if
2378 * rx_GetSpecific located the client structure.
2383 ObtainWriteLock(&client->lock); /* released at end */
2389 authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2391 ("FindClient: authenticating connection: authClass=%d\n",
2393 if (authClass == 1) {
2394 /* A bcrypt tickets, no longer supported */
2395 ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2396 viceid = AnonymousID;
2397 expTime = 0x7fffffff;
2398 } else if (authClass == 2) {
2401 /* kerberos ticket */
2402 code = rxkad_GetServerInfo(tcon, /*level */ 0, (afs_uint32 *)&expTime,
2403 tname, tinst, tcell, &kvno);
2405 ViceLog(1, ("Failed to get rxkad ticket info\n"));
2406 viceid = AnonymousID;
2407 expTime = 0x7fffffff;
2409 int ilen = strlen(tinst);
2411 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2412 tname, tinst, tcell, expTime, kvno));
2413 strncpy(uname, tname, sizeof(uname));
2415 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2418 strcat(uname, tinst);
2420 /* translate the name to a vice id */
2421 code = MapName_r(uname, tcell, &viceid);
2425 ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2428 viceid = AnonymousID;
2429 expTime = 0x7fffffff;
2433 viceid = AnonymousID; /* unknown security class */
2434 expTime = 0x7fffffff;
2437 if (!client) { /* loop */
2438 host = h_GetHost_r(tcon); /* Returns with incremented refCount */
2444 /* First try to find the client structure */
2445 for (client = host->FirstClient; client; client = client->next) {
2446 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2447 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2450 ObtainWriteLock(&client->lock);
2456 /* Still no client structure - get one */
2459 if (host->hostFlags & HOSTDELETED) {
2464 /* Retry to find the client structure */
2465 for (client = host->FirstClient; client; client = client->next) {
2466 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2467 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2469 goto retryfirstclient;
2474 ObtainWriteLock(&client->lock);
2475 client->refCount = 1;
2476 client->host = host;
2477 #if FS_STATS_DETAILED
2478 client->InSameNetwork = host->InSameNetwork;
2479 #endif /* FS_STATS_DETAILED */
2480 client->ViceId = viceid;
2481 client->expTime = expTime; /* rx only */
2482 client->authClass = authClass; /* rx only */
2483 client->sid = rxr_CidOf(tcon);
2484 client->VenusEpoch = rxr_GetEpoch(tcon);
2485 client->CPS.prlist_val = NULL;
2486 client->CPS.prlist_len = 0;
2490 client->prfail = fail;
2492 if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2493 client->CPS.prlist_len = 0;
2494 if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2495 free(client->CPS.prlist_val);
2496 client->CPS.prlist_val = NULL;
2497 client->ViceId = viceid;
2498 client->expTime = expTime;
2500 if (viceid == ANONYMOUSID) {
2501 client->CPS.prlist_len = AnonCPS.prlist_len;
2502 client->CPS.prlist_val = AnonCPS.prlist_val;
2505 code = hpr_GetCPS(viceid, &client->CPS);
2510 ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2511 code, viceid, client->host,
2512 afs_inet_ntoa_r(client->host->host,hoststr),
2513 ntohs(client->host->port)));
2515 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2516 * all protection servers and reevaluates things if no
2517 * sync server or quorum is found we could still end up
2518 * with one of these errors. In such case we would like to
2519 * reevaluate the rpc call to find if there's cps for this
2520 * guy. We treat other errors (except network failures
2521 * ones - i.e. code < 0) as an indication that there is no
2522 * CPS for this host. Ideally we could like to deal this
2523 * problem the other way around (i.e. if code == NOCPS
2524 * ignore else retry next time) but the problem is that
2525 * there're other errors (i.e. EPERM) for which we don't
2526 * want to retry and we don't know the whole code list!
2528 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2532 /* the disabling of system:administrators is so iffy and has so many
2533 * possible failure modes that we will disable it again */
2534 /* Turn off System:Administrator for safety
2535 * if (AL_IsAMember(SystemId, client->CPS) == 0)
2536 * osi_Assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2539 /* Now, tcon may already be set to a rock, since we blocked with no host
2540 * or client locks set above in pr_GetCPS (XXXX some locking is probably
2541 * required). So, before setting the RPC's rock, we should disconnect
2542 * the RPC from the other client structure's rock.
2544 oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2545 if (oldClient && oldClient != client && oldClient->sid == rxr_CidOf(tcon)
2546 && oldClient->VenusEpoch == rxr_GetEpoch(tcon)) {
2548 if (!oldClient->deleted) {
2549 /* if we didn't create it, it's not ours to put back */
2551 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2552 "conn %p (host %s:%d) had client %p(%x)\n",
2553 client, client->sid, tcon,
2554 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2555 ntohs(rxr_PortOf(tcon)),
2556 oldClient, oldClient->sid));
2557 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2558 free(client->CPS.prlist_val);
2559 client->CPS.prlist_val = NULL;
2560 client->CPS.prlist_len = 0;
2562 /* We should perhaps check for 0 here */
2564 ReleaseWriteLock(&client->lock);
2569 oldClient->refCount++;
2571 h_Hold_r(oldClient->host);
2572 h_Release_r(client->host);
2575 ObtainWriteLock(&oldClient->lock);
2578 host = oldClient->host;
2580 ViceLog(0, ("FindClient: deleted client %p(%x ref %d host %p href "
2581 "%d) already had conn %p (host %s:%d, cid %x), stolen "
2582 "by client %p(%x, ref %d host %p href %d)\n",
2583 oldClient, oldClient->sid, oldClient->refCount,
2584 oldClient->host, oldClient->host->refCount, tcon,
2585 afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2586 ntohs(rxr_PortOf(tcon)), rxr_CidOf(tcon),
2587 client, client->sid, client->refCount,
2588 client->host, client->host->refCount));
2589 /* rx_SetSpecific will be done immediately below */
2592 /* Avoid chaining in more than once. */
2596 if (host->hostFlags & HOSTDELETED) {
2601 client->host = NULL;
2603 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2604 free(client->CPS.prlist_val);
2605 client->CPS.prlist_val = NULL;
2606 client->CPS.prlist_len = 0;
2609 ReleaseWriteLock(&client->lock);
2614 client->next = host->FirstClient;
2615 host->FirstClient = client;
2617 CurrentConnections++; /* increment number of connections */
2619 rx_SetSpecific(tcon, rxcon_client_key, client);
2620 ReleaseWriteLock(&client->lock);
2624 } /*h_FindClient_r */
2627 h_ReleaseClient_r(struct client *client)
2629 osi_Assert(client->refCount > 0);
2636 * Sigh: this one is used to get the client AGAIN within the individual
2637 * server routines. This does not bother h_Holding the host, since
2638 * this is assumed already have been done by the server main loop.
2639 * It does check tokens, since only the server routines can return the
2640 * VICETOKENDEAD error code
2643 GetClient(struct rx_connection *tcon, struct client **cp)
2645 struct client *client;
2650 client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2651 if (client == NULL) {
2653 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2654 tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2655 ntohs(rxr_PortOf(tcon))));
2659 if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2661 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2662 tcon, rxr_CidOf(tcon), client->sid));
2666 if (client && client->LastCall > client->expTime && client->expTime) {
2668 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2669 afs_inet_ntoa_r(client->host->host, hoststr),
2670 ntohs(client->host->port), client->expTime));
2672 return VICETOKENDEAD;
2674 if (client->deleted) {
2675 ViceLog(0, ("GetClient: got deleted client, connection will appear "
2676 "anonymous; tcon %p cid %x client %p ref %d host %p "
2677 "(%s:%d) href %d ViceId %d\n",
2678 tcon, rxr_CidOf(tcon), client, client->refCount,
2680 afs_inet_ntoa_r(client->host->host, hoststr),
2681 (int)ntohs(client->host->port), client->host->refCount,
2682 (int)client->ViceId));
2692 PutClient(struct client **cp)
2698 h_ReleaseClient_r(*cp);
2705 /* Client user name for short term use. Note that this is NOT inexpensive */
2707 h_UserName(struct client *client)
2709 static char User[PR_MAXNAMELEN + 1];
2713 lids.idlist_len = 1;
2714 lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2715 if (!lids.idlist_val) {
2716 ViceLogThenPanic(0, ("Failed malloc in h_UserName\n"));
2718 lnames.namelist_len = 0;
2719 lnames.namelist_val = (prname *) 0;
2720 lids.idlist_val[0] = client->ViceId;
2721 if (hpr_IdToName(&lids, &lnames)) {
2722 /* We need to free id we alloced above! */
2723 free(lids.idlist_val);
2724 return "*UNKNOWN USER NAME*";
2726 strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2727 free(lids.idlist_val);
2728 free(lnames.namelist_val);
2737 ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2738 CEs, CEBlocks, HTs, HTBlocks));
2744 h_PrintClient(struct host *host, void *rock)
2746 StreamHandle_t *file = (StreamHandle_t *)rock;
2747 struct client *client;
2752 time_t LastCall, expTime;
2756 LastCall = host->LastCall;
2757 if (host->hostFlags & HOSTDELETED) {
2761 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2762 localtime_r(&LastCall, &tm));
2763 snprintf(tmpStr, sizeof tmpStr, "Host %s:%d down = %d, LastCall %s\n",
2764 afs_inet_ntoa_r(host->host, hoststr),
2765 ntohs(host->port), (host->hostFlags & VENUSDOWN),
2767 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2768 for (client = host->FirstClient; client; client = client->next) {
2769 if (!client->deleted) {
2770 expTime = client->expTime;
2771 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2772 localtime_r(&expTime, &tm));
2773 snprintf(tmpStr, sizeof tmpStr,
2774 " user id=%d, name=%s, sl=%s till %s\n",
2775 client->ViceId, h_UserName(client),
2776 client->authClass ? "Authenticated"
2777 : "Not authenticated",
2778 client->authClass ? tbuffer : "No Limit");
2779 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2780 snprintf(tmpStr, sizeof tmpStr, " CPS-%d is [",
2781 client->CPS.prlist_len);
2782 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2783 if (client->CPS.prlist_val) {
2784 for (i = 0; i < client->CPS.prlist_len; i++) {
2785 snprintf(tmpStr, sizeof tmpStr, " %d",
2786 client->CPS.prlist_val[i]);
2787 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2790 sprintf(tmpStr, "]\n");
2791 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2797 } /*h_PrintClient */
2802 * Print a list of clients, with last security level and token value seen,
2806 h_PrintClients(void)
2813 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2817 ("Couldn't create client dump file %s\n",
2818 AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2821 now = FT_ApproxTime();
2822 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2823 localtime_r(&now, &tm));
2824 snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n\n",
2826 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2827 h_Enumerate(h_PrintClient, (char *)file);
2828 STREAM_REALLYCLOSE(file);
2829 ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2836 h_DumpHost(struct host *host, void *rock)
2838 StreamHandle_t *file = (StreamHandle_t *)rock;
2845 snprintf(tmpStr, sizeof tmpStr,
2846 "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u "
2847 "down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u "
2849 afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
2850 host->index, host->cblist, CheckLock(&host->lock),
2851 host->LastCall, host->ActiveCall, (host->hostFlags & VENUSDOWN),
2852 host->hostFlags & HOSTDELETED, host->Console,
2853 host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2855 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2856 if (host->hcps.prlist_val)
2857 for (i = 0; i < host->hcps.prlist_len; i++) {
2858 snprintf(tmpStr, sizeof tmpStr, " %d", host->hcps.prlist_val[i]);
2859 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2861 sprintf(tmpStr, "] [");
2862 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2863 if (host->interface)
2864 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2866 sprintf(tmpStr, " %s:%d",
2867 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2868 ntohs(host->interface->interface[i].port));
2869 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2871 sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2872 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2884 StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2891 ("Couldn't create host dump file %s\n",
2892 AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2895 now = FT_ApproxTime();
2896 strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2897 localtime_r(&now, &tm));
2898 snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n\n", tbuffer);
2899 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2900 h_Enumerate(h_DumpHost, (char *)file);
2901 STREAM_REALLYCLOSE(file);
2902 ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2906 #ifdef AFS_DEMAND_ATTACH_FS
2909 * host state serialization
2911 static int h_stateFillHeader(struct host_state_header * hdr);
2912 static int h_stateCheckHeader(struct host_state_header * hdr);
2913 static int h_stateAllocMap(struct fs_dump_state * state);
2914 static int h_stateSaveHost(struct host * host, void *rock);
2915 static int h_stateRestoreHost(struct fs_dump_state * state);
2916 static int h_stateRestoreIndex(struct host * h, void *rock);
2917 static int h_stateVerifyHost(struct host * h, void *rock);
2918 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
2919 afs_uint32 addr, afs_uint16 port, int valid);
2920 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2921 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2922 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2925 /* this procedure saves all host state to disk for fast startup */
2927 h_stateSave(struct fs_dump_state * state)
2929 AssignInt64(state->eof_offset, &state->hdr->h_offset);
2932 ViceLog(0, ("h_stateSave: hostCount=%d\n", hostCount));
2934 /* invalidate host state header */
2935 memset(state->h_hdr, 0, sizeof(struct host_state_header));
2937 if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2938 sizeof(struct host_state_header))) {
2943 fs_stateIncEOF(state, sizeof(struct host_state_header));
2945 h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2950 h_stateFillHeader(state->h_hdr);
2952 /* write the real header to disk */
2953 state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2954 sizeof(struct host_state_header));
2961 * host state serialization
2963 * this procedure restores all host state from a disk for fast startup
2966 h_stateRestore(struct fs_dump_state * state)
2970 /* seek to the right position and read in the host state header */
2971 if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2972 sizeof(struct host_state_header))) {
2977 /* check the validity of the header */
2978 if (h_stateCheckHeader(state->h_hdr)) {
2983 records = state->h_hdr->records;
2985 if (h_stateAllocMap(state)) {
2990 /* iterate over records restoring host state */
2991 for (i=0; i < records; i++) {
2992 if (h_stateRestoreHost(state) != 0) {
3003 h_stateRestoreIndices(struct fs_dump_state * state)
3005 h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
3010 h_stateRestoreIndex(struct host * h, void *rock)
3012 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3013 if (cb_OldToNew(state, h->cblist, &h->cblist)) {
3014 return H_ENUMERATE_BAIL(0);
3020 h_stateVerify(struct fs_dump_state * state)
3022 h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
3027 h_stateVerifyHost(struct host * h, void* rock)
3029 struct fs_dump_state *state = (struct fs_dump_state *)rock;
3033 ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3034 return H_ENUMERATE_BAIL(0);
3038 for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
3039 if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
3040 h->interface->interface[i].port,
3041 h->interface->interface[i].valid)) {
3045 if (h_stateVerifyUuidHash(state, h)) {
3048 } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
3052 if (cb_stateVerifyHCBList(state, h)) {
3060 * verify a host is either in, or absent from, the addr hash table.
3062 * @param[in] state fs dump state
3063 * @param[in] h host we're dealing with
3064 * @param[in] addr addr to look for (NBO)
3065 * @param[in] port port to look for (NBO)
3066 * @param[in] valid 1 if we're verifying that the specified addr and port
3067 * in the hash table point to the specified host. 0 if we're
3068 * verifying that the specified addr and port do NOT point
3069 * to the specified host
3071 * @return operation status
3072 * @retval 1 failed to verify, bail out
3073 * @retval 0 verified successfully, all is well
3076 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3077 afs_uint32 addr, afs_uint16 port, int valid)
3079 int ret = 0, found = 0;
3080 struct host *host = NULL;
3081 struct h_AddrHashChain *chain;
3082 int index = h_HashIndex(addr);
3086 for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3087 host = chain->hostPtr;
3089 afs_inet_ntoa_r(addr, tmp);
3090 ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3094 if ((chain->addr == addr) && (chain->port == port)) {
3097 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3098 "points to different host struct (%d, %d)\n",
3099 h->index, host->index));
3100 state->flags.warnings_generated = 1;
3104 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3105 "marked invalid, but points to the containing "
3106 "host\n", afs_inet_ntoa_r(addr, tmp),
3107 (unsigned)htons(port)));
3115 if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3116 ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3117 FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3124 if (!found && valid) {
3125 afs_inet_ntoa_r(addr, tmp);
3126 if (state->mode == FS_STATE_LOAD_MODE) {
3127 ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3128 tmp, (unsigned)htons(port)));
3132 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3133 tmp, (unsigned)htons(port)));
3134 state->flags.warnings_generated = 1;
3143 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3145 int ret = 0, found = 0;
3146 struct host *host = NULL;
3147 struct h_UuidHashChain *chain;
3148 afsUUID * uuidp = &h->interface->uuid;
3149 int index = h_UuidHashIndex(uuidp);
3153 for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3154 host = chain->hostPtr;
3156 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3157 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3161 if (host->interface &&
3162 afs_uuid_equal(&host->interface->uuid, uuidp)) {
3164 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3165 h->index, host->index));
3166 state->flags.warnings_generated = 1;
3171 if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3172 ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3173 FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3181 afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3182 if (state->mode == FS_STATE_LOAD_MODE) {
3183 ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3187 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3188 state->flags.warnings_generated = 1;
3196 /* create the host state header structure */
3198 h_stateFillHeader(struct host_state_header * hdr)
3200 hdr->stamp.magic = HOST_STATE_MAGIC;
3201 hdr->stamp.version = HOST_STATE_VERSION;
3205 /* check the contents of the host state header structure */
3207 h_stateCheckHeader(struct host_state_header * hdr)
3211 if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3212 ViceLog(0, ("check_host_state_header: invalid state header\n"));
3215 else if (hdr->stamp.version != HOST_STATE_VERSION) {
3216 ViceLog(0, ("check_host_state_header: unknown version number\n"));
3222 /* allocate the host id mapping table */
3224 h_stateAllocMap(struct fs_dump_state * state)
3226 state->h_map.len = state->h_hdr->index_max + 1;
3227 state->h_map.entries = (struct idx_map_entry_t *)
3228 calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3229 return (state->h_map.entries != NULL) ? 0 : 1;
3232 /* function called by h_Enumerate to save a host to disk */
3234 h_stateSaveHost(struct host * host, void* rock)
3236 struct fs_dump_state *state = (struct fs_dump_state *) rock;
3237 int if_len=0, hcps_len=0;
3238 struct hostDiskEntry hdsk;
3239 struct host_state_entry_header hdr;
3240 struct Interface * ifp = NULL;
3241 afs_int32 * hcps = NULL;
3242 struct iovec iov[4];
3245 memset(&hdr, 0, sizeof(hdr));
3247 if (state->h_hdr->index_max < host->index) {
3248 state->h_hdr->index_max = host->index;
3251 h_hostToDiskEntry_r(host, &hdsk);
3252 if (host->interface) {
3253 if_len = sizeof(struct Interface) +
3254 ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3255 ifp = (struct Interface *) malloc(if_len);
3256 osi_Assert(ifp != NULL);
3257 memcpy(ifp, host->interface, if_len);
3258 hdr.interfaces = host->interface->numberOfInterfaces;
3259 iov[iovcnt].iov_base = (char *) ifp;
3260 iov[iovcnt].iov_len = if_len;
3263 if (host->hcps.prlist_val) {
3264 hdr.hcps = host->hcps.prlist_len;
3265 hcps_len = hdr.hcps * sizeof(afs_int32);
3266 hcps = (afs_int32 *) malloc(hcps_len);
3267 osi_Assert(hcps != NULL);
3268 memcpy(hcps, host->hcps.prlist_val, hcps_len);
3269 iov[iovcnt].iov_base = (char *) hcps;
3270 iov[iovcnt].iov_len = hcps_len;
3274 if (hdsk.index > state->h_hdr->index_max)
3275 state->h_hdr->index_max = hdsk.index;
3277 hdr.len = sizeof(struct host_state_entry_header) +
3278 sizeof(struct hostDiskEntry) + if_len + hcps_len;
3279 hdr.magic = HOST_STATE_ENTRY_MAGIC;
3281 iov[0].iov_base = (char *) &hdr;
3282 iov[0].iov_len = sizeof(hdr);
3283 iov[1].iov_base = (char *) &hdsk;
3284 iov[1].iov_len = sizeof(struct hostDiskEntry);
3286 if (fs_stateWriteV(state, iov, iovcnt)) {
3287 ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3291 fs_stateIncEOF(state, hdr.len);
3293 state->h_hdr->records++;
3300 return H_ENUMERATE_BAIL(0);
3305 /* restores a host from disk */
3307 h_stateRestoreHost(struct fs_dump_state * state)
3309 int ifp_len=0, hcps_len=0, bail=0;
3310 struct host_state_entry_header hdr;
3311 struct hostDiskEntry hdsk;
3312 struct host *host = NULL;
3313 struct Interface *ifp = NULL;
3314 afs_int32 * hcps = NULL;
3315 struct iovec iov[3];
3318 if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3319 ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3325 if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3326 ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3332 iov[0].iov_base = (char *) &hdsk;
3333 iov[0].iov_len = sizeof(struct hostDiskEntry);
3335 if (hdr.interfaces) {
3336 ifp_len = sizeof(struct Interface) +
3337 ((hdr.interfaces-1) * sizeof(struct AddrPort));
3338 ifp = (struct Interface *) malloc(ifp_len);
3339 osi_Assert(ifp != NULL);
3340 iov[iovcnt].iov_base = (char *) ifp;
3341 iov[iovcnt].iov_len = ifp_len;
3345 hcps_len = hdr.hcps * sizeof(afs_int32);
3346 hcps = (afs_int32 *) malloc(hcps_len);
3347 osi_Assert(hcps != NULL);
3348 iov[iovcnt].iov_base = (char *) hcps;
3349 iov[iovcnt].iov_len = hcps_len;
3353 if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3354 ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3359 if (fs_stateReadV(state, iov, iovcnt)) {
3360 ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3365 if (!hdr.hcps && hdsk.hcps_valid) {
3366 /* valid, zero-length host cps ; does this ever happen? */
3367 hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3368 osi_Assert(hcps != NULL);
3371 /* for restoring state, we better be able to get a host! */
3373 osi_Assert(host != NULL);
3376 host->interface = ifp;
3379 host->hcps.prlist_val = hcps;
3380 host->hcps.prlist_len = hdr.hcps;
3383 h_diskEntryToHost_r(&hdsk, host);
3384 h_SetupCallbackConn_r(host);
3386 h_AddHostToAddrHashTable_r(host->host, host->port, host);
3389 for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3390 if (ifp->interface[i].valid &&
3391 !(ifp->interface[i].addr == host->host &&
3392 ifp->interface[i].port == host->port)) {
3393 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3394 ifp->interface[i].port,
3398 h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3400 h_InsertList_r(host);
3402 /* setup host id map entry */
3403 state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3404 state->h_map.entries[hdsk.index].new_idx = host->index;
3416 /* serialize a host structure to disk */
3418 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3420 out->host = in->host;
3421 out->port = in->port;
3422 out->hostFlags = in->hostFlags;
3423 out->Console = in->Console;
3424 out->hcpsfailed = in->hcpsfailed;
3425 out->LastCall = in->LastCall;
3426 out->ActiveCall = in->ActiveCall;
3427 out->cpsCall = in->cpsCall;
3428 out->cblist = in->cblist;
3429 #ifdef FS_STATS_DETAILED
3430 out->InSameNetwork = in->InSameNetwork;
3433 /* special fields we save, but are not memcpy'd back on restore */
3434 out->index = in->index;
3435 out->hcps_len = in->hcps.prlist_len;
3436 out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3439 /* restore a host structure from disk */
3441 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3443 out->host = in->host;
3444 out->port = in->port;
3445 out->hostFlags = in->hostFlags;
3446 out->Console = in->Console;
3447 out->hcpsfailed = in->hcpsfailed;
3448 out->LastCall = in->LastCall;
3449 out->ActiveCall = in->ActiveCall;
3450 out->cpsCall = in->cpsCall;
3451 out->cblist = in->cblist;
3452 #ifdef FS_STATS_DETAILED
3453 out->InSameNetwork = in->InSameNetwork;
3457 /* index translation routines */
3459 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3463 /* hosts use a zero-based index, so old==0 is valid */
3465 if (old >= state->h_map.len) {
3466 ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3468 } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
3469 ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3472 *new = state->h_map.entries[old].new_idx;
3477 #endif /* AFS_DEMAND_ATTACH_FS */
3481 * This counts the number of workstations, the number of active workstations,
3482 * and the number of workstations declared "down" (i.e. not heard from
3483 * recently). An active workstation has received a call since the cutoff
3484 * time argument passed.
3487 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3490 int num = 0, active = 0, del = 0;
3494 for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3495 if (!(host->hostFlags & HOSTDELETED)) {
3497 if (host->ActiveCall > cutofftime)
3499 if (host->hostFlags & VENUSDOWN)
3503 if (count != hostCount) {
3504 ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3505 } else if (host != NULL) {
3506 ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3507 ShutDownAndCore(PANIC);
3517 } /*h_GetWorkStats */
3520 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp,
3521 afs_int32 cutofftime)
3523 int num, active, del;
3524 h_GetWorkStats(&num, &active, &del, cutofftime);
3533 /*------------------------------------------------------------------------
3534 * PRIVATE h_ClassifyAddress
3537 * Given a target IP address and a candidate IP address (both
3538 * in host byte order), classify the candidate into one of three
3539 * buckets in relation to the target by bumping the counters passed
3543 * a_targetAddr : Target address.
3544 * a_candAddr : Candidate address.
3545 * a_sameNetOrSubnetP : Ptr to counter to bump when the two
3546 * addresses are either in the same network
3547 * or the same subnet.
3548 * a_diffSubnetP : ...when the candidate is in a different
3550 * a_diffNetworkP : ...when the candidate is in a different
3557 * The target and candidate addresses are both in host byte
3558 * order, NOT network byte order, when passed in.
3562 *------------------------------------------------------------------------*/
3565 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3566 afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3567 afs_int32 * a_diffNetworkP)
3568 { /*h_ClassifyAddress */
3570 afs_uint32 targetNet;
3571 afs_uint32 targetSubnet;
3573 afs_uint32 candSubnet;
3576 * Put bad values into the subnet info to start with.
3578 targetSubnet = (afs_uint32) 0;
3579 candSubnet = (afs_uint32) 0;
3582 * Pull out the network and subnetwork numbers from the target
3583 * and candidate addresses. We can short-circuit this whole
3584 * affair if the target and candidate addresses are not of the
3587 if (IN_CLASSA(a_targetAddr)) {
3588 if (!(IN_CLASSA(a_candAddr))) {
3589 (*a_diffNetworkP)++;
3592 targetNet = a_targetAddr & IN_CLASSA_NET;
3593 candNet = a_candAddr & IN_CLASSA_NET;
3594 if (IN_SUBNETA(a_targetAddr))
3595 targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3596 if (IN_SUBNETA(a_candAddr))
3597 candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3598 } else if (IN_CLASSB(a_targetAddr)) {
3599 if (!(IN_CLASSB(a_candAddr))) {
3600 (*a_diffNetworkP)++;
3603 targetNet = a_targetAddr & IN_CLASSB_NET;
3604 candNet = a_candAddr & IN_CLASSB_NET;
3605 if (IN_SUBNETB(a_targetAddr))
3606 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3607 if (IN_SUBNETB(a_candAddr))
3608 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3609 } /*Class B target */
3610 else if (IN_CLASSC(a_targetAddr)) {
3611 if (!(IN_CLASSC(a_candAddr))) {
3612 (*a_diffNetworkP)++;
3615 targetNet = a_targetAddr & IN_CLASSC_NET;
3616 candNet = a_candAddr & IN_CLASSC_NET;
3619 * Note that class C addresses can't have subnets,
3620 * so we leave the defaults untouched.
3622 } /*Class C target */
3624 targetNet = a_targetAddr;
3625 candNet = a_candAddr;
3626 } /*Class D address */
3629 * Now, simply compare the extracted net and subnet values for
3630 * the two addresses (which at this point are known to be of the
3633 if (targetNet == candNet) {
3634 if (targetSubnet == candSubnet)
3635 (*a_sameNetOrSubnetP)++;
3639 (*a_diffNetworkP)++;
3641 } /*h_ClassifyAddress */
3644 /*------------------------------------------------------------------------
3645 * EXPORTED h_GetHostNetStats
3648 * Iterate through the host table, and classify each (non-deleted)
3649 * host entry into ``proximity'' categories (same net or subnet,
3650 * different subnet, different network).
3653 * a_numHostsP : Set to total number of (non-deleted) hosts.
3654 * a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3655 * a_diffSubnetP : Set to # hosts on diff subnet as server.
3656 * a_diffNetworkP : Set to # hosts on diff network as server.
3662 * We only count non-deleted hosts. The storage pointed to by our
3663 * parameters is zeroed upon entry.
3667 *------------------------------------------------------------------------*/
3670 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3671 afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3672 { /*h_GetHostNetStats */
3674 struct host *hostP; /*Ptr to current host entry */
3675 afs_uint32 currAddr_HBO; /*Curr host addr, host byte order */
3679 * Clear out the storage pointed to by our parameters.
3681 *a_numHostsP = (afs_int32) 0;
3682 *a_sameNetOrSubnetP = (afs_int32) 0;
3683 *a_diffSubnetP = (afs_int32) 0;
3684 *a_diffNetworkP = (afs_int32) 0;
3687 for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3688 if (!(hostP->hostFlags & HOSTDELETED)) {
3690 * Bump the number of undeleted host entries found.
3691 * In classifying the current entry's address, make
3692 * sure to first convert to host byte order.
3695 currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3696 h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3697 a_sameNetOrSubnetP, a_diffSubnetP,
3699 } /*Only look at non-deleted hosts */
3700 } /*For each host record hashed to this index */
3701 if (count != hostCount) {
3702 ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3703 } else if (hostP != NULL) {
3704 ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3705 ShutDownAndCore(PANIC);
3708 } /*h_GetHostNetStats */
3710 static afs_uint32 checktime;
3711 static afs_uint32 clientdeletetime;
3712 static struct AFSFid zerofid;
3716 * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3717 * Since it can serialize them, and pile up, it should be a separate LWP
3718 * from other events.
3722 CheckHost(struct host *host, int flags, void *rock)
3724 struct client *client;
3725 struct rx_connection *cb_conn = NULL;
3728 #ifdef AFS_DEMAND_ATTACH_FS
3729 /* kill the checkhost lwp ASAP during shutdown */
3731 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3733 return H_ENUMERATE_BAIL(flags);
3738 /* Host is held by h_Enumerate */
3740 for (client = host->FirstClient; client; client = client->next) {
3741 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3742 client->deleted = 1;
3743 host->hostFlags |= CLIENTDELETED;
3746 if (host->LastCall < checktime) {
3748 if (!(host->hostFlags & HOSTDELETED)) {
3749 host->hostFlags |= HWHO_INPROGRESS;
3750 cb_conn = host->callback_rxcon;
3751 rx_GetConnection(cb_conn);
3752 if (host->LastCall < clientdeletetime) {
3753 host->hostFlags |= HOSTDELETED;
3754 if (!(host->hostFlags & VENUSDOWN)) {
3755 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3756 if (host->interface) {
3759 RXAFSCB_InitCallBackState3(cb_conn,
3765 RXAFSCB_InitCallBackState(cb_conn);
3768 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3771 (void)afs_inet_ntoa_r(host->host, hoststr);
3773 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3774 hoststr, ntohs(host->port)));
3775 host->hostFlags |= VENUSDOWN;
3777 /* Note: it's safe to delete hosts even if they have call
3778 * back state, because break delayed callbacks (called when a
3779 * message is received from the workstation) will always send a
3780 * break all call backs to the workstation if there is no
3785 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3787 (void)afs_inet_ntoa_r(host->host, hoststr);
3788 if (host->interface) {
3789 afsUUID uuid = host->interface->uuid;
3791 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3794 if (MultiProbeAlternateAddress_r(host)) {
3795 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3796 hoststr, ntohs(host->port), code));
3797 host->hostFlags |= VENUSDOWN;
3802 code = RXAFSCB_Probe(cb_conn);
3806 ("CheckHost: Probe failed for host %s:%d, code %d\n",
3807 hoststr, ntohs(host->port), code));
3808 host->hostFlags |= VENUSDOWN;
3814 rx_PutConnection(cb_conn);
3817 host->hostFlags &= ~HWHO_INPROGRESS;
3828 CheckHost_r(struct host *host, void *dummy)
3830 struct client *client;
3831 struct rx_connection *cb_conn = NULL;
3834 #ifdef AFS_DEMAND_ATTACH_FS
3835 /* kill the checkhost lwp ASAP during shutdown */
3837 if (fs_state.mode == FS_MODE_SHUTDOWN) {
3839 return H_ENUMERATE_BAIL(0);
3844 /* Host is held by h_Enumerate_r */
3845 for (client = host->FirstClient; client; client = client->next) {
3846 if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3847 client->deleted = 1;
3848 host->hostFlags |= CLIENTDELETED;
3851 if (host->LastCall < checktime) {
3853 if (!(host->hostFlags & HOSTDELETED)) {
3854 host->hostFlags |= HWHO_INPROGRESS;
3855 cb_conn = host->callback_rxcon;
3856 rx_GetConnection(cb_conn);
3857 if (host->LastCall < clientdeletetime) {
3858 host->hostFlags |= HOSTDELETED;
3859 if (!(host->hostFlags & VENUSDOWN)) {
3860 host->hostFlags &= ~ALTADDR; /* alternate address invalid */
3861 if (host->interface) {
3864 RXAFSCB_InitCallBackState3(cb_conn,
3870 RXAFSCB_InitCallBackState(cb_conn);
3873 host->hostFlags |= ALTADDR; /* alternate addresses valid */
3876 (void)afs_inet_ntoa_r(host->host, hoststr);
3878 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3879 hoststr, ntohs(host->port)));
3880 host->hostFlags |= VENUSDOWN;
3882 /* Note: it's safe to delete hosts even if they have call
3883 * back state, because break delayed callbacks (called when a
3884 * message is received from the workstation) will always send a
3885 * break all call backs to the workstation if there is no
3890 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3892 (void)afs_inet_ntoa_r(host->host, hoststr);
3893 if (host->interface) {
3894 afsUUID uuid = host->interface->uuid;
3896 code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3899 if (MultiProbeAlternateAddress_r(host)) {
3900 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3901 hoststr, ntohs(host->port), code));
3902 host->hostFlags |= VENUSDOWN;
3907 code = RXAFSCB_Probe(cb_conn);
3911 ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3912 hoststr, ntohs(host->port), code));
3913 host->hostFlags |= VENUSDOWN;
3919 rx_PutConnection(cb_conn);
3922 host->hostFlags &= ~HWHO_INPROGRESS;
3932 * Set VenusDown for any hosts that have not had a call in 15 minutes and
3933 * don't respond to a probe. Note that VenusDown can only be cleared if
3934 * a message is received from the host (see ServerLWP in file.c).
3935 * Delete hosts that have not had any calls in 1 hour, clients that
3936 * have not had any calls in 15 minutes.
3938 * This routine is called roughly every 5 minutes.
3943 afs_uint32 now = FT_ApproxTime();
3945 memset(&zerofid, 0, sizeof(zerofid));
3947 * Send a probe to the workstation if it hasn't been heard from in
3950 checktime = now - 15 * 60;
3951 clientdeletetime = now - 120 * 60; /* 2 hours ago */
3954 h_Enumerate_r(CheckHost_r, hostList, NULL);
3959 * This is called with host locked and held. At this point, the
3960 * hostAddrHashTable has an entry for the primary addr/port inserted
3961 * by h_Alloc_r(). No other interfaces should be considered valid.
3963 * The addresses in the interfaceAddr list are in host byte order.
3966 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3973 struct Interface *interface;
3976 afs_uint16 port7001 = htons(7001);
3981 number = interf->numberOfInterfaces;
3982 myAddr = host->host; /* current interface address */
3983 myPort = host->port; /* current port */
3986 ("initInterfaceAddr : host %s:%d numAddr %d\n",
3987 afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3989 /* validation checks */
3990 if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3992 ("Invalid number of alternate addresses is %d\n", number));
3997 * The client's notion of its own IP addresses is not reliable.
3999 * 1. The client list might contain private address ranges which
4000 * are likely to be re-used by many clients allocated addresses
4003 * 2. The client list will not include any public addresses that
4004 * are hidden by a NAT.
4006 * 3. Private address ranges that are exposed to the server will
4007 * be obtained from the rx connections that use them.
4009 * 4. Lists provided by the client are not necessarily truthful.
4010 * Many existing clients (UNIX) do not refresh the IP address
4011 * list as the actual assigned addresses change. The end result
4012 * is that they report the initial address list for the lifetime
4013 * of the process. In other words, a client can report addresses
4014 * that they are in fact not using. Adding these addresses to
4015 * the host interface list without verification is not only
4016 * pointless, it is downright dangerous.
4018 * We therefore do not add alternate addresses to the addr hash table.
4019 * We only use them for multi-rx callback breaks.
4023 * Convert IP addresses to network byte order, and remove
4024 * duplicate IP addresses from the interface list, and
4025 * determine whether or not the incoming addr/port is
4026 * listed. Note that if the address matches it is not
4027 * truly a match because the port number for the entries
4028 * in the interface list are port 7001 and the port number
4029 * for this connection might not be 7001.
4031 for (i = 0, count = 0, found = 0; i < number; i++) {
4032 interf->addr_in[i] = htonl(interf->addr_in[i]);
4033 for (j = 0; j < count; j++) {
4034 if (interf->addr_in[j] == interf->addr_in[i])
4038 interf->addr_in[count] = interf->addr_in[i];
4039 if (interf->addr_in[count] == myAddr &&
4047 * Allocate and initialize an interface structure for this host.
4050 interface = (struct Interface *)
4051 malloc(sizeof(struct Interface) +
4052 (sizeof(struct AddrPort) * (count - 1)));
4054 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
4056 interface->numberOfInterfaces = count;
4058 interface = (struct Interface *)
4059 malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
4061 ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4063 interface->numberOfInterfaces = count + 1;
4064 interface->interface[count].addr = myAddr;
4065 interface->interface[count].port = myPort;
4066 interface->interface[count].valid = 1;
4069 for (i = 0; i < count; i++) {
4071 interface->interface[i].addr = interf->addr_in[i];
4072 /* We store the port as 7001 because the addresses reported by
4073 * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4074 * are coming from fully connected hosts (no NAT/PATs)
4076 interface->interface[i].port = port7001;
4077 interface->interface[i].valid =
4078 (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4081 interface->uuid = interf->uuid;
4083 osi_Assert(!host->interface);
4084 host->interface = interface;
4086 if (LogLevel >= 125) {
4087 afsUUID_to_string(&interface->uuid, uuidstr, 127);
4089 ViceLog(125, ("--- uuid %s\n", uuidstr));
4090 for (i = 0; i < host->interface->numberOfInterfaces; i++) {
4091 ViceLog(125, ("--- alt address %s:%d\n",
4092 afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4093 ntohs(host->interface->interface[i].port)));
4100 /* deleted a HashChain structure for this address and host */
4101 /* returns 1 on success */
4103 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4107 struct h_AddrHashChain **hp, *th;
4109 if (addr == 0 && port == 0)
4112 for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4114 osi_Assert(th->hostPtr);
4115 if (th->hostPtr == host && th->addr == addr && th->port == port) {
4116 ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4117 host, afs_inet_ntoa_r(host->host, hoststr),
4118 ntohs(host->port)));
4125 ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4126 host, afs_inet_ntoa_r(host->host, hoststr),
4127 ntohs(host->port)));
4133 ** prints out all alternate interface address for the host. The 'level'
4134 ** parameter indicates what level of debugging sets this output
4137 printInterfaceAddr(struct host *host, int level)
4142 if (host->interface) {
4143 /* check alternate addresses */
4144 number = host->interface->numberOfInterfaces;
4146 ViceLog(level, ("no-addresses "));
4148 for (i = 0; i < number; i++)
4149 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4150 ntohs(host->interface->interface[i].port)));
4153 ViceLog(level, ("\n"));