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