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