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