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