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