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