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