viced: Check for HOSTDELETED in stillborn check
[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         && !(oldClient->host->hostFlags & HOSTDELETED)) {
2547         char hoststr[16];
2548         if (!oldClient->deleted) {
2549             /* if we didn't create it, it's not ours to put back */
2550             if (created) {
2551                 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2552                             "conn %p (host %s:%d) had client %p(%x)\n",
2553                             client, client->sid, tcon,
2554                             afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2555                             ntohs(rxr_PortOf(tcon)),
2556                             oldClient, oldClient->sid));
2557                 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2558                     free(client->CPS.prlist_val);
2559                 client->CPS.prlist_val = NULL;
2560                 client->CPS.prlist_len = 0;
2561             }
2562             /* We should perhaps check for 0 here */
2563             client->refCount--;
2564             ReleaseWriteLock(&client->lock);
2565             if (created) {
2566                 FreeCE(client);
2567                 created = 0;
2568             }
2569             oldClient->refCount++;
2570
2571             h_Hold_r(oldClient->host);
2572             h_Release_r(client->host);
2573
2574             H_UNLOCK;
2575             ObtainWriteLock(&oldClient->lock);
2576             H_LOCK;
2577             client = oldClient;
2578             host = oldClient->host;
2579         } else {
2580             ViceLog(0, ("FindClient: deleted client %p(%x ref %d host %p href "
2581                         "%d) already had conn %p (host %s:%d, cid %x), stolen "
2582                         "by client %p(%x, ref %d host %p href %d)\n",
2583                         oldClient, oldClient->sid, oldClient->refCount,
2584                         oldClient->host, oldClient->host->refCount, tcon,
2585                         afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2586                         ntohs(rxr_PortOf(tcon)), rxr_CidOf(tcon),
2587                         client, client->sid, client->refCount,
2588                         client->host, client->host->refCount));
2589             /* rx_SetSpecific will be done immediately below */
2590         }
2591     }
2592     /* Avoid chaining in more than once. */
2593     if (created) {
2594         h_Lock_r(host);
2595
2596         if (host->hostFlags & HOSTDELETED) {
2597             h_Unlock_r(host);
2598             h_Release_r(host);
2599
2600             host = NULL;
2601             client->host = NULL;
2602
2603             if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2604                 free(client->CPS.prlist_val);
2605             client->CPS.prlist_val = NULL;
2606             client->CPS.prlist_len = 0;
2607
2608             client->refCount--;
2609             ReleaseWriteLock(&client->lock);
2610             FreeCE(client);
2611             return NULL;
2612         }
2613
2614         client->next = host->FirstClient;
2615         host->FirstClient = client;
2616         h_Unlock_r(host);
2617         CurrentConnections++;   /* increment number of connections */
2618     }
2619     rx_SetSpecific(tcon, rxcon_client_key, client);
2620     ReleaseWriteLock(&client->lock);
2621
2622     return client;
2623
2624 }                               /*h_FindClient_r */
2625
2626 int
2627 h_ReleaseClient_r(struct client *client)
2628 {
2629     osi_Assert(client->refCount > 0);
2630     client->refCount--;
2631     return 0;
2632 }
2633
2634
2635 /*
2636  * Sigh:  this one is used to get the client AGAIN within the individual
2637  * server routines.  This does not bother h_Holding the host, since
2638  * this is assumed already have been done by the server main loop.
2639  * It does check tokens, since only the server routines can return the
2640  * VICETOKENDEAD error code
2641  */
2642 int
2643 GetClient(struct rx_connection *tcon, struct client **cp)
2644 {
2645     struct client *client;
2646     char hoststr[16];
2647
2648     H_LOCK;
2649     *cp = NULL;
2650     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2651     if (client == NULL) {
2652         ViceLog(0,
2653                 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2654                  tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2655                  ntohs(rxr_PortOf(tcon))));
2656         H_UNLOCK;
2657         return VBUSY;
2658     }
2659     if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2660         ViceLog(0,
2661                 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2662                  tcon, rxr_CidOf(tcon), client->sid));
2663         H_UNLOCK;
2664         return VBUSY;
2665     }
2666     if (client && client->LastCall > client->expTime && client->expTime) {
2667         ViceLog(1,
2668                 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2669                  afs_inet_ntoa_r(client->host->host, hoststr),
2670                  ntohs(client->host->port), client->expTime));
2671         H_UNLOCK;
2672         return VICETOKENDEAD;
2673     }
2674     if (client->deleted) {
2675         ViceLog(0, ("GetClient: got deleted client, connection will appear "
2676                     "anonymous; tcon %p cid %x client %p ref %d host %p "
2677                     "(%s:%d) href %d ViceId %d\n",
2678                     tcon, rxr_CidOf(tcon), client, client->refCount,
2679                     client->host,
2680                     afs_inet_ntoa_r(client->host->host, hoststr),
2681                     (int)ntohs(client->host->port), client->host->refCount,
2682                     (int)client->ViceId));
2683     }
2684
2685     client->refCount++;
2686     *cp = client;
2687     H_UNLOCK;
2688     return 0;
2689 }                               /*GetClient */
2690
2691 int
2692 PutClient(struct client **cp)
2693 {
2694     if (*cp == NULL)
2695         return -1;
2696
2697     H_LOCK;
2698     h_ReleaseClient_r(*cp);
2699     *cp = NULL;
2700     H_UNLOCK;
2701     return 0;
2702 }                               /*PutClient */
2703
2704
2705 /* Client user name for short term use.  Note that this is NOT inexpensive */
2706 char *
2707 h_UserName(struct client *client)
2708 {
2709     static char User[PR_MAXNAMELEN + 1];
2710     namelist lnames;
2711     idlist lids;
2712
2713     lids.idlist_len = 1;
2714     lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2715     if (!lids.idlist_val) {
2716         ViceLogThenPanic(0, ("Failed malloc in h_UserName\n"));
2717     }
2718     lnames.namelist_len = 0;
2719     lnames.namelist_val = (prname *) 0;
2720     lids.idlist_val[0] = client->ViceId;
2721     if (hpr_IdToName(&lids, &lnames)) {
2722         /* We need to free id we alloced above! */
2723         free(lids.idlist_val);
2724         return "*UNKNOWN USER NAME*";
2725     }
2726     strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2727     free(lids.idlist_val);
2728     free(lnames.namelist_val);
2729     return User;
2730 }                               /*h_UserName */
2731
2732
2733 void
2734 h_PrintStats(void)
2735 {
2736     ViceLog(0,
2737             ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2738              CEs, CEBlocks, HTs, HTBlocks));
2739
2740 }                               /*h_PrintStats */
2741
2742
2743 static int
2744 h_PrintClient(struct host *host, void *rock)
2745 {
2746     StreamHandle_t *file = (StreamHandle_t *)rock;
2747     struct client *client;
2748     int i;
2749     char tmpStr[256];
2750     char tbuffer[32];
2751     char hoststr[16];
2752     time_t LastCall, expTime;
2753     struct tm tm;
2754
2755     H_LOCK;
2756     LastCall = host->LastCall;
2757     if (host->hostFlags & HOSTDELETED) {
2758         H_UNLOCK;
2759         return 0;
2760     }
2761     strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2762              localtime_r(&LastCall, &tm));
2763     snprintf(tmpStr, sizeof tmpStr, "Host %s:%d down = %d, LastCall %s\n",
2764              afs_inet_ntoa_r(host->host, hoststr),
2765              ntohs(host->port), (host->hostFlags & VENUSDOWN),
2766              tbuffer);
2767     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2768     for (client = host->FirstClient; client; client = client->next) {
2769         if (!client->deleted) {
2770             expTime = client->expTime;
2771             strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2772                      localtime_r(&expTime, &tm));
2773             snprintf(tmpStr, sizeof tmpStr,
2774                      "    user id=%d,  name=%s, sl=%s till %s\n",
2775                      client->ViceId, h_UserName(client),
2776                      client->authClass ? "Authenticated"
2777                                        : "Not authenticated",
2778                      client->authClass ? tbuffer : "No Limit");
2779             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2780             snprintf(tmpStr, sizeof tmpStr, "      CPS-%d is [",
2781                          client->CPS.prlist_len);
2782             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2783             if (client->CPS.prlist_val) {
2784                 for (i = 0; i < client->CPS.prlist_len; i++) {
2785                     snprintf(tmpStr, sizeof tmpStr, " %d",
2786                              client->CPS.prlist_val[i]);
2787                     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2788                 }
2789             }
2790             sprintf(tmpStr, "]\n");
2791             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2792         }
2793     }
2794     H_UNLOCK;
2795     return 0;
2796
2797 }                               /*h_PrintClient */
2798
2799
2800
2801 /*
2802  * Print a list of clients, with last security level and token value seen,
2803  * if known
2804  */
2805 void
2806 h_PrintClients(void)
2807 {
2808     time_t now;
2809     char tmpStr[256];
2810     char tbuffer[32];
2811     struct tm tm;
2812
2813     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2814
2815     if (file == NULL) {
2816         ViceLog(0,
2817                 ("Couldn't create client dump file %s\n",
2818                  AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2819         return;
2820     }
2821     now = FT_ApproxTime();
2822     strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2823              localtime_r(&now, &tm));
2824     snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n\n",
2825              tbuffer);
2826     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2827     h_Enumerate(h_PrintClient, (char *)file);
2828     STREAM_REALLYCLOSE(file);
2829     ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2830 }
2831
2832
2833
2834
2835 static int
2836 h_DumpHost(struct host *host, void *rock)
2837 {
2838     StreamHandle_t *file = (StreamHandle_t *)rock;
2839
2840     int i;
2841     char tmpStr[256];
2842     char hoststr[16];
2843
2844     H_LOCK;
2845     snprintf(tmpStr, sizeof tmpStr,
2846              "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u "
2847              "down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u "
2848              "hcps [",
2849              afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
2850              host->index, host->cblist, CheckLock(&host->lock),
2851              host->LastCall, host->ActiveCall, (host->hostFlags & VENUSDOWN),
2852              host->hostFlags & HOSTDELETED, host->Console,
2853              host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2854              host->cpsCall);
2855     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2856     if (host->hcps.prlist_val)
2857         for (i = 0; i < host->hcps.prlist_len; i++) {
2858             snprintf(tmpStr, sizeof tmpStr, " %d", host->hcps.prlist_val[i]);
2859             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2860         }
2861     sprintf(tmpStr, "] [");
2862     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2863     if (host->interface)
2864         for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2865             char hoststr[16];
2866             sprintf(tmpStr, " %s:%d",
2867                      afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2868                      ntohs(host->interface->interface[i].port));
2869             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2870         }
2871     sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->refCount, host->hostFlags);
2872     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2873
2874     H_UNLOCK;
2875     return 0;
2876
2877 }                               /*h_DumpHost */
2878
2879
2880 void
2881 h_DumpHosts(void)
2882 {
2883     time_t now;
2884     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2885     char tmpStr[256];
2886     char tbuffer[32];
2887     struct tm tm;
2888
2889     if (file == NULL) {
2890         ViceLog(0,
2891                 ("Couldn't create host dump file %s\n",
2892                  AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2893         return;
2894     }
2895     now = FT_ApproxTime();
2896     strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2897              localtime_r(&now, &tm));
2898     snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n\n", tbuffer);
2899     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2900     h_Enumerate(h_DumpHost, (char *)file);
2901     STREAM_REALLYCLOSE(file);
2902     ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2903
2904 }                               /*h_DumpHosts */
2905
2906 #ifdef AFS_DEMAND_ATTACH_FS
2907 /*
2908  * demand attach fs
2909  * host state serialization
2910  */
2911 static int h_stateFillHeader(struct host_state_header * hdr);
2912 static int h_stateCheckHeader(struct host_state_header * hdr);
2913 static int h_stateAllocMap(struct fs_dump_state * state);
2914 static int h_stateSaveHost(struct host * host, void *rock);
2915 static int h_stateRestoreHost(struct fs_dump_state * state);
2916 static int h_stateRestoreIndex(struct host * h, void *rock);
2917 static int h_stateVerifyHost(struct host * h, void *rock);
2918 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
2919                                  afs_uint32 addr, afs_uint16 port, int valid);
2920 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2921 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2922 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2923
2924 /**
2925  * Is this host busy?
2926  *
2927  * This is just a hint and should not be trusted; this should probably only be
2928  * used by the host state serialization code when trying to detect if a host
2929  * can be sanely serialized to disk or not. If this function returns 1, the
2930  * host may be in an invalid state and thus should not be saved to disk.
2931  */
2932 static int
2933 h_isBusy_r(struct host *host)
2934 {
2935     struct Lock *hostLock = &host->lock;
2936     int locked = 0;
2937
2938     LOCK_LOCK(hostLock);
2939     if (hostLock->excl_locked || hostLock->readers_reading) {
2940         locked = 1;
2941     }
2942     LOCK_UNLOCK(hostLock);
2943
2944     if (locked) {
2945         return 1;
2946     }
2947
2948     if ((host->hostFlags & HWHO_INPROGRESS) || !(host->hostFlags & ALTADDR)) {
2949         /* We shouldn't hit this if the host wasn't locked, but just in case... */
2950         return 1;
2951     }
2952
2953     return 0;
2954 }
2955
2956 /* this procedure saves all host state to disk for fast startup */
2957 int
2958 h_stateSave(struct fs_dump_state * state)
2959 {
2960     AssignInt64(state->eof_offset, &state->hdr->h_offset);
2961
2962     /* XXX debug */
2963     ViceLog(0, ("h_stateSave:  hostCount=%d\n", hostCount));
2964
2965     /* invalidate host state header */
2966     memset(state->h_hdr, 0, sizeof(struct host_state_header));
2967
2968     if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2969                             sizeof(struct host_state_header))) {
2970         state->bail = 1;
2971         goto done;
2972     }
2973
2974     fs_stateIncEOF(state, sizeof(struct host_state_header));
2975
2976     h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2977     if (state->bail) {
2978         goto done;
2979     }
2980
2981     h_stateFillHeader(state->h_hdr);
2982
2983     /* write the real header to disk */
2984     state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2985                                       sizeof(struct host_state_header));
2986
2987  done:
2988     return state->bail;
2989 }
2990
2991 /* demand attach fs
2992  * host state serialization
2993  *
2994  * this procedure restores all host state from a disk for fast startup
2995  */
2996 int
2997 h_stateRestore(struct fs_dump_state * state)
2998 {
2999     int i, records;
3000
3001     /* seek to the right position and read in the host state header */
3002     if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
3003                            sizeof(struct host_state_header))) {
3004         state->bail = 1;
3005         goto done;
3006     }
3007
3008     /* check the validity of the header */
3009     if (h_stateCheckHeader(state->h_hdr)) {
3010         state->bail = 1;
3011         goto done;
3012     }
3013
3014     records = state->h_hdr->records;
3015
3016     if (h_stateAllocMap(state)) {
3017         state->bail = 1;
3018         goto done;
3019     }
3020
3021     /* iterate over records restoring host state */
3022     for (i=0; i < records; i++) {
3023         if (h_stateRestoreHost(state) != 0) {
3024             state->bail = 1;
3025             break;
3026         }
3027     }
3028
3029  done:
3030     return state->bail;
3031 }
3032
3033 int
3034 h_stateRestoreIndices(struct fs_dump_state * state)
3035 {
3036     h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
3037     return state->bail;
3038 }
3039
3040 static int
3041 h_stateRestoreIndex(struct host * h, void *rock)
3042 {
3043     struct fs_dump_state *state = (struct fs_dump_state *)rock;
3044     if (cb_OldToNew(state, h->cblist, &h->cblist)) {
3045         return H_ENUMERATE_BAIL(0);
3046     }
3047     return 0;
3048 }
3049
3050 int
3051 h_stateVerify(struct fs_dump_state * state)
3052 {
3053     h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
3054     return state->bail;
3055 }
3056
3057 static int
3058 h_stateVerifyHost(struct host * h, void* rock)
3059 {
3060     struct fs_dump_state *state = (struct fs_dump_state *)rock;
3061     int i;
3062
3063     if (h == NULL) {
3064         ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3065         return H_ENUMERATE_BAIL(0);
3066     }
3067
3068     if (h->interface) {
3069         for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
3070             if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr,
3071                                       h->interface->interface[i].port,
3072                                       h->interface->interface[i].valid)) {
3073                 state->bail = 1;
3074             }
3075         }
3076         if (h_stateVerifyUuidHash(state, h)) {
3077             state->bail = 1;
3078         }
3079     } else if (h_stateVerifyAddrHash(state, h, h->host, h->port, 1)) {
3080         state->bail = 1;
3081     }
3082
3083     if (cb_stateVerifyHCBList(state, h)) {
3084         state->bail = 1;
3085     }
3086
3087     return 0;
3088 }
3089
3090 /**
3091  * verify a host is either in, or absent from, the addr hash table.
3092  *
3093  * @param[in] state  fs dump state
3094  * @param[in] h      host we're dealing with
3095  * @param[in] addr   addr to look for (NBO)
3096  * @param[in] port   port to look for (NBO)
3097  * @param[in] valid  1 if we're verifying that the specified addr and port
3098  *                   in the hash table point to the specified host. 0 if we're
3099  *                   verifying that the specified addr and port do NOT point
3100  *                   to the specified host
3101  *
3102  * @return operation status
3103  *  @retval 1 failed to verify, bail out
3104  *  @retval 0 verified successfully, all is well
3105  */
3106 static int
3107 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3108                       afs_uint32 addr, afs_uint16 port, int valid)
3109 {
3110     int ret = 0, found = 0;
3111     struct host *host = NULL;
3112     struct h_AddrHashChain *chain;
3113     int index = h_HashIndex(addr);
3114     char tmp[16];
3115     int chain_len = 0;
3116
3117     for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3118         host = chain->hostPtr;
3119         if (host == NULL) {
3120             afs_inet_ntoa_r(addr, tmp);
3121             ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3122             ret = 1;
3123             goto done;
3124         }
3125         if ((chain->addr == addr) && (chain->port == port)) {
3126             if (host != h) {
3127                 if (valid) {
3128                     ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3129                                 "points to different host struct (%d, %d)\n",
3130                                 h->index, host->index));
3131                     state->flags.warnings_generated = 1;
3132                 }
3133             } else {
3134                 if (!valid) {
3135                     ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3136                                 "marked invalid, but points to the containing "
3137                                 "host\n", afs_inet_ntoa_r(addr, tmp),
3138                                 (unsigned)htons(port)));
3139                     ret = 1;
3140                     goto done;
3141                 }
3142             }
3143             found = 1;
3144             break;
3145         }
3146         if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3147             ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3148                         FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3149             ret = 1;
3150             goto done;
3151         }
3152         chain_len++;
3153     }
3154
3155     if (!found && valid) {
3156         afs_inet_ntoa_r(addr, tmp);
3157         if (state->mode == FS_STATE_LOAD_MODE) {
3158             ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3159                         tmp, (unsigned)htons(port)));
3160             ret = 1;
3161             goto done;
3162         } else {
3163             ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3164                         tmp, (unsigned)htons(port)));
3165             state->flags.warnings_generated = 1;
3166         }
3167     }
3168
3169  done:
3170     return ret;
3171 }
3172
3173 static int
3174 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3175 {
3176     int ret = 0, found = 0;
3177     struct host *host = NULL;
3178     struct h_UuidHashChain *chain;
3179     afsUUID * uuidp = &h->interface->uuid;
3180     int index = h_UuidHashIndex(uuidp);
3181     char tmp[40];
3182     int chain_len = 0;
3183
3184     for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3185         host = chain->hostPtr;
3186         if (host == NULL) {
3187             afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3188             ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3189             ret = 1;
3190             goto done;
3191         }
3192         if (host->interface &&
3193             afs_uuid_equal(&host->interface->uuid, uuidp)) {
3194             if (host != h) {
3195                 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3196                             h->index, host->index));
3197                 state->flags.warnings_generated = 1;
3198             }
3199             found = 1;
3200             goto done;
3201         }
3202         if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3203             ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3204                         FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3205             ret = 1;
3206             goto done;
3207         }
3208         chain_len++;
3209     }
3210
3211     if (!found) {
3212         afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3213         if (state->mode == FS_STATE_LOAD_MODE) {
3214             ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3215             ret = 1;
3216             goto done;
3217         } else {
3218             ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3219             state->flags.warnings_generated = 1;
3220         }
3221     }
3222
3223  done:
3224     return ret;
3225 }
3226
3227 /* create the host state header structure */
3228 static int
3229 h_stateFillHeader(struct host_state_header * hdr)
3230 {
3231     hdr->stamp.magic = HOST_STATE_MAGIC;
3232     hdr->stamp.version = HOST_STATE_VERSION;
3233     return 0;
3234 }
3235
3236 /* check the contents of the host state header structure */
3237 static int
3238 h_stateCheckHeader(struct host_state_header * hdr)
3239 {
3240     int ret=0;
3241
3242     if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3243         ViceLog(0, ("check_host_state_header: invalid state header\n"));
3244         ret = 1;
3245     }
3246     else if (hdr->stamp.version != HOST_STATE_VERSION) {
3247         ViceLog(0, ("check_host_state_header: unknown version number\n"));
3248         ret = 1;
3249     }
3250     return ret;
3251 }
3252
3253 /* allocate the host id mapping table */
3254 static int
3255 h_stateAllocMap(struct fs_dump_state * state)
3256 {
3257     state->h_map.len = state->h_hdr->index_max + 1;
3258     state->h_map.entries = (struct idx_map_entry_t *)
3259         calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3260     return (state->h_map.entries != NULL) ? 0 : 1;
3261 }
3262
3263 /* function called by h_Enumerate to save a host to disk */
3264 static int
3265 h_stateSaveHost(struct host * host, void* rock)
3266 {
3267     struct fs_dump_state *state = (struct fs_dump_state *) rock;
3268     int if_len=0, hcps_len=0;
3269     struct hostDiskEntry hdsk;
3270     struct host_state_entry_header hdr;
3271     struct Interface * ifp = NULL;
3272     afs_int32 * hcps = NULL;
3273     struct iovec iov[4];
3274     int iovcnt = 2;
3275
3276     if (h_isBusy_r(host)) {
3277         char hoststr[16];
3278         ViceLog(1, ("Not saving host %s:%d to disk; host appears busy\n",
3279                     afs_inet_ntoa_r(host->host, hoststr), (int)ntohs(host->port)));
3280         /* Make sure we don't try to save callbacks to disk for this host, or
3281          * we'll get confused on restore */
3282         DeleteAllCallBacks_r(host, 1);
3283         return 0;
3284     }
3285
3286     memset(&hdr, 0, sizeof(hdr));
3287
3288     if (state->h_hdr->index_max < host->index) {
3289         state->h_hdr->index_max = host->index;
3290     }
3291
3292     h_hostToDiskEntry_r(host, &hdsk);
3293     if (host->interface) {
3294         if_len = sizeof(struct Interface) +
3295             ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3296         ifp = (struct Interface *) malloc(if_len);
3297         osi_Assert(ifp != NULL);
3298         memcpy(ifp, host->interface, if_len);
3299         hdr.interfaces = host->interface->numberOfInterfaces;
3300         iov[iovcnt].iov_base = (char *) ifp;
3301         iov[iovcnt].iov_len = if_len;
3302         iovcnt++;
3303     }
3304     if (host->hcps.prlist_val) {
3305         hdr.hcps = host->hcps.prlist_len;
3306         hcps_len = hdr.hcps * sizeof(afs_int32);
3307         hcps = (afs_int32 *) malloc(hcps_len);
3308         osi_Assert(hcps != NULL);
3309         memcpy(hcps, host->hcps.prlist_val, hcps_len);
3310         iov[iovcnt].iov_base = (char *) hcps;
3311         iov[iovcnt].iov_len = hcps_len;
3312         iovcnt++;
3313     }
3314
3315     if (hdsk.index > state->h_hdr->index_max)
3316         state->h_hdr->index_max = hdsk.index;
3317
3318     hdr.len = sizeof(struct host_state_entry_header) +
3319         sizeof(struct hostDiskEntry) + if_len + hcps_len;
3320     hdr.magic = HOST_STATE_ENTRY_MAGIC;
3321
3322     iov[0].iov_base = (char *) &hdr;
3323     iov[0].iov_len = sizeof(hdr);
3324     iov[1].iov_base = (char *) &hdsk;
3325     iov[1].iov_len = sizeof(struct hostDiskEntry);
3326
3327     if (fs_stateWriteV(state, iov, iovcnt)) {
3328         ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3329         state->bail = 1;
3330     }
3331
3332     fs_stateIncEOF(state, hdr.len);
3333
3334     state->h_hdr->records++;
3335
3336     if (ifp)
3337         free(ifp);
3338     if (hcps)
3339         free(hcps);
3340     if (state->bail) {
3341         return H_ENUMERATE_BAIL(0);
3342     }
3343     return 0;
3344 }
3345
3346 /* restores a host from disk */
3347 static int
3348 h_stateRestoreHost(struct fs_dump_state * state)
3349 {
3350     int ifp_len=0, hcps_len=0, bail=0;
3351     struct host_state_entry_header hdr;
3352     struct hostDiskEntry hdsk;
3353     struct host *host = NULL;
3354     struct Interface *ifp = NULL;
3355     afs_int32 * hcps = NULL;
3356     struct iovec iov[3];
3357     int iovcnt = 1;
3358
3359     if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3360         ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3361                     state->fn));
3362         bail = 1;
3363         goto done;
3364     }
3365
3366     if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3367         ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3368                     state->fn));
3369         bail = 1;
3370         goto done;
3371     }
3372
3373     iov[0].iov_base = (char *) &hdsk;
3374     iov[0].iov_len = sizeof(struct hostDiskEntry);
3375
3376     if (hdr.interfaces) {
3377         ifp_len = sizeof(struct Interface) +
3378             ((hdr.interfaces-1) * sizeof(struct AddrPort));
3379         ifp = (struct Interface *) malloc(ifp_len);
3380         osi_Assert(ifp != NULL);
3381         iov[iovcnt].iov_base = (char *) ifp;
3382         iov[iovcnt].iov_len = ifp_len;
3383         iovcnt++;
3384     }
3385     if (hdr.hcps) {
3386         hcps_len = hdr.hcps * sizeof(afs_int32);
3387         hcps = (afs_int32 *) malloc(hcps_len);
3388         osi_Assert(hcps != NULL);
3389         iov[iovcnt].iov_base = (char *) hcps;
3390         iov[iovcnt].iov_len = hcps_len;
3391         iovcnt++;
3392     }
3393
3394     if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3395         ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3396         bail = 1;
3397         goto done;
3398     }
3399
3400     if (fs_stateReadV(state, iov, iovcnt)) {
3401         ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3402         bail = 1;
3403         goto done;
3404     }
3405
3406     if (!hdr.hcps && hdsk.hcps_valid) {
3407         /* valid, zero-length host cps ; does this ever happen? */
3408         hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3409         osi_Assert(hcps != NULL);
3410     }
3411
3412     if ((hdsk.hostFlags & HWHO_INPROGRESS) || !(hdsk.hostFlags & ALTADDR)) {
3413         char hoststr[16];
3414         ViceLog(0, ("h_stateRestoreHost: skipping host %s:%d due to invalid flags 0x%x\n",
3415                     afs_inet_ntoa_r(hdsk.host, hoststr), (int)ntohs(hdsk.port),
3416                     (unsigned)hdsk.hostFlags));
3417         bail = 0;
3418         state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_SKIPPED;
3419         goto done;
3420     }
3421
3422     /* for restoring state, we better be able to get a host! */
3423     host = GetHT();
3424     osi_Assert(host != NULL);
3425
3426     if (ifp) {
3427         host->interface = ifp;
3428     }
3429     if (hcps) {
3430         host->hcps.prlist_val = hcps;
3431         host->hcps.prlist_len = hdr.hcps;
3432     }
3433
3434     h_diskEntryToHost_r(&hdsk, host);
3435     h_SetupCallbackConn_r(host);
3436
3437     h_AddHostToAddrHashTable_r(host->host, host->port, host);
3438     if (ifp) {
3439         int i;
3440         for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3441             if (ifp->interface[i].valid &&
3442                 !(ifp->interface[i].addr == host->host &&
3443                   ifp->interface[i].port == host->port)) {
3444                 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3445                                            ifp->interface[i].port,
3446                                            host);
3447             }
3448         }
3449         h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3450     }
3451     h_InsertList_r(host);
3452
3453     /* setup host id map entry */
3454     state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_VALID;
3455     state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3456     state->h_map.entries[hdsk.index].new_idx = host->index;
3457
3458  done:
3459     if (bail) {
3460         if (ifp)
3461             free(ifp);
3462         if (hcps)
3463             free(hcps);
3464     }
3465     return bail;
3466 }
3467
3468 /* serialize a host structure to disk */
3469 static void
3470 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3471 {
3472     out->host = in->host;
3473     out->port = in->port;
3474     out->hostFlags = in->hostFlags;
3475     out->Console = in->Console;
3476     out->hcpsfailed = in->hcpsfailed;
3477     out->LastCall = in->LastCall;
3478     out->ActiveCall = in->ActiveCall;
3479     out->cpsCall = in->cpsCall;
3480     out->cblist = in->cblist;
3481 #ifdef FS_STATS_DETAILED
3482     out->InSameNetwork = in->InSameNetwork;
3483 #endif
3484
3485     /* special fields we save, but are not memcpy'd back on restore */
3486     out->index = in->index;
3487     out->hcps_len = in->hcps.prlist_len;
3488     out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3489 }
3490
3491 /* restore a host structure from disk */
3492 static void
3493 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3494 {
3495     out->host = in->host;
3496     out->port = in->port;
3497     out->hostFlags = in->hostFlags;
3498     out->Console = in->Console;
3499     out->hcpsfailed = in->hcpsfailed;
3500     out->LastCall = in->LastCall;
3501     out->ActiveCall = in->ActiveCall;
3502     out->cpsCall = in->cpsCall;
3503     out->cblist = in->cblist;
3504 #ifdef FS_STATS_DETAILED
3505     out->InSameNetwork = in->InSameNetwork;
3506 #endif
3507 }
3508
3509 /* index translation routines */
3510 int
3511 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3512 {
3513     int ret = 0;
3514
3515     /* hosts use a zero-based index, so old==0 is valid */
3516
3517     if (old >= state->h_map.len) {
3518         ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3519         ret = 1;
3520     } else if (state->h_map.entries[old].valid != FS_STATE_IDX_VALID ||
3521                state->h_map.entries[old].old_idx != old) { /* sanity check */
3522         ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3523         ret = 1;
3524     } else {
3525         *new = state->h_map.entries[old].new_idx;
3526     }
3527
3528     return ret;
3529 }
3530 #endif /* AFS_DEMAND_ATTACH_FS */
3531
3532
3533 /*
3534  * This counts the number of workstations, the number of active workstations,
3535  * and the number of workstations declared "down" (i.e. not heard from
3536  * recently).  An active workstation has received a call since the cutoff
3537  * time argument passed.
3538  */
3539 void
3540 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3541 {
3542     struct host *host;
3543     int num = 0, active = 0, del = 0;
3544     int count;
3545
3546     H_LOCK;
3547     for (count = 0, host = hostList; host && count < hostCount; host = host->next, count++) {
3548         if (!(host->hostFlags & HOSTDELETED)) {
3549             num++;
3550             if (host->ActiveCall > cutofftime)
3551                 active++;
3552             if (host->hostFlags & VENUSDOWN)
3553                 del++;
3554         }
3555     }
3556     if (count != hostCount) {
3557         ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3558     } else if (host != NULL) {
3559         ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3560         ShutDownAndCore(PANIC);
3561     }
3562     H_UNLOCK;
3563     if (nump)
3564         *nump = num;
3565     if (activep)
3566         *activep = active;
3567     if (delp)
3568         *delp = del;
3569
3570 }                               /*h_GetWorkStats */
3571
3572 void
3573 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp, 
3574                  afs_int32 cutofftime)
3575 {
3576     int num, active, del;
3577     h_GetWorkStats(&num, &active, &del, cutofftime);
3578     if (nump)
3579         *nump = num;
3580     if (activep)
3581         *activep = active;
3582     if (delp)
3583         *delp = del;
3584 }
3585
3586 /*------------------------------------------------------------------------
3587  * PRIVATE h_ClassifyAddress
3588  *
3589  * Description:
3590  *      Given a target IP address and a candidate IP address (both
3591  *      in host byte order), classify the candidate into one of three
3592  *      buckets in relation to the target by bumping the counters passed
3593  *      in as parameters.
3594  *
3595  * Arguments:
3596  *      a_targetAddr       : Target address.
3597  *      a_candAddr         : Candidate address.
3598  *      a_sameNetOrSubnetP : Ptr to counter to bump when the two
3599  *                           addresses are either in the same network
3600  *                           or the same subnet.
3601  *      a_diffSubnetP      : ...when the candidate is in a different
3602  *                           subnet.
3603  *      a_diffNetworkP     : ...when the candidate is in a different
3604  *                           network.
3605  *
3606  * Returns:
3607  *      Nothing.
3608  *
3609  * Environment:
3610  *      The target and candidate addresses are both in host byte
3611  *      order, NOT network byte order, when passed in.
3612  *
3613  * Side Effects:
3614  *      As advertised.
3615  *------------------------------------------------------------------------*/
3616
3617 static void
3618 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3619                   afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3620                   afs_int32 * a_diffNetworkP)
3621 {                               /*h_ClassifyAddress */
3622
3623     afs_uint32 targetNet;
3624     afs_uint32 targetSubnet;
3625     afs_uint32 candNet;
3626     afs_uint32 candSubnet;
3627
3628     /*
3629      * Put bad values into the subnet info to start with.
3630      */
3631     targetSubnet = (afs_uint32) 0;
3632     candSubnet = (afs_uint32) 0;
3633
3634     /*
3635      * Pull out the network and subnetwork numbers from the target
3636      * and candidate addresses.  We can short-circuit this whole
3637      * affair if the target and candidate addresses are not of the
3638      * same class.
3639      */
3640     if (IN_CLASSA(a_targetAddr)) {
3641         if (!(IN_CLASSA(a_candAddr))) {
3642             (*a_diffNetworkP)++;
3643             return;
3644         }
3645         targetNet = a_targetAddr & IN_CLASSA_NET;
3646         candNet = a_candAddr & IN_CLASSA_NET;
3647         if (IN_SUBNETA(a_targetAddr))
3648             targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3649         if (IN_SUBNETA(a_candAddr))
3650             candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3651     } else if (IN_CLASSB(a_targetAddr)) {
3652         if (!(IN_CLASSB(a_candAddr))) {
3653             (*a_diffNetworkP)++;
3654             return;
3655         }
3656         targetNet = a_targetAddr & IN_CLASSB_NET;
3657         candNet = a_candAddr & IN_CLASSB_NET;
3658         if (IN_SUBNETB(a_targetAddr))
3659             targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3660         if (IN_SUBNETB(a_candAddr))
3661             candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3662     } /*Class B target */
3663     else if (IN_CLASSC(a_targetAddr)) {
3664         if (!(IN_CLASSC(a_candAddr))) {
3665             (*a_diffNetworkP)++;
3666             return;
3667         }
3668         targetNet = a_targetAddr & IN_CLASSC_NET;
3669         candNet = a_candAddr & IN_CLASSC_NET;
3670
3671         /*
3672          * Note that class C addresses can't have subnets,
3673          * so we leave the defaults untouched.
3674          */
3675     } /*Class C target */
3676     else {
3677         targetNet = a_targetAddr;
3678         candNet = a_candAddr;
3679     }                           /*Class D address */
3680
3681     /*
3682      * Now, simply compare the extracted net and subnet values for
3683      * the two addresses (which at this point are known to be of the
3684      * same class)
3685      */
3686     if (targetNet == candNet) {
3687         if (targetSubnet == candSubnet)
3688             (*a_sameNetOrSubnetP)++;
3689         else
3690             (*a_diffSubnetP)++;
3691     } else
3692         (*a_diffNetworkP)++;
3693
3694 }                               /*h_ClassifyAddress */
3695
3696
3697 /*------------------------------------------------------------------------
3698  * EXPORTED h_GetHostNetStats
3699  *
3700  * Description:
3701  *      Iterate through the host table, and classify each (non-deleted)
3702  *      host entry into ``proximity'' categories (same net or subnet,
3703  *      different subnet, different network).
3704  *
3705  * Arguments:
3706  *      a_numHostsP        : Set to total number of (non-deleted) hosts.
3707  *      a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3708  *      a_diffSubnetP      : Set to # hosts on diff subnet as server.
3709  *      a_diffNetworkP     : Set to # hosts on diff network as server.
3710  *
3711  * Returns:
3712  *      Nothing.
3713  *
3714  * Environment:
3715  *      We only count non-deleted hosts.  The storage pointed to by our
3716  *      parameters is zeroed upon entry.
3717  *
3718  * Side Effects:
3719  *      As advertised.
3720  *------------------------------------------------------------------------*/
3721
3722 void
3723 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3724                   afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3725 {                               /*h_GetHostNetStats */
3726
3727     struct host *hostP; /*Ptr to current host entry */
3728     afs_uint32 currAddr_HBO;    /*Curr host addr, host byte order */
3729     int count;
3730
3731     /*
3732      * Clear out the storage pointed to by our parameters.
3733      */
3734     *a_numHostsP = (afs_int32) 0;
3735     *a_sameNetOrSubnetP = (afs_int32) 0;
3736     *a_diffSubnetP = (afs_int32) 0;
3737     *a_diffNetworkP = (afs_int32) 0;
3738
3739     H_LOCK;
3740     for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->next, count++) {
3741         if (!(hostP->hostFlags & HOSTDELETED)) {
3742             /*
3743              * Bump the number of undeleted host entries found.
3744              * In classifying the current entry's address, make
3745              * sure to first convert to host byte order.
3746              */
3747             (*a_numHostsP)++;
3748             currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3749             h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3750                               a_sameNetOrSubnetP, a_diffSubnetP,
3751                               a_diffNetworkP);
3752         }                       /*Only look at non-deleted hosts */
3753     }                           /*For each host record hashed to this index */
3754     if (count != hostCount) {
3755         ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3756     } else if (hostP != NULL) {
3757         ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3758         ShutDownAndCore(PANIC);
3759     }
3760     H_UNLOCK;
3761 }                               /*h_GetHostNetStats */
3762
3763 static afs_uint32 checktime;
3764 static afs_uint32 clientdeletetime;
3765 static struct AFSFid zerofid;
3766
3767
3768 /*
3769  * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3770  * Since it can serialize them, and pile up, it should be a separate LWP
3771  * from other events.
3772  */
3773 #if 0
3774 static int
3775 CheckHost(struct host *host, int flags, void *rock)
3776 {
3777     struct client *client;
3778     struct rx_connection *cb_conn = NULL;
3779     int code;
3780
3781 #ifdef AFS_DEMAND_ATTACH_FS
3782     /* kill the checkhost lwp ASAP during shutdown */
3783     FS_STATE_RDLOCK;
3784     if (fs_state.mode == FS_MODE_SHUTDOWN) {
3785         FS_STATE_UNLOCK;
3786         return H_ENUMERATE_BAIL(flags);
3787     }
3788     FS_STATE_UNLOCK;
3789 #endif
3790
3791     /* Host is held by h_Enumerate */
3792     H_LOCK;
3793     for (client = host->FirstClient; client; client = client->next) {
3794         if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3795             client->deleted = 1;
3796             host->hostFlags |= CLIENTDELETED;
3797         }
3798     }
3799     if (host->LastCall < checktime) {
3800         h_Lock_r(host);
3801         if (!(host->hostFlags & HOSTDELETED)) {
3802             host->hostFlags |= HWHO_INPROGRESS;
3803             cb_conn = host->callback_rxcon;
3804             rx_GetConnection(cb_conn);
3805             if (host->LastCall < clientdeletetime) {
3806                 host->hostFlags |= HOSTDELETED;
3807                 if (!(host->hostFlags & VENUSDOWN)) {
3808                     host->hostFlags &= ~ALTADDR;        /* alternate address invalid */
3809                     if (host->interface) {
3810                         H_UNLOCK;
3811                         code =
3812                             RXAFSCB_InitCallBackState3(cb_conn,
3813                                                        &FS_HostUUID);
3814                         H_LOCK;
3815                     } else {
3816                         H_UNLOCK;
3817                         code =
3818                             RXAFSCB_InitCallBackState(cb_conn);
3819                         H_LOCK;
3820                     }
3821                     host->hostFlags |= ALTADDR; /* alternate addresses valid */
3822                     if (code) {
3823                         char hoststr[16];
3824                         (void)afs_inet_ntoa_r(host->host, hoststr);
3825                         ViceLog(0,
3826                                 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3827                                  hoststr, ntohs(host->port)));
3828                         host->hostFlags |= VENUSDOWN;
3829                     }
3830                     /* Note:  it's safe to delete hosts even if they have call
3831                      * back state, because break delayed callbacks (called when a
3832                      * message is received from the workstation) will always send a
3833                      * break all call backs to the workstation if there is no
3834                      * callback.
3835                      */
3836                 }
3837             } else {
3838                 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3839                     char hoststr[16];
3840                     (void)afs_inet_ntoa_r(host->host, hoststr);
3841                     if (host->interface) {
3842                         afsUUID uuid = host->interface->uuid;
3843                         H_UNLOCK;
3844                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3845                         H_LOCK;
3846                         if (code) {
3847                             if (MultiProbeAlternateAddress_r(host)) {
3848                                 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3849                                             hoststr, ntohs(host->port), code));
3850                                 host->hostFlags |= VENUSDOWN;
3851                             }
3852                         }
3853                     } else {
3854                         H_UNLOCK;
3855                         code = RXAFSCB_Probe(cb_conn);
3856                         H_LOCK;
3857                         if (code) {
3858                             ViceLog(0,
3859                                     ("CheckHost: Probe failed for host %s:%d, code %d\n",
3860                                      hoststr, ntohs(host->port), code));
3861                             host->hostFlags |= VENUSDOWN;
3862                         }
3863                     }
3864                 }
3865             }
3866             H_UNLOCK;
3867             rx_PutConnection(cb_conn);
3868             cb_conn=NULL;
3869             H_LOCK;
3870             host->hostFlags &= ~HWHO_INPROGRESS;
3871         }
3872         h_Unlock_r(host);
3873     }
3874     H_UNLOCK;
3875     return held;
3876
3877 }                               /*CheckHost */
3878 #endif
3879
3880 int
3881 CheckHost_r(struct host *host, void *dummy)
3882 {
3883     struct client *client;
3884     struct rx_connection *cb_conn = NULL;
3885     int code;
3886
3887 #ifdef AFS_DEMAND_ATTACH_FS
3888     /* kill the checkhost lwp ASAP during shutdown */
3889     FS_STATE_RDLOCK;
3890     if (fs_state.mode == FS_MODE_SHUTDOWN) {
3891         FS_STATE_UNLOCK;
3892         return H_ENUMERATE_BAIL(0);
3893     }
3894     FS_STATE_UNLOCK;
3895 #endif
3896
3897     /* Host is held by h_Enumerate_r */
3898     for (client = host->FirstClient; client; client = client->next) {
3899         if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3900             client->deleted = 1;
3901             host->hostFlags |= CLIENTDELETED;
3902         }
3903     }
3904     if (host->LastCall < checktime) {
3905         h_Lock_r(host);
3906         if (!(host->hostFlags & HOSTDELETED)) {
3907             host->hostFlags |= HWHO_INPROGRESS;
3908             cb_conn = host->callback_rxcon;
3909             rx_GetConnection(cb_conn);
3910             if (host->LastCall < clientdeletetime) {
3911                 host->hostFlags |= HOSTDELETED;
3912                 if (!(host->hostFlags & VENUSDOWN)) {
3913                     host->hostFlags &= ~ALTADDR;        /* alternate address invalid */
3914                     if (host->interface) {
3915                         H_UNLOCK;
3916                         code =
3917                             RXAFSCB_InitCallBackState3(cb_conn,
3918                                                        &FS_HostUUID);
3919                         H_LOCK;
3920                     } else {
3921                         H_UNLOCK;
3922                         code =
3923                             RXAFSCB_InitCallBackState(cb_conn);
3924                         H_LOCK;
3925                     }
3926                     host->hostFlags |= ALTADDR; /* alternate addresses valid */
3927                     if (code) {
3928                         char hoststr[16];
3929                         (void)afs_inet_ntoa_r(host->host, hoststr);
3930                         ViceLog(0,
3931                                 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3932                                  hoststr, ntohs(host->port)));
3933                         host->hostFlags |= VENUSDOWN;
3934                     }
3935                     /* Note:  it's safe to delete hosts even if they have call
3936                      * back state, because break delayed callbacks (called when a
3937                      * message is received from the workstation) will always send a
3938                      * break all call backs to the workstation if there is no
3939                      * callback.
3940                      */
3941                 }
3942             } else {
3943                 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3944                     char hoststr[16];
3945                     (void)afs_inet_ntoa_r(host->host, hoststr);
3946                     if (host->interface) {
3947                         afsUUID uuid = host->interface->uuid;
3948                         H_UNLOCK;
3949                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3950                         H_LOCK;
3951                         if (code) {
3952                             if (MultiProbeAlternateAddress_r(host)) {
3953                                 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3954                                             hoststr, ntohs(host->port), code));
3955                                 host->hostFlags |= VENUSDOWN;
3956                             }
3957                         }
3958                     } else {
3959                         H_UNLOCK;
3960                         code = RXAFSCB_Probe(cb_conn);
3961                         H_LOCK;
3962                         if (code) {
3963                             ViceLog(0,
3964                                     ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
3965                                      hoststr, ntohs(host->port), code));
3966                             host->hostFlags |= VENUSDOWN;
3967                         }
3968                     }
3969                 }
3970             }
3971             H_UNLOCK;
3972             rx_PutConnection(cb_conn);
3973             cb_conn=NULL;
3974             H_LOCK;
3975             host->hostFlags &= ~HWHO_INPROGRESS;
3976         }
3977         h_Unlock_r(host);
3978     }
3979     return 0;
3980
3981 }                               /*CheckHost_r */
3982
3983
3984 /*
3985  * Set VenusDown for any hosts that have not had a call in 15 minutes and
3986  * don't respond to a probe.  Note that VenusDown can only be cleared if
3987  * a message is received from the host (see ServerLWP in file.c).
3988  * Delete hosts that have not had any calls in 1 hour, clients that
3989  * have not had any calls in 15 minutes.
3990  *
3991  * This routine is called roughly every 5 minutes.
3992  */
3993 void
3994 h_CheckHosts(void)
3995 {
3996     afs_uint32 now = FT_ApproxTime();
3997
3998     memset(&zerofid, 0, sizeof(zerofid));
3999     /*
4000      * Send a probe to the workstation if it hasn't been heard from in
4001      * 15 minutes
4002      */
4003     checktime = now - 15 * 60;
4004     clientdeletetime = now - 120 * 60;  /* 2 hours ago */
4005
4006     H_LOCK;
4007     h_Enumerate_r(CheckHost_r, hostList, NULL);
4008     H_UNLOCK;
4009 }                               /*h_CheckHosts */
4010
4011 /*
4012  * This is called with host locked and held. At this point, the
4013  * hostAddrHashTable has an entry for the primary addr/port inserted
4014  * by h_Alloc_r().  No other interfaces should be considered valid.
4015  *
4016  * The addresses in the interfaceAddr list are in host byte order.
4017  */
4018 int
4019 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
4020 {
4021     int i, j;
4022     int number, count;
4023     afs_uint32 myAddr;
4024     afs_uint16 myPort;
4025     int found;
4026     struct Interface *interface;
4027     char hoststr[16];
4028     char uuidstr[128];
4029     afs_uint16 port7001 = htons(7001);
4030
4031     osi_Assert(host);
4032     osi_Assert(interf);
4033
4034     number = interf->numberOfInterfaces;
4035     myAddr = host->host;        /* current interface address */
4036     myPort = host->port;        /* current port */
4037
4038     ViceLog(125,
4039             ("initInterfaceAddr : host %s:%d numAddr %d\n",
4040               afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
4041
4042     /* validation checks */
4043     if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
4044         ViceLog(0,
4045                 ("Invalid number of alternate addresses is %d\n", number));
4046         return -1;
4047     }
4048
4049     /*
4050      * The client's notion of its own IP addresses is not reliable.
4051      *
4052      * 1. The client list might contain private address ranges which
4053      *    are likely to be re-used by many clients allocated addresses
4054      *    by a NAT.
4055      *
4056      * 2. The client list will not include any public addresses that
4057      *    are hidden by a NAT.
4058      *
4059      * 3. Private address ranges that are exposed to the server will
4060      *    be obtained from the rx connections that use them.
4061      *
4062      * 4. Lists provided by the client are not necessarily truthful.
4063      *    Many existing clients (UNIX) do not refresh the IP address
4064      *    list as the actual assigned addresses change.  The end result
4065      *    is that they report the initial address list for the lifetime
4066      *    of the process.  In other words, a client can report addresses
4067      *    that they are in fact not using.  Adding these addresses to
4068      *    the host interface list without verification is not only
4069      *    pointless, it is downright dangerous.
4070      *
4071      * We therefore do not add alternate addresses to the addr hash table.
4072      * We only use them for multi-rx callback breaks.
4073      */
4074
4075     /*
4076      * Convert IP addresses to network byte order, and remove
4077      * duplicate IP addresses from the interface list, and
4078      * determine whether or not the incoming addr/port is
4079      * listed.  Note that if the address matches it is not
4080      * truly a match because the port number for the entries
4081      * in the interface list are port 7001 and the port number
4082      * for this connection might not be 7001.
4083      */
4084     for (i = 0, count = 0, found = 0; i < number; i++) {
4085         interf->addr_in[i] = htonl(interf->addr_in[i]);
4086         for (j = 0; j < count; j++) {
4087             if (interf->addr_in[j] == interf->addr_in[i])
4088                 break;
4089         }
4090         if (j == count) {
4091             interf->addr_in[count] = interf->addr_in[i];
4092             if (interf->addr_in[count] == myAddr &&
4093                 port7001 == myPort)
4094                 found = 1;
4095             count++;
4096         }
4097     }
4098
4099     /*
4100      * Allocate and initialize an interface structure for this host.
4101      */
4102     if (found) {
4103         interface = (struct Interface *)
4104             malloc(sizeof(struct Interface) +
4105                    (sizeof(struct AddrPort) * (count - 1)));
4106         if (!interface) {
4107             ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
4108         }
4109         interface->numberOfInterfaces = count;
4110     } else {
4111         interface = (struct Interface *)
4112             malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
4113         if (!interface) {
4114             ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4115         }
4116         interface->numberOfInterfaces = count + 1;
4117         interface->interface[count].addr = myAddr;
4118         interface->interface[count].port = myPort;
4119         interface->interface[count].valid = 1;
4120     }
4121
4122     for (i = 0; i < count; i++) {
4123
4124         interface->interface[i].addr = interf->addr_in[i];
4125         /* We store the port as 7001 because the addresses reported by
4126          * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4127          * are coming from fully connected hosts (no NAT/PATs)
4128          */
4129         interface->interface[i].port = port7001;
4130         interface->interface[i].valid =
4131             (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4132     }
4133
4134     interface->uuid = interf->uuid;
4135
4136     osi_Assert(!host->interface);
4137     host->interface = interface;
4138
4139     if (LogLevel >= 125) {
4140         afsUUID_to_string(&interface->uuid, uuidstr, 127);
4141
4142         ViceLog(125, ("--- uuid %s\n", uuidstr));
4143         for (i = 0; i < host->interface->numberOfInterfaces; i++) {
4144             ViceLog(125, ("--- alt address %s:%d\n",
4145                           afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4146                           ntohs(host->interface->interface[i].port)));
4147         }
4148     }
4149
4150     return 0;
4151 }
4152
4153 /* deleted a HashChain structure for this address and host */
4154 /* returns 1 on success */
4155 int
4156 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4157                                 struct host *host)
4158 {
4159     char hoststr[16];
4160     struct h_AddrHashChain **hp, *th;
4161
4162     if (addr == 0 && port == 0)
4163         return 1;
4164
4165     for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4166          hp = &th->next) {
4167         osi_Assert(th->hostPtr);
4168         if (th->hostPtr == host && th->addr == addr && th->port == port) {
4169             ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4170                           host, afs_inet_ntoa_r(host->host, hoststr),
4171                           ntohs(host->port)));
4172             *hp = th->next;
4173             free(th);
4174             return 1;
4175         }
4176     }
4177     ViceLog(125,
4178             ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4179              host, afs_inet_ntoa_r(host->host, hoststr),
4180              ntohs(host->port)));
4181     return 0;
4182 }
4183
4184
4185 /*
4186 ** prints out all alternate interface address for the host. The 'level'
4187 ** parameter indicates what level of debugging sets this output
4188 */
4189 void
4190 printInterfaceAddr(struct host *host, int level)
4191 {
4192     int i, number;
4193     char hoststr[16];
4194
4195     if (host->interface) {
4196         /* check alternate addresses */
4197         number = host->interface->numberOfInterfaces;
4198         if (number == 0) {
4199             ViceLog(level, ("no-addresses "));
4200         } else {
4201             for (i = 0; i < number; i++)
4202                 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
4203                                 ntohs(host->interface->interface[i].port)));
4204         }
4205     }
4206     ViceLog(level, ("\n"));
4207 }