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