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