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