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