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