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