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