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