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