viced: fix missing host lock in h_Enumerate
[openafs.git] / src / viced / host.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
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
8  *
9  * Portions Copyright (c) 2006 Sine Nomine Associates
10  */
11
12 #include <afsconfig.h>
13 #include <afs/param.h>
14
15
16 #include <stdio.h>
17 #include <errno.h>
18 #include <string.h>
19 #ifdef AFS_NT40_ENV
20 #include <fcntl.h>
21 #include <winsock2.h>
22 #else
23 #include <sys/file.h>
24 #include <netdb.h>
25 #include <netinet/in.h>
26 #endif
27
28 #include <afs/stds.h>
29 #include <rx/xdr.h>
30 #include <afs/afs_assert.h>
31 #include <lwp.h>
32 #include <lock.h>
33 #include <afs/afsint.h>
34 #define FSINT_COMMON_XG
35 #include <afs/afscbint.h>
36 #include <afs/rxgen_consts.h>
37 #include <afs/nfs.h>
38 #include <afs/errors.h>
39 #include <afs/ihandle.h>
40 #include <afs/vnode.h>
41 #include <afs/volume.h>
42 #ifdef AFS_ATHENA_STDENV
43 #include <krb.h>
44 #endif
45 #include <afs/acl.h>
46 #include <afs/ptclient.h>
47 #include <afs/ptuser.h>
48 #include <afs/prs_fs.h>
49 #include <afs/auth.h>
50 #include <afs/afsutil.h>
51 #include <afs/com_err.h>
52 #include <rx/rx.h>
53 #include <afs/cellconfig.h>
54 #include <stdlib.h>
55 #include "viced_prototypes.h"
56 #include "viced.h"
57 #include "host.h"
58 #include "callback.h"
59 #ifdef AFS_DEMAND_ATTACH_FS
60 #include "../util/afsutil_prototypes.h"
61 #include "../tviced/serialize_state.h"
62 #endif /* AFS_DEMAND_ATTACH_FS */
63
64 #ifdef AFS_PTHREAD_ENV
65 pthread_mutex_t host_glock_mutex;
66 #endif /* AFS_PTHREAD_ENV */
67
68 extern int Console;
69 extern int CurrentConnections;
70 extern int SystemId;
71 extern int AnonymousID;
72 extern prlist AnonCPS;
73 extern int LogLevel;
74 extern struct afsconf_dir *confDir;     /* config dir object */
75 extern int lwps;                /* the max number of server threads */
76 extern afsUUID FS_HostUUID;
77
78 afsUUID nulluuid;
79 int CEs = 0;                    /* active clients */
80 int CEBlocks = 0;               /* number of blocks of CEs */
81 struct client *CEFree = 0;      /* first free client */
82 struct host *hostList = 0;      /* linked list of all hosts */
83 int hostCount = 0;              /* number of hosts in hostList */
84 int rxcon_ident_key;
85 int rxcon_client_key;
86
87 static struct rx_securityClass *sc = NULL;
88
89 static void h_SetupCallbackConn_r(struct host * host);
90 static int h_threadquota(int);
91
92 #define CESPERBLOCK 73
93 struct CEBlock {                /* block of CESPERBLOCK file entries */
94     struct client entry[CESPERBLOCK];
95 };
96
97 void h_TossStuff_r(struct host *host);
98
99 /*
100  * Make sure the subnet macros have been defined.
101  */
102 #ifndef IN_SUBNETA
103 #define IN_SUBNETA(i)           ((((afs_int32)(i))&0x80800000)==0x00800000)
104 #endif
105
106 #ifndef IN_CLASSA_SUBNET
107 #define IN_CLASSA_SUBNET        0xffff0000
108 #endif
109
110 #ifndef IN_SUBNETB
111 #define IN_SUBNETB(i)           ((((afs_int32)(i))&0xc0008000)==0x80008000)
112 #endif
113
114 #ifndef IN_CLASSB_SUBNET
115 #define IN_CLASSB_SUBNET        0xffffff00
116 #endif
117
118
119 /* get a new block of CEs and chain it on CEFree */
120 static void
121 GetCEBlock(void)
122 {
123     struct CEBlock *block;
124     int i;
125
126     block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
127     if (!block) {
128         ViceLog(0, ("Failed malloc in GetCEBlock\n"));
129         ShutDownAndCore(PANIC);
130     }
131
132     for (i = 0; i < (CESPERBLOCK - 1); i++) {
133         Lock_Init(&block->entry[i].lock);
134         block->entry[i].next = &(block->entry[i + 1]);
135     }
136     block->entry[CESPERBLOCK - 1].next = 0;
137     Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
138     CEFree = (struct client *)block;
139     CEBlocks++;
140
141 }                               /*GetCEBlock */
142
143
144 /* get the next available CE */
145 static struct client *
146 GetCE(void)
147 {
148     struct client *entry;
149
150     if (CEFree == 0)
151         GetCEBlock();
152     if (CEFree == 0) {
153         ViceLog(0, ("CEFree NULL in GetCE\n"));
154         ShutDownAndCore(PANIC);
155     }
156
157     entry = CEFree;
158     CEFree = entry->next;
159     CEs++;
160     memset(entry, 0, CLIENT_TO_ZERO(entry));
161     return (entry);
162
163 }                               /*GetCE */
164
165
166 /* return an entry to the free list */
167 static void
168 FreeCE(struct client *entry)
169 {
170     entry->VenusEpoch = 0;
171     entry->sid = 0;
172     entry->next = CEFree;
173     CEFree = entry;
174     CEs--;
175
176 }                               /*FreeCE */
177
178 /*
179  * The HTs and HTBlocks variables were formerly static, but they are
180  * now referenced elsewhere in the FileServer.
181  */
182 int HTs = 0;                    /* active file entries */
183 int HTBlocks = 0;               /* number of blocks of HTs */
184 static struct host *HTFree = 0; /* first free file entry */
185
186 /*
187  * Hash tables of host pointers. We need two tables, one
188  * to map IP addresses onto host pointers, and another
189  * to map host UUIDs onto host pointers.
190  */
191 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
192 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
193 #define h_HashIndex(hostip) (ntohl(hostip) & (h_HASHENTRIES-1))
194 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
195
196 struct HTBlock {                /* block of HTSPERBLOCK file entries */
197     struct host entry[h_HTSPERBLOCK];
198 };
199
200
201 /* get a new block of HTs and chain it on HTFree */
202 static void
203 GetHTBlock(void)
204 {
205     struct HTBlock *block;
206     int i;
207     static int index = 0;
208
209     if (HTBlocks == h_MAXHOSTTABLES) {
210         ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
211         ShutDownAndCore(PANIC);
212     }
213
214     block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
215     if (!block) {
216         ViceLog(0, ("Failed malloc in GetHTBlock\n"));
217         ShutDownAndCore(PANIC);
218     }
219 #ifdef AFS_PTHREAD_ENV
220     for (i = 0; i < (h_HTSPERBLOCK); i++)
221         CV_INIT(&block->entry[i].cond, "block entry", CV_DEFAULT, 0);
222 #endif /* AFS_PTHREAD_ENV */
223     for (i = 0; i < (h_HTSPERBLOCK); i++)
224         Lock_Init(&block->entry[i].lock);
225     for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
226         block->entry[i].next = &(block->entry[i + 1]);
227     for (i = 0; i < (h_HTSPERBLOCK); i++)
228         block->entry[i].index = index++;
229     block->entry[h_HTSPERBLOCK - 1].next = 0;
230     HTFree = (struct host *)block;
231     hosttableptrs[HTBlocks++] = block->entry;
232
233 }                               /*GetHTBlock */
234
235
236 /* get the next available HT */
237 static struct host *
238 GetHT(void)
239 {
240     struct host *entry;
241
242     if (HTFree == NULL)
243         GetHTBlock();
244     osi_Assert(HTFree != NULL);
245     entry = HTFree;
246     HTFree = entry->next;
247     HTs++;
248     memset(entry, 0, HOST_TO_ZERO(entry));
249     return (entry);
250
251 }                               /*GetHT */
252
253
254 /* return an entry to the free list */
255 static void
256 FreeHT(struct host *entry)
257 {
258     entry->next = HTFree;
259     HTFree = entry;
260     HTs--;
261
262 }                               /*FreeHT */
263
264 afs_int32
265 hpr_Initialize(struct ubik_client **uclient)
266 {
267     afs_int32 code;
268     struct rx_connection *serverconns[MAXSERVERS];
269     struct rx_securityClass *sc;
270     struct afsconf_dir *tdir;
271     afs_int32 scIndex;
272     struct afsconf_cell info;
273     afs_int32 i;
274     char cellstr[64];
275
276     tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
277     if (!tdir) {
278         ViceLog(0, ("hpr_Initialize: Could not open configuration directory: %s", AFSDIR_SERVER_ETC_DIRPATH));
279         return -1;
280     }
281
282     code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
283     if (code) {
284         ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]", code));
285         afsconf_Close(tdir);
286         return code;
287     }
288
289     code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
290     if (code) {
291         ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s",
292                     cellstr, confDir->name, AFSDIR_CELLSERVDB_FILE));
293         afsconf_Close(tdir);
294         return code;
295     }
296
297     code = rx_Init(0);
298     if (code) {
299         ViceLog(0, ("hpr_Initialize: Could not initialize rx."));
300         afsconf_Close(tdir);
301         return code;
302     }
303
304     /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
305      * to force use of the KeyFile.  secLevel == 0 implies -noauth was
306      * specified. */
307     if ((afsconf_GetLatestKey(tdir, 0, 0) == 0)) {
308         code = afsconf_ClientAuthSecure(tdir, &sc, &scIndex);
309         if (code)
310             ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s (so trying noauth)", code, afs_error_message(code)));
311         if (code)
312             scIndex = RX_SECIDX_NULL;
313     }
314     if ((scIndex == RX_SECIDX_NULL) && (sc == NULL))
315         sc = rxnull_NewClientSecurityObject();
316     if (scIndex == RX_SECIDX_NULL)
317         ViceLog(0, ("hpr_Initialize: Could not get afs tokens, running unauthenticated. [%d]", code));
318
319     memset(serverconns, 0, sizeof(serverconns));        /* terminate list!!! */
320     for (i = 0; i < info.numServers; i++) {
321         serverconns[i] =
322             rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
323                              info.hostAddr[i].sin_port, PRSRV,
324                              sc, scIndex);
325     }
326
327     code = ubik_ClientInit(serverconns, uclient);
328     if (code) {
329         ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]", code));
330     }
331     afsconf_Close(tdir);
332     code = rxs_Release(sc);
333     return code;
334 }
335
336 int
337 hpr_End(struct ubik_client *uclient)
338 {
339     int code = 0;
340
341     if (uclient) {
342         code = ubik_ClientDestroy(uclient);
343     }
344     return code;
345 }
346
347 int
348 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
349 {
350 #ifdef AFS_PTHREAD_ENV
351     afs_int32 code;
352     afs_int32 over;
353     struct ubik_client *uclient =
354         (struct ubik_client *)pthread_getspecific(viced_uclient_key);
355
356     if (!uclient) {
357         code = hpr_Initialize(&uclient);
358         if (!code)
359             osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
360         else
361             return code;
362     }
363
364     over = 0;
365     code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
366     if (code != PRSUCCESS)
367         return code;
368     if (over) {
369       /* do something about this, probably make a new call */
370       /* don't forget there's a hard limit in the interface */
371         fprintf(stderr,
372                 "membership list for host id %d exceeds display limit\n",
373                 host);
374     }
375     return 0;
376 #else
377     return pr_GetHostCPS(host, CPS);
378 #endif
379 }
380
381 int
382 hpr_NameToId(namelist *names, idlist *ids)
383 {
384 #ifdef AFS_PTHREAD_ENV
385     afs_int32 code;
386     afs_int32 i;
387     struct ubik_client *uclient =
388         (struct ubik_client *)pthread_getspecific(viced_uclient_key);
389
390     if (!uclient) {
391         code = hpr_Initialize(&uclient);
392         if (!code)
393             osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
394         else
395             return code;
396     }
397
398     for (i = 0; i < names->namelist_len; i++)
399         stolower(names->namelist_val[i]);
400     code = ubik_PR_NameToID(uclient, 0, names, ids);
401     return code;
402 #else
403     return pr_NameToId(names, ids);
404 #endif
405 }
406
407 int
408 hpr_IdToName(idlist *ids, namelist *names)
409 {
410 #ifdef AFS_PTHREAD_ENV
411     afs_int32 code;
412     struct ubik_client *uclient =
413         (struct ubik_client *)pthread_getspecific(viced_uclient_key);
414
415     if (!uclient) {
416         code = hpr_Initialize(&uclient);
417         if (!code)
418             osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
419         else
420             return code;
421     }
422
423     code = ubik_PR_IDToName(uclient, 0, ids, names);
424     return code;
425 #else
426     return pr_IdToName(ids, names);
427 #endif
428 }
429
430 int
431 hpr_GetCPS(afs_int32 id, prlist *CPS)
432 {
433 #ifdef AFS_PTHREAD_ENV
434     afs_int32 code;
435     afs_int32 over;
436     struct ubik_client *uclient =
437         (struct ubik_client *)pthread_getspecific(viced_uclient_key);
438
439     if (!uclient) {
440         code = hpr_Initialize(&uclient);
441         if (!code)
442             osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
443         else
444             return code;
445     }
446
447     over = 0;
448     code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
449     if (code != PRSUCCESS)
450         return code;
451     if (over) {
452       /* do something about this, probably make a new call */
453       /* don't forget there's a hard limit in the interface */
454         fprintf(stderr, "membership list for id %d exceeds display limit\n",
455                 id);
456     }
457     return 0;
458 #else
459     return pr_GetCPS(id, CPS);
460 #endif
461 }
462
463 static short consolePort = 0;
464
465 int
466 h_Lock_r(struct host *host)
467 {
468     H_UNLOCK;
469     h_Lock(host);
470     H_LOCK;
471     return 0;
472 }
473
474 /**
475   * Non-blocking lock
476   * returns 1 if already locked
477   * else returns locks and returns 0
478   */
479
480 int
481 h_NBLock_r(struct host *host)
482 {
483     struct Lock *hostLock = &host->lock;
484     int locked = 0;
485
486     H_UNLOCK;
487     LOCK_LOCK(hostLock);
488     if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
489         hostLock->excl_locked = WRITE_LOCK;
490     else
491         locked = 1;
492
493     LOCK_UNLOCK(hostLock);
494     H_LOCK;
495     if (locked)
496         return 1;
497     else
498         return 0;
499 }
500
501
502 #if FS_STATS_DETAILED
503 /*------------------------------------------------------------------------
504  * PRIVATE h_AddrInSameNetwork
505  *
506  * Description:
507  *      Given a target IP address and a candidate IP address (both
508  *      in host byte order), return a non-zero value (1) if the
509  *      candidate address is in a different network from the target
510  *      address.
511  *
512  * Arguments:
513  *      a_targetAddr       : Target address.
514  *      a_candAddr         : Candidate address.
515  *
516  * Returns:
517  *      1 if the candidate address is in the same net as the target,
518  *      0 otherwise.
519  *
520  * Environment:
521  *      The target and candidate addresses are both in host byte
522  *      order, NOT network byte order, when passed in.  We return
523  *      our value as a character, since that's the type of field in
524  *      the host structure, where this info will be stored.
525  *
526  * Side Effects:
527  *      As advertised.
528  *------------------------------------------------------------------------*/
529
530 static char
531 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
532 {                               /*h_AddrInSameNetwork */
533
534     afs_uint32 targetNet;
535     afs_uint32 candNet;
536
537     /*
538      * Pull out the network and subnetwork numbers from the target
539      * and candidate addresses.  We can short-circuit this whole
540      * affair if the target and candidate addresses are not of the
541      * same class.
542      */
543     if (IN_CLASSA(a_targetAddr)) {
544         if (!(IN_CLASSA(a_candAddr))) {
545             return (0);
546         }
547         targetNet = a_targetAddr & IN_CLASSA_NET;
548         candNet = a_candAddr & IN_CLASSA_NET;
549     } else if (IN_CLASSB(a_targetAddr)) {
550         if (!(IN_CLASSB(a_candAddr))) {
551             return (0);
552         }
553         targetNet = a_targetAddr & IN_CLASSB_NET;
554         candNet = a_candAddr & IN_CLASSB_NET;
555     } /*Class B target */
556     else if (IN_CLASSC(a_targetAddr)) {
557         if (!(IN_CLASSC(a_candAddr))) {
558             return (0);
559         }
560         targetNet = a_targetAddr & IN_CLASSC_NET;
561         candNet = a_candAddr & IN_CLASSC_NET;
562     } /*Class C target */
563     else {
564         targetNet = a_targetAddr;
565         candNet = a_candAddr;
566     }                           /*Class D address */
567
568     /*
569      * Now, simply compare the extracted net values for the two addresses
570      * (which at this point are known to be of the same class)
571      */
572     if (targetNet == candNet)
573         return (1);
574     else
575         return (0);
576
577 }                               /*h_AddrInSameNetwork */
578 #endif /* FS_STATS_DETAILED */
579
580
581 /* Assumptions: called with held host */
582 void
583 h_gethostcps_r(struct host *host, afs_int32 now)
584 {
585     int code;
586     int slept = 0;
587
588     /* wait if somebody else is already doing the getCPS call */
589     while (host->hostFlags & HCPS_INPROGRESS) {
590         slept = 1;              /* I did sleep */
591         host->hostFlags |= HCPS_WAITING;        /* I am sleeping now */
592 #ifdef AFS_PTHREAD_ENV
593         CV_WAIT(&host->cond, &host_glock_mutex);
594 #else /* AFS_PTHREAD_ENV */
595         if ((code = LWP_WaitProcess(&(host->hostFlags))) != LWP_SUCCESS)
596             ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
597 #endif /* AFS_PTHREAD_ENV */
598     }
599
600
601     host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
602     if (host->hcps.prlist_val)
603         free(host->hcps.prlist_val);    /* this is for hostaclRefresh */
604     host->hcps.prlist_val = NULL;
605     host->hcps.prlist_len = 0;
606     host->cpsCall = slept ? (FT_ApproxTime()) : (now);
607
608     H_UNLOCK;
609     code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
610     H_LOCK;
611     if (code) {
612         char hoststr[16];
613         /*
614          * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
615          * and reevaluates things if no sync server or quorum is found we could still end up
616          * with one of these errors. In such case we would like to reevaluate the rpc call to
617          * find if there's cps for this guy. We treat other errors (except network failures
618          * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
619          * we could like to deal this problem the other way around (i.e. if code == NOCPS
620          * ignore else retry next time) but the problem is that there're other errors (i.e.
621          * EPERM) for which we don't want to retry and we don't know the whole code list!
622          */
623         if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
624             /*
625              * We would have preferred to use a while loop and try again since ops in protected
626              * acls for this host will fail now but they'll be reevaluated on any subsequent
627              * call. The attempt to wait for a quorum/sync site or network error won't work
628              * since this problems really should only occurs during a complete fileserver
629              * restart. Since the fileserver will start before the ptservers (and thus before
630              * quorums are complete) clients will be utilizing all the fileserver's lwps!!
631              */
632             host->hcpsfailed = 1;
633             ViceLog(0,
634                     ("Warning:  GetHostCPS failed (%d) for %p (%s:%d); will retry\n",
635                      code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
636         } else {
637             host->hcpsfailed = 0;
638             ViceLog(1,
639                     ("gethost:  GetHostCPS failed (%d) for %p (%s:%d); ignored\n",
640                      code, host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
641         }
642         if (host->hcps.prlist_val)
643             free(host->hcps.prlist_val);
644         host->hcps.prlist_val = NULL;
645         host->hcps.prlist_len = 0;      /* Make sure it's zero */
646     } else
647         host->hcpsfailed = 0;
648
649     host->hostFlags &= ~HCPS_INPROGRESS;
650     /* signal all who are waiting */
651     if (host->hostFlags & HCPS_WAITING) {       /* somebody is waiting */
652         host->hostFlags &= ~HCPS_WAITING;
653 #ifdef AFS_PTHREAD_ENV
654         CV_BROADCAST(&host->cond);
655 #else /* AFS_PTHREAD_ENV */
656         if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
657             ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
658 #endif /* AFS_PTHREAD_ENV */
659     }
660 }
661
662 /* args in net byte order */
663 void
664 h_flushhostcps(afs_uint32 hostaddr, afs_uint16 hport)
665 {
666     struct host *host;
667
668     H_LOCK;
669     h_Lookup_r(hostaddr, hport, &host);
670     if (host) {
671         host->hcpsfailed = 1;
672         h_Release_r(host);
673     }
674     H_UNLOCK;
675     return;
676 }
677
678
679 /*
680  * Allocate a host.  It will be identified by the peer (ip,port) info in the
681  * rx connection provided.  The host is returned held and locked
682  */
683 #define DEF_ROPCONS 2115
684
685 struct host *
686 h_Alloc_r(struct rx_connection *r_con)
687 {
688     struct servent *serverentry;
689     struct host *host;
690 #if FS_STATS_DETAILED
691     afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
692 #endif /* FS_STATS_DETAILED */
693
694     host = GetHT();
695
696     host->host = rxr_HostOf(r_con);
697     host->port = rxr_PortOf(r_con);
698
699     h_AddHostToAddrHashTable_r(host->host, host->port, host);
700
701     if (consolePort == 0) {     /* find the portal number for console */
702 #if     defined(AFS_OSF_ENV)
703         serverentry = getservbyname("ropcons", "");
704 #else
705         serverentry = getservbyname("ropcons", 0);
706 #endif
707         if (serverentry)
708             consolePort = serverentry->s_port;
709         else
710             consolePort = htons(DEF_ROPCONS);   /* Use a default */
711     }
712     if (host->port == consolePort)
713         host->Console = 1;
714     /* Make a callback channel even for the console, on the off chance that it
715      * makes a request that causes a break call back.  It shouldn't. */
716     h_SetupCallbackConn_r(host);
717     host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
718     host->hostFlags = 0;
719     host->hcps.prlist_val = NULL;
720     host->hcps.prlist_len = 0;
721     host->interface = NULL;
722 #ifdef undef
723     host->hcpsfailed = 0;       /* save cycles */
724     h_gethostcps(host);         /* do this under host hold/lock */
725 #endif
726     host->FirstClient = NULL;
727     h_Hold_r(host);
728     h_Lock_r(host);
729     h_InsertList_r(host);       /* update global host List */
730 #if FS_STATS_DETAILED
731     /*
732      * Compare the new host's IP address (in host byte order) with ours
733      * (the File Server's), remembering if they are in the same network.
734      */
735     newHostAddr_HBO = (afs_uint32) ntohl(host->host);
736     host->InSameNetwork =
737         h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
738 #endif /* FS_STATS_DETAILED */
739     return host;
740
741 }                               /*h_Alloc_r */
742
743
744
745 /* Make a callback channel even for the console, on the off chance that it
746  * makes a request that causes a break call back.  It shouldn't. */
747 static void
748 h_SetupCallbackConn_r(struct host * host)
749 {
750     if (!sc)
751         sc = rxnull_NewClientSecurityObject();
752     host->callback_rxcon =
753         rx_NewConnection(host->host, host->port, 1, sc, 0);
754     rx_SetConnDeadTime(host->callback_rxcon, 50);
755     rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
756 }
757
758 /* h_Lookup_r
759  * Lookup a host given an IP address and UDP port number.
760  * hostaddr and hport are in network order
761  * hostaddr and hport are in network order
762  * On return, refCount is incremented.
763  */
764 int
765 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, struct host **hostp)
766 {
767     afs_int32 now;
768     struct host *host = NULL;
769     struct h_AddrHashChain *chain;
770     int index = h_HashIndex(haddr);
771     extern int hostaclRefresh;
772
773   restart:
774     for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
775         host = chain->hostPtr;
776         osi_Assert(host);
777         if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
778             && chain->port == hport) {
779             if ((host->hostFlags & HWHO_INPROGRESS) &&
780                 h_threadquota(host->lock.num_waiting)) {
781                 *hostp = 0;
782                 return VBUSY;
783             }
784             h_Hold_r(host);
785             h_Lock_r(host);
786             if (host->hostFlags & HOSTDELETED) {
787                 h_Unlock_r(host);
788                 h_Release_r(host);
789                 host = NULL;
790                 goto restart;
791             }
792             h_Unlock_r(host);
793             now = FT_ApproxTime();      /* always evaluate "now" */
794             if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
795                 /*
796                  * Every hostaclRefresh period (def 2 hrs) get the new
797                  * membership list for the host.  Note this could be the
798                  * first time that the host is added to a group.  Also
799                  * here we also retry on previous legitimate hcps failures.
800                  *
801                  * If we get here refCount is elevated.
802                  */
803                 h_gethostcps_r(host, now);
804             }
805             break;
806         }
807         host = NULL;
808     }
809     *hostp = host;
810     return 0;
811 }                               /*h_Lookup */
812
813 /* Lookup a host given its UUID. */
814 struct host *
815 h_LookupUuid_r(afsUUID * uuidp)
816 {
817     struct host *host = 0;
818     struct h_UuidHashChain *chain;
819     int index = h_UuidHashIndex(uuidp);
820
821     for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
822         host = chain->hostPtr;
823         osi_Assert(host);
824         if (!(host->hostFlags & HOSTDELETED) && host->interface
825             && afs_uuid_equal(&host->interface->uuid, uuidp)) {
826             return host;
827         }
828     }
829     return NULL;
830 }                               /*h_Lookup */
831
832
833 /* h_TossStuff_r:  Toss anything in the host structure (the host or
834  * clients marked for deletion.  Called from h_Release_r ONLY.
835  * To be called, there must be no holds, and either host->deleted
836  * or host->clientDeleted must be set.
837  */
838 void
839 h_TossStuff_r(struct host *host)
840 {
841     struct client **cp, *client;
842     int code;
843
844     /* make sure host doesn't go away over h_NBLock_r */
845     h_Hold_r(host);
846
847     code = h_NBLock_r(host);
848
849     /* don't use h_Release_r, since that may call h_TossStuff_r again */
850     h_Decrement_r(host);
851
852     /* if somebody still has this host locked */
853     if (code != 0) {
854         char hoststr[16];
855         ViceLog(0,
856                 ("Warning:  h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was locked.\n",
857                  host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
858         return;
859     } else {
860         h_Unlock_r(host);
861     }
862
863     /* if somebody still has this host held */
864     /* we must check this _after_ h_NBLock_r, since h_NBLock_r can drop and
865      * reacquire H_LOCK */
866     if (host->refCount > 0) {
867         char hoststr[16];
868         ViceLog(0,
869                 ("Warning:  h_TossStuff_r failed; Host %" AFS_PTR_FMT " (%s:%d) was held.\n",
870                  host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
871         return;
872     }
873
874     /* ASSUMPTION: rxi_FreeConnection() does not yield */
875     for (cp = &host->FirstClient; (client = *cp);) {
876         if ((host->hostFlags & HOSTDELETED) || client->deleted) {
877             int code;
878             ObtainWriteLockNoBlock(&client->lock, code);
879             if (code < 0) {
880                 char hoststr[16];
881                 ViceLog(0,
882                         ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
883                          "client %p was locked.\n",
884                          host, afs_inet_ntoa_r(host->host, hoststr),
885                          ntohs(host->port), client));
886                 return;
887             }
888
889             if (client->refCount) {
890                 char hoststr[16];
891                 ViceLog(0,
892                         ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
893                          "client %p refcount %d.\n",
894                          host, afs_inet_ntoa_r(host->host, hoststr),
895                          ntohs(host->port), client, client->refCount));
896                 /* This is the same thing we do if the host is locked */
897                 ReleaseWriteLock(&client->lock);
898                 return;
899             }
900             client->CPS.prlist_len = 0;
901             if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
902                 free(client->CPS.prlist_val);
903             client->CPS.prlist_val = NULL;
904             CurrentConnections--;
905             *cp = client->next;
906             ReleaseWriteLock(&client->lock);
907             FreeCE(client);
908         } else
909             cp = &client->next;
910     }
911
912     /* We've just cleaned out all the deleted clients; clear the flag */
913     host->hostFlags &= ~CLIENTDELETED;
914
915     if (host->hostFlags & HOSTDELETED) {
916         struct rx_connection *rxconn;
917         struct AddrPort hostAddrPort;
918         int i;
919
920         if (host->Console & 1)
921             Console--;
922         if ((rxconn = host->callback_rxcon)) {
923             host->callback_rxcon = (struct rx_connection *)0;
924             rx_DestroyConnection(rxconn);
925         }
926         if (host->hcps.prlist_val)
927             free(host->hcps.prlist_val);
928         host->hcps.prlist_val = NULL;
929         host->hcps.prlist_len = 0;
930         DeleteAllCallBacks_r(host, 1);
931         host->hostFlags &= ~RESETDONE;  /* just to be safe */
932
933         /* if alternate addresses do not exist */
934         if (!(host->interface)) {
935             h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
936         } else {
937             h_DeleteHostFromUuidHashTable_r(host);
938             h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
939             /* delete the hash entry for each valid alternate addresses */
940             for (i = 0; i < host->interface->numberOfInterfaces; i++) {
941                 hostAddrPort = host->interface->interface[i];
942                 /*
943                  * if the interface addr/port is the primary, we already
944                  * removed it.  If the addr/port is not valid, its not
945                  * in the hash table.
946                  */
947                 if (hostAddrPort.valid &&
948                     (host->host != hostAddrPort.addr ||
949                      host->port != hostAddrPort.port))
950                     h_DeleteHostFromAddrHashTable_r(hostAddrPort.addr, hostAddrPort.port, host);
951             }
952             free(host->interface);
953             host->interface = NULL;
954         }                       /* if alternate address exists */
955
956         h_DeleteList_r(host);   /* remove host from global host List */
957         FreeHT(host);
958     }
959 }                               /*h_TossStuff_r */
960
961
962
963 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
964  * system at the start of the enumeration (perhaps more).  Hosts may be deleted
965  * (have delete flag set); ditto for clients.  refCount is always incremented
966  * before (*proc) is called.  The param flags is passed to (*proc) as the
967  * param flags, permitting (*proc) to stop the enumeration (BAIL).
968  *
969  * Needed?  Why not always h_Hold_r and h_Release_r in (*proc), or even -never-
970  * h_Hold_r or h_Release_r in (*proc)?
971  *
972  * **The proc should return 0 if the host should be released, 1 if it should
973  * be held after enumeration.
974  */
975 void
976 h_Enumerate(int (*proc) (struct host*, int, void *), void *param)
977 {
978     struct host *host, **list;
979     int *flags;
980     int i, count;
981     int totalCount;
982
983     H_LOCK;
984     if (hostCount == 0) {
985         H_UNLOCK;
986         return;
987     }
988     list = (struct host **)malloc(hostCount * sizeof(struct host *));
989     if (!list) {
990         ViceLog(0, ("Failed malloc in h_Enumerate (list)\n"));
991         osi_Panic("Failed malloc in h_Enumerate (list)\n");
992     }
993     flags = (int *)malloc(hostCount * sizeof(int));
994     if (!flags) {
995         ViceLog(0, ("Failed malloc in h_Enumerate (flags)\n"));
996         osi_Panic("Failed malloc in h_Enumerate (flags)\n");
997     }
998     for (totalCount = count = 0, host = hostList;
999          host && totalCount < hostCount;
1000          host = host->next, totalCount++) {
1001
1002         if (!(host->hostFlags & HOSTDELETED)) {
1003             list[count] = host;
1004             h_Hold_r(host);
1005             count++;
1006         }
1007     }
1008     if (totalCount != hostCount) {
1009         ViceLog(0, ("h_Enumerate found %d of %d hosts\n", totalCount, hostCount));
1010     } else if (host != NULL) {
1011         ViceLog(0, ("h_Enumerate found more than %d hosts\n", hostCount));
1012         ShutDownAndCore(PANIC);
1013     }
1014     H_UNLOCK;
1015     for (i = 0; i < count; i++) {
1016         flags[i] = (*proc) (list[i], flags[i], param);
1017         H_LOCK;
1018         h_Release_r(list[i]);
1019         H_UNLOCK;
1020         /* bail out of the enumeration early */
1021         if (H_ENUMERATE_ISSET_BAIL(flags[i]))
1022             break;
1023     }
1024     free((void *)list);
1025     free((void *)flags);
1026 }       /* h_Enumerate */
1027
1028
1029 /* h_Enumerate_r (revised):
1030  * Calls (*proc)(host, flags, 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.  The param flags is passed to (*proc) as the
1034  * param flags, permitting (*proc) to stop the enumeration (BAIL).
1035  *
1036  * Needed?  Why not always h_Hold_r and h_Release_r in (*proc), or even -never-
1037  * h_Hold_r or h_Release_r in (*proc)?
1038  *
1039  * @note Assumes that hostList is only prepended to, that a host is never
1040  *       inserted into the middle. Otherwise this would not be guaranteed to
1041  *       terminate.
1042  *
1043  * **The proc should return 0 if the host should be released, 1 if it should
1044  * be held after enumeration.
1045  */
1046 void
1047 h_Enumerate_r(int (*proc) (struct host *, int, void *),
1048               struct host *enumstart, void *param)
1049 {
1050     struct host *host, *next;
1051     int flags = 0;
1052     int nflags = 0;
1053     int count;
1054     int origHostCount;
1055
1056     if (hostCount == 0) {
1057         return;
1058     }
1059
1060     host = enumstart;
1061     enumstart = NULL;
1062
1063     /* find the first non-deleted host, so we know where to actually start
1064      * enumerating */
1065     for (count = 0; host && count < hostCount; count++) {
1066         if (!(host->hostFlags & HOSTDELETED)) {
1067             enumstart = host;
1068             break;
1069         }
1070         host = host->next;
1071     }
1072     if (!enumstart) {
1073         /* we didn't find a non-deleted host... */
1074
1075         if (host && count >= hostCount) {
1076             /* ...because we found a loop */
1077             ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", hostCount));
1078             ShutDownAndCore(PANIC);
1079         }
1080
1081         /* ...because the hostList is full of deleted hosts */
1082         return;
1083     }
1084
1085     h_Hold_r(enumstart);
1086
1087     /* remember hostCount, lest it change over the potential H_LOCK drop in
1088      * h_Release_r */
1089     origHostCount = hostCount;
1090
1091     for (count = 0, host = enumstart; host && count < origHostCount; host = next, flags = nflags, count++) {
1092         next = host->next;
1093
1094         /* find the next non-deleted host */
1095         while (next && (next->hostFlags & HOSTDELETED)) {
1096             next = next->next;
1097             /* inc count for the skipped-over host */
1098             if (++count > origHostCount) {
1099                 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1100                 ShutDownAndCore(PANIC);
1101             }
1102         }
1103         if (next && !H_ENUMERATE_ISSET_BAIL(flags))
1104             h_Hold_r(next);
1105
1106         if (!(host->hostFlags & HOSTDELETED)) {
1107             flags = (*proc) (host, flags, param);
1108             if (H_ENUMERATE_ISSET_BAIL(flags)) {
1109                 h_Release_r(host); /* this might free up the host */
1110                 break;
1111             }
1112         }
1113         h_Release_r(host); /* this might free up the host */
1114     }
1115     if (host != NULL && count >= origHostCount) {
1116         ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1117         ShutDownAndCore(PANIC);
1118     }
1119 }       /*h_Enumerate_r */
1120
1121
1122 /* inserts a new HashChain structure corresponding to this UUID */
1123 void
1124 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1125 {
1126     int index;
1127     struct h_UuidHashChain *chain;
1128     char uuid1[128], uuid2[128];
1129     char hoststr[16];
1130
1131     /* hash into proper bucket */
1132     index = h_UuidHashIndex(uuid);
1133
1134     /* don't add the same entry multiple times */
1135     for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1136         if (!chain->hostPtr)
1137             continue;
1138
1139         if (chain->hostPtr->interface &&
1140             afs_uuid_equal(&chain->hostPtr->interface->uuid, uuid)) {
1141             if (LogLevel >= 125) {
1142                 afsUUID_to_string(&chain->hostPtr->interface->uuid, uuid1,
1143                                   127);
1144                 afsUUID_to_string(uuid, uuid2, 127);
1145                 ViceLog(125, ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s) exists as %s:%d (uuid %s)\n",
1146                               host, uuid1,
1147                               afs_inet_ntoa_r(chain->hostPtr->host, hoststr),
1148                               ntohs(chain->hostPtr->port), uuid2));
1149             }
1150             return;
1151         }
1152     }
1153
1154     /* insert into beginning of list for this bucket */
1155     chain = (struct h_UuidHashChain *)malloc(sizeof(struct h_UuidHashChain));
1156     if (!chain) {
1157         ViceLog(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1158         osi_Panic("Failed malloc in h_AddHostToUuidHashTable_r\n");
1159     }
1160     chain->hostPtr = host;
1161     chain->next = hostUuidHashTable[index];
1162     hostUuidHashTable[index] = chain;
1163          if (LogLevel < 125)
1164                return;
1165      afsUUID_to_string(uuid, uuid2, 127);
1166      ViceLog(125,
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));
1170 }
1171
1172 /* deletes a HashChain structure corresponding to this host */
1173 int
1174 h_DeleteHostFromUuidHashTable_r(struct host *host)
1175 {
1176      int index;
1177      struct h_UuidHashChain **uhp, *uth;
1178      char uuid1[128];
1179      char hoststr[16];
1180
1181      if (!host->interface)
1182        return 0;
1183
1184      /* hash into proper bucket */
1185      index = h_UuidHashIndex(&host->interface->uuid);
1186
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) {
1192              ViceLog(125,
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)));
1196              *uhp = uth->next;
1197              free(uth);
1198              return 1;
1199          }
1200      }
1201      ViceLog(125,
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)));
1205      return 0;
1206 }
1207
1208 /*
1209  * This is called with host locked and held.
1210  *
1211  * All addresses are in network byte order.
1212  */
1213 static int
1214 invalidateInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1215 {
1216     int i;
1217     int number;
1218     struct Interface *interface;
1219     char hoststr[16], hoststr2[16];
1220
1221     osi_Assert(host);
1222     osi_Assert(host->interface);
1223
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),
1227                   ntohs(port)));
1228
1229     /*
1230      * Make sure this address is on the list of known addresses
1231      * for this host.
1232      */
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;
1241             }
1242             return 0;
1243         }
1244     }
1245
1246     /* not found */
1247     return 0;
1248 }
1249
1250 /*
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.
1256  *
1257  * All addresses are in network byte order.
1258  */
1259 static int
1260 removeAddress_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1261 {
1262     int i;
1263     char hoststr[16], hoststr2[16];
1264     struct rx_connection *rxconn;
1265
1266     if (!host->interface || host->interface->numberOfInterfaces == 1) {
1267         if (host->host == addr && host->port == port) {
1268             ViceLog(25,
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;
1272             /*
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.
1278              */
1279         } else {
1280             ViceLog(0,
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)));
1283         }
1284     } else {
1285         if (host->host == addr && host->port == port)  {
1286             removeInterfaceAddr_r(host, addr, port);
1287
1288             for (i=0; i < host->interface->numberOfInterfaces; i++) {
1289                 if (host->interface->interface[i].valid) {
1290                     ViceLog(25,
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);
1298                     break;
1299                 }
1300             }
1301
1302             if (i == host->interface->numberOfInterfaces) {
1303                 ViceLog(25,
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 */
1308                 host->host = 0;
1309                 host->port = 0;
1310             } else {
1311                 rxconn = host->callback_rxcon;
1312                 host->callback_rxcon = NULL;
1313
1314                 if (rxconn) {
1315                     rx_DestroyConnection(rxconn);
1316                     rxconn = NULL;
1317                 }
1318
1319                 if (!sc)
1320                     sc = rxnull_NewClientSecurityObject();
1321                 host->callback_rxcon =
1322                     rx_NewConnection(host->host, host->port, 1, sc, 0);
1323                 rx_SetConnDeadTime(host->callback_rxcon, 50);
1324                 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
1325             }
1326         } else {
1327             /* not the primary addr/port, just invalidate it */
1328             invalidateInterfaceAddr_r(host, addr, port);
1329         }
1330     }
1331
1332     return 0;
1333 }
1334
1335 static void
1336 createHostAddrHashChain_r(int index, afs_uint32 addr, afs_uint16 port, struct host *host)
1337 {
1338     struct h_AddrHashChain *chain;
1339     char hoststr[16];
1340
1341     /* insert into beginning of list for this bucket */
1342     chain = (struct h_AddrHashChain *)malloc(sizeof(struct h_AddrHashChain));
1343     if (!chain) {
1344         ViceLog(0, ("Failed malloc in h_AddHostToAddrHashTable_r\n"));
1345         osi_Panic("Failed malloc in h_AddHostToAddrHashTable_r\n");
1346     }
1347     chain->hostPtr = host;
1348     chain->next = hostAddrHashTable[index];
1349     chain->addr = addr;
1350     chain->port = port;
1351     hostAddrHashTable[index] = chain;
1352     ViceLog(125, ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " added as %s:%d\n",
1353                   host, afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1354 }
1355
1356 /**
1357  * Resolve host address conflicts when hashing by address.
1358  *
1359  * @param[in]   addr    an ip address of the interface
1360  * @param[in]   port    the port of the interface
1361  * @param[in]   newHost the host being added with this address
1362  * @param[in]   oldHost the host previously added with this address
1363  */
1364 static void
1365 reconcileHosts_r(afs_uint32 addr, afs_uint16 port, struct host *newHost,
1366                  struct host *oldHost)
1367 {
1368     struct rx_connection *cb = NULL;
1369     int code = 0;
1370     struct interfaceAddr interf;
1371     Capabilities caps;
1372     afsUUID *newHostUuid = &nulluuid;
1373     afsUUID *oldHostUuid = &nulluuid;
1374     char hoststr[16];
1375
1376     ViceLog(125,
1377             ("reconcileHosts_r: addr %s:%d newHost %" AFS_PTR_FMT " oldHost %"
1378              AFS_PTR_FMT, afs_inet_ntoa_r(addr, hoststr), ntohs(port),
1379              newHost, oldHost));
1380
1381     osi_Assert(oldHost != newHost);
1382     caps.Capabilities_val = NULL;
1383
1384     if (!sc) {
1385         sc = rxnull_NewClientSecurityObject();
1386     }
1387
1388     cb = rx_NewConnection(addr, port, 1, sc, 0);
1389     rx_SetConnDeadTime(cb, 50);
1390     rx_SetConnHardDeadTime(cb, AFS_HARDDEADTIME);
1391
1392     h_Hold_r(newHost);
1393     h_Hold_r(oldHost);
1394     H_UNLOCK;
1395     code = RXAFSCB_TellMeAboutYourself(cb, &interf, &caps);
1396     if (code == RXGEN_OPCODE) {
1397         code = RXAFSCB_WhoAreYou(cb, &interf);
1398     }
1399     H_LOCK;
1400
1401     if (code == RXGEN_OPCODE ||
1402         (code == 0 && afs_uuid_equal(&interf.uuid, &nulluuid))) {
1403         ViceLog(0,
1404                 ("reconcileHosts_r: WhoAreYou not supported for connection (%s:%d), error %d\n",
1405                  afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1406         goto fail;
1407     }
1408     if (code != 0) {
1409         ViceLog(0,
1410                 ("reconcileHosts_r: WhoAreYou failed for connection (%s:%d), error %d\n",
1411                  afs_inet_ntoa_r(addr, hoststr), ntohs(port), code));
1412         goto fail;
1413     }
1414
1415     /* Since lock was dropped, the hosts may have been deleted during the rpcs. */
1416     if ((newHost->hostFlags & HOSTDELETED)
1417         && (oldHost->hostFlags & HOSTDELETED)) {
1418         ViceLog(5,
1419                 ("reconcileHosts_r: new and old hosts were deleted during probe.\n"));
1420         goto done;
1421     }
1422
1423     /* A check can be done if at least one of the hosts has a uuid. It
1424      * is an error if the hosts have the same (not null) uuid. */
1425     if ((!(newHost->hostFlags & HOSTDELETED)) && newHost->interface) {
1426         newHostUuid = &(newHost->interface->uuid);
1427     }
1428     if ((!(oldHost->hostFlags & HOSTDELETED)) && oldHost->interface) {
1429         oldHostUuid = &(oldHost->interface->uuid);
1430     }
1431     if (afs_uuid_equal(newHostUuid, &nulluuid) &&
1432         afs_uuid_equal(oldHostUuid, &nulluuid)) {
1433         ViceLog(0,
1434                 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), no uuids\n",
1435                  afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1436         goto done;
1437     }
1438     if (afs_uuid_equal(newHostUuid, oldHostUuid)) {
1439         ViceLog(0,
1440                 ("reconcileHosts_r: Cannot reconcile hosts for connection (%s:%d), same uuids\n",
1441                  afs_inet_ntoa_r(addr, hoststr), ntohs(port)));
1442         goto done;
1443     }
1444
1445     /* Determine which host should be hashed */
1446     if ((!(newHost->hostFlags & HOSTDELETED))
1447         && afs_uuid_equal(newHostUuid, &(interf.uuid))) {
1448         /* Install the new host into the hash before removing the stale
1449          * addresses. Walk the hash chain again since the hash table may have
1450          * been changed when the host lock was dropped to get the uuid. */
1451         struct h_AddrHashChain *chain;
1452         int index = h_HashIndex(addr);
1453         for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1454             if (chain->addr == addr && chain->port == port) {
1455                 chain->hostPtr = newHost;
1456                 removeAddress_r(oldHost, addr, port);
1457                 goto done;
1458             }
1459         }
1460         createHostAddrHashChain_r(index, addr, port, newHost);
1461         removeAddress_r(oldHost, addr, port);
1462         goto done;
1463     }
1464     if ((!(oldHost->hostFlags & HOSTDELETED))
1465         && afs_uuid_equal(oldHostUuid, &(interf.uuid))) {
1466         removeAddress_r(newHost, addr, port);
1467         goto done;
1468     }
1469
1470   fail:
1471     if (!(newHost->hostFlags & HOSTDELETED)) {
1472         removeAddress_r(newHost, addr, port);
1473     }
1474     if (!(oldHost->hostFlags & HOSTDELETED)) {
1475         removeAddress_r(oldHost, addr, port);
1476     }
1477
1478   done:
1479     h_Release_r(newHost);
1480     h_Release_r(oldHost);
1481     rx_DestroyConnection(cb);
1482     return;
1483 }
1484
1485 /* inserts a new HashChain structure corresponding to this address */
1486 void
1487 h_AddHostToAddrHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1488 {
1489     int index;
1490     struct h_AddrHashChain *chain;
1491     char hoststr[16];
1492
1493     /* hash into proper bucket */
1494     index = h_HashIndex(addr);
1495
1496     /* don't add the same address:port pair entry multiple times */
1497     for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
1498         if (chain->addr == addr && chain->port == port) {
1499             if (chain->hostPtr == host) {
1500                 ViceLog(125,
1501                         ("h_AddHostToAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) already hashed\n",
1502                           host, afs_inet_ntoa_r(chain->addr, hoststr),
1503                           ntohs(chain->port)));
1504                 return;
1505             }
1506             if (!(chain->hostPtr->hostFlags & HOSTDELETED)) {
1507                 /* attempt to resolve host address collision */
1508                 reconcileHosts_r(addr, port, host, chain->hostPtr);
1509                 return;
1510             }
1511         }
1512     }
1513     createHostAddrHashChain_r(index, addr, port, host);
1514 }
1515
1516 /*
1517  * This is called with host locked and held.
1518  * It is called to either validate or add an additional interface
1519  * address/port on the specified host.
1520  *
1521  * All addresses are in network byte order.
1522  */
1523 int
1524 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1525 {
1526     int i;
1527     int number;
1528     struct Interface *interface;
1529     char hoststr[16], hoststr2[16];
1530
1531     osi_Assert(host);
1532     osi_Assert(host->interface);
1533
1534     /*
1535      * Make sure this address is on the list of known addresses
1536      * for this host.
1537      */
1538     number = host->interface->numberOfInterfaces;
1539     for (i = 0; i < number; i++) {
1540         if (host->interface->interface[i].addr == addr &&
1541              host->interface->interface[i].port == port) {
1542             ViceLog(125,
1543                     ("addInterfaceAddr : found host %" AFS_PTR_FMT " (%s:%d) adding %s:%d%s\n",
1544                      host, afs_inet_ntoa_r(host->host, hoststr),
1545                      ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1546                      ntohs(port), host->interface->interface[i].valid ? "" :
1547                      ", validating"));
1548
1549             if (host->interface->interface[i].valid == 0) {
1550                 host->interface->interface[i].valid = 1;
1551                 h_AddHostToAddrHashTable_r(addr, port, host);
1552             }
1553             return 0;
1554         }
1555     }
1556
1557     ViceLog(125, ("addInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) adding %s:%d\n",
1558                   host, afs_inet_ntoa_r(host->host, hoststr),
1559                   ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1560                   ntohs(port)));
1561
1562     interface = (struct Interface *)
1563         malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1564     if (!interface) {
1565         ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
1566         osi_Panic("Failed malloc in addInterfaceAddr_r\n");
1567     }
1568     interface->numberOfInterfaces = number + 1;
1569     interface->uuid = host->interface->uuid;
1570     for (i = 0; i < number; i++)
1571         interface->interface[i] = host->interface->interface[i];
1572
1573     /* Add the new valid interface */
1574     interface->interface[number].addr = addr;
1575     interface->interface[number].port = port;
1576     interface->interface[number].valid = 1;
1577     h_AddHostToAddrHashTable_r(addr, port, host);
1578     free(host->interface);
1579     host->interface = interface;
1580
1581     return 0;
1582 }
1583
1584
1585 /*
1586  * This is called with host locked and held.
1587  *
1588  * All addresses are in network byte order.
1589  */
1590 int
1591 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1592 {
1593     int i;
1594     int number;
1595     struct Interface *interface;
1596     char hoststr[16], hoststr2[16];
1597
1598     osi_Assert(host);
1599     osi_Assert(host->interface);
1600
1601     ViceLog(125, ("removeInterfaceAddr : host %" AFS_PTR_FMT " (%s:%d) addr %s:%d\n",
1602                   host, afs_inet_ntoa_r(host->host, hoststr),
1603                   ntohs(host->port), afs_inet_ntoa_r(addr, hoststr2),
1604                   ntohs(port)));
1605
1606     /*
1607      * Make sure this address is on the list of known addresses
1608      * for this host.
1609      */
1610     interface = host->interface;
1611     number = host->interface->numberOfInterfaces;
1612     for (i = 0; i < number; i++) {
1613         if (interface->interface[i].addr == addr &&
1614             interface->interface[i].port == port) {
1615             if (interface->interface[i].valid)
1616                 h_DeleteHostFromAddrHashTable_r(addr, port, host);
1617             number--;
1618             for (; i < number; i++) {
1619                 interface->interface[i] = interface->interface[i+1];
1620             }
1621             interface->numberOfInterfaces = number;
1622             return 0;
1623         }
1624     }
1625     /* not found */
1626     return 0;
1627 }
1628
1629
1630
1631 static int
1632 h_threadquota(int waiting)
1633 {
1634     if (lwps > 64) {
1635         if (waiting > 5)
1636             return 1;
1637     } else if (lwps > 32) {
1638         if (waiting > 4)
1639             return 1;
1640     } else if (lwps > 16) {
1641         if (waiting > 3)
1642             return 1;
1643     } else {
1644         if (waiting > 2)
1645             return 1;
1646     }
1647     return 0;
1648 }
1649
1650 /* If found, host is returned with refCount incremented */
1651 struct host *
1652 h_GetHost_r(struct rx_connection *tcon)
1653 {
1654     struct host *host;
1655     struct host *oldHost;
1656     int code;
1657     struct interfaceAddr interf;
1658     int interfValid = 0;
1659     struct Identity *identP = NULL;
1660     afs_uint32 haddr;
1661     afs_uint16 hport;
1662     char hoststr[16], hoststr2[16];
1663     Capabilities caps;
1664     struct rx_connection *cb_conn = NULL;
1665     struct rx_connection *cb_in = NULL;
1666
1667     caps.Capabilities_val = NULL;
1668
1669     haddr = rxr_HostOf(tcon);
1670     hport = rxr_PortOf(tcon);
1671   retry:
1672     if (cb_in) {
1673         rx_DestroyConnection(cb_in);
1674         cb_in = NULL;
1675     }
1676     if (caps.Capabilities_val)
1677         free(caps.Capabilities_val);
1678     caps.Capabilities_val = NULL;
1679     caps.Capabilities_len = 0;
1680
1681     code = 0;
1682     if (h_Lookup_r(haddr, hport, &host))
1683         return 0;
1684     identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1685     if (host && !identP && !(host->Console & 1)) {
1686         /* This is a new connection, and we already have a host
1687          * structure for this address. Verify that the identity
1688          * of the caller matches the identity in the host structure.
1689          */
1690         if ((host->hostFlags & HWHO_INPROGRESS) &&
1691             h_threadquota(host->lock.num_waiting)) {
1692                 h_Release_r(host);
1693             host = NULL;
1694             goto gethost_out;
1695         }
1696         h_Lock_r(host);
1697         if (!(host->hostFlags & ALTADDR) ||
1698             (host->hostFlags & HOSTDELETED)) {
1699             /* Another thread is doing initialization
1700              * or this host was deleted while we
1701              * waited for the lock. */
1702             h_Unlock_r(host);
1703             ViceLog(125,
1704                     ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1705                      host, afs_inet_ntoa_r(host->host, hoststr),
1706                      ntohs(host->port)));
1707             h_Release_r(host);
1708             goto retry;
1709         }
1710         host->hostFlags |= HWHO_INPROGRESS;
1711         host->hostFlags &= ~ALTADDR;
1712
1713         /* We received a new connection from an IP address/port
1714          * that is associated with 'host' but the address/port of
1715          * the callback connection does not have to match it.
1716          * If there is a match, we can use the existing callback
1717          * connection to verify the UUID.  If they do not match
1718          * we need to use a new callback connection to verify the
1719          * UUID of the incoming caller and perhaps use the old
1720          * callback connection to verify that the old address/port
1721          * is still valid.
1722          */
1723
1724         cb_conn = host->callback_rxcon;
1725         rx_GetConnection(cb_conn);
1726         H_UNLOCK;
1727         if (haddr == host->host && hport == host->port) {
1728             /* The existing callback connection matches the
1729              * incoming connection so just use it.
1730              */
1731             code =
1732                 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1733             if (code == RXGEN_OPCODE)
1734                 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1735         } else {
1736             /* We do not have a match.  Create a new connection
1737              * for the new addr/port and use multi_Rx to probe
1738              * both of them simultaneously.
1739              */
1740             if (!sc)
1741                 sc = rxnull_NewClientSecurityObject();
1742             cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1743             rx_SetConnDeadTime(cb_in, 50);
1744             rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1745
1746             code =
1747                 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1748             if (code == RXGEN_OPCODE)
1749                 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1750         }
1751         rx_PutConnection(cb_conn);
1752         cb_conn=NULL;
1753         H_LOCK;
1754         if ((code == RXGEN_OPCODE) ||
1755             ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1756             identP = (struct Identity *)malloc(sizeof(struct Identity));
1757             if (!identP) {
1758                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1759                 osi_Panic("Failed malloc in h_GetHost_r\n");
1760             }
1761             identP->valid = 0;
1762             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1763             if (cb_in == NULL) {
1764                 /* The host on this connection was unable to respond to
1765                  * the WhoAreYou. We will treat this as a new connection
1766                  * from the existing host. The worst that can happen is
1767                  * that we maintain some extra callback state information */
1768                 if (host->interface) {
1769                     ViceLog(0,
1770                             ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1771                              host,
1772                              afs_inet_ntoa_r(host->host, hoststr),
1773                              ntohs(host->port)));
1774                     host->hostFlags |= HOSTDELETED;
1775                     host->hostFlags &= ~HWHO_INPROGRESS;
1776                     h_Unlock_r(host);
1777                     h_Release_r(host);
1778                     host = NULL;
1779                     goto retry;
1780                 }
1781             } else {
1782                 /* The incoming connection does not support WhoAreYou but
1783                  * the original one might have.  Use removeAddress_r() to
1784                  * remove this addr/port from the host that was found.
1785                  * If there are no more addresses left for the host it
1786                  * will be deleted.  Then we retry.
1787                  */
1788                 removeAddress_r(host, haddr, hport);
1789                 host->hostFlags &= ~HWHO_INPROGRESS;
1790                 host->hostFlags |= ALTADDR;
1791                 h_Unlock_r(host);
1792                 h_Release_r(host);
1793                 host = NULL;
1794                 goto retry;
1795             }
1796         } else if (code == 0) {
1797             interfValid = 1;
1798             identP = (struct Identity *)malloc(sizeof(struct Identity));
1799             if (!identP) {
1800                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1801                 osi_Panic("Failed malloc in h_GetHost_r\n");
1802             }
1803             identP->valid = 1;
1804             identP->uuid = interf.uuid;
1805             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1806             /* Check whether the UUID on this connection matches
1807              * the UUID in the host structure. If they don't match
1808              * then this is not the same host as before. */
1809             if (!host->interface
1810                 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1811                 if (cb_in) {
1812                         ViceLog(25,
1813                                         ("Uuid doesn't match connection (%s:%d).\n",
1814                                          afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1815                         removeAddress_r(host, haddr, hport);
1816                 } else {
1817                     ViceLog(25,
1818                             ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1819                              host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1820
1821                     removeAddress_r(host, host->host, host->port);
1822                 }
1823                 host->hostFlags &= ~HWHO_INPROGRESS;
1824                 host->hostFlags |= ALTADDR;
1825                 h_Unlock_r(host);
1826                 h_Release_r(host);
1827                 host = NULL;
1828                 goto retry;
1829             } else if (cb_in) {
1830                 /* the UUID matched the client at the incoming addr/port
1831                  * but this is not the address of the active callback
1832                  * connection.  Try that connection and see if the client
1833                  * is still there and if the reported UUID is the same.
1834                  */
1835                 int code2;
1836                 afsUUID uuid = host->interface->uuid;
1837                 cb_conn = host->callback_rxcon;
1838                 rx_GetConnection(cb_conn);
1839                 rx_SetConnDeadTime(cb_conn, 2);
1840                 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1841                 H_UNLOCK;
1842                 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1843                 H_LOCK;
1844                 rx_SetConnDeadTime(cb_conn, 50);
1845                 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1846                 rx_PutConnection(cb_conn);
1847                 cb_conn=NULL;
1848                 if (code2) {
1849                     /* The primary address is either not responding or
1850                      * is not the client we are looking for.  Need to
1851                      * remove the primary address and add swap in the new
1852                      * callback connection, and destroy the old one.
1853                      */
1854                     struct rx_connection *rxconn;
1855                     ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1856                                host,
1857                                afs_inet_ntoa_r(host->host, hoststr),
1858                                ntohs(host->port),code2));
1859
1860                     /*
1861                      * make sure we add and then remove.  otherwise, we
1862                      * might end up with no valid interfaces after the
1863                      * remove and the host will have been marked deleted.
1864                      */
1865                     addInterfaceAddr_r(host, haddr, hport);
1866                     removeInterfaceAddr_r(host, host->host, host->port);
1867                     host->host = haddr;
1868                     host->port = hport;
1869                     rxconn = host->callback_rxcon;
1870                     host->callback_rxcon = cb_in;
1871                     cb_in = NULL;
1872
1873                     if (rxconn) {
1874                         /*
1875                          * If rx_DestroyConnection calls h_FreeConnection we
1876                          * will deadlock on the host_glock_mutex. Work around
1877                          * the problem by unhooking the client from the
1878                          * connection before destroying the connection.
1879                          */
1880                         rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1881                         rx_DestroyConnection(rxconn);
1882                     }
1883                 }
1884             }
1885         } else {
1886             if (cb_in) {
1887                 /* A callback to the incoming connection address is failing.
1888                  * Assume that the addr/port is no longer associated with the host
1889                  * returned by h_Lookup_r.
1890                  */
1891                 ViceLog(0,
1892                         ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1893                          afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1894                 removeAddress_r(host, haddr, hport);
1895                 host->hostFlags &= ~HWHO_INPROGRESS;
1896                 host->hostFlags |= ALTADDR;
1897                 h_Unlock_r(host);
1898                 h_Release_r(host);
1899                 host = NULL;
1900                 rx_DestroyConnection(cb_in);
1901                 cb_in = NULL;
1902                 goto gethost_out;
1903             } else {
1904                 ViceLog(0,
1905                         ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1906                          host, afs_inet_ntoa_r(host->host, hoststr),
1907                          ntohs(host->port), code));
1908                 host->hostFlags |= VENUSDOWN;
1909             }
1910         }
1911         if (caps.Capabilities_val
1912             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1913             host->hostFlags |= HERRORTRANS;
1914         else
1915             host->hostFlags &= ~(HERRORTRANS);
1916         host->hostFlags |= ALTADDR;
1917         host->hostFlags &= ~HWHO_INPROGRESS;
1918         h_Unlock_r(host);
1919     } else if (host) {
1920         if (!(host->hostFlags & ALTADDR)) {
1921             /* another thread is doing the initialisation */
1922             ViceLog(125,
1923                     ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1924                      host, afs_inet_ntoa_r(host->host, hoststr),
1925                      ntohs(host->port)));
1926             h_Lock_r(host);
1927             h_Unlock_r(host);
1928             ViceLog(125,
1929                     ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1930                      host, afs_inet_ntoa_r(host->host, hoststr),
1931                      ntohs(host->port)));
1932             h_Release_r(host);
1933             goto retry;
1934         }
1935         /* We need to check whether the identity in the host structure
1936          * matches the identity on the connection. If they don't match
1937          * then treat this a new host. */
1938         if (!(host->Console & 1)
1939             && ((!identP->valid && host->interface)
1940                 || (identP->valid && !host->interface)
1941                 || (identP->valid
1942                     && !afs_uuid_equal(&identP->uuid,
1943                                        &host->interface->uuid)))) {
1944             char uuid1[128], uuid2[128];
1945             if (identP->valid)
1946                 afsUUID_to_string(&identP->uuid, uuid1, 127);
1947             if (host->interface)
1948                 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1949             ViceLog(0,
1950                     ("CB: new identity for host %p (%s:%d), "
1951                      "deleting(%x %p %s %s)\n",
1952                      host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1953                      identP->valid, host->interface,
1954                      identP->valid ? uuid1 : "no_uuid",
1955                      host->interface ? uuid2 : "no_uuid"));
1956
1957             /* The host in the cache is not the host for this connection */
1958             h_Lock_r(host);
1959             host->hostFlags |= HOSTDELETED;
1960             h_Unlock_r(host);
1961             h_Release_r(host);
1962             goto retry;
1963         }
1964     } else {
1965         host = h_Alloc_r(tcon); /* returned held and locked */
1966         h_gethostcps_r(host, FT_ApproxTime());
1967         if (!(host->Console & 1)) {
1968             int pident = 0;
1969             cb_conn = host->callback_rxcon;
1970             rx_GetConnection(cb_conn);
1971             host->hostFlags |= HWHO_INPROGRESS;
1972             H_UNLOCK;
1973             code =
1974                 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1975             if (code == RXGEN_OPCODE)
1976                 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1977             rx_PutConnection(cb_conn);
1978             cb_conn=NULL;
1979             H_LOCK;
1980             if ((code == RXGEN_OPCODE) ||
1981                 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1982                 if (!identP)
1983                     identP =
1984                         (struct Identity *)malloc(sizeof(struct Identity));
1985                 else
1986                     pident = 1;
1987
1988                 if (!identP) {
1989                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1990                     osi_Panic("Failed malloc in h_GetHost_r\n");
1991                 }
1992                 identP->valid = 0;
1993                 if (!pident)
1994                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1995                 ViceLog(25,
1996                         ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1997                          host, afs_inet_ntoa_r(host->host, hoststr),
1998                          ntohs(host->port)));
1999                 code = 0;
2000             } else if (code == 0) {
2001                 if (!identP)
2002                     identP =
2003                         (struct Identity *)malloc(sizeof(struct Identity));
2004                 else
2005                     pident = 1;
2006
2007                 if (!identP) {
2008                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
2009                     osi_Panic("Failed malloc in h_GetHost_r\n");
2010                 }
2011                 identP->valid = 1;
2012                 interfValid = 1;
2013                 identP->uuid = interf.uuid;
2014                 if (!pident)
2015                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
2016                 ViceLog(25,
2017                         ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
2018                          host, afs_inet_ntoa_r(host->host, hoststr),
2019                          ntohs(host->port)));
2020             }
2021             if (code == 0 && !identP->valid) {
2022                 cb_conn = host->callback_rxcon;
2023                 rx_GetConnection(cb_conn);
2024                 H_UNLOCK;
2025                 code = RXAFSCB_InitCallBackState(cb_conn);
2026                 rx_PutConnection(cb_conn);
2027                 cb_conn=NULL;
2028                 H_LOCK;
2029             } else if (code == 0) {
2030                 oldHost = h_LookupUuid_r(&identP->uuid);
2031                 if (oldHost) {
2032                     h_Hold_r(oldHost);
2033                     h_Lock_r(oldHost);
2034
2035                     if (oldHost->hostFlags & HOSTDELETED) {
2036                         h_Unlock_r(oldHost);
2037                         h_Release_r(oldHost);
2038                         oldHost = NULL;
2039                     }
2040                 }
2041
2042                 if (oldHost) {
2043                     int probefail = 0;
2044
2045                     oldHost->hostFlags |= HWHO_INPROGRESS;
2046
2047                     if (oldHost->interface) {
2048                         int code2;
2049                         afsUUID uuid = oldHost->interface->uuid;
2050                         cb_conn = oldHost->callback_rxcon;
2051                         rx_GetConnection(cb_conn);
2052                         rx_SetConnDeadTime(cb_conn, 2);
2053                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2054                         H_UNLOCK;
2055                         code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2056                         H_LOCK;
2057                         rx_SetConnDeadTime(cb_conn, 50);
2058                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2059                         rx_PutConnection(cb_conn);
2060                         cb_conn=NULL;
2061                         if (code2) {
2062                             /* The primary address is either not responding or
2063                              * is not the client we are looking for.
2064                              * MultiProbeAlternateAddress_r() will remove the
2065                              * alternate interfaces that do not have the same
2066                              * Uuid. */
2067                             ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
2068                                          oldHost,
2069                                          afs_inet_ntoa_r(oldHost->host, hoststr),
2070                                          ntohs(oldHost->port),code2));
2071                             MultiProbeAlternateAddress_r(oldHost);
2072                             probefail = 1;
2073                         }
2074                     } else {
2075                         probefail = 1;
2076                     }
2077
2078                     /* This is a new address for an existing host. Update
2079                      * the list of interfaces for the existing host and
2080                      * delete the host structure we just allocated. */
2081
2082                     /* prevent warnings while manipulating interface lists */
2083                     host->hostFlags |= HOSTDELETED;
2084
2085                     if (oldHost->host != haddr || oldHost->port != hport) {
2086                         struct rx_connection *rxconn;
2087
2088                         ViceLog(25,
2089                                  ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
2090                                    oldHost,
2091                                    afs_inet_ntoa_r(oldHost->host, hoststr2),
2092                                    ntohs(oldHost->port),
2093                                    afs_inet_ntoa_r(haddr, hoststr),
2094                                    ntohs(hport)));
2095                         /*
2096                          * add then remove.  otherwise the host may get marked
2097                          * deleted if we removed the only valid address.
2098                          */
2099                         addInterfaceAddr_r(oldHost, haddr, hport);
2100                         if (probefail || oldHost->host == haddr) {
2101                             /*
2102                              * The probe failed which means that the old
2103                              * address is either unreachable or is not the
2104                              * same host we were just contacted by.  We will
2105                              * also remove addresses if only the port has
2106                              * changed because that indicates the client
2107                              * is behind a NAT.
2108                              */
2109                             removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
2110                         } else {
2111                             int i;
2112                             struct Interface *interface = oldHost->interface;
2113                             int number = oldHost->interface->numberOfInterfaces;
2114                             for (i = 0; i < number; i++) {
2115                                 if (interface->interface[i].addr == haddr &&
2116                                     interface->interface[i].port != hport) {
2117                                     /*
2118                                      * We have just been contacted by a client
2119                                      * that has been seen from behind a NAT
2120                                      * and at least one other address.
2121                                      */
2122                                     removeInterfaceAddr_r(oldHost, haddr,
2123                                                           interface->interface[i].port);
2124                                     break;
2125                                 }
2126                             }
2127                         }
2128                         h_AddHostToAddrHashTable_r(haddr, hport, oldHost);
2129                         oldHost->host = haddr;
2130                         oldHost->port = hport;
2131                         rxconn = oldHost->callback_rxcon;
2132                         oldHost->callback_rxcon = host->callback_rxcon;
2133                         host->callback_rxcon = rxconn;
2134
2135                         /* don't destroy rxconn here; let h_TossStuff_r
2136                          * take care of that via h_Release_r below */
2137                     }
2138                     host->hostFlags &= ~HWHO_INPROGRESS;
2139                     h_Unlock_r(host);
2140                     /* release host because it was allocated by h_Alloc_r */
2141                     h_Release_r(host);
2142                     host = oldHost;
2143                     /* the new host is held and locked */
2144                 } else {
2145                     /* This really is a new host */
2146                     h_AddHostToUuidHashTable_r(&identP->uuid, host);
2147                     cb_conn = host->callback_rxcon;
2148                     rx_GetConnection(cb_conn);
2149                     H_UNLOCK;
2150                     code =
2151                         RXAFSCB_InitCallBackState3(cb_conn,
2152                                                    &FS_HostUUID);
2153                     rx_PutConnection(cb_conn);
2154                     cb_conn=NULL;
2155                     H_LOCK;
2156                     if (code == 0) {
2157                         ViceLog(25,
2158                                 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2159                                  host, afs_inet_ntoa_r(host->host, hoststr),
2160                                  ntohs(host->port)));
2161                         osi_Assert(interfValid == 1);
2162                         initInterfaceAddr_r(host, &interf);
2163                     }
2164                 }
2165             }
2166             if (code) {
2167                 ViceLog(0,
2168                         ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2169                          host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2170                 host->hostFlags |= VENUSDOWN;
2171             } else {
2172                 ViceLog(125,
2173                         ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2174                          host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2175                 host->hostFlags |= RESETDONE;
2176             }
2177         }
2178         if (caps.Capabilities_val
2179             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2180             host->hostFlags |= HERRORTRANS;
2181         else
2182             host->hostFlags &= ~(HERRORTRANS);
2183         host->hostFlags |= ALTADDR;     /* host structure initialization complete */
2184         host->hostFlags &= ~HWHO_INPROGRESS;
2185         h_Unlock_r(host);
2186     }
2187
2188  gethost_out:
2189     if (caps.Capabilities_val)
2190         free(caps.Capabilities_val);
2191     caps.Capabilities_val = NULL;
2192     caps.Capabilities_len = 0;
2193     if (cb_in) {
2194         rx_DestroyConnection(cb_in);
2195         cb_in = NULL;
2196     }
2197     return host;
2198
2199 }                               /*h_GetHost_r */
2200
2201
2202 static char localcellname[PR_MAXNAMELEN + 1];
2203 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
2204 int  num_lrealms = -1;
2205
2206 /* not reentrant */
2207 void
2208 h_InitHostPackage(void)
2209 {
2210     memset(&nulluuid, 0, sizeof(afsUUID));
2211     afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
2212     if (num_lrealms == -1) {
2213         int i;
2214         for (i=0; i<AFS_NUM_LREALMS; i++) {
2215             if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
2216                 break;
2217         }
2218
2219         if (i == 0) {
2220             ViceLog(0,
2221                     ("afs_krb_get_lrealm failed, using %s.\n",
2222                      localcellname));
2223             strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
2224             num_lrealms = i =1;
2225         } else {
2226             num_lrealms = i;
2227         }
2228
2229         /* initialize the rest of the local realms to nullstring for debugging */
2230         for (; i<AFS_NUM_LREALMS; i++)
2231             local_realms[i][0] = '\0';
2232     }
2233     rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2234     rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2235     MUTEX_INIT(&host_glock_mutex, "host glock", MUTEX_DEFAULT, 0);
2236 }
2237
2238 static int
2239 MapName_r(char *aname, char *acell, afs_int32 * aval)
2240 {
2241     namelist lnames;
2242     idlist lids;
2243     afs_int32 code;
2244     afs_int32 anamelen, cnamelen;
2245     int foreign = 0;
2246     char *tname;
2247
2248     anamelen = strlen(aname);
2249     if (anamelen >= PR_MAXNAMELEN)
2250         return -1;              /* bad name -- caller interprets this as anonymous, but retries later */
2251
2252     lnames.namelist_len = 1;
2253     lnames.namelist_val = (prname *) aname;     /* don't malloc in the common case */
2254     lids.idlist_len = 0;
2255     lids.idlist_val = NULL;
2256
2257     cnamelen = strlen(acell);
2258     if (cnamelen) {
2259         if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2260             ViceLog(2,
2261                     ("MapName: cell is foreign.  cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2262                     acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2263             if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2264                 ViceLog(2,
2265                         ("MapName: Name too long, using AnonymousID for %s@%s\n",
2266                          aname, acell));
2267                 *aval = AnonymousID;
2268                 return 0;
2269             }
2270             foreign = 1;        /* attempt cross-cell authentication */
2271             tname = (char *)malloc(PR_MAXNAMELEN);
2272             if (!tname) {
2273                 ViceLog(0, ("Failed malloc in MapName_r\n"));
2274                 osi_Panic("Failed malloc in MapName_r\n");
2275             }
2276             strcpy(tname, aname);
2277             tname[anamelen] = '@';
2278             strcpy(tname + anamelen + 1, acell);
2279             lnames.namelist_val = (prname *) tname;
2280         }
2281     }
2282
2283     H_UNLOCK;
2284     code = hpr_NameToId(&lnames, &lids);
2285     H_LOCK;
2286     if (code == 0) {
2287         if (lids.idlist_val) {
2288             *aval = lids.idlist_val[0];
2289             if (*aval == AnonymousID) {
2290                 ViceLog(2,
2291                         ("MapName: NameToId on %s returns anonymousID\n",
2292                          lnames.namelist_val[0]));
2293             }
2294             free(lids.idlist_val);      /* return parms are not malloced in stub if server proc aborts */
2295         } else {
2296             ViceLog(0,
2297                     ("MapName: NameToId on '%s' is unknown\n",
2298                      lnames.namelist_val[0]));
2299             code = -1;
2300         }
2301     }
2302
2303     if (foreign) {
2304         free(lnames.namelist_val);      /* We allocated this above, so we must free it now. */
2305     }
2306     return code;
2307 }
2308
2309 /*MapName*/
2310
2311
2312 /* NOTE: this returns the client with a Write lock and a refCount */
2313 struct client *
2314 h_ID2Client(afs_int32 vid)
2315 {
2316     struct client *client;
2317     struct host *host;
2318     int count;
2319
2320     H_LOCK;
2321     for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
2322         if (host->hostFlags & HOSTDELETED)
2323             continue;
2324         for (client = host->FirstClient; client; client = client->next) {
2325             if (!client->deleted && client->ViceId == vid) {
2326                 client->refCount++;
2327                 H_UNLOCK;
2328                 ObtainWriteLock(&client->lock);
2329                 return client;
2330             }
2331         }
2332     }
2333     if (count != hostCount) {
2334         ViceLog(0, ("h_ID2Client found %d of %d hosts\n", count, hostCount));
2335     } else if (host != NULL) {
2336         ViceLog(0, ("h_ID2Client found more than %d hosts\n", hostCount));
2337         ShutDownAndCore(PANIC);
2338     }
2339
2340     H_UNLOCK;
2341     return NULL;
2342 }
2343
2344 /*
2345  * Called by the server main loop.  Returns a h_Held client, which must be
2346  * released later the main loop.  Allocates a client if the matching one
2347  * isn't around. The client is returned with its reference count incremented
2348  * by one. The caller must call h_ReleaseClient_r when finished with
2349  * the client.
2350  *
2351  * The refCount on client->host is returned incremented.  h_ReleaseClient_r
2352  * does not decrement the refCount on client->host.
2353  */
2354 struct client *
2355 h_FindClient_r(struct rx_connection *tcon)
2356 {
2357     struct client *client;
2358     struct host *host = NULL;
2359     struct client *oldClient;
2360     afs_int32 viceid = 0;
2361     afs_int32 expTime;
2362     afs_int32 code;
2363     int authClass;
2364 #if (64-MAXKTCNAMELEN)
2365     ticket name length != 64
2366 #endif
2367     char tname[64];
2368     char tinst[64];
2369     char uname[PR_MAXNAMELEN];
2370     char tcell[MAXKTCREALMLEN];
2371     int fail = 0;
2372     int created = 0;
2373
2374     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2375     if (client && client->sid == rxr_CidOf(tcon)
2376         && client->VenusEpoch == rxr_GetEpoch(tcon)
2377         && !(client->host->hostFlags & HOSTDELETED)) {
2378
2379         client->refCount++;
2380         h_Hold_r(client->host);
2381         if (!client->deleted && client->prfail != 2) {
2382             /* Could add shared lock on client here */
2383             /* note that we don't have to lock entry in this path to
2384              * ensure CPS is initialized, since we don't call rx_SetSpecific
2385              * until initialization is done, and we only get here if
2386              * rx_GetSpecific located the client structure.
2387              */
2388             return client;
2389         }
2390         H_UNLOCK;
2391         ObtainWriteLock(&client->lock); /* released at end */
2392         H_LOCK;
2393     } else {
2394         client = NULL;
2395     }
2396
2397     authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2398     ViceLog(5,
2399             ("FindClient: authenticating connection: authClass=%d\n",
2400              authClass));
2401     if (authClass == 1) {
2402         /* A bcrypt tickets, no longer supported */
2403         ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2404         viceid = AnonymousID;
2405         expTime = 0x7fffffff;
2406     } else if (authClass == 2) {
2407         afs_int32 kvno;
2408
2409         /* kerberos ticket */
2410         code = rxkad_GetServerInfo(tcon, /*level */ 0, (afs_uint32 *)&expTime,
2411                                    tname, tinst, tcell, &kvno);
2412         if (code) {
2413             ViceLog(1, ("Failed to get rxkad ticket info\n"));
2414             viceid = AnonymousID;
2415             expTime = 0x7fffffff;
2416         } else {
2417             int ilen = strlen(tinst);
2418             ViceLog(5,
2419                     ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2420                      tname, tinst, tcell, expTime, kvno));
2421             strncpy(uname, tname, sizeof(uname));
2422             if (ilen) {
2423                 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2424                     goto bad_name;
2425                 strcat(uname, ".");
2426                 strcat(uname, tinst);
2427             }
2428             /* translate the name to a vice id */
2429             code = MapName_r(uname, tcell, &viceid);
2430             if (code) {
2431               bad_name:
2432                 ViceLog(1,
2433                         ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2434                          tcell, code));
2435                 fail = 1;
2436                 viceid = AnonymousID;
2437                 expTime = 0x7fffffff;
2438             }
2439         }
2440     } else {
2441         viceid = AnonymousID;   /* unknown security class */
2442         expTime = 0x7fffffff;
2443     }
2444
2445     if (!client) { /* loop */
2446         host = h_GetHost_r(tcon);       /* Returns with incremented refCount  */
2447
2448         if (!host)
2449             return NULL;
2450
2451     retryfirstclient:
2452         /* First try to find the client structure */
2453         for (client = host->FirstClient; client; client = client->next) {
2454             if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2455                 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2456                 client->refCount++;
2457                 H_UNLOCK;
2458                 ObtainWriteLock(&client->lock);
2459                 H_LOCK;
2460                 break;
2461             }
2462         }
2463
2464         /* Still no client structure - get one */
2465         if (!client) {
2466             h_Lock_r(host);
2467             if (host->hostFlags & HOSTDELETED) {
2468                 h_Unlock_r(host);
2469                 h_Release_r(host);
2470                 return NULL;
2471             }
2472             /* Retry to find the client structure */
2473             for (client = host->FirstClient; client; client = client->next) {
2474                 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2475                     && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2476                     h_Unlock_r(host);
2477                     goto retryfirstclient;
2478                 }
2479             }
2480             created = 1;
2481             client = GetCE();
2482             ObtainWriteLock(&client->lock);
2483             client->refCount = 1;
2484             client->host = host;
2485 #if FS_STATS_DETAILED
2486             client->InSameNetwork = host->InSameNetwork;
2487 #endif /* FS_STATS_DETAILED */
2488             client->ViceId = viceid;
2489             client->expTime = expTime;  /* rx only */
2490             client->authClass = authClass;      /* rx only */
2491             client->sid = rxr_CidOf(tcon);
2492             client->VenusEpoch = rxr_GetEpoch(tcon);
2493             client->CPS.prlist_val = NULL;
2494             client->CPS.prlist_len = 0;
2495             h_Unlock_r(host);
2496         }
2497     }
2498     client->prfail = fail;
2499
2500     if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2501         client->CPS.prlist_len = 0;
2502         if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2503             free(client->CPS.prlist_val);
2504         client->CPS.prlist_val = NULL;
2505         client->ViceId = viceid;
2506         client->expTime = expTime;
2507
2508         if (viceid == ANONYMOUSID) {
2509             client->CPS.prlist_len = AnonCPS.prlist_len;
2510             client->CPS.prlist_val = AnonCPS.prlist_val;
2511         } else {
2512             H_UNLOCK;
2513             code = hpr_GetCPS(viceid, &client->CPS);
2514             H_LOCK;
2515             if (code) {
2516                 char hoststr[16];
2517                 ViceLog(0,
2518                         ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2519                          code, viceid, client->host,
2520                          afs_inet_ntoa_r(client->host->host,hoststr),
2521                          ntohs(client->host->port)));
2522
2523                 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2524                  * all protection servers and reevaluates things if no
2525                  * sync server or quorum is found we could still end up
2526                  * with one of these errors. In such case we would like to
2527                  * reevaluate the rpc call to find if there's cps for this
2528                  * guy. We treat other errors (except network failures
2529                  * ones - i.e. code < 0) as an indication that there is no
2530                  * CPS for this host.  Ideally we could like to deal this
2531                  * problem the other way around (i.e.  if code == NOCPS
2532                  * ignore else retry next time) but the problem is that
2533                  * there're other errors (i.e.  EPERM) for which we don't
2534                  * want to retry and we don't know the whole code list!
2535                  */
2536                 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2537                     client->prfail = 1;
2538             }
2539         }
2540         /* the disabling of system:administrators is so iffy and has so many
2541          * possible failure modes that we will disable it again */
2542         /* Turn off System:Administrator for safety
2543          * if (AL_IsAMember(SystemId, client->CPS) == 0)
2544          * osi_Assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2545     }
2546
2547     /* Now, tcon may already be set to a rock, since we blocked with no host
2548      * or client locks set above in pr_GetCPS (XXXX some locking is probably
2549      * required).  So, before setting the RPC's rock, we should disconnect
2550      * the RPC from the other client structure's rock.
2551      */
2552     oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2553     if (oldClient && oldClient != client && oldClient->sid == rxr_CidOf(tcon)
2554         && oldClient->VenusEpoch == rxr_GetEpoch(tcon)) {
2555         char hoststr[16];
2556         if (!oldClient->deleted) {
2557             /* if we didn't create it, it's not ours to put back */
2558             if (created) {
2559                 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2560                             "conn %p (host %s:%d) had client %p(%x)\n",
2561                             client, client->sid, tcon,
2562                             afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2563                             ntohs(rxr_PortOf(tcon)),
2564                             oldClient, oldClient->sid));
2565                 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2566                     free(client->CPS.prlist_val);
2567                 client->CPS.prlist_val = NULL;
2568                 client->CPS.prlist_len = 0;
2569             }
2570             /* We should perhaps check for 0 here */
2571             client->refCount--;
2572             ReleaseWriteLock(&client->lock);
2573             if (created) {
2574                 FreeCE(client);
2575                 created = 0;
2576             }
2577             oldClient->refCount++;
2578             H_UNLOCK;
2579             ObtainWriteLock(&oldClient->lock);
2580             H_LOCK;
2581             client = oldClient;
2582         } else {
2583             ViceLog(0, ("FindClient: deleted client %p(%x) already had "
2584                         "conn %p (host %s:%d), stolen by client %p(%x)\n",
2585                         oldClient, oldClient->sid, tcon,
2586                         afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2587                         ntohs(rxr_PortOf(tcon)),
2588                         client, client->sid));
2589             /* rx_SetSpecific will be done immediately below */
2590         }
2591     }
2592     /* Avoid chaining in more than once. */
2593     if (created) {
2594         h_Lock_r(host);
2595
2596         if (host->hostFlags & HOSTDELETED) {
2597             h_Unlock_r(host);
2598             h_Release_r(host);
2599
2600             host = NULL;
2601             client->host = NULL;
2602
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;
2607
2608             client->refCount--;
2609             ReleaseWriteLock(&client->lock);
2610             FreeCE(client);
2611             return NULL;
2612         }
2613
2614         client->next = host->FirstClient;
2615         host->FirstClient = client;
2616         h_Unlock_r(host);
2617         CurrentConnections++;   /* increment number of connections */
2618     }
2619     rx_SetSpecific(tcon, rxcon_client_key, client);
2620     ReleaseWriteLock(&client->lock);
2621
2622     return client;
2623
2624 }                               /*h_FindClient_r */
2625
2626 int
2627 h_ReleaseClient_r(struct client *client)
2628 {
2629     osi_Assert(client->refCount > 0);
2630     client->refCount--;
2631     return 0;
2632 }
2633
2634
2635 /*
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
2641  */
2642 int
2643 GetClient(struct rx_connection *tcon, struct client **cp)
2644 {
2645     struct client *client;
2646     char hoststr[16];
2647
2648     H_LOCK;
2649     *cp = NULL;
2650     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2651     if (client == NULL) {
2652         ViceLog(0,
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))));
2656         H_UNLOCK;
2657         return VBUSY;
2658     }
2659     if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2660         ViceLog(0,
2661                 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2662                  tcon, rxr_CidOf(tcon), client->sid));
2663         H_UNLOCK;
2664         return VBUSY;
2665     }
2666     if (client && client->LastCall > client->expTime && client->expTime) {
2667         ViceLog(1,
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));
2671         H_UNLOCK;
2672         return VICETOKENDEAD;
2673     }
2674
2675     client->refCount++;
2676     *cp = client;
2677     H_UNLOCK;
2678     return 0;
2679 }                               /*GetClient */
2680
2681 int
2682 PutClient(struct client **cp)
2683 {
2684     if (*cp == NULL)
2685         return -1;
2686
2687     H_LOCK;
2688     h_ReleaseClient_r(*cp);
2689     *cp = NULL;
2690     H_UNLOCK;
2691     return 0;
2692 }                               /*PutClient */
2693
2694
2695 /* Client user name for short term use.  Note that this is NOT inexpensive */
2696 char *
2697 h_UserName(struct client *client)
2698 {
2699     static char User[PR_MAXNAMELEN + 1];
2700     namelist lnames;
2701     idlist lids;
2702
2703     lids.idlist_len = 1;
2704     lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2705     if (!lids.idlist_val) {
2706         ViceLog(0, ("Failed malloc in h_UserName\n"));
2707         osi_Panic("Failed malloc in h_UserName\n");
2708     }
2709     lnames.namelist_len = 0;
2710     lnames.namelist_val = (prname *) 0;
2711     lids.idlist_val[0] = client->ViceId;
2712     if (hpr_IdToName(&lids, &lnames)) {
2713         /* We need to free id we alloced above! */
2714         free(lids.idlist_val);
2715         return "*UNKNOWN USER NAME*";
2716     }
2717     strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2718     free(lids.idlist_val);
2719     free(lnames.namelist_val);
2720     return User;
2721 }                               /*h_UserName */
2722
2723
2724 void
2725 h_PrintStats(void)
2726 {
2727     ViceLog(0,
2728             ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2729              CEs, CEBlocks, HTs, HTBlocks));
2730
2731 }                               /*h_PrintStats */
2732
2733
2734 static int
2735 h_PrintClient(struct host *host, int flags, void *rock)
2736 {
2737     StreamHandle_t *file = (StreamHandle_t *)rock;
2738     struct client *client;
2739     int i;
2740     char tmpStr[256];
2741     char tbuffer[32];
2742     char hoststr[16];
2743     time_t LastCall, expTime;
2744
2745     H_LOCK;
2746     LastCall = host->LastCall;
2747     if (host->hostFlags & HOSTDELETED) {
2748         H_UNLOCK;
2749         return flags;
2750     }
2751     (void)afs_snprintf(tmpStr, sizeof tmpStr,
2752                        "Host %s:%d down = %d, LastCall %s",
2753                        afs_inet_ntoa_r(host->host, hoststr),
2754                        ntohs(host->port), (host->hostFlags & VENUSDOWN),
2755                        afs_ctime(&LastCall, tbuffer,
2756                                  sizeof(tbuffer)));
2757     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2758     for (client = host->FirstClient; client; client = client->next) {
2759         if (!client->deleted) {
2760                 expTime = client->expTime;
2761                 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2762                                    "    user id=%d,  name=%s, sl=%s till %s",
2763                                    client->ViceId, h_UserName(client),
2764                                    client->
2765                                    authClass ? "Authenticated" :
2766                                    "Not authenticated",
2767                                    client->
2768                                    authClass ? afs_ctime(&expTime, tbuffer,
2769                                                          sizeof(tbuffer))
2770                                    : "No Limit\n");
2771                 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2772             (void)afs_snprintf(tmpStr, sizeof tmpStr, "      CPS-%d is [",
2773                                client->CPS.prlist_len);
2774             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2775             if (client->CPS.prlist_val) {
2776                 for (i = 0; i > client->CPS.prlist_len; i++) {
2777                     (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2778                                        client->CPS.prlist_val[i]);
2779                     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2780                 }
2781             }
2782             sprintf(tmpStr, "]\n");
2783             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2784         }
2785     }
2786     H_UNLOCK;
2787     return flags;
2788
2789 }                               /*h_PrintClient */
2790
2791
2792
2793 /*
2794  * Print a list of clients, with last security level and token value seen,
2795  * if known
2796  */
2797 void
2798 h_PrintClients(void)
2799 {
2800     time_t now;
2801     char tmpStr[256];
2802     char tbuffer[32];
2803
2804     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2805
2806     if (file == NULL) {
2807         ViceLog(0,
2808                 ("Couldn't create client dump file %s\n",
2809                  AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2810         return;
2811     }
2812     now = FT_ApproxTime();
2813     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
2814                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2815     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2816     h_Enumerate(h_PrintClient, (char *)file);
2817     STREAM_REALLYCLOSE(file);
2818     ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2819 }
2820
2821
2822
2823
2824 static int
2825 h_DumpHost(struct host *host, int flags, void *rock)
2826 {
2827     StreamHandle_t *file = (StreamHandle_t *)rock;
2828
2829     int i;
2830     char tmpStr[256];
2831     char hoststr[16];
2832
2833     H_LOCK;
2834     (void)afs_snprintf(tmpStr, sizeof tmpStr,
2835                        "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u hcps [",
2836                        afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), host->index,
2837                        host->cblist, CheckLock(&host->lock), host->LastCall,
2838                        host->ActiveCall, (host->hostFlags & VENUSDOWN),
2839                        host->hostFlags & HOSTDELETED, host->Console,
2840                        host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2841                        host->cpsCall);
2842     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2843     if (host->hcps.prlist_val)
2844         for (i = 0; i < host->hcps.prlist_len; i++) {
2845             (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2846                                host->hcps.prlist_val[i]);
2847             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2848         }
2849     sprintf(tmpStr, "] [");
2850     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2851     if (host->interface)
2852         for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2853             char hoststr[16];
2854             sprintf(tmpStr, " %s:%d",
2855                      afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2856                      ntohs(host->interface->interface[i].port));
2857             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2858         }
2859     sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2860     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2861
2862     H_UNLOCK;
2863     return flags;
2864
2865 }                               /*h_DumpHost */
2866
2867
2868 void
2869 h_DumpHosts(void)
2870 {
2871     time_t now;
2872     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2873     char tmpStr[256];
2874     char tbuffer[32];
2875
2876     if (file == NULL) {
2877         ViceLog(0,
2878                 ("Couldn't create host dump file %s\n",
2879                  AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2880         return;
2881     }
2882     now = FT_ApproxTime();
2883     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
2884                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2885     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2886     h_Enumerate(h_DumpHost, (char *)file);
2887     STREAM_REALLYCLOSE(file);
2888     ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2889
2890 }                               /*h_DumpHosts */
2891
2892 #ifdef AFS_DEMAND_ATTACH_FS
2893 /*
2894  * demand attach fs
2895  * host state serialization
2896  */
2897 static int h_stateFillHeader(struct host_state_header * hdr);
2898 static int h_stateCheckHeader(struct host_state_header * hdr);
2899 static int h_stateAllocMap(struct fs_dump_state * state);
2900 static int h_stateSaveHost(struct host * host, int flags, void *rock);
2901 static int h_stateRestoreHost(struct fs_dump_state * state);
2902 static int h_stateRestoreIndex(struct host * h, int flags, void *rock);
2903 static int h_stateVerifyHost(struct host * h, int flags, void *rock);
2904 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
2905                                  afs_uint32 addr, afs_uint16 port, int valid);
2906 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2907 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2908 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2909
2910
2911 /* this procedure saves all host state to disk for fast startup */
2912 int
2913 h_stateSave(struct fs_dump_state * state)
2914 {
2915     AssignInt64(state->eof_offset, &state->hdr->h_offset);
2916
2917     /* XXX debug */
2918     ViceLog(0, ("h_stateSave:  hostCount=%d\n", hostCount));
2919
2920     /* invalidate host state header */
2921     memset(state->h_hdr, 0, sizeof(struct host_state_header));
2922
2923     if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2924                             sizeof(struct host_state_header))) {
2925         state->bail = 1;
2926         goto done;
2927     }
2928
2929     fs_stateIncEOF(state, sizeof(struct host_state_header));
2930
2931     h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2932     if (state->bail) {
2933         goto done;
2934     }
2935
2936     h_stateFillHeader(state->h_hdr);
2937
2938     /* write the real header to disk */
2939     state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2940                                       sizeof(struct host_state_header));
2941
2942  done:
2943     return state->bail;
2944 }
2945
2946 /* demand attach fs
2947  * host state serialization
2948  *
2949  * this procedure restores all host state from a disk for fast startup
2950  */
2951 int
2952 h_stateRestore(struct fs_dump_state * state)
2953 {
2954     int i, records;
2955
2956     /* seek to the right position and read in the host state header */
2957     if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2958                            sizeof(struct host_state_header))) {
2959         state->bail = 1;
2960         goto done;
2961     }
2962
2963     /* check the validity of the header */
2964     if (h_stateCheckHeader(state->h_hdr)) {
2965         state->bail = 1;
2966         goto done;
2967     }
2968
2969     records = state->h_hdr->records;
2970
2971     if (h_stateAllocMap(state)) {
2972         state->bail = 1;
2973         goto done;
2974     }
2975
2976     /* iterate over records restoring host state */
2977     for (i=0; i < records; i++) {
2978         if (h_stateRestoreHost(state) != 0) {
2979             state->bail = 1;
2980             break;
2981         }
2982     }
2983
2984  done:
2985     return state->bail;
2986 }
2987
2988 int
2989 h_stateRestoreIndices(struct fs_dump_state * state)
2990 {
2991     h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
2992     return state->bail;
2993 }
2994
2995 static int
2996 h_stateRestoreIndex(struct host * h, int flags, void *rock)
2997 {
2998     struct fs_dump_state *state = (struct fs_dump_state *)rock;
2999     if (cb_OldToNew(state, h->cblist, &h->cblist)) {
3000         return H_ENUMERATE_BAIL(flags);
3001     }
3002     return flags;
3003 }
3004
3005 int
3006 h_stateVerify(struct fs_dump_state * state)
3007 {
3008     h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
3009     return state->bail;
3010 }
3011
3012 static int
3013 h_stateVerifyHost(struct host * h, int flags, void* rock)
3014 {
3015     struct fs_dump_state *state = (struct fs_dump_state *)rock;
3016     int i;
3017
3018     if (h == NULL) {
3019         ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3020         return H_ENUMERATE_BAIL(flags);
3021     }
3022
3023     if (h->interface) {
3024         for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
3025             if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
3026                                       h->interface->interface[i].port,
3027                                       h->interface->interface[i].valid)) {
3028                 state->bail = 1;
3029             }
3030         }
3031         if (h_stateVerifyUuidHash(state, h)) {
3032             state->bail = 1;
3033         }
3034     } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
3035         state->bail = 1;
3036     }
3037
3038     if (cb_stateVerifyHCBList(state, h)) {
3039         state->bail = 1;
3040     }
3041
3042     return flags;
3043 }
3044
3045 /**
3046  * verify a host is either in, or absent from, the addr hash table.
3047  *
3048  * @param[in] state  fs dump state
3049  * @param[in] h      host we're dealing with
3050  * @param[in] addr   addr to look for (NBO)
3051  * @param[in] port   port to look for (NBO)
3052  * @param[in] valid  1 if we're verifying that the specified addr and port
3053  *                   in the hash table point to the specified host. 0 if we're
3054  *                   verifying that the specified addr and port do NOT point
3055  *                   to the specified host
3056  *
3057  * @return operation status
3058  *  @retval 1 failed to verify, bail out
3059  *  @retval 0 verified successfully, all is well
3060  */
3061 static int
3062 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3063                       afs_uint32 addr, afs_uint16 port, int valid)
3064 {
3065     int ret = 0, found = 0;
3066     struct host *host = NULL;
3067     struct h_AddrHashChain *chain;
3068     int index = h_HashIndex(addr);
3069     char tmp[16];
3070     int chain_len = 0;
3071
3072     for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3073         host = chain->hostPtr;
3074         if (host == NULL) {
3075             afs_inet_ntoa_r(addr, tmp);
3076             ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3077             ret = 1;
3078             goto done;
3079         }
3080         if ((chain->addr == addr) && (chain->port == port)) {
3081             if (host != h) {
3082                 if (valid) {
3083                     ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3084                                 "points to different host struct (%d, %d)\n",
3085                                 h->index, host->index));
3086                     state->flags.warnings_generated = 1;
3087                 }
3088             } else {
3089                 if (!valid) {
3090                     ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3091                                 "marked invalid, but points to the containing "
3092                                 "host\n", afs_inet_ntoa_r(addr, tmp),
3093                                 (unsigned)htons(port)));
3094                     ret = 1;
3095                     goto done;
3096                 }
3097             }
3098             found = 1;
3099             break;
3100         }
3101         if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3102             ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3103                         FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3104             ret = 1;
3105             goto done;
3106         }
3107         chain_len++;
3108     }
3109
3110     if (!found && valid) {
3111         afs_inet_ntoa_r(addr, tmp);
3112         if (state->mode == FS_STATE_LOAD_MODE) {
3113             ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3114                         tmp, (unsigned)htons(port)));
3115             ret = 1;
3116             goto done;
3117         } else {
3118             ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3119                         tmp, (unsigned)htons(port)));
3120             state->flags.warnings_generated = 1;
3121         }
3122     }
3123
3124  done:
3125     return ret;
3126 }
3127
3128 static int
3129 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3130 {
3131     int ret = 0, found = 0;
3132     struct host *host = NULL;
3133     struct h_UuidHashChain *chain;
3134     afsUUID * uuidp = &h->interface->uuid;
3135     int index = h_UuidHashIndex(uuidp);
3136     char tmp[40];
3137     int chain_len = 0;
3138
3139     for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3140         host = chain->hostPtr;
3141         if (host == NULL) {
3142             afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3143             ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3144             ret = 1;
3145             goto done;
3146         }
3147         if (host->interface &&
3148             afs_uuid_equal(&host->interface->uuid, uuidp)) {
3149             if (host != h) {
3150                 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3151                             h->index, host->index));
3152                 state->flags.warnings_generated = 1;
3153             }
3154             found = 1;
3155             goto done;
3156         }
3157         if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3158             ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3159                         FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3160             ret = 1;
3161             goto done;
3162         }
3163         chain_len++;
3164     }
3165
3166     if (!found) {
3167         afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3168         if (state->mode == FS_STATE_LOAD_MODE) {
3169             ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3170             ret = 1;
3171             goto done;
3172         } else {
3173             ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3174             state->flags.warnings_generated = 1;
3175         }
3176     }
3177
3178  done:
3179     return ret;
3180 }
3181
3182 /* create the host state header structure */
3183 static int
3184 h_stateFillHeader(struct host_state_header * hdr)
3185 {
3186     hdr->stamp.magic = HOST_STATE_MAGIC;
3187     hdr->stamp.version = HOST_STATE_VERSION;
3188     return 0;
3189 }
3190
3191 /* check the contents of the host state header structure */
3192 static int
3193 h_stateCheckHeader(struct host_state_header * hdr)
3194 {
3195     int ret=0;
3196
3197     if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3198         ViceLog(0, ("check_host_state_header: invalid state header\n"));
3199         ret = 1;
3200     }
3201     else if (hdr->stamp.version != HOST_STATE_VERSION) {
3202         ViceLog(0, ("check_host_state_header: unknown version number\n"));
3203         ret = 1;
3204     }
3205     return ret;
3206 }
3207
3208 /* allocate the host id mapping table */
3209 static int
3210 h_stateAllocMap(struct fs_dump_state * state)
3211 {
3212     state->h_map.len = state->h_hdr->index_max + 1;
3213     state->h_map.entries = (struct idx_map_entry_t *)
3214         calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3215     return (state->h_map.entries != NULL) ? 0 : 1;
3216 }
3217
3218 /* function called by h_Enumerate to save a host to disk */
3219 static int
3220 h_stateSaveHost(struct host * host, int flags, void* rock)
3221 {
3222     struct fs_dump_state *state = (struct fs_dump_state *) rock;
3223     int if_len=0, hcps_len=0;
3224     struct hostDiskEntry hdsk;
3225     struct host_state_entry_header hdr;
3226     struct Interface * ifp = NULL;
3227     afs_int32 * hcps = NULL;
3228     struct iovec iov[4];
3229     int iovcnt = 2;
3230
3231     memset(&hdr, 0, sizeof(hdr));
3232
3233     if (state->h_hdr->index_max < host->index) {
3234         state->h_hdr->index_max = host->index;
3235     }
3236
3237     h_hostToDiskEntry_r(host, &hdsk);
3238     if (host->interface) {
3239         if_len = sizeof(struct Interface) +
3240             ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3241         ifp = (struct Interface *) malloc(if_len);
3242         osi_Assert(ifp != NULL);
3243         memcpy(ifp, host->interface, if_len);
3244         hdr.interfaces = host->interface->numberOfInterfaces;
3245         iov[iovcnt].iov_base = (char *) ifp;
3246         iov[iovcnt].iov_len = if_len;
3247         iovcnt++;
3248     }
3249     if (host->hcps.prlist_val) {
3250         hdr.hcps = host->hcps.prlist_len;
3251         hcps_len = hdr.hcps * sizeof(afs_int32);
3252         hcps = (afs_int32 *) malloc(hcps_len);
3253         osi_Assert(hcps != NULL);
3254         memcpy(hcps, host->hcps.prlist_val, hcps_len);
3255         iov[iovcnt].iov_base = (char *) hcps;
3256         iov[iovcnt].iov_len = hcps_len;
3257         iovcnt++;
3258     }
3259
3260     if (hdsk.index > state->h_hdr->index_max)
3261         state->h_hdr->index_max = hdsk.index;
3262
3263     hdr.len = sizeof(struct host_state_entry_header) +
3264         sizeof(struct hostDiskEntry) + if_len + hcps_len;
3265     hdr.magic = HOST_STATE_ENTRY_MAGIC;
3266
3267     iov[0].iov_base = (char *) &hdr;
3268     iov[0].iov_len = sizeof(hdr);
3269     iov[1].iov_base = (char *) &hdsk;
3270     iov[1].iov_len = sizeof(struct hostDiskEntry);
3271
3272     if (fs_stateWriteV(state, iov, iovcnt)) {
3273         ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3274         state->bail = 1;
3275     }
3276
3277     fs_stateIncEOF(state, hdr.len);
3278
3279     state->h_hdr->records++;
3280
3281     if (ifp)
3282         free(ifp);
3283     if (hcps)
3284         free(hcps);
3285     if (state->bail) {
3286         return H_ENUMERATE_BAIL(flags);
3287     }
3288     return flags;
3289 }
3290
3291 /* restores a host from disk */
3292 static int
3293 h_stateRestoreHost(struct fs_dump_state * state)
3294 {
3295     int ifp_len=0, hcps_len=0, bail=0;
3296     struct host_state_entry_header hdr;
3297     struct hostDiskEntry hdsk;
3298     struct host *host = NULL;
3299     struct Interface *ifp = NULL;
3300     afs_int32 * hcps = NULL;
3301     struct iovec iov[3];
3302     int iovcnt = 1;
3303
3304     if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3305         ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3306                     state->fn));
3307         bail = 1;
3308         goto done;
3309     }
3310
3311     if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3312         ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3313                     state->fn));
3314         bail = 1;
3315         goto done;
3316     }
3317
3318     iov[0].iov_base = (char *) &hdsk;
3319     iov[0].iov_len = sizeof(struct hostDiskEntry);
3320
3321     if (hdr.interfaces) {
3322         ifp_len = sizeof(struct Interface) +
3323             ((hdr.interfaces-1) * sizeof(struct AddrPort));
3324         ifp = (struct Interface *) malloc(ifp_len);
3325         osi_Assert(ifp != NULL);
3326         iov[iovcnt].iov_base = (char *) ifp;
3327         iov[iovcnt].iov_len = ifp_len;
3328         iovcnt++;
3329     }
3330     if (hdr.hcps) {
3331         hcps_len = hdr.hcps * sizeof(afs_int32);
3332         hcps = (afs_int32 *) malloc(hcps_len);
3333         osi_Assert(hcps != NULL);
3334         iov[iovcnt].iov_base = (char *) hcps;
3335         iov[iovcnt].iov_len = hcps_len;
3336         iovcnt++;
3337     }
3338
3339     if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3340         ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3341         bail = 1;
3342         goto done;
3343     }
3344
3345     if (fs_stateReadV(state, iov, iovcnt)) {
3346         ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3347         bail = 1;
3348         goto done;
3349     }
3350
3351     if (!hdr.hcps && hdsk.hcps_valid) {
3352         /* valid, zero-length host cps ; does this ever happen? */
3353         hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3354         osi_Assert(hcps != NULL);
3355     }
3356
3357     host = GetHT();
3358     osi_Assert(host != NULL);
3359
3360     if (ifp) {
3361         host->interface = ifp;
3362     }
3363     if (hcps) {
3364         host->hcps.prlist_val = hcps;
3365         host->hcps.prlist_len = hdr.hcps;
3366     }
3367
3368     h_diskEntryToHost_r(&hdsk, host);
3369     h_SetupCallbackConn_r(host);
3370
3371     h_AddHostToAddrHashTable_r(host->host, host->port, host);
3372     if (ifp) {
3373         int i;
3374         for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3375             if (ifp->interface[i].valid &&
3376                 !(ifp->interface[i].addr == host->host &&
3377                   ifp->interface[i].port == host->port)) {
3378                 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3379                                            ifp->interface[i].port,
3380                                            host);
3381             }
3382         }
3383         h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3384     }
3385     h_InsertList_r(host);
3386
3387     /* setup host id map entry */
3388     state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3389     state->h_map.entries[hdsk.index].new_idx = host->index;
3390
3391  done:
3392     if (bail) {
3393         if (ifp)
3394             free(ifp);
3395         if (hcps)
3396             free(hcps);
3397     }
3398     return bail;
3399 }
3400
3401 /* serialize a host structure to disk */
3402 static void
3403 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3404 {
3405     out->host = in->host;
3406     out->port = in->port;
3407     out->hostFlags = in->hostFlags;
3408     out->Console = in->Console;
3409     out->hcpsfailed = in->hcpsfailed;
3410     out->LastCall = in->LastCall;
3411     out->ActiveCall = in->ActiveCall;
3412     out->cpsCall = in->cpsCall;
3413     out->cblist = in->cblist;
3414 #ifdef FS_STATS_DETAILED
3415     out->InSameNetwork = in->InSameNetwork;
3416 #endif
3417
3418     /* special fields we save, but are not memcpy'd back on restore */
3419     out->index = in->index;
3420     out->hcps_len = in->hcps.prlist_len;
3421     out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3422 }
3423
3424 /* restore a host structure from disk */
3425 static void
3426 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3427 {
3428     out->host = in->host;
3429     out->port = in->port;
3430     out->hostFlags = in->hostFlags;
3431     out->Console = in->Console;
3432     out->hcpsfailed = in->hcpsfailed;
3433     out->LastCall = in->LastCall;
3434     out->ActiveCall = in->ActiveCall;
3435     out->cpsCall = in->cpsCall;
3436     out->cblist = in->cblist;
3437 #ifdef FS_STATS_DETAILED
3438     out->InSameNetwork = in->InSameNetwork;
3439 #endif
3440 }
3441
3442 /* index translation routines */
3443 int
3444 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3445 {
3446     int ret = 0;
3447
3448     /* hosts use a zero-based index, so old==0 is valid */
3449
3450     if (old >= state->h_map.len) {
3451         ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3452         ret = 1;
3453     } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
3454         ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3455         ret = 1;
3456     } else {
3457         *new = state->h_map.entries[old].new_idx;
3458     }
3459
3460     return ret;
3461 }
3462 #endif /* AFS_DEMAND_ATTACH_FS */
3463
3464
3465 /*
3466  * This counts the number of workstations, the number of active workstations,
3467  * and the number of workstations declared "down" (i.e. not heard from
3468  * recently).  An active workstation has received a call since the cutoff
3469  * time argument passed.
3470  */
3471 void
3472 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3473 {
3474     struct host *host;
3475     int num = 0, active = 0, del = 0;
3476     int count;
3477
3478     H_LOCK;
3479     for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3480         if (!(host->hostFlags & HOSTDELETED)) {
3481             num++;
3482             if (host->ActiveCall > cutofftime)
3483                 active++;
3484             if (host->hostFlags & VENUSDOWN)
3485                 del++;
3486         }
3487     }
3488     if (count != hostCount) {
3489         ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3490     } else if (host != NULL) {
3491         ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3492         ShutDownAndCore(PANIC);
3493     }
3494     H_UNLOCK;
3495     if (nump)
3496         *nump = num;
3497     if (activep)
3498         *activep = active;
3499     if (delp)
3500         *delp = del;
3501
3502 }                               /*h_GetWorkStats */
3503
3504 void
3505 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp, 
3506                  afs_int32 cutofftime)
3507 {
3508     int num, active, del;
3509     h_GetWorkStats(&num, &active, &del, cutofftime);
3510     if (nump)
3511         *nump = num;
3512     if (activep)
3513         *activep = active;
3514     if (delp)
3515         *delp = del;
3516 }
3517
3518 /*------------------------------------------------------------------------
3519  * PRIVATE h_ClassifyAddress
3520  *
3521  * Description:
3522  *      Given a target IP address and a candidate IP address (both
3523  *      in host byte order), classify the candidate into one of three
3524  *      buckets in relation to the target by bumping the counters passed
3525  *      in as parameters.
3526  *
3527  * Arguments:
3528  *      a_targetAddr       : Target address.
3529  *      a_candAddr         : Candidate address.
3530  *      a_sameNetOrSubnetP : Ptr to counter to bump when the two
3531  *                           addresses are either in the same network
3532  *                           or the same subnet.
3533  *      a_diffSubnetP      : ...when the candidate is in a different
3534  *                           subnet.
3535  *      a_diffNetworkP     : ...when the candidate is in a different
3536  *                           network.
3537  *
3538  * Returns:
3539  *      Nothing.
3540  *
3541  * Environment:
3542  *      The target and candidate addresses are both in host byte
3543  *      order, NOT network byte order, when passed in.
3544  *
3545  * Side Effects:
3546  *      As advertised.
3547  *------------------------------------------------------------------------*/
3548
3549 static void
3550 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3551                   afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3552                   afs_int32 * a_diffNetworkP)
3553 {                               /*h_ClassifyAddress */
3554
3555     afs_uint32 targetNet;
3556     afs_uint32 targetSubnet;
3557     afs_uint32 candNet;
3558     afs_uint32 candSubnet;
3559
3560     /*
3561      * Put bad values into the subnet info to start with.
3562      */
3563     targetSubnet = (afs_uint32) 0;
3564     candSubnet = (afs_uint32) 0;
3565
3566     /*
3567      * Pull out the network and subnetwork numbers from the target
3568      * and candidate addresses.  We can short-circuit this whole
3569      * affair if the target and candidate addresses are not of the
3570      * same class.
3571      */
3572     if (IN_CLASSA(a_targetAddr)) {
3573         if (!(IN_CLASSA(a_candAddr))) {
3574             (*a_diffNetworkP)++;
3575             return;
3576         }
3577         targetNet = a_targetAddr & IN_CLASSA_NET;
3578         candNet = a_candAddr & IN_CLASSA_NET;
3579         if (IN_SUBNETA(a_targetAddr))
3580             targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3581         if (IN_SUBNETA(a_candAddr))
3582             candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3583     } else if (IN_CLASSB(a_targetAddr)) {
3584         if (!(IN_CLASSB(a_candAddr))) {
3585             (*a_diffNetworkP)++;
3586             return;
3587         }
3588         targetNet = a_targetAddr & IN_CLASSB_NET;
3589         candNet = a_candAddr & IN_CLASSB_NET;
3590         if (IN_SUBNETB(a_targetAddr))
3591             targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3592         if (IN_SUBNETB(a_candAddr))
3593             candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3594     } /*Class B target */
3595     else if (IN_CLASSC(a_targetAddr)) {
3596         if (!(IN_CLASSC(a_candAddr))) {
3597             (*a_diffNetworkP)++;
3598             return;
3599         }
3600         targetNet = a_targetAddr & IN_CLASSC_NET;
3601         candNet = a_candAddr & IN_CLASSC_NET;
3602
3603         /*
3604          * Note that class C addresses can't have subnets,
3605          * so we leave the defaults untouched.
3606          */
3607     } /*Class C target */
3608     else {
3609         targetNet = a_targetAddr;
3610         candNet = a_candAddr;
3611     }                           /*Class D address */
3612
3613     /*
3614      * Now, simply compare the extracted net and subnet values for
3615      * the two addresses (which at this point are known to be of the
3616      * same class)
3617      */
3618     if (targetNet == candNet) {
3619         if (targetSubnet == candSubnet)
3620             (*a_sameNetOrSubnetP)++;
3621         else
3622             (*a_diffSubnetP)++;
3623     } else
3624         (*a_diffNetworkP)++;
3625
3626 }                               /*h_ClassifyAddress */
3627
3628
3629 /*------------------------------------------------------------------------
3630  * EXPORTED h_GetHostNetStats
3631  *
3632  * Description:
3633  *      Iterate through the host table, and classify each (non-deleted)
3634  *      host entry into ``proximity'' categories (same net or subnet,
3635  *      different subnet, different network).
3636  *
3637  * Arguments:
3638  *      a_numHostsP        : Set to total number of (non-deleted) hosts.
3639  *      a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3640  *      a_diffSubnetP      : Set to # hosts on diff subnet as server.
3641  *      a_diffNetworkP     : Set to # hosts on diff network as server.
3642  *
3643  * Returns:
3644  *      Nothing.
3645  *
3646  * Environment:
3647  *      We only count non-deleted hosts.  The storage pointed to by our
3648  *      parameters is zeroed upon entry.
3649  *
3650  * Side Effects:
3651  *      As advertised.
3652  *------------------------------------------------------------------------*/
3653
3654 void
3655 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3656                   afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3657 {                               /*h_GetHostNetStats */
3658
3659     struct host *hostP; /*Ptr to current host entry */
3660     afs_uint32 currAddr_HBO;    /*Curr host addr, host byte order */
3661     int count;
3662
3663     /*
3664      * Clear out the storage pointed to by our parameters.
3665      */
3666     *a_numHostsP = (afs_int32) 0;
3667     *a_sameNetOrSubnetP = (afs_int32) 0;
3668     *a_diffSubnetP = (afs_int32) 0;
3669     *a_diffNetworkP = (afs_int32) 0;
3670
3671     H_LOCK;
3672     for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3673         if (!(hostP->hostFlags & HOSTDELETED)) {
3674             /*
3675              * Bump the number of undeleted host entries found.
3676              * In classifying the current entry's address, make
3677              * sure to first convert to host byte order.
3678              */
3679             (*a_numHostsP)++;
3680             currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3681             h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3682                               a_sameNetOrSubnetP, a_diffSubnetP,
3683                               a_diffNetworkP);
3684         }                       /*Only look at non-deleted hosts */
3685     }                           /*For each host record hashed to this index */
3686     if (count != hostCount) {
3687         ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3688     } else if (hostP != NULL) {
3689         ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3690         ShutDownAndCore(PANIC);
3691     }
3692     H_UNLOCK;
3693 }                               /*h_GetHostNetStats */
3694
3695 static afs_uint32 checktime;
3696 static afs_uint32 clientdeletetime;
3697 static struct AFSFid zerofid;
3698
3699
3700 /*
3701  * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3702  * Since it can serialize them, and pile up, it should be a separate LWP
3703  * from other events.
3704  */
3705 #if 0
3706 static int
3707 CheckHost(struct host *host, int flags, void *rock)
3708 {
3709     struct client *client;
3710     struct rx_connection *cb_conn = NULL;
3711     int code;
3712
3713 #ifdef AFS_DEMAND_ATTACH_FS
3714     /* kill the checkhost lwp ASAP during shutdown */
3715     FS_STATE_RDLOCK;
3716     if (fs_state.mode == FS_MODE_SHUTDOWN) {
3717         FS_STATE_UNLOCK;
3718         return H_ENUMERATE_BAIL(flags);
3719     }
3720     FS_STATE_UNLOCK;
3721 #endif
3722
3723     /* Host is held by h_Enumerate */
3724     H_LOCK;
3725     for (client = host->FirstClient; client; client = client->next) {
3726         if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3727             client->deleted = 1;
3728             host->hostFlags |= CLIENTDELETED;
3729         }
3730     }
3731     if (host->LastCall < checktime) {
3732         h_Lock_r(host);
3733         if (!(host->hostFlags & HOSTDELETED)) {
3734             host->hostFlags |= HWHO_INPROGRESS;
3735             cb_conn = host->callback_rxcon;
3736             rx_GetConnection(cb_conn);
3737             if (host->LastCall < clientdeletetime) {
3738                 host->hostFlags |= HOSTDELETED;
3739                 if (!(host->hostFlags & VENUSDOWN)) {
3740                     host->hostFlags &= ~ALTADDR;        /* alternate address invalid */
3741                     if (host->interface) {
3742                         H_UNLOCK;
3743                         code =
3744                             RXAFSCB_InitCallBackState3(cb_conn,
3745                                                        &FS_HostUUID);
3746                         H_LOCK;
3747                     } else {
3748                         H_UNLOCK;
3749                         code =
3750                             RXAFSCB_InitCallBackState(cb_conn);
3751                         H_LOCK;
3752                     }
3753                     host->hostFlags |= ALTADDR; /* alternate addresses valid */
3754                     if (code) {
3755                         char hoststr[16];
3756                         (void)afs_inet_ntoa_r(host->host, hoststr);
3757                         ViceLog(0,
3758                                 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3759                                  hoststr, ntohs(host->port)));
3760                         host->hostFlags |= VENUSDOWN;
3761                     }
3762                     /* Note:  it's safe to delete hosts even if they have call
3763                      * back state, because break delayed callbacks (called when a
3764                      * message is received from the workstation) will always send a
3765                      * break all call backs to the workstation if there is no
3766                      * callback.
3767                      */
3768                 }
3769             } else {
3770                 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3771                     char hoststr[16];
3772                     (void)afs_inet_ntoa_r(host->host, hoststr);
3773                     if (host->interface) {
3774                         afsUUID uuid = host->interface->uuid;
3775                         H_UNLOCK;
3776                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3777                         H_LOCK;
3778                         if (code) {
3779                             if (MultiProbeAlternateAddress_r(host)) {
3780                                 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3781                                             hoststr, ntohs(host->port), code));
3782                                 host->hostFlags |= VENUSDOWN;
3783                             }
3784                         }
3785                     } else {
3786                         H_UNLOCK;
3787                         code = RXAFSCB_Probe(cb_conn);
3788                         H_LOCK;
3789                         if (code) {
3790                             ViceLog(0,
3791                                     ("CheckHost: Probe failed for host %s:%d, code %d\n",
3792                                      hoststr, ntohs(host->port), code));
3793                             host->hostFlags |= VENUSDOWN;
3794                         }
3795                     }
3796                 }
3797             }
3798             H_UNLOCK;
3799             rx_PutConnection(cb_conn);
3800             cb_conn=NULL;
3801             H_LOCK;
3802             host->hostFlags &= ~HWHO_INPROGRESS;
3803         }
3804         h_Unlock_r(host);
3805     }
3806     H_UNLOCK;
3807     return held;
3808
3809 }                               /*CheckHost */
3810 #endif
3811
3812 int
3813 CheckHost_r(struct host *host, int flags, void *dummy)
3814 {
3815     struct client *client;
3816     struct rx_connection *cb_conn = NULL;
3817     int code;
3818
3819 #ifdef AFS_DEMAND_ATTACH_FS
3820     /* kill the checkhost lwp ASAP during shutdown */
3821     FS_STATE_RDLOCK;
3822     if (fs_state.mode == FS_MODE_SHUTDOWN) {
3823         FS_STATE_UNLOCK;
3824         return H_ENUMERATE_BAIL(flags);
3825     }
3826     FS_STATE_UNLOCK;
3827 #endif
3828
3829     /* Host is held by h_Enumerate_r */
3830     for (client = host->FirstClient; client; client = client->next) {
3831         if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3832             client->deleted = 1;
3833             host->hostFlags |= CLIENTDELETED;
3834         }
3835     }
3836     if (host->LastCall < checktime) {
3837         h_Lock_r(host);
3838         if (!(host->hostFlags & HOSTDELETED)) {
3839             cb_conn = host->callback_rxcon;
3840             rx_GetConnection(cb_conn);
3841             if (host->LastCall < clientdeletetime) {
3842                 host->hostFlags |= HOSTDELETED;
3843                 if (!(host->hostFlags & VENUSDOWN)) {
3844                     host->hostFlags &= ~ALTADDR;        /* alternate address invalid */
3845                     if (host->interface) {
3846                         H_UNLOCK;
3847                         code =
3848                             RXAFSCB_InitCallBackState3(cb_conn,
3849                                                        &FS_HostUUID);
3850                         H_LOCK;
3851                     } else {
3852                         H_UNLOCK;
3853                         code =
3854                             RXAFSCB_InitCallBackState(cb_conn);
3855                         H_LOCK;
3856                     }
3857                     host->hostFlags |= ALTADDR; /* alternate addresses valid */
3858                     if (code) {
3859                         char hoststr[16];
3860                         (void)afs_inet_ntoa_r(host->host, hoststr);
3861                         ViceLog(0,
3862                                 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3863                                  hoststr, ntohs(host->port)));
3864                         host->hostFlags |= VENUSDOWN;
3865                     }
3866                     /* Note:  it's safe to delete hosts even if they have call
3867                      * back state, because break delayed callbacks (called when a
3868                      * message is received from the workstation) will always send a
3869                      * break all call backs to the workstation if there is no
3870                      * callback.
3871                      */
3872                 }
3873             } else {
3874                 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3875                     char hoststr[16];
3876                     (void)afs_inet_ntoa_r(host->host, hoststr);
3877                     if (host->interface) {
3878                         afsUUID uuid = host->interface->uuid;
3879                         H_UNLOCK;
3880                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3881                         H_LOCK;
3882                         if (code) {
3883                             if (MultiProbeAlternateAddress_r(host)) {
3884                                 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3885                                             hoststr, ntohs(host->port), code));
3886                                 host->hostFlags |= VENUSDOWN;
3887                             }
3888                         }
3889                     } else {
3890                         H_UNLOCK;
3891                         code = RXAFSCB_Probe(cb_conn);
3892                         H_LOCK;
3893                         if (code) {
3894                             ViceLog(0,
3895                                     ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3896                                      hoststr, ntohs(host->port), code));
3897                             host->hostFlags |= VENUSDOWN;
3898                         }
3899                     }
3900                 }
3901             }
3902             H_UNLOCK;
3903             rx_PutConnection(cb_conn);
3904             cb_conn=NULL;
3905             H_LOCK;
3906         }
3907         h_Unlock_r(host);
3908     }
3909     return flags;
3910
3911 }                               /*CheckHost_r */
3912
3913
3914 /*
3915  * Set VenusDown for any hosts that have not had a call in 15 minutes and
3916  * don't respond to a probe.  Note that VenusDown can only be cleared if
3917  * a message is received from the host (see ServerLWP in file.c).
3918  * Delete hosts that have not had any calls in 1 hour, clients that
3919  * have not had any calls in 15 minutes.
3920  *
3921  * This routine is called roughly every 5 minutes.
3922  */
3923 void
3924 h_CheckHosts(void)
3925 {
3926     afs_uint32 now = FT_ApproxTime();
3927
3928     memset(&zerofid, 0, sizeof(zerofid));
3929     /*
3930      * Send a probe to the workstation if it hasn't been heard from in
3931      * 15 minutes
3932      */
3933     checktime = now - 15 * 60;
3934     clientdeletetime = now - 120 * 60;  /* 2 hours ago */
3935
3936     H_LOCK;
3937     h_Enumerate_r(CheckHost_r, hostList, NULL);
3938     H_UNLOCK;
3939 }                               /*h_CheckHosts */
3940
3941 /*
3942  * This is called with host locked and held. At this point, the
3943  * hostAddrHashTable has an entry for the primary addr/port inserted
3944  * by h_Alloc_r().  No other interfaces should be considered valid.
3945  *
3946  * The addresses in the interfaceAddr list are in host byte order.
3947  */
3948 int
3949 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3950 {
3951     int i, j;
3952     int number, count;
3953     afs_uint32 myAddr;
3954     afs_uint16 myPort;
3955     int found;
3956     struct Interface *interface;
3957     char hoststr[16];
3958     char uuidstr[128];
3959     afs_uint16 port7001 = htons(7001);
3960
3961     osi_Assert(host);
3962     osi_Assert(interf);
3963
3964     number = interf->numberOfInterfaces;
3965     myAddr = host->host;        /* current interface address */
3966     myPort = host->port;        /* current port */
3967
3968     ViceLog(125,
3969             ("initInterfaceAddr : host %s:%d numAddr %d\n",
3970               afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3971
3972     /* validation checks */
3973     if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3974         ViceLog(0,
3975                 ("Invalid number of alternate addresses is %d\n", number));
3976         return -1;
3977     }
3978
3979     /*
3980      * The client's notion of its own IP addresses is not reliable.
3981      *
3982      * 1. The client list might contain private address ranges which
3983      *    are likely to be re-used by many clients allocated addresses
3984      *    by a NAT.
3985      *
3986      * 2. The client list will not include any public addresses that
3987      *    are hidden by a NAT.
3988      *
3989      * 3. Private address ranges that are exposed to the server will
3990      *    be obtained from the rx connections that use them.
3991      *
3992      * 4. Lists provided by the client are not necessarily truthful.
3993      *    Many existing clients (UNIX) do not refresh the IP address
3994      *    list as the actual assigned addresses change.  The end result
3995      *    is that they report the initial address list for the lifetime
3996      *    of the process.  In other words, a client can report addresses
3997      *    that they are in fact not using.  Adding these addresses to
3998      *    the host interface list without verification is not only
3999      *    pointless, it is downright dangerous.
4000      *
4001      * We therefore do not add alternate addresses to the addr hash table.
4002      * We only use them for multi-rx callback breaks.
4003      */
4004
4005     /*
4006      * Convert IP addresses to network byte order, and remove
4007      * duplicate IP addresses from the interface list, and
4008      * determine whether or not the incoming addr/port is
4009      * listed.  Note that if the address matches it is not
4010      * truly a match because the port number for the entries
4011      * in the interface list are port 7001 and the port number
4012      * for this connection might not be 7001.
4013      */
4014     for (i = 0, count = 0, found = 0; i < number; i++) {
4015         interf->addr_in[i] = htonl(interf->addr_in[i]);
4016         for (j = 0; j < count; j++) {
4017             if (interf->addr_in[j] == interf->addr_in[i])
4018                 break;
4019         }
4020         if (j == count) {
4021             interf->addr_in[count] = interf->addr_in[i];
4022             if (interf->addr_in[count] == myAddr &&
4023                 port7001 == myPort)
4024                 found = 1;
4025             count++;
4026         }
4027     }
4028
4029     /*
4030      * Allocate and initialize an interface structure for this host.
4031      */
4032     if (found) {
4033         interface = (struct Interface *)
4034             malloc(sizeof(struct Interface) +
4035                    (sizeof(struct AddrPort) * (count - 1)));
4036         if (!interface) {
4037             ViceLog(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
4038             osi_Panic("Failed malloc in initInterfaceAddr_r 1\n");
4039         }
4040         interface->numberOfInterfaces = count;
4041     } else {
4042         interface = (struct Interface *)
4043             malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
4044         if (!interface) {
4045             ViceLog(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4046             osi_Panic("Failed malloc in initInterfaceAddr_r 2\n");
4047         }
4048         interface->numberOfInterfaces = count + 1;
4049         interface->interface[count].addr = myAddr;
4050         interface->interface[count].port = myPort;
4051         interface->interface[count].valid = 1;
4052     }
4053
4054     for (i = 0; i < count; i++) {
4055
4056         interface->interface[i].addr = interf->addr_in[i];
4057         /* We store the port as 7001 because the addresses reported by
4058          * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4059          * are coming from fully connected hosts (no NAT/PATs)
4060          */
4061         interface->interface[i].port = port7001;
4062         interface->interface[i].valid =
4063             (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4064     }
4065
4066     interface->uuid = interf->uuid;
4067
4068     osi_Assert(!host->interface);
4069     host->interface = interface;
4070
4071     if (LogLevel >= 125) {
4072         afsUUID_to_string(&interface->uuid, uuidstr, 127);
4073
4074         ViceLog(125, ("--- uuid %s\n", uuidstr));
4075         for (i = 0; i < host->interface->numberOfInterfaces; i++) {
4076             ViceLog(125, ("--- alt address %s:%d\n",
4077                           afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4078                           ntohs(host->interface->interface[i].port)));
4079         }
4080     }
4081
4082     return 0;
4083 }
4084
4085 /* deleted a HashChain structure for this address and host */
4086 /* returns 1 on success */
4087 int
4088 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4089                                 struct host *host)
4090 {
4091     char hoststr[16];
4092     struct h_AddrHashChain **hp, *th;
4093
4094     if (addr == 0 && port == 0)
4095         return 1;
4096
4097     for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4098          hp = &th->next) {
4099         osi_Assert(th->hostPtr);
4100         if (th->hostPtr == host && th->addr == addr && th->port == port) {
4101             ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4102                           host, afs_inet_ntoa_r(host->host, hoststr),
4103                           ntohs(host->port)));
4104             *hp = th->next;
4105             free(th);
4106             return 1;
4107         }
4108     }
4109     ViceLog(125,
4110             ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4111              host, afs_inet_ntoa_r(host->host, hoststr),
4112              ntohs(host->port)));
4113     return 0;
4114 }
4115
4116
4117 /*
4118 ** prints out all alternate interface address for the host. The 'level'
4119 ** parameter indicates what level of debugging sets this output
4120 */
4121 void
4122 printInterfaceAddr(struct host *host, int level)
4123 {
4124     int i, number;
4125     char hoststr[16];
4126
4127     if (host->interface) {
4128         /* check alternate addresses */
4129         number = host->interface->numberOfInterfaces;
4130         if (number == 0) {
4131             ViceLog(level, ("no-addresses "));
4132         } else {
4133             for (i = 0; i < number; i++)
4134                 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4135                                 ntohs(host->interface->interface[i].port)));
4136         }
4137     }
4138     ViceLog(level, ("\n"));
4139 }