Don't cast the pointer past to memset
[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             rxconn = host->callback_rxcon;
1448             host->callback_rxcon = NULL;
1449
1450             if (rxconn) {
1451                 struct client *client;
1452                 /*
1453                  * If rx_DestroyConnection calls h_FreeConnection we will
1454                  * deadlock on the host_glock_mutex. Work around the problem
1455                  * by unhooking the client from the connection before
1456                  * destroying the connection.
1457                  */
1458                 client = rx_GetSpecific(rxconn, rxcon_client_key);
1459                 rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1460                 rx_DestroyConnection(rxconn);
1461             }
1462
1463             for (i=0; i < host->interface->numberOfInterfaces; i++) {
1464                 if (host->interface->interface[i].valid) {
1465                     ViceLog(25,
1466                              ("Removed address for host %" AFS_PTR_FMT " (%s:%d), new primary interface %s:%d.\n",
1467                                host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1468                                afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr2), 
1469                                ntohs(host->interface->interface[i].port)));
1470                     host->host = host->interface->interface[i].addr;
1471                     host->port = host->interface->interface[i].port;
1472                     h_AddHostToAddrHashTable_r(host->host, host->port, host);
1473                     break;
1474                 }
1475             }
1476
1477             if (i == host->interface->numberOfInterfaces) {
1478                 ViceLog(25,
1479                          ("Removed only address for host %" AFS_PTR_FMT " (%s:%d), no valid alternate interfaces, deleting host.\n",
1480                            host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1481                 host->hostFlags |= HOSTDELETED;
1482                 /* addr/port was removed from the hash table */
1483                 host->host = 0;
1484                 host->port = 0;
1485             } else {
1486                 if (!sc)
1487                     sc = rxnull_NewClientSecurityObject();
1488                 host->callback_rxcon =
1489                     rx_NewConnection(host->host, host->port, 1, sc, 0);
1490                 rx_SetConnDeadTime(host->callback_rxcon, 50);
1491                 rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
1492             }
1493         } else {
1494             /* not the primary addr/port, just invalidate it */
1495             invalidateInterfaceAddr_r(host, addr, port);
1496         }
1497     }
1498
1499     return 0;
1500 }
1501 static int
1502 h_threadquota(int waiting) 
1503 {
1504     if (lwps > 64) {
1505         if (waiting > 5)
1506             return 1;
1507     } else if (lwps > 32) {
1508         if (waiting > 4)
1509             return 1;
1510     } else if (lwps > 16) {
1511         if (waiting > 3)
1512             return 1;
1513     } else {
1514         if (waiting > 2)
1515             return 1;
1516     }
1517     return 0;
1518 }
1519
1520 /* Host is returned held */
1521 struct host *
1522 h_GetHost_r(struct rx_connection *tcon)
1523 {
1524     struct host *host;
1525     struct host *oldHost;
1526     int code;
1527     int held;
1528     struct interfaceAddr interf;
1529     int interfValid = 0;
1530     struct Identity *identP = NULL;
1531     afs_uint32 haddr;
1532     afs_uint16 hport;
1533     char hoststr[16], hoststr2[16];
1534     Capabilities caps;
1535     struct rx_connection *cb_conn = NULL;
1536     struct rx_connection *cb_in = NULL;
1537
1538     caps.Capabilities_val = NULL;
1539
1540     haddr = rxr_HostOf(tcon);
1541     hport = rxr_PortOf(tcon);
1542   retry:
1543     if (cb_in) {
1544         rx_DestroyConnection(cb_in);
1545         cb_in = NULL;
1546     }
1547     if (caps.Capabilities_val)
1548         free(caps.Capabilities_val);
1549     caps.Capabilities_val = NULL;
1550     caps.Capabilities_len = 0;
1551
1552     code = 0;
1553     if (h_Lookup_r(haddr, hport, &held, &host))
1554         return 0;
1555     identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1556     if (host && !identP && !(host->Console & 1)) {
1557         /* This is a new connection, and we already have a host
1558          * structure for this address. Verify that the identity
1559          * of the caller matches the identity in the host structure.
1560          */
1561         if ((host->hostFlags & HWHO_INPROGRESS) && 
1562             h_threadquota(host->lock.num_waiting)) {
1563             if (!held)
1564                 h_Release_r(host);
1565             host = NULL;
1566             goto gethost_out;
1567         }
1568         h_Lock_r(host);
1569         if (!(host->hostFlags & ALTADDR)) {
1570             /* Another thread is doing initialization */
1571             h_Unlock_r(host);
1572             if (!held)
1573                 h_Release_r(host);
1574             ViceLog(125,
1575                     ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1576                      host, afs_inet_ntoa_r(host->host, hoststr),
1577                      ntohs(host->port)));
1578             goto retry;
1579         }
1580         host->hostFlags |= HWHO_INPROGRESS;
1581         host->hostFlags &= ~ALTADDR;
1582
1583         /* We received a new connection from an IP address/port
1584          * that is associated with 'host' but the address/port of
1585          * the callback connection does not have to match it.
1586          * If there is a match, we can use the existing callback
1587          * connection to verify the UUID.  If they do not match
1588          * we need to use a new callback connection to verify the
1589          * UUID of the incoming caller and perhaps use the old 
1590          * callback connection to verify that the old address/port
1591          * is still valid.
1592          */
1593         
1594         cb_conn = host->callback_rxcon;
1595         rx_GetConnection(cb_conn);
1596         H_UNLOCK;
1597         if (haddr == host->host && hport == host->port) {
1598             /* The existing callback connection matches the 
1599              * incoming connection so just use it.
1600              */
1601             code =
1602                 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1603             if (code == RXGEN_OPCODE)
1604                 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1605         } else {
1606             /* We do not have a match.  Create a new connection
1607              * for the new addr/port and use multi_Rx to probe
1608              * both of them simultaneously.
1609              */
1610             if (!sc)
1611                 sc = rxnull_NewClientSecurityObject();
1612             cb_in = rx_NewConnection(haddr, hport, 1, sc, 0);
1613             rx_SetConnDeadTime(cb_in, 50);
1614             rx_SetConnHardDeadTime(cb_in, AFS_HARDDEADTIME);
1615             
1616             code =
1617                 RXAFSCB_TellMeAboutYourself(cb_in, &interf, &caps);
1618             if (code == RXGEN_OPCODE)
1619                 code = RXAFSCB_WhoAreYou(cb_in, &interf);
1620         }
1621         rx_PutConnection(cb_conn);
1622         cb_conn=NULL;
1623         H_LOCK;
1624         if ((code == RXGEN_OPCODE) || 
1625             ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1626             identP = (struct Identity *)malloc(sizeof(struct Identity));
1627             if (!identP) {
1628                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1629                 assert(0);
1630             }
1631             identP->valid = 0;
1632             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1633             if (cb_in == NULL) {
1634                 /* The host on this connection was unable to respond to 
1635                  * the WhoAreYou. We will treat this as a new connection
1636                  * from the existing host. The worst that can happen is
1637                  * that we maintain some extra callback state information */
1638                 if (host->interface) {
1639                     ViceLog(0,
1640                             ("Host %" AFS_PTR_FMT " (%s:%d) used to support WhoAreYou, deleting.\n",
1641                              host, 
1642                              afs_inet_ntoa_r(host->host, hoststr),
1643                              ntohs(host->port)));
1644                     host->hostFlags |= HOSTDELETED;
1645                     host->hostFlags &= ~HWHO_INPROGRESS;
1646                     h_Unlock_r(host);
1647                     if (!held)
1648                         h_Release_r(host);
1649                     host = NULL;
1650                     goto retry;
1651                 }
1652             } else {
1653                 /* The incoming connection does not support WhoAreYou but
1654                  * the original one might have.  Use removeAddress_r() to
1655                  * remove this addr/port from the host that was found.
1656                  * If there are no more addresses left for the host it 
1657                  * will be deleted.  Then we retry.
1658                  */
1659                 removeAddress_r(host, haddr, hport);
1660                 host->hostFlags &= ~HWHO_INPROGRESS;
1661                 host->hostFlags |= ALTADDR;
1662                 h_Unlock_r(host);
1663                 if (!held)
1664                     h_Release_r(host);
1665                 host = NULL;
1666                 goto retry;
1667             }
1668         } else if (code == 0) {
1669             interfValid = 1;
1670             identP = (struct Identity *)malloc(sizeof(struct Identity));
1671             if (!identP) {
1672                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1673                 assert(0);
1674             }
1675             identP->valid = 1;
1676             identP->uuid = interf.uuid;
1677             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1678             /* Check whether the UUID on this connection matches
1679              * the UUID in the host structure. If they don't match
1680              * then this is not the same host as before. */
1681             if (!host->interface
1682                 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1683                 if (cb_in) {
1684                     ViceLog(25,
1685                             ("Uuid doesn't match connection (%s:%d).\n",
1686                              afs_inet_ntoa_r(haddr, hoststr), ntohs(hport)));
1687                     
1688                     removeAddress_r(host, haddr, hport);
1689                 } else {
1690                     ViceLog(25,
1691                             ("Uuid doesn't match host %" AFS_PTR_FMT " (%s:%d).\n",
1692                              host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1693                     
1694                     removeAddress_r(host, host->host, host->port);
1695                 }
1696                 host->hostFlags &= ~HWHO_INPROGRESS;
1697                 host->hostFlags |= ALTADDR;
1698                 h_Unlock_r(host);
1699                 if (!held)
1700                     h_Release_r(host);
1701                 host = NULL;
1702                 goto retry;
1703             } else if (cb_in) {
1704                 /* the UUID matched the client at the incoming addr/port 
1705                  * but this is not the address of the active callback 
1706                  * connection.  Try that connection and see if the client
1707                  * is still there and if the reported UUID is the same.
1708                  */
1709                 int code2;
1710                 afsUUID uuid = host->interface->uuid;
1711                 cb_conn = host->callback_rxcon;
1712                 rx_GetConnection(cb_conn);
1713                 rx_SetConnDeadTime(cb_conn, 2);
1714                 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1715                 H_UNLOCK;
1716                 code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1717                 H_LOCK;
1718                 rx_SetConnDeadTime(cb_conn, 50);
1719                 rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1720                 rx_PutConnection(cb_conn);
1721                 cb_conn=NULL;
1722                 if (code2) {
1723                     /* The primary address is either not responding or
1724                      * is not the client we are looking for.  Need to
1725                      * remove the primary address and add swap in the new 
1726                      * callback connection, and destroy the old one.
1727                      */
1728                     struct rx_connection *rxconn;
1729                     ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1730                                host, 
1731                                afs_inet_ntoa_r(host->host, hoststr),
1732                                ntohs(host->port),code2));
1733
1734                     /* 
1735                      * make sure we add and then remove.  otherwise, we
1736                      * might end up with no valid interfaces after the 
1737                      * remove and the host will have been marked deleted.
1738                      */
1739                     addInterfaceAddr_r(host, haddr, hport);
1740                     removeInterfaceAddr_r(host, host->host, host->port);
1741                     host->host = haddr;
1742                     host->port = hport;
1743                     rxconn = host->callback_rxcon;
1744                     host->callback_rxcon = cb_in;
1745                     cb_in = NULL;
1746                     
1747                     if (rxconn) {
1748                         struct client *client;
1749                         /*
1750                          * If rx_DestroyConnection calls h_FreeConnection we will
1751                          * deadlock on the host_glock_mutex. Work around the problem
1752                          * by unhooking the client from the connection before
1753                          * destroying the connection.
1754                          */
1755                         client = rx_GetSpecific(rxconn, rxcon_client_key);
1756                         rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1757                         rx_DestroyConnection(rxconn);
1758                     }
1759                 }
1760             }
1761         } else {
1762             if (cb_in) {
1763                 /* A callback to the incoming connection address is failing.  
1764                  * Assume that the addr/port is no longer associated with the host
1765                  * returned by h_Lookup_r.
1766                  */
1767                 ViceLog(0,
1768                         ("CB: WhoAreYou failed for connection (%s:%d) , error %d\n",
1769                          afs_inet_ntoa_r(haddr, hoststr), ntohs(hport), code));
1770                 removeAddress_r(host, haddr, hport);
1771                 host->hostFlags &= ~HWHO_INPROGRESS;
1772                 host->hostFlags |= ALTADDR;
1773                 h_Unlock_r(host);
1774                 if (!held)
1775                     h_Release_r(host);
1776                 host = NULL;
1777                 rx_DestroyConnection(cb_in);
1778                 cb_in = NULL;
1779                 goto gethost_out;
1780             } else {
1781                 ViceLog(0,
1782                         ("CB: WhoAreYou failed for host %" AFS_PTR_FMT " (%s:%d), error %d\n",
1783                          host, afs_inet_ntoa_r(host->host, hoststr),
1784                          ntohs(host->port), code));
1785                 host->hostFlags |= VENUSDOWN;
1786             }
1787         }
1788         if (caps.Capabilities_val
1789             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1790             host->hostFlags |= HERRORTRANS;
1791         else
1792             host->hostFlags &= ~(HERRORTRANS);
1793         host->hostFlags |= ALTADDR;
1794         host->hostFlags &= ~HWHO_INPROGRESS;
1795         h_Unlock_r(host);
1796     } else if (host) {
1797         if (!(host->hostFlags & ALTADDR)) {
1798             /* another thread is doing the initialisation */
1799             ViceLog(125,
1800                     ("Host %" AFS_PTR_FMT " (%s:%d) waiting for host-init to complete\n",
1801                      host, afs_inet_ntoa_r(host->host, hoststr),
1802                      ntohs(host->port)));
1803             h_Lock_r(host);
1804             h_Unlock_r(host);
1805             if (!held)
1806                 h_Release_r(host);
1807             ViceLog(125,
1808                     ("Host %" AFS_PTR_FMT " (%s:%d) starting h_Lookup again\n",
1809                      host, afs_inet_ntoa_r(host->host, hoststr),
1810                      ntohs(host->port)));
1811             goto retry;
1812         }
1813         /* We need to check whether the identity in the host structure
1814          * matches the identity on the connection. If they don't match
1815          * then treat this a new host. */
1816         if (!(host->Console & 1)
1817             && ((!identP->valid && host->interface)
1818                 || (identP->valid && !host->interface)
1819                 || (identP->valid
1820                     && !afs_uuid_equal(&identP->uuid,
1821                                        &host->interface->uuid)))) {
1822             char uuid1[128], uuid2[128];
1823             if (identP->valid)
1824                 afsUUID_to_string(&identP->uuid, uuid1, 127);
1825             if (host->interface)
1826                 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1827             ViceLog(0,
1828                     ("CB: new identity for host %" AFS_PTR_FMT " (%s:%d), deleting(%x %x %s %s)\n",
1829                      host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1830                      identP->valid, host->interface,
1831                      identP->valid ? uuid1 : "no_uuid",
1832                      host->interface ? uuid2 : "no_uuid"));
1833
1834             /* The host in the cache is not the host for this connection */
1835             h_Lock_r(host);
1836             host->hostFlags |= HOSTDELETED;
1837             h_Unlock_r(host);
1838             if (!held)
1839                 h_Release_r(host);
1840             goto retry;
1841         }
1842     } else {
1843         host = h_Alloc_r(tcon); /* returned held and locked */
1844         h_gethostcps_r(host, FT_ApproxTime());
1845         if (!(host->Console & 1)) {
1846             int pident = 0;
1847             cb_conn = host->callback_rxcon;
1848             rx_GetConnection(cb_conn);
1849             host->hostFlags |= HWHO_INPROGRESS;
1850             H_UNLOCK;
1851             code =
1852                 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1853             if (code == RXGEN_OPCODE)
1854                 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1855             rx_PutConnection(cb_conn);
1856             cb_conn=NULL;
1857             H_LOCK;
1858             if ((code == RXGEN_OPCODE) || 
1859                 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
1860                 if (!identP)
1861                     identP =
1862                         (struct Identity *)malloc(sizeof(struct Identity));
1863                 else
1864                     pident = 1;
1865
1866                 if (!identP) {
1867                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1868                     assert(0);
1869                 }
1870                 identP->valid = 0;
1871                 if (!pident)
1872                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1873                 ViceLog(25,
1874                         ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
1875                          host, afs_inet_ntoa_r(host->host, hoststr),
1876                          ntohs(host->port)));
1877                 code = 0;
1878             } else if (code == 0) {
1879                 if (!identP)
1880                     identP =
1881                         (struct Identity *)malloc(sizeof(struct Identity));
1882                 else
1883                     pident = 1;
1884
1885                 if (!identP) {
1886                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1887                     assert(0);
1888                 }
1889                 identP->valid = 1;
1890                 interfValid = 1;
1891                 identP->uuid = interf.uuid;
1892                 if (!pident)
1893                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1894                 ViceLog(25,
1895                         ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
1896                          host, afs_inet_ntoa_r(host->host, hoststr),
1897                          ntohs(host->port)));
1898             }
1899             if (code == 0 && !identP->valid) {
1900                 cb_conn = host->callback_rxcon;
1901                 rx_GetConnection(cb_conn);
1902                 H_UNLOCK;
1903                 code = RXAFSCB_InitCallBackState(cb_conn);
1904                 rx_PutConnection(cb_conn);
1905                 cb_conn=NULL;
1906                 H_LOCK;
1907             } else if (code == 0) {
1908                 oldHost = h_LookupUuid_r(&identP->uuid);
1909                 if (oldHost) {
1910                     int probefail = 0;
1911
1912                     if (!h_Held_r(oldHost))
1913                         h_Hold_r(oldHost);
1914                     h_Lock_r(oldHost);
1915                     oldHost->hostFlags |= HWHO_INPROGRESS;
1916
1917                     if (oldHost->interface) {
1918                         int code2;
1919                         afsUUID uuid = oldHost->interface->uuid;
1920                         cb_conn = oldHost->callback_rxcon;
1921                         rx_GetConnection(cb_conn);
1922                         rx_SetConnDeadTime(cb_conn, 2);
1923                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1924                         H_UNLOCK;
1925                         code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1926                         H_LOCK;
1927                         rx_SetConnDeadTime(cb_conn, 50);
1928                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1929                         rx_PutConnection(cb_conn);
1930                         cb_conn=NULL;
1931                         if (code2) {
1932                             /* The primary address is either not responding or
1933                              * is not the client we are looking for.  
1934                              * MultiProbeAlternateAddress_r() will remove the
1935                              * alternate interfaces that do not have the same
1936                              * Uuid. */
1937                             ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
1938                                          oldHost, 
1939                                          afs_inet_ntoa_r(oldHost->host, hoststr),
1940                                          ntohs(oldHost->port),code2));
1941                             MultiProbeAlternateAddress_r(oldHost);
1942                             probefail = 1;
1943                         }
1944                     } else {
1945                         probefail = 1;
1946                     }
1947
1948                     /* This is a new address for an existing host. Update
1949                      * the list of interfaces for the existing host and
1950                      * delete the host structure we just allocated. */
1951
1952                     /* prevent warnings while manipulating interface lists */
1953                     host->hostFlags |= HOSTDELETED;
1954
1955                     if (oldHost->host != haddr || oldHost->port != hport) {
1956                         struct rx_connection *rxconn;
1957
1958                         ViceLog(25,
1959                                  ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
1960                                    oldHost, 
1961                                    afs_inet_ntoa_r(oldHost->host, hoststr2),
1962                                    ntohs(oldHost->port),
1963                                    afs_inet_ntoa_r(haddr, hoststr),
1964                                    ntohs(hport)));
1965                         /* 
1966                          * add then remove.  otherwise the host may get marked
1967                          * deleted if we removed the only valid address.
1968                          */
1969                         addInterfaceAddr_r(oldHost, haddr, hport);
1970                         if (probefail || oldHost->host == haddr) {
1971                             /* 
1972                              * The probe failed which means that the old 
1973                              * address is either unreachable or is not the 
1974                              * same host we were just contacted by.  We will 
1975                              * also remove addresses if only the port has 
1976                              * changed because that indicates the client
1977                              * is behind a NAT. 
1978                              */
1979                             removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
1980                         } else {
1981                             int i;
1982                             struct Interface *interface = oldHost->interface;
1983                             int number = oldHost->interface->numberOfInterfaces;
1984                             for (i = 0; i < number; i++) {
1985                                 if (interface->interface[i].addr == haddr &&
1986                                     interface->interface[i].port != hport) {
1987                                     /* 
1988                                      * We have just been contacted by a client
1989                                      * that has been seen from behind a NAT 
1990                                      * and at least one other address.
1991                                      */
1992                                     removeInterfaceAddr_r(oldHost, haddr, 
1993                                                           interface->interface[i].port);
1994                                     break;
1995                                 }
1996                             }
1997                         }
1998                         h_AddHostToAddrHashTable_r(haddr, hport, oldHost);
1999                         oldHost->host = haddr;
2000                         oldHost->port = hport;
2001                         rxconn = oldHost->callback_rxcon;
2002                         oldHost->callback_rxcon = host->callback_rxcon;
2003                         host->callback_rxcon = NULL;
2004                         
2005                         if (rxconn) {
2006                             struct client *client;
2007                             /*
2008                              * If rx_DestroyConnection calls h_FreeConnection we will
2009                              * deadlock on the host_glock_mutex. Work around the problem
2010                              * by unhooking the client from the connection before
2011                              * destroying the connection.
2012                              */
2013                             client = rx_GetSpecific(rxconn, rxcon_client_key);
2014                             rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
2015                             rx_DestroyConnection(rxconn);
2016                         }
2017                     }
2018                     host->hostFlags &= ~HWHO_INPROGRESS;
2019                     h_Unlock_r(host);
2020                     /* release host because it was allocated by h_Alloc_r */
2021                     h_Release_r(host);
2022                     host = oldHost;
2023                     /* the new host is held and locked */
2024                 } else {
2025                     /* This really is a new host */
2026                     h_AddHostToUuidHashTable_r(&identP->uuid, host);
2027                     cb_conn = host->callback_rxcon;
2028                     rx_GetConnection(cb_conn);          
2029                     H_UNLOCK;
2030                     code =
2031                         RXAFSCB_InitCallBackState3(cb_conn,
2032                                                    &FS_HostUUID);
2033                     rx_PutConnection(cb_conn);
2034                     cb_conn=NULL;
2035                     H_LOCK;
2036                     if (code == 0) {
2037                         ViceLog(25,
2038                                 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2039                                  host, afs_inet_ntoa_r(host->host, hoststr),
2040                                  ntohs(host->port)));
2041                         assert(interfValid == 1);
2042                         initInterfaceAddr_r(host, &interf);
2043                     }
2044                 }
2045             }
2046             if (code) {
2047                 ViceLog(0,
2048                         ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2049                          host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2050                 host->hostFlags |= VENUSDOWN;
2051             } else {
2052                 ViceLog(125,
2053                         ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2054                          host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2055                 host->hostFlags |= RESETDONE;
2056             }
2057         }
2058         if (caps.Capabilities_val
2059             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2060             host->hostFlags |= HERRORTRANS;
2061         else
2062             host->hostFlags &= ~(HERRORTRANS);
2063         host->hostFlags |= ALTADDR;     /* host structure initialization complete */
2064         host->hostFlags &= ~HWHO_INPROGRESS;
2065         h_Unlock_r(host);
2066     }
2067
2068  gethost_out:
2069     if (caps.Capabilities_val)
2070         free(caps.Capabilities_val);
2071     caps.Capabilities_val = NULL;
2072     caps.Capabilities_len = 0;
2073     if (cb_in) {
2074         rx_DestroyConnection(cb_in);
2075         cb_in = NULL;
2076     }
2077     return host;
2078
2079 }                               /*h_GetHost_r */
2080
2081
2082 static char localcellname[PR_MAXNAMELEN + 1];
2083 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
2084 int  num_lrealms = -1;
2085
2086 /* not reentrant */
2087 void
2088 h_InitHostPackage(void)
2089 {
2090     memset(&nulluuid, 0, sizeof(afsUUID));
2091     afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
2092     if (num_lrealms == -1) {
2093         int i;
2094         for (i=0; i<AFS_NUM_LREALMS; i++) {
2095             if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
2096                 break;
2097         }
2098
2099         if (i == 0) {
2100             ViceLog(0,
2101                     ("afs_krb_get_lrealm failed, using %s.\n",
2102                      localcellname));
2103             strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
2104             num_lrealms = i =1;
2105         } else {
2106             num_lrealms = i;
2107         }
2108
2109         /* initialize the rest of the local realms to nullstring for debugging */
2110         for (; i<AFS_NUM_LREALMS; i++)
2111             local_realms[i][0] = '\0';
2112     }
2113     rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2114     rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2115 #ifdef AFS_PTHREAD_ENV
2116     assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
2117 #endif /* AFS_PTHREAD_ENV */
2118 }
2119
2120 static int
2121 MapName_r(char *aname, char *acell, afs_int32 * aval)
2122 {
2123     namelist lnames;
2124     idlist lids;
2125     afs_int32 code;
2126     afs_int32 anamelen, cnamelen;
2127     int foreign = 0;
2128     char *tname;
2129
2130     anamelen = strlen(aname);
2131     if (anamelen >= PR_MAXNAMELEN)
2132         return -1;              /* bad name -- caller interprets this as anonymous, but retries later */
2133
2134     lnames.namelist_len = 1;
2135     lnames.namelist_val = (prname *) aname;     /* don't malloc in the common case */
2136     lids.idlist_len = 0;
2137     lids.idlist_val = NULL;
2138
2139     cnamelen = strlen(acell);
2140     if (cnamelen) {
2141         if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
2142             ViceLog(2,
2143                     ("MapName: cell is foreign.  cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
2144                     acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
2145             if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
2146                 ViceLog(2,
2147                         ("MapName: Name too long, using AnonymousID for %s@%s\n",
2148                          aname, acell));
2149                 *aval = AnonymousID;
2150                 return 0;
2151             }
2152             foreign = 1;        /* attempt cross-cell authentication */
2153             tname = (char *)malloc(PR_MAXNAMELEN);
2154             if (!tname) {
2155                 ViceLog(0, ("Failed malloc in MapName_r\n"));
2156                 assert(0);
2157             }
2158             strcpy(tname, aname);
2159             tname[anamelen] = '@';
2160             strcpy(tname + anamelen + 1, acell);
2161             lnames.namelist_val = (prname *) tname;
2162         }
2163     }
2164
2165     H_UNLOCK;
2166     code = hpr_NameToId(&lnames, &lids);
2167     H_LOCK;
2168     if (code == 0) {
2169         if (lids.idlist_val) {
2170             *aval = lids.idlist_val[0];
2171             if (*aval == AnonymousID) {
2172                 ViceLog(2,
2173                         ("MapName: NameToId on %s returns anonymousID\n",
2174                          lnames.namelist_val));
2175             }
2176             free(lids.idlist_val);      /* return parms are not malloced in stub if server proc aborts */
2177         } else {
2178             ViceLog(0,
2179                     ("MapName: NameToId on '%s' is unknown\n",
2180                      lnames.namelist_val));
2181             code = -1;
2182         }
2183     }
2184
2185     if (foreign) {
2186         free(lnames.namelist_val);      /* We allocated this above, so we must free it now. */
2187     }
2188     return code;
2189 }
2190
2191 /*MapName*/
2192
2193
2194 /* NOTE: this returns the client with a Write lock and a refCount */
2195 struct client *
2196 h_ID2Client(afs_int32 vid)
2197 {
2198     register struct client *client;
2199     register struct host *host;
2200
2201     H_LOCK;
2202     for (host = hostList; host; host = host->next) {
2203         if (host->hostFlags & HOSTDELETED)
2204             continue;
2205         for (client = host->FirstClient; client; client = client->next) {
2206             if (!client->deleted && client->ViceId == vid) {
2207                 client->refCount++;
2208                 H_UNLOCK;
2209                 ObtainWriteLock(&client->lock);
2210                 return client;
2211             }
2212         }
2213     }
2214
2215     H_UNLOCK;
2216     return NULL;
2217 }
2218
2219 /*
2220  * Called by the server main loop.  Returns a h_Held client, which must be
2221  * released later the main loop.  Allocates a client if the matching one
2222  * isn't around. The client is returned with its reference count incremented
2223  * by one. The caller must call h_ReleaseClient_r when finished with
2224  * the client.
2225  *
2226  * the client->host is returned held.  h_ReleaseClient_r does not release
2227  * the hold on client->host.
2228  */
2229 struct client *
2230 h_FindClient_r(struct rx_connection *tcon)
2231 {
2232     register struct client *client;
2233     struct host *host = NULL;
2234     struct client *oldClient;
2235     afs_int32 viceid = 0;
2236     afs_int32 expTime;
2237     afs_int32 code;
2238     int authClass;
2239 #if (64-MAXKTCNAMELEN)
2240     ticket name length != 64
2241 #endif
2242     char tname[64];
2243     char tinst[64];
2244     char uname[PR_MAXNAMELEN];
2245     char tcell[MAXKTCREALMLEN];
2246     int fail = 0;
2247     int created = 0;
2248
2249     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2250     if (client && client->sid == rxr_CidOf(tcon) 
2251         && client->VenusEpoch == rxr_GetEpoch(tcon)) {
2252         client->refCount++;
2253         h_Hold_r(client->host);
2254         if (!client->deleted && client->prfail != 2) {  
2255             /* Could add shared lock on client here */
2256             /* note that we don't have to lock entry in this path to
2257              * ensure CPS is initialized, since we don't call rx_SetSpecific
2258              * until initialization is done, and we only get here if
2259              * rx_GetSpecific located the client structure.
2260              */
2261             return client;
2262         }
2263         H_UNLOCK;
2264         ObtainWriteLock(&client->lock); /* released at end */
2265         H_LOCK;
2266     } else {
2267         client = NULL;
2268     }
2269
2270     authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
2271     ViceLog(5,
2272             ("FindClient: authenticating connection: authClass=%d\n",
2273              authClass));
2274     if (authClass == 1) {
2275         /* A bcrypt tickets, no longer supported */
2276         ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2277         viceid = AnonymousID;
2278         expTime = 0x7fffffff;
2279     } else if (authClass == 2) {
2280         afs_int32 kvno;
2281     
2282         /* kerberos ticket */
2283         code = rxkad_GetServerInfo(tcon, /*level */ 0, (afs_uint32 *)&expTime,
2284                                    tname, tinst, tcell, &kvno);
2285         if (code) {
2286             ViceLog(1, ("Failed to get rxkad ticket info\n"));
2287             viceid = AnonymousID;
2288             expTime = 0x7fffffff;
2289         } else {
2290             int ilen = strlen(tinst);
2291             ViceLog(5,
2292                     ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2293                      tname, tinst, tcell, expTime, kvno));
2294             strncpy(uname, tname, sizeof(uname));
2295             if (ilen) {
2296                 if (strlen(uname) + 1 + ilen >= sizeof(uname))
2297                     goto bad_name;
2298                 strcat(uname, ".");
2299                 strcat(uname, tinst);
2300             }
2301             /* translate the name to a vice id */
2302             code = MapName_r(uname, tcell, &viceid);
2303             if (code) {
2304               bad_name:
2305                 ViceLog(1,
2306                         ("failed to map name=%s, cell=%s -> code=%d\n", uname,
2307                          tcell, code));
2308                 fail = 1;
2309                 viceid = AnonymousID;
2310                 expTime = 0x7fffffff;
2311             }
2312         }
2313     } else {
2314         viceid = AnonymousID;   /* unknown security class */
2315         expTime = 0x7fffffff;
2316     }
2317
2318     if (!client) { /* loop */
2319         host = h_GetHost_r(tcon);       /* Returns it h_Held */
2320
2321         if (!host) 
2322             return 0;
2323
2324     retryfirstclient:
2325         /* First try to find the client structure */
2326         for (client = host->FirstClient; client; client = client->next) {
2327             if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2328                 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2329                 client->refCount++;
2330                 H_UNLOCK;
2331                 ObtainWriteLock(&client->lock);
2332                 H_LOCK;
2333                 break;
2334             }
2335         }
2336
2337         /* Still no client structure - get one */
2338         if (!client) {
2339             h_Lock_r(host);
2340             /* Retry to find the client structure */
2341             for (client = host->FirstClient; client; client = client->next) {
2342                 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
2343                     && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
2344                     h_Unlock_r(host);
2345                     goto retryfirstclient;
2346                 }
2347             }
2348             created = 1;
2349             client = GetCE();
2350             ObtainWriteLock(&client->lock);
2351             client->refCount = 1;
2352             client->host = host;
2353 #if FS_STATS_DETAILED
2354             client->InSameNetwork = host->InSameNetwork;
2355 #endif /* FS_STATS_DETAILED */
2356             client->ViceId = viceid;
2357             client->expTime = expTime;  /* rx only */
2358             client->authClass = authClass;      /* rx only */
2359             client->sid = rxr_CidOf(tcon);
2360             client->VenusEpoch = rxr_GetEpoch(tcon);
2361             client->CPS.prlist_val = NULL;
2362             client->CPS.prlist_len = 0;
2363             h_Unlock_r(host);
2364         }
2365     }
2366     client->prfail = fail;
2367
2368     if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
2369         client->CPS.prlist_len = 0;
2370         if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
2371             free(client->CPS.prlist_val);
2372         client->CPS.prlist_val = NULL;
2373         client->ViceId = viceid;
2374         client->expTime = expTime;
2375
2376         if (viceid == ANONYMOUSID) {
2377             client->CPS.prlist_len = AnonCPS.prlist_len;
2378             client->CPS.prlist_val = AnonCPS.prlist_val;
2379         } else {
2380             H_UNLOCK;
2381             code = hpr_GetCPS(viceid, &client->CPS);
2382             H_LOCK;
2383             if (code) {
2384                 char hoststr[16];
2385                 ViceLog(0,
2386                         ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2387                          code, viceid, client->host, 
2388                          afs_inet_ntoa_r(client->host->host,hoststr),
2389                          ntohs(client->host->port)));
2390
2391                 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2392                  * all protection servers and reevaluates things if no
2393                  * sync server or quorum is found we could still end up
2394                  * with one of these errors. In such case we would like to
2395                  * reevaluate the rpc call to find if there's cps for this
2396                  * guy. We treat other errors (except network failures
2397                  * ones - i.e. code < 0) as an indication that there is no
2398                  * CPS for this host.  Ideally we could like to deal this
2399                  * problem the other way around (i.e.  if code == NOCPS
2400                  * ignore else retry next time) but the problem is that
2401                  * there're other errors (i.e.  EPERM) for which we don't
2402                  * want to retry and we don't know the whole code list!
2403                  */
2404                 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2405                     client->prfail = 1;
2406             }
2407         }
2408         /* the disabling of system:administrators is so iffy and has so many
2409          * possible failure modes that we will disable it again */
2410         /* Turn off System:Administrator for safety  
2411          * if (AL_IsAMember(SystemId, client->CPS) == 0)
2412          * assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
2413     }
2414
2415     /* Now, tcon may already be set to a rock, since we blocked with no host
2416      * or client locks set above in pr_GetCPS (XXXX some locking is probably
2417      * required).  So, before setting the RPC's rock, we should disconnect
2418      * the RPC from the other client structure's rock.
2419      */
2420     oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2421     if (oldClient && oldClient != client && oldClient->sid == rxr_CidOf(tcon)
2422         && oldClient->VenusEpoch == rxr_GetEpoch(tcon)) {
2423         char hoststr[16];
2424         if (!oldClient->deleted) {
2425             /* if we didn't create it, it's not ours to put back */
2426             if (created) {
2427                 ViceLog(0, ("FindClient: stillborn client %x(%x); conn %x (host %s:%d) had client %x(%x)\n", 
2428                             client, client->sid, tcon, 
2429                             afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2430                             ntohs(rxr_PortOf(tcon)),
2431                             oldClient, oldClient->sid));
2432                 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
2433                     free(client->CPS.prlist_val);
2434                 client->CPS.prlist_val = NULL;
2435                 client->CPS.prlist_len = 0;
2436             }
2437             /* We should perhaps check for 0 here */
2438             client->refCount--;
2439             ReleaseWriteLock(&client->lock);
2440             if (created) {
2441                 FreeCE(client);
2442                 created = 0;
2443             } 
2444             oldClient->refCount++;
2445             H_UNLOCK;
2446             ObtainWriteLock(&oldClient->lock);
2447             H_LOCK;
2448             client = oldClient;
2449         } else {
2450             ViceLog(0, ("FindClient: deleted client %x(%x) already had conn %x (host %s:%d), stolen by client %x(%x)\n", 
2451                         oldClient, oldClient->sid, tcon, 
2452                         afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2453                         ntohs(rxr_PortOf(tcon)),
2454                         client, client->sid));
2455             /* rx_SetSpecific will be done immediately below */
2456         }
2457     }
2458     /* Avoid chaining in more than once. */
2459     if (created) {
2460         h_Lock_r(host);
2461         client->next = host->FirstClient;
2462         host->FirstClient = client;
2463         h_Unlock_r(host);
2464         CurrentConnections++;   /* increment number of connections */
2465     }
2466     rx_SetSpecific(tcon, rxcon_client_key, client);
2467     ReleaseWriteLock(&client->lock);
2468
2469     return client;
2470
2471 }                               /*h_FindClient_r */
2472
2473 int
2474 h_ReleaseClient_r(struct client *client)
2475 {
2476     assert(client->refCount > 0);
2477     client->refCount--;
2478     return 0;
2479 }
2480
2481
2482 /*
2483  * Sigh:  this one is used to get the client AGAIN within the individual
2484  * server routines.  This does not bother h_Holding the host, since
2485  * this is assumed already have been done by the server main loop.
2486  * It does check tokens, since only the server routines can return the
2487  * VICETOKENDEAD error code
2488  */
2489 int
2490 GetClient(struct rx_connection *tcon, struct client **cp)
2491 {
2492     register struct client *client;
2493     char hoststr[16];
2494
2495     H_LOCK;
2496     *cp = NULL;
2497     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2498     if (client == NULL) {
2499         ViceLog(0,
2500                 ("GetClient: no client in conn %x (host %s:%d), VBUSYING\n",
2501                  tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2502                  ntohs(rxr_PortOf(tcon))));
2503         H_UNLOCK;
2504         return VBUSY;
2505     }
2506     if (rxr_CidOf(tcon) != client->sid || rxr_GetEpoch(tcon) != client->VenusEpoch) {
2507         ViceLog(0,
2508                 ("GetClient: tcon %x tcon sid %d client sid %d\n",
2509                  tcon, rxr_CidOf(tcon), client->sid));
2510         H_UNLOCK;
2511         return VBUSY;
2512     }
2513     if (client && client->LastCall > client->expTime && client->expTime) {
2514         ViceLog(1,
2515                 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2516                  afs_inet_ntoa_r(client->host->host, hoststr),
2517                  ntohs(client->host->port), client->expTime));
2518         H_UNLOCK;
2519         return VICETOKENDEAD;
2520     }
2521
2522     client->refCount++;
2523     *cp = client;
2524     H_UNLOCK;
2525     return 0;
2526 }                               /*GetClient */
2527
2528 int
2529 PutClient(struct client **cp)
2530 {
2531     if (*cp == NULL) 
2532         return -1;
2533
2534     H_LOCK;
2535     h_ReleaseClient_r(*cp);
2536     *cp = NULL;
2537     H_UNLOCK;
2538     return 0;
2539 }                               /*PutClient */
2540
2541
2542 /* Client user name for short term use.  Note that this is NOT inexpensive */
2543 char *
2544 h_UserName(struct client *client)
2545 {
2546     static char User[PR_MAXNAMELEN + 1];
2547     namelist lnames;
2548     idlist lids;
2549
2550     lids.idlist_len = 1;
2551     lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
2552     if (!lids.idlist_val) {
2553         ViceLog(0, ("Failed malloc in h_UserName\n"));
2554         assert(0);
2555     }
2556     lnames.namelist_len = 0;
2557     lnames.namelist_val = (prname *) 0;
2558     lids.idlist_val[0] = client->ViceId;
2559     if (hpr_IdToName(&lids, &lnames)) {
2560         /* We need to free id we alloced above! */
2561         free(lids.idlist_val);
2562         return "*UNKNOWN USER NAME*";
2563     }
2564     strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2565     free(lids.idlist_val);
2566     free(lnames.namelist_val);
2567     return User;
2568 }                               /*h_UserName */
2569
2570
2571 void
2572 h_PrintStats(void)
2573 {
2574     ViceLog(0,
2575             ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2576              CEs, CEBlocks, HTs, HTBlocks));
2577
2578 }                               /*h_PrintStats */
2579
2580
2581 static int
2582 h_PrintClient(register struct host *host, int held, void *rock)
2583 {
2584     StreamHandle_t *file = (StreamHandle_t *)rock;
2585     register struct client *client;
2586     int i;
2587     char tmpStr[256];
2588     char tbuffer[32];
2589     char hoststr[16];
2590     time_t LastCall, expTime;
2591
2592     H_LOCK;
2593     LastCall = host->LastCall;
2594     if (host->hostFlags & HOSTDELETED) {
2595         H_UNLOCK;
2596         return held;
2597     }
2598     (void)afs_snprintf(tmpStr, sizeof tmpStr,
2599                        "Host %s:%d down = %d, LastCall %s",
2600                        afs_inet_ntoa_r(host->host, hoststr),
2601                        ntohs(host->port), (host->hostFlags & VENUSDOWN),
2602                        afs_ctime(&LastCall, tbuffer,
2603                                  sizeof(tbuffer)));
2604     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2605     for (client = host->FirstClient; client; client = client->next) {
2606         if (!client->deleted) {
2607                 expTime = client->expTime;
2608                 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2609                                    "    user id=%d,  name=%s, sl=%s till %s",
2610                                    client->ViceId, h_UserName(client),
2611                                    client->
2612                                    authClass ? "Authenticated" :
2613                                    "Not authenticated",
2614                                    client->
2615                                    authClass ? afs_ctime(&expTime, tbuffer,
2616                                                          sizeof(tbuffer))
2617                                    : "No Limit\n");
2618                 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2619             (void)afs_snprintf(tmpStr, sizeof tmpStr, "      CPS-%d is [",
2620                                client->CPS.prlist_len);
2621             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2622             if (client->CPS.prlist_val) {
2623                 for (i = 0; i > client->CPS.prlist_len; i++) {
2624                     (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2625                                        client->CPS.prlist_val[i]);
2626                     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2627                 }
2628             }
2629             sprintf(tmpStr, "]\n");
2630             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2631         }
2632     }
2633     H_UNLOCK;
2634     return held;
2635
2636 }                               /*h_PrintClient */
2637
2638
2639
2640 /*
2641  * Print a list of clients, with last security level and token value seen,
2642  * if known
2643  */
2644 void
2645 h_PrintClients(void)
2646 {
2647     time_t now;
2648     char tmpStr[256];
2649     char tbuffer[32];
2650
2651     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2652
2653     if (file == NULL) {
2654         ViceLog(0,
2655                 ("Couldn't create client dump file %s\n",
2656                  AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2657         return;
2658     }
2659     now = FT_ApproxTime();
2660     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
2661                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2662     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2663     h_Enumerate(h_PrintClient, (char *)file);
2664     STREAM_REALLYCLOSE(file);
2665     ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2666 }
2667
2668
2669
2670
2671 static int
2672 h_DumpHost(register struct host *host, int held, void *rock)
2673 {
2674     StreamHandle_t *file = (StreamHandle_t *)rock;
2675     
2676     int i;
2677     char tmpStr[256];
2678     char hoststr[16];
2679
2680     H_LOCK;
2681     (void)afs_snprintf(tmpStr, sizeof tmpStr,
2682                        "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 [",
2683                        afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), host->index,
2684                        host->cblist, CheckLock(&host->lock), host->LastCall,
2685                        host->ActiveCall, (host->hostFlags & VENUSDOWN),
2686                        host->hostFlags & HOSTDELETED, host->Console,
2687                        host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2688                        host->cpsCall);
2689     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2690     if (host->hcps.prlist_val)
2691         for (i = 0; i < host->hcps.prlist_len; i++) {
2692             (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2693                                host->hcps.prlist_val[i]);
2694             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2695         }
2696     sprintf(tmpStr, "] [");
2697     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2698     if (host->interface)
2699         for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2700             char hoststr[16];
2701             sprintf(tmpStr, " %s:%d", 
2702                      afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2703                      ntohs(host->interface->interface[i].port));
2704             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2705         }
2706     sprintf(tmpStr, "] holds: ");
2707     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2708
2709     for (i = 0; i < h_maxSlots; i++) {
2710         sprintf(tmpStr, "%04x", host->holds[i]);
2711         (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2712     }
2713     sprintf(tmpStr, " slot/bit: %ld/%d\n", (long int) h_holdSlot(), 
2714             h_holdbit());
2715     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2716
2717     H_UNLOCK;
2718     return held;
2719
2720 }                               /*h_DumpHost */
2721
2722
2723 void
2724 h_DumpHosts(void)
2725 {
2726     time_t now;
2727     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2728     char tmpStr[256];
2729     char tbuffer[32];
2730
2731     if (file == NULL) {
2732         ViceLog(0,
2733                 ("Couldn't create host dump file %s\n",
2734                  AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2735         return;
2736     }
2737     now = FT_ApproxTime();
2738     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
2739                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2740     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2741     h_Enumerate(h_DumpHost, (char *)file);
2742     STREAM_REALLYCLOSE(file);
2743     ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2744
2745 }                               /*h_DumpHosts */
2746
2747 #ifdef AFS_DEMAND_ATTACH_FS
2748 /*
2749  * demand attach fs
2750  * host state serialization
2751  */
2752 static int h_stateFillHeader(struct host_state_header * hdr);
2753 static int h_stateCheckHeader(struct host_state_header * hdr);
2754 static int h_stateAllocMap(struct fs_dump_state * state);
2755 static int h_stateSaveHost(struct host * host, int held, void *rock);
2756 static int h_stateRestoreHost(struct fs_dump_state * state);
2757 static int h_stateRestoreIndex(struct host * h, int held, void *rock);
2758 static int h_stateVerifyHost(struct host * h, int held, void *rock);
2759 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port);
2760 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2761 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2762 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2763
2764
2765 /* this procedure saves all host state to disk for fast startup */
2766 int
2767 h_stateSave(struct fs_dump_state * state)
2768 {
2769     AssignInt64(state->eof_offset, &state->hdr->h_offset);
2770
2771     /* XXX debug */
2772     ViceLog(0, ("h_stateSave:  hostCount=%d\n", hostCount));
2773
2774     /* invalidate host state header */
2775     memset(state->h_hdr, 0, sizeof(struct host_state_header));
2776
2777     if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2778                             sizeof(struct host_state_header))) {
2779         state->bail = 1;
2780         goto done;
2781     }
2782
2783     fs_stateIncEOF(state, sizeof(struct host_state_header));
2784
2785     h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2786     if (state->bail) {
2787         goto done;
2788     }
2789
2790     h_stateFillHeader(state->h_hdr);
2791
2792     /* write the real header to disk */
2793     state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2794                                       sizeof(struct host_state_header));
2795
2796  done:
2797     return state->bail;
2798 }
2799
2800 /* demand attach fs
2801  * host state serialization
2802  *
2803  * this procedure restores all host state from a disk for fast startup 
2804  */
2805 int
2806 h_stateRestore(struct fs_dump_state * state)
2807 {
2808     int i, records;
2809
2810     /* seek to the right position and read in the host state header */
2811     if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2812                            sizeof(struct host_state_header))) {
2813         state->bail = 1;
2814         goto done;
2815     }
2816
2817     /* check the validity of the header */
2818     if (h_stateCheckHeader(state->h_hdr)) {
2819         state->bail = 1;
2820         goto done;
2821     }
2822
2823     records = state->h_hdr->records;
2824
2825     if (h_stateAllocMap(state)) {
2826         state->bail = 1;
2827         goto done;
2828     }
2829
2830     /* iterate over records restoring host state */
2831     for (i=0; i < records; i++) {
2832         if (h_stateRestoreHost(state) != 0) {
2833             state->bail = 1;
2834             break;
2835         }
2836     }
2837
2838  done:
2839     return state->bail;
2840 }
2841
2842 int
2843 h_stateRestoreIndices(struct fs_dump_state * state)
2844 {
2845     h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
2846     return state->bail;
2847 }
2848
2849 static int
2850 h_stateRestoreIndex(struct host * h, int held, void *rock)
2851 {
2852     struct fs_dump_state *state = (struct fs_dump_state *)rock;
2853     if (cb_OldToNew(state, h->cblist, &h->cblist)) {
2854         return H_ENUMERATE_BAIL(held);
2855     }
2856     return held;
2857 }
2858
2859 int
2860 h_stateVerify(struct fs_dump_state * state)
2861 {
2862     h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
2863     return state->bail;
2864 }
2865
2866 static int
2867 h_stateVerifyHost(struct host * h, int held, void* rock)
2868 {
2869     struct fs_dump_state *state = (struct fs_dump_state *)rock;
2870     int i;
2871
2872     if (h == NULL) {
2873         ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
2874         return H_ENUMERATE_BAIL(held);
2875     }
2876
2877     if (h->interface) {
2878         for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
2879             if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr, 
2880                                       h->interface->interface[i].port)) {
2881                 state->bail = 1;
2882             }
2883         }
2884         if (h_stateVerifyUuidHash(state, h)) {
2885             state->bail = 1;
2886         }
2887     } else if (h_stateVerifyAddrHash(state, h, h->host, h->port)) {
2888         state->bail = 1;
2889     }
2890
2891     if (cb_stateVerifyHCBList(state, h)) {
2892         state->bail = 1;
2893     }
2894
2895     return held;
2896 }
2897
2898 static int
2899 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port)
2900 {
2901     int ret = 0, found = 0;
2902     struct host *host = NULL;
2903     struct h_AddrHashChain *chain;
2904     int index = h_HashIndex(addr);
2905     char tmp[16];
2906     int chain_len = 0;
2907
2908     for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
2909         host = chain->hostPtr;
2910         if (host == NULL) {
2911             afs_inet_ntoa_r(addr, tmp);
2912             ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
2913             ret = 1;
2914             goto done;
2915         }
2916         if ((chain->addr == addr) && (chain->port == port)) {
2917             if (host != h) {
2918                 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry points to different host struct (%d, %d)\n", 
2919                             h->index, host->index));
2920                 state->flags.warnings_generated = 1;
2921             }
2922             found = 1;
2923             break;
2924         }
2925         if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
2926             ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2927                         FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
2928             ret = 1;
2929             goto done;
2930         }
2931         chain_len++;
2932     }
2933
2934     if (!found) {
2935         afs_inet_ntoa_r(addr, tmp);
2936         if (state->mode == FS_STATE_LOAD_MODE) {
2937             ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s not found in hash\n", tmp));
2938             ret = 1;
2939             goto done;
2940         } else {
2941             ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s not found in hash\n", tmp));
2942             state->flags.warnings_generated = 1;
2943         }
2944     }
2945
2946  done:
2947     return ret;
2948 }
2949
2950 static int
2951 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
2952 {
2953     int ret = 0, found = 0;
2954     struct host *host = NULL;
2955     struct h_UuidHashChain *chain;
2956     afsUUID * uuidp = &h->interface->uuid;
2957     int index = h_UuidHashIndex(uuidp);
2958     char tmp[40];
2959     int chain_len = 0;
2960
2961     for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
2962         host = chain->hostPtr;
2963         if (host == NULL) {
2964             afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2965             ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
2966             ret = 1;
2967             goto done;
2968         }
2969         if (host->interface &&
2970             afs_uuid_equal(&host->interface->uuid, uuidp)) {
2971             if (host != h) {
2972                 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n", 
2973                             h->index, host->index));
2974                 state->flags.warnings_generated = 1;
2975             }
2976             found = 1;
2977             goto done;
2978         }
2979         if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
2980             ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2981                         FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
2982             ret = 1;
2983             goto done;
2984         }
2985         chain_len++;
2986     }
2987
2988     if (!found) {
2989         afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2990         if (state->mode == FS_STATE_LOAD_MODE) {
2991             ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
2992             ret = 1;
2993             goto done;
2994         } else {
2995             ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
2996             state->flags.warnings_generated = 1;
2997         }
2998     }
2999
3000  done:
3001     return ret;
3002 }
3003
3004 /* create the host state header structure */
3005 static int
3006 h_stateFillHeader(struct host_state_header * hdr)
3007 {
3008     hdr->stamp.magic = HOST_STATE_MAGIC;
3009     hdr->stamp.version = HOST_STATE_VERSION;
3010     return 0;
3011 }
3012
3013 /* check the contents of the host state header structure */
3014 static int
3015 h_stateCheckHeader(struct host_state_header * hdr)
3016 {
3017     int ret=0;
3018
3019     if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3020         ViceLog(0, ("check_host_state_header: invalid state header\n"));
3021         ret = 1;
3022     }
3023     else if (hdr->stamp.version != HOST_STATE_VERSION) {
3024         ViceLog(0, ("check_host_state_header: unknown version number\n"));
3025         ret = 1;
3026     }
3027     return ret;
3028 }
3029
3030 /* allocate the host id mapping table */
3031 static int
3032 h_stateAllocMap(struct fs_dump_state * state)
3033 {
3034     state->h_map.len = state->h_hdr->index_max + 1;
3035     state->h_map.entries = (struct idx_map_entry_t *)
3036         calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3037     return (state->h_map.entries != NULL) ? 0 : 1;
3038 }
3039
3040 /* function called by h_Enumerate to save a host to disk */
3041 static int
3042 h_stateSaveHost(struct host * host, int held, void* rock)
3043 {
3044     struct fs_dump_state *state = (struct fs_dump_state *) rock;
3045     int if_len=0, hcps_len=0;
3046     struct hostDiskEntry hdsk;
3047     struct host_state_entry_header hdr;
3048     struct Interface * ifp = NULL;
3049     afs_int32 * hcps = NULL;
3050     struct iovec iov[4];
3051     int iovcnt = 2;
3052
3053     memset(&hdr, 0, sizeof(hdr));
3054
3055     if (state->h_hdr->index_max < host->index) {
3056         state->h_hdr->index_max = host->index;
3057     }
3058
3059     h_hostToDiskEntry_r(host, &hdsk);
3060     if (host->interface) {
3061         if_len = sizeof(struct Interface) + 
3062             ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3063         ifp = (struct Interface *) malloc(if_len);
3064         assert(ifp != NULL);
3065         memcpy(ifp, host->interface, if_len);
3066         hdr.interfaces = host->interface->numberOfInterfaces;
3067         iov[iovcnt].iov_base = (char *) ifp;
3068         iov[iovcnt].iov_len = if_len;
3069         iovcnt++;
3070     }
3071     if (host->hcps.prlist_val) {
3072         hdr.hcps = host->hcps.prlist_len;
3073         hcps_len = hdr.hcps * sizeof(afs_int32);
3074         hcps = (afs_int32 *) malloc(hcps_len);
3075         assert(hcps != NULL);
3076         memcpy(hcps, host->hcps.prlist_val, hcps_len);
3077         iov[iovcnt].iov_base = (char *) hcps;
3078         iov[iovcnt].iov_len = hcps_len;
3079         iovcnt++;
3080     }
3081
3082     if (hdsk.index > state->h_hdr->index_max)
3083         state->h_hdr->index_max = hdsk.index;
3084
3085     hdr.len = sizeof(struct host_state_entry_header) + 
3086         sizeof(struct hostDiskEntry) + if_len + hcps_len;
3087     hdr.magic = HOST_STATE_ENTRY_MAGIC;
3088
3089     iov[0].iov_base = (char *) &hdr;
3090     iov[0].iov_len = sizeof(hdr);
3091     iov[1].iov_base = (char *) &hdsk;
3092     iov[1].iov_len = sizeof(struct hostDiskEntry);
3093     
3094     if (fs_stateWriteV(state, iov, iovcnt)) {
3095         ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3096         state->bail = 1;
3097     }
3098
3099     fs_stateIncEOF(state, hdr.len);
3100
3101     state->h_hdr->records++;
3102
3103     if (ifp)
3104         free(ifp);
3105     if (hcps)
3106         free(hcps);
3107     if (state->bail) {
3108         return H_ENUMERATE_BAIL(held);
3109     }
3110     return held;
3111 }
3112
3113 /* restores a host from disk */
3114 static int
3115 h_stateRestoreHost(struct fs_dump_state * state)
3116 {
3117     int ifp_len=0, hcps_len=0, bail=0;
3118     struct host_state_entry_header hdr;
3119     struct hostDiskEntry hdsk;
3120     struct host *host = NULL;
3121     struct Interface *ifp = NULL;
3122     afs_int32 * hcps = NULL;
3123     struct iovec iov[3];
3124     int iovcnt = 1;
3125
3126     if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3127         ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3128                     state->fn));
3129         bail = 1;
3130         goto done;
3131     }
3132
3133     if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3134         ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3135                     state->fn));
3136         bail = 1;
3137         goto done;
3138     }
3139
3140     iov[0].iov_base = (char *) &hdsk;
3141     iov[0].iov_len = sizeof(struct hostDiskEntry);
3142
3143     if (hdr.interfaces) {
3144         ifp_len = sizeof(struct Interface) +
3145             ((hdr.interfaces-1) * sizeof(struct AddrPort));
3146         ifp = (struct Interface *) malloc(ifp_len);
3147         assert(ifp != NULL);
3148         iov[iovcnt].iov_base = (char *) ifp;
3149         iov[iovcnt].iov_len = ifp_len;
3150         iovcnt++;
3151     }
3152     if (hdr.hcps) {
3153         hcps_len = hdr.hcps * sizeof(afs_int32);
3154         hcps = (afs_int32 *) malloc(hcps_len);
3155         assert(hcps != NULL);
3156         iov[iovcnt].iov_base = (char *) hcps;
3157         iov[iovcnt].iov_len = hcps_len;
3158         iovcnt++;
3159     }
3160
3161     if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3162         ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3163         bail = 1;
3164         goto done;
3165     }
3166
3167     if (fs_stateReadV(state, iov, iovcnt)) {
3168         ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3169         bail = 1;
3170         goto done;
3171     }
3172
3173     if (!hdr.hcps && hdsk.hcps_valid) {
3174         /* valid, zero-length host cps ; does this ever happen? */
3175         hcps = (afs_int32 *) malloc(sizeof(afs_int32));
3176         assert(hcps != NULL);
3177     }
3178
3179     host = GetHT();
3180     assert(host != NULL);
3181
3182     if (ifp) {
3183         host->interface = ifp;
3184     }
3185     if (hcps) {
3186         host->hcps.prlist_val = hcps;
3187         host->hcps.prlist_len = hdr.hcps;
3188     }
3189
3190     h_diskEntryToHost_r(&hdsk, host);
3191     h_SetupCallbackConn_r(host);
3192
3193     h_AddHostToAddrHashTable_r(host->host, host->port, host);
3194     if (ifp) {
3195         int i;
3196         for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3197             if (ifp->interface[i].valid && 
3198                 !(ifp->interface[i].addr == host->host &&
3199                   ifp->interface[i].port == host->port)) {
3200                 h_AddHostToAddrHashTable_r(ifp->interface[i].addr, 
3201                                            ifp->interface[i].port, 
3202                                            host);
3203             }
3204         }
3205         h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3206     }
3207     h_InsertList_r(host);
3208
3209     /* setup host id map entry */
3210     state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3211     state->h_map.entries[hdsk.index].new_idx = host->index;
3212
3213  done:
3214     if (bail) {
3215         if (ifp)
3216             free(ifp);
3217         if (hcps)
3218             free(hcps);
3219     }
3220     return bail;
3221 }
3222
3223 /* serialize a host structure to disk */
3224 static void
3225 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3226 {
3227     out->host = in->host;
3228     out->port = in->port;
3229     out->hostFlags = in->hostFlags;
3230     out->Console = in->Console;
3231     out->hcpsfailed = in->hcpsfailed;
3232     out->LastCall = in->LastCall;
3233     out->ActiveCall = in->ActiveCall;
3234     out->cpsCall = in->cpsCall;
3235     out->cblist = in->cblist;
3236 #ifdef FS_STATS_DETAILED
3237     out->InSameNetwork = in->InSameNetwork;
3238 #endif
3239
3240     /* special fields we save, but are not memcpy'd back on restore */
3241     out->index = in->index;
3242     out->hcps_len = in->hcps.prlist_len;
3243     out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
3244 }
3245
3246 /* restore a host structure from disk */
3247 static void
3248 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3249 {
3250     out->host = in->host;
3251     out->port = in->port;
3252     out->hostFlags = in->hostFlags;
3253     out->Console = in->Console;
3254     out->hcpsfailed = in->hcpsfailed;
3255     out->LastCall = in->LastCall;
3256     out->ActiveCall = in->ActiveCall;
3257     out->cpsCall = in->cpsCall;
3258     out->cblist = in->cblist;
3259 #ifdef FS_STATS_DETAILED
3260     out->InSameNetwork = in->InSameNetwork;
3261 #endif
3262 }
3263
3264 /* index translation routines */
3265 int
3266 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3267 {
3268     int ret = 0;
3269
3270     /* hosts use a zero-based index, so old==0 is valid */
3271
3272     if (old >= state->h_map.len) {
3273         ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3274         ret = 1;
3275     } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
3276         ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3277         ret = 1;
3278     } else {
3279         *new = state->h_map.entries[old].new_idx;
3280     }
3281
3282     return ret;
3283 }
3284 #endif /* AFS_DEMAND_ATTACH_FS */
3285
3286
3287 /*
3288  * This counts the number of workstations, the number of active workstations,
3289  * and the number of workstations declared "down" (i.e. not heard from
3290  * recently).  An active workstation has received a call since the cutoff
3291  * time argument passed.
3292  */
3293 void
3294 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3295 {
3296     register struct host *host;
3297     register int num = 0, active = 0, del = 0;
3298
3299     H_LOCK;
3300     for (host = hostList; host; host = host->next) {
3301         if (!(host->hostFlags & HOSTDELETED)) {
3302             num++;
3303             if (host->ActiveCall > cutofftime)
3304                 active++;
3305             if (host->hostFlags & VENUSDOWN)
3306                 del++;
3307         }
3308     }
3309     H_UNLOCK;
3310     if (nump)
3311         *nump = num;
3312     if (activep)
3313         *activep = active;
3314     if (delp)
3315         *delp = del;
3316
3317 }                               /*h_GetWorkStats */
3318
3319
3320 /*------------------------------------------------------------------------
3321  * PRIVATE h_ClassifyAddress
3322  *
3323  * Description:
3324  *      Given a target IP address and a candidate IP address (both
3325  *      in host byte order), classify the candidate into one of three
3326  *      buckets in relation to the target by bumping the counters passed
3327  *      in as parameters.
3328  *
3329  * Arguments:
3330  *      a_targetAddr       : Target address.
3331  *      a_candAddr         : Candidate address.
3332  *      a_sameNetOrSubnetP : Ptr to counter to bump when the two
3333  *                           addresses are either in the same network
3334  *                           or the same subnet.
3335  *      a_diffSubnetP      : ...when the candidate is in a different
3336  *                           subnet.
3337  *      a_diffNetworkP     : ...when the candidate is in a different
3338  *                           network.
3339  *
3340  * Returns:
3341  *      Nothing.
3342  *
3343  * Environment:
3344  *      The target and candidate addresses are both in host byte
3345  *      order, NOT network byte order, when passed in.
3346  *
3347  * Side Effects:
3348  *      As advertised.
3349  *------------------------------------------------------------------------*/
3350
3351 static void
3352 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3353                   afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3354                   afs_int32 * a_diffNetworkP)
3355 {                               /*h_ClassifyAddress */
3356
3357     afs_uint32 targetNet;
3358     afs_uint32 targetSubnet;
3359     afs_uint32 candNet;
3360     afs_uint32 candSubnet;
3361
3362     /*
3363      * Put bad values into the subnet info to start with.
3364      */
3365     targetSubnet = (afs_uint32) 0;
3366     candSubnet = (afs_uint32) 0;
3367
3368     /*
3369      * Pull out the network and subnetwork numbers from the target
3370      * and candidate addresses.  We can short-circuit this whole
3371      * affair if the target and candidate addresses are not of the
3372      * same class.
3373      */
3374     if (IN_CLASSA(a_targetAddr)) {
3375         if (!(IN_CLASSA(a_candAddr))) {
3376             (*a_diffNetworkP)++;
3377             return;
3378         }
3379         targetNet = a_targetAddr & IN_CLASSA_NET;
3380         candNet = a_candAddr & IN_CLASSA_NET;
3381         if (IN_SUBNETA(a_targetAddr))
3382             targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3383         if (IN_SUBNETA(a_candAddr))
3384             candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3385     } else if (IN_CLASSB(a_targetAddr)) {
3386         if (!(IN_CLASSB(a_candAddr))) {
3387             (*a_diffNetworkP)++;
3388             return;
3389         }
3390         targetNet = a_targetAddr & IN_CLASSB_NET;
3391         candNet = a_candAddr & IN_CLASSB_NET;
3392         if (IN_SUBNETB(a_targetAddr))
3393             targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3394         if (IN_SUBNETB(a_candAddr))
3395             candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3396     } /*Class B target */
3397     else if (IN_CLASSC(a_targetAddr)) {
3398         if (!(IN_CLASSC(a_candAddr))) {
3399             (*a_diffNetworkP)++;
3400             return;
3401         }
3402         targetNet = a_targetAddr & IN_CLASSC_NET;
3403         candNet = a_candAddr & IN_CLASSC_NET;
3404
3405         /*
3406          * Note that class C addresses can't have subnets,
3407          * so we leave the defaults untouched.
3408          */
3409     } /*Class C target */
3410     else {
3411         targetNet = a_targetAddr;
3412         candNet = a_candAddr;
3413     }                           /*Class D address */
3414
3415     /*
3416      * Now, simply compare the extracted net and subnet values for
3417      * the two addresses (which at this point are known to be of the
3418      * same class)
3419      */
3420     if (targetNet == candNet) {
3421         if (targetSubnet == candSubnet)
3422             (*a_sameNetOrSubnetP)++;
3423         else
3424             (*a_diffSubnetP)++;
3425     } else
3426         (*a_diffNetworkP)++;
3427
3428 }                               /*h_ClassifyAddress */
3429
3430
3431 /*------------------------------------------------------------------------
3432  * EXPORTED h_GetHostNetStats
3433  *
3434  * Description:
3435  *      Iterate through the host table, and classify each (non-deleted)
3436  *      host entry into ``proximity'' categories (same net or subnet,
3437  *      different subnet, different network).
3438  *
3439  * Arguments:
3440  *      a_numHostsP        : Set to total number of (non-deleted) hosts.
3441  *      a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3442  *      a_diffSubnetP      : Set to # hosts on diff subnet as server.
3443  *      a_diffNetworkP     : Set to # hosts on diff network as server.
3444  *
3445  * Returns:
3446  *      Nothing.
3447  *
3448  * Environment:
3449  *      We only count non-deleted hosts.  The storage pointed to by our
3450  *      parameters is zeroed upon entry.
3451  *
3452  * Side Effects:
3453  *      As advertised.
3454  *------------------------------------------------------------------------*/
3455
3456 void
3457 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3458                   afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3459 {                               /*h_GetHostNetStats */
3460
3461     register struct host *hostP;        /*Ptr to current host entry */
3462     register afs_uint32 currAddr_HBO;   /*Curr host addr, host byte order */
3463
3464     /*
3465      * Clear out the storage pointed to by our parameters.
3466      */
3467     *a_numHostsP = (afs_int32) 0;
3468     *a_sameNetOrSubnetP = (afs_int32) 0;
3469     *a_diffSubnetP = (afs_int32) 0;
3470     *a_diffNetworkP = (afs_int32) 0;
3471
3472     H_LOCK;
3473     for (hostP = hostList; hostP; hostP = hostP->next) {
3474         if (!(hostP->hostFlags & HOSTDELETED)) {
3475             /*
3476              * Bump the number of undeleted host entries found.
3477              * In classifying the current entry's address, make
3478              * sure to first convert to host byte order.
3479              */
3480             (*a_numHostsP)++;
3481             currAddr_HBO = (afs_uint32) ntohl(hostP->host);
3482             h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3483                               a_sameNetOrSubnetP, a_diffSubnetP,
3484                               a_diffNetworkP);
3485         }                       /*Only look at non-deleted hosts */
3486     }                           /*For each host record hashed to this index */
3487     H_UNLOCK;
3488 }                               /*h_GetHostNetStats */
3489
3490 static afs_uint32 checktime;
3491 static afs_uint32 clientdeletetime;
3492 static struct AFSFid zerofid;
3493
3494
3495 /*
3496  * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3497  * Since it can serialize them, and pile up, it should be a separate LWP
3498  * from other events.
3499  */
3500 #if 0
3501 static int
3502 CheckHost(register struct host *host, int held, void *rock)
3503 {
3504     register struct client *client;
3505     struct rx_connection *cb_conn = NULL;
3506     int code;
3507
3508 #ifdef AFS_DEMAND_ATTACH_FS
3509     /* kill the checkhost lwp ASAP during shutdown */
3510     FS_STATE_RDLOCK;
3511     if (fs_state.mode == FS_MODE_SHUTDOWN) {
3512         FS_STATE_UNLOCK;
3513         return H_ENUMERATE_BAIL(held);
3514     }
3515     FS_STATE_UNLOCK;
3516 #endif
3517
3518     /* Host is held by h_Enumerate */
3519     H_LOCK;
3520     for (client = host->FirstClient; client; client = client->next) {
3521         if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3522             client->deleted = 1;
3523             host->hostFlags |= CLIENTDELETED;
3524         }
3525     }
3526     if (host->LastCall < checktime) {
3527         h_Lock_r(host);
3528         host->hostFlags |= HWHO_INPROGRESS;
3529         if (!(host->hostFlags & HOSTDELETED)) {
3530             cb_conn = host->callback_rxcon;
3531             rx_GetConnection(cb_conn);
3532             if (host->LastCall < clientdeletetime) {
3533                 host->hostFlags |= HOSTDELETED;
3534                 if (!(host->hostFlags & VENUSDOWN)) {
3535                     host->hostFlags &= ~ALTADDR;        /* alternate address invalid */
3536                     if (host->interface) {
3537                         H_UNLOCK;
3538                         code =
3539                             RXAFSCB_InitCallBackState3(cb_conn,
3540                                                        &FS_HostUUID);
3541                         H_LOCK;
3542                     } else {
3543                         H_UNLOCK;
3544                         code =
3545                             RXAFSCB_InitCallBackState(cb_conn);
3546                         H_LOCK;
3547                     }
3548                     host->hostFlags |= ALTADDR; /* alternate addresses valid */
3549                     if (code) {
3550                         char hoststr[16];
3551                         (void)afs_inet_ntoa_r(host->host, hoststr);
3552                         ViceLog(0,
3553                                 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3554                                  hoststr, ntohs(host->port)));
3555                         host->hostFlags |= VENUSDOWN;
3556                     }
3557                     /* Note:  it's safe to delete hosts even if they have call
3558                      * back state, because break delayed callbacks (called when a
3559                      * message is received from the workstation) will always send a 
3560                      * break all call backs to the workstation if there is no
3561                      * callback.
3562                      */
3563                 }
3564             } else {
3565                 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3566                     char hoststr[16];
3567                     (void)afs_inet_ntoa_r(host->host, hoststr);
3568                     if (host->interface) {
3569                         afsUUID uuid = host->interface->uuid;
3570                         H_UNLOCK;
3571                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3572                         H_LOCK;
3573                         if (code) {
3574                             if (MultiProbeAlternateAddress_r(host)) {
3575                                 ViceLog(0,("CheckHost: Probing all interfaces of host %s:%d failed, code %d\n",
3576                                             hoststr, ntohs(host->port), code));
3577                                 host->hostFlags |= VENUSDOWN;
3578                             }
3579                         }
3580                     } else {
3581                         H_UNLOCK;
3582                         code = RXAFSCB_Probe(cb_conn);
3583                         H_LOCK;
3584                         if (code) {
3585                             ViceLog(0,
3586                                     ("CheckHost: Probe failed for host %s:%d, code %d\n", 
3587                                      hoststr, ntohs(host->port), code));
3588                             host->hostFlags |= VENUSDOWN;
3589                         }
3590                     }
3591                 }
3592             }
3593             H_UNLOCK;
3594             rx_PutConnection(cb_conn);
3595             cb_conn=NULL;
3596             H_LOCK;
3597         }
3598         host->hostFlags &= ~HWHO_INPROGRESS;
3599         h_Unlock_r(host);
3600     }
3601     H_UNLOCK;
3602     return held;
3603
3604 }                               /*CheckHost */
3605 #endif
3606
3607 int
3608 CheckHost_r(register struct host *host, int held, void *dummy)
3609 {
3610     register struct client *client;
3611     struct rx_connection *cb_conn = NULL;
3612     int code;
3613
3614 #ifdef AFS_DEMAND_ATTACH_FS
3615     /* kill the checkhost lwp ASAP during shutdown */
3616     FS_STATE_RDLOCK;
3617     if (fs_state.mode == FS_MODE_SHUTDOWN) {
3618         FS_STATE_UNLOCK;
3619         return H_ENUMERATE_BAIL(held);
3620     }
3621     FS_STATE_UNLOCK;
3622 #endif
3623
3624     /* Host is held by h_Enumerate_r */
3625     for (client = host->FirstClient; client; client = client->next) {
3626         if (client->refCount == 0 && client->LastCall < clientdeletetime) {
3627             client->deleted = 1;
3628             host->hostFlags |= CLIENTDELETED;
3629         }
3630     }
3631     if (host->LastCall < checktime) {
3632         h_Lock_r(host);
3633         if (!(host->hostFlags & HOSTDELETED)) {
3634             cb_conn = host->callback_rxcon;
3635             rx_GetConnection(cb_conn);
3636             if (host->LastCall < clientdeletetime) {
3637                 host->hostFlags |= HOSTDELETED;
3638                 if (!(host->hostFlags & VENUSDOWN)) {
3639                     host->hostFlags &= ~ALTADDR;        /* alternate address invalid */
3640                     if (host->interface) {
3641                         H_UNLOCK;
3642                         code =
3643                             RXAFSCB_InitCallBackState3(cb_conn,
3644                                                        &FS_HostUUID);
3645                         H_LOCK;
3646                     } else {
3647                         H_UNLOCK;
3648                         code =
3649                             RXAFSCB_InitCallBackState(cb_conn);
3650                         H_LOCK;
3651                     }
3652                     host->hostFlags |= ALTADDR; /* alternate addresses valid */
3653                     if (code) {
3654                         char hoststr[16];
3655                         (void)afs_inet_ntoa_r(host->host, hoststr);
3656                         ViceLog(0,
3657                                 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
3658                                  hoststr, ntohs(host->port)));
3659                         host->hostFlags |= VENUSDOWN;
3660                     }
3661                     /* Note:  it's safe to delete hosts even if they have call
3662                      * back state, because break delayed callbacks (called when a
3663                      * message is received from the workstation) will always send a 
3664                      * break all call backs to the workstation if there is no
3665                      * callback.
3666                      */
3667                 }
3668             } else {
3669                 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
3670                     char hoststr[16];
3671                     (void)afs_inet_ntoa_r(host->host, hoststr);
3672                     if (host->interface) {
3673                         afsUUID uuid = host->interface->uuid;
3674                         H_UNLOCK;
3675                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
3676                         H_LOCK;
3677                         if (code) {
3678                             if (MultiProbeAlternateAddress_r(host)) {
3679                                 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
3680                                             hoststr, ntohs(host->port), code));
3681                                 host->hostFlags |= VENUSDOWN;
3682                             }
3683                         }
3684                     } else {
3685                         H_UNLOCK;
3686                         code = RXAFSCB_Probe(cb_conn);
3687                         H_LOCK;
3688                         if (code) {
3689                             ViceLog(0,
3690                                     ("CheckHost_r: Probe failed for host %s:%d, code %d\n", 
3691                                      hoststr, ntohs(host->port), code));
3692                             host->hostFlags |= VENUSDOWN;
3693                         }
3694                     }
3695                 }
3696             }
3697             H_UNLOCK;
3698             rx_PutConnection(cb_conn);
3699             cb_conn=NULL;
3700             H_LOCK;
3701         }
3702         h_Unlock_r(host);
3703     }
3704     return held;
3705
3706 }                               /*CheckHost_r */
3707
3708
3709 /*
3710  * Set VenusDown for any hosts that have not had a call in 15 minutes and
3711  * don't respond to a probe.  Note that VenusDown can only be cleared if
3712  * a message is received from the host (see ServerLWP in file.c).
3713  * Delete hosts that have not had any calls in 1 hour, clients that
3714  * have not had any calls in 15 minutes.
3715  *
3716  * This routine is called roughly every 5 minutes.
3717  */
3718 void
3719 h_CheckHosts(void)
3720 {
3721     afs_uint32 now = FT_ApproxTime();
3722
3723     memset(&zerofid, 0, sizeof(zerofid));
3724     /*
3725      * Send a probe to the workstation if it hasn't been heard from in
3726      * 15 minutes
3727      */
3728     checktime = now - 15 * 60;
3729     clientdeletetime = now - 120 * 60;  /* 2 hours ago */
3730     
3731     H_LOCK;
3732     h_Enumerate_r(CheckHost_r, hostList, NULL);
3733     H_UNLOCK;
3734 }                               /*h_CheckHosts */
3735
3736 /*
3737  * This is called with host locked and held. At this point, the
3738  * hostAddrHashTable has an entry for the primary addr/port inserted
3739  * by h_Alloc_r().  No other interfaces should be considered valid.
3740  *
3741  * The addresses in the interfaceAddr list are in host byte order.
3742  */
3743 int
3744 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3745 {
3746     int i, j;
3747     int number, count;
3748     afs_uint32 myAddr;
3749     afs_uint16 myPort;
3750     int found;
3751     struct Interface *interface;
3752     char hoststr[16];
3753     char uuidstr[128];
3754     afs_uint16 port7001 = htons(7001);
3755
3756     assert(host);
3757     assert(interf);
3758
3759     number = interf->numberOfInterfaces;
3760     myAddr = host->host;        /* current interface address */
3761     myPort = host->port;        /* current port */
3762
3763     ViceLog(125,
3764             ("initInterfaceAddr : host %s:%d numAddr %d\n", 
3765               afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
3766
3767     /* validation checks */
3768     if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3769         ViceLog(0,
3770                 ("Invalid number of alternate addresses is %d\n", number));
3771         return -1;
3772     }
3773
3774     /*
3775      * The client's notion of its own IP addresses is not reliable.  
3776      *
3777      * 1. The client list might contain private address ranges which
3778      *    are likely to be re-used by many clients allocated addresses
3779      *    by a NAT.
3780      *
3781      * 2. The client list will not include any public addresses that
3782      *    are hidden by a NAT.
3783      *
3784      * 3. Private address ranges that are exposed to the server will
3785      *    be obtained from the rx connections that use them.
3786      *
3787      * 4. Lists provided by the client are not necessarily truthful.
3788      *    Many existing clients (UNIX) do not refresh the IP address
3789      *    list as the actual assigned addresses change.  The end result
3790      *    is that they report the initial address list for the lifetime
3791      *    of the process.  In other words, a client can report addresses
3792      *    that they are in fact not using.  Adding these addresses to
3793      *    the host interface list without verification is not only
3794      *    pointless, it is downright dangerous.
3795      *
3796      * We therefore do not add alternate addresses to the addr hash table.
3797      * We only use them for multi-rx callback breaks.
3798      */
3799
3800     /*
3801      * Convert IP addresses to network byte order, and remove
3802      * duplicate IP addresses from the interface list, and 
3803      * determine whether or not the incoming addr/port is 
3804      * listed.  Note that if the address matches it is not
3805      * truly a match because the port number for the entries
3806      * in the interface list are port 7001 and the port number
3807      * for this connection might not be 7001.
3808      */
3809     for (i = 0, count = 0, found = 0; i < number; i++) {
3810         interf->addr_in[i] = htonl(interf->addr_in[i]);
3811         for (j = 0; j < count; j++) {
3812             if (interf->addr_in[j] == interf->addr_in[i])
3813                 break;
3814         }
3815         if (j == count) {
3816             interf->addr_in[count] = interf->addr_in[i];
3817             if (interf->addr_in[count] == myAddr &&
3818                 port7001 == myPort)
3819                 found = 1;
3820             count++;
3821         }
3822     }
3823
3824     /*
3825      * Allocate and initialize an interface structure for this host.
3826      */
3827     if (found) {
3828         interface = (struct Interface *)
3829             malloc(sizeof(struct Interface) +
3830                    (sizeof(struct AddrPort) * (count - 1)));
3831         if (!interface) {
3832             ViceLog(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
3833             assert(0);
3834         }
3835         interface->numberOfInterfaces = count;
3836     } else {
3837         interface = (struct Interface *)
3838             malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
3839         if (!interface) {
3840             ViceLog(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
3841             assert(0);
3842         }
3843         interface->numberOfInterfaces = count + 1;
3844         interface->interface[count].addr = myAddr;
3845         interface->interface[count].port = myPort;
3846         interface->interface[count].valid = 1;
3847     }
3848
3849     for (i = 0; i < count; i++) {
3850
3851         interface->interface[i].addr = interf->addr_in[i];
3852         /* We store the port as 7001 because the addresses reported by 
3853          * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
3854          * are coming from fully connected hosts (no NAT/PATs)
3855          */
3856         interface->interface[i].port = port7001;
3857         interface->interface[i].valid = 
3858             (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
3859     }
3860
3861     interface->uuid = interf->uuid;
3862
3863     assert(!host->interface);
3864     host->interface = interface;
3865
3866     if (LogLevel >= 125) {
3867         afsUUID_to_string(&interface->uuid, uuidstr, 127);
3868         
3869         ViceLog(125, ("--- uuid %s\n", uuidstr));
3870         for (i = 0; i < host->interface->numberOfInterfaces; i++) {
3871             ViceLog(125, ("--- alt address %s:%d\n", 
3872                           afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3873                           ntohs(host->interface->interface[i].port)));
3874         }
3875     }
3876
3877     return 0;
3878 }
3879
3880 /* deleted a HashChain structure for this address and host */
3881 /* returns 1 on success */
3882 int
3883 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port, 
3884                                 struct host *host)
3885 {
3886     char hoststr[16];
3887     register struct h_AddrHashChain **hp, *th;
3888
3889     if (addr == 0 && port == 0)
3890         return 1;
3891
3892     for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp); 
3893          hp = &th->next) {
3894         assert(th->hostPtr);
3895         if (th->hostPtr == host && th->addr == addr && th->port == port) {
3896             ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
3897                           host, afs_inet_ntoa_r(host->host, hoststr),
3898                           ntohs(host->port)));
3899             *hp = th->next;
3900             free(th);
3901             return 1;
3902         }
3903     }
3904     ViceLog(125, 
3905             ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
3906              host, afs_inet_ntoa_r(host->host, hoststr), 
3907              ntohs(host->port)));
3908     return 0;
3909 }
3910
3911
3912 /*
3913 ** prints out all alternate interface address for the host. The 'level'
3914 ** parameter indicates what level of debugging sets this output
3915 */
3916 void
3917 printInterfaceAddr(struct host *host, int level)
3918 {
3919     int i, number;
3920     char hoststr[16];
3921
3922     if (host->interface) {
3923         /* check alternate addresses */
3924         number = host->interface->numberOfInterfaces;
3925         if (number == 0) {
3926             ViceLog(level, ("no-addresses "));
3927         } else {
3928             for (i = 0; i < number; i++)
3929                 ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3930                                 ntohs(host->interface->interface[i].port)));
3931         }
3932     }
3933     ViceLog(level, ("\n"));
3934 }