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