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