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