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