ptuser: guarantee that all names are valid C strings
[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 static struct rx_securityClass *sc = NULL;
71 static int h_quota_limit;
72
73 /* arguments for PerHost_EnumerateClient enumeration */
74 struct enumclient_args {
75     VolumeId vid;
76     int (*proc)(struct client *client, void *rock);
77     void *rock;
78 };
79
80 static void h_SetupCallbackConn_r(struct host * host);
81 static int h_threadquota(int);
82 static int initInterfaceAddr_r(struct host *, struct interfaceAddr *);
83
84 #define CESPERBLOCK 73
85 struct CEBlock {                /* block of CESPERBLOCK file entries */
86     struct client entry[CESPERBLOCK];
87 };
88
89 void h_TossStuff_r(struct host *host);
90
91 /*
92  * Make sure the subnet macros have been defined.
93  */
94 #ifndef IN_SUBNETA
95 #define IN_SUBNETA(i)           ((((afs_int32)(i))&0x80800000)==0x00800000)
96 #endif
97
98 #ifndef IN_CLASSA_SUBNET
99 #define IN_CLASSA_SUBNET        0xffff0000
100 #endif
101
102 #ifndef IN_SUBNETB
103 #define IN_SUBNETB(i)           ((((afs_int32)(i))&0xc0008000)==0x80008000)
104 #endif
105
106 #ifndef IN_CLASSB_SUBNET
107 #define IN_CLASSB_SUBNET        0xffffff00
108 #endif
109
110
111 /* get a new block of CEs and chain it on CEFree */
112 static void
113 GetCEBlock(void)
114 {
115     struct CEBlock *block;
116     int i;
117
118     block = malloc(sizeof(struct CEBlock));
119     if (!block) {
120         ViceLog(0, ("Failed malloc in GetCEBlock\n"));
121         ShutDownAndCore(PANIC);
122     }
123
124     for (i = 0; i < (CESPERBLOCK - 1); i++) {
125         Lock_Init(&block->entry[i].lock);
126         block->entry[i].z.next = &(block->entry[i + 1]);
127     }
128     block->entry[CESPERBLOCK - 1].z.next = 0;
129     Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
130     CEFree = (struct client *)block;
131     CEBlocks++;
132
133 }                               /*GetCEBlock */
134
135
136 /* get the next available CE */
137 static struct client *
138 GetCE(void)
139 {
140     struct client *entry;
141
142     if (CEFree == 0)
143         GetCEBlock();
144     if (CEFree == 0) {
145         ViceLog(0, ("CEFree NULL in GetCE\n"));
146         ShutDownAndCore(PANIC);
147     }
148
149     entry = CEFree;
150     CEFree = entry->z.next;
151     CEs++;
152     memset(&entry->z, 0, sizeof(struct client_to_zero));
153     return (entry);
154
155 }                               /*GetCE */
156
157
158 /* return an entry to the free list */
159 static void
160 FreeCE(struct client *entry)
161 {
162     entry->z.VenusEpoch = 0;
163     entry->z.sid = 0;
164     entry->z.next = CEFree;
165     CEFree = entry;
166     CEs--;
167
168 }                               /*FreeCE */
169
170 /*
171  * The HTs and HTBlocks variables were formerly static, but they are
172  * now referenced elsewhere in the FileServer.
173  */
174 int HTs = 0;                    /* active file entries */
175 int HTBlocks = 0;               /* number of blocks of HTs */
176 static struct host *HTFree = 0; /* first free file entry */
177
178 /*
179  * Hash tables of host pointers. We need two tables, one
180  * to map IP addresses onto host pointers, and another
181  * to map host UUIDs onto host pointers.
182  */
183 static struct h_AddrHashChain *hostAddrHashTable[h_HASHENTRIES];
184 static struct h_UuidHashChain *hostUuidHashTable[h_HASHENTRIES];
185 #define h_HashIndex(hostip) (ntohl(hostip) & (h_HASHENTRIES-1))
186 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
187
188 struct HTBlock {                /* block of HTSPERBLOCK file entries */
189     struct host entry[h_HTSPERBLOCK];
190 };
191
192
193 /* get a new block of HTs and chain it on HTFree */
194 static void
195 GetHTBlock(void)
196 {
197     struct HTBlock *block;
198     int i;
199     static int index = 0;
200
201     if (HTBlocks == h_MAXHOSTTABLES) {
202         ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
203         return;
204     }
205
206     block = malloc(sizeof(struct HTBlock));
207     if (!block) {
208         ViceLog(0, ("Failed malloc in GetHTBlock\n"));
209         ShutDownAndCore(PANIC);
210     }
211     for (i = 0; i < (h_HTSPERBLOCK); i++)
212         opr_cv_init(&block->entry[i].cond);
213     for (i = 0; i < (h_HTSPERBLOCK); i++)
214         Lock_Init(&block->entry[i].lock);
215     for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
216         block->entry[i].z.next = &(block->entry[i + 1]);
217     for (i = 0; i < (h_HTSPERBLOCK); i++)
218         block->entry[i].index = index++;
219     block->entry[h_HTSPERBLOCK - 1].z.next = 0;
220     HTFree = (struct host *)block;
221     hosttableptrs[HTBlocks++] = block->entry;
222
223 }                               /*GetHTBlock */
224
225
226 /* get the next available HT */
227 static struct host *
228 GetHT(void)
229 {
230     struct host *entry;
231
232     if (HTFree == NULL)
233         GetHTBlock();
234     if (HTFree == NULL)
235         return NULL;
236     entry = HTFree;
237     HTFree = entry->z.next;
238     HTs++;
239     memset(&entry->z, 0, sizeof(struct host_to_zero));
240     return (entry);
241
242 }                               /*GetHT */
243
244
245 /* return an entry to the free list */
246 static void
247 FreeHT(struct host *entry)
248 {
249     entry->z.next = HTFree;
250     HTFree = entry;
251     HTs--;
252
253 }                               /*FreeHT */
254
255 afs_int32
256 hpr_Initialize(struct ubik_client **uclient)
257 {
258     afs_int32 code, code2;
259     struct rx_connection *serverconns[MAXSERVERS];
260     struct rx_securityClass *sc;
261     struct afsconf_dir *tdir;
262     afs_int32 scIndex;
263     struct afsconf_cell info;
264     afs_int32 i;
265     char cellstr[64];
266
267     tdir = afsconf_Open(FS_configPath);
268     if (!tdir) {
269         ViceLog(0,
270                 ("hpr_Initialize: Could not open configuration directory: %s\n",
271                  FS_configPath));
272         return -1;
273     }
274
275     code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
276     if (code) {
277         ViceLog(0, ("hpr_Initialize: Could not get local cell. [%d]\n", code));
278         afsconf_Close(tdir);
279         return code;
280     }
281
282     code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
283     if (code) {
284         ViceLog(0, ("hpr_Initialize: Could not locate cell %s in %s/%s\n",
285                     cellstr, tdir->name, AFSDIR_CELLSERVDB_FILE));
286         afsconf_Close(tdir);
287         return code;
288     }
289
290     code = rx_Init(0);
291     if (code) {
292         ViceLog(0, ("hpr_Initialize: Could not initialize rx.\n"));
293         afsconf_Close(tdir);
294         return code;
295     }
296
297     /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
298      * to force use of the KeyFile.  secLevel == 0 implies -noauth was
299      * specified. */
300     code = afsconf_ClientAuthSecure(tdir, &sc, &scIndex);
301     if (code) {
302         ViceLog(0, ("hpr_Initialize: clientauthsecure returns %d %s "
303                     "(so trying noauth)\n", code, afs_error_message(code)));
304         scIndex = RX_SECIDX_NULL;
305         sc = rxnull_NewClientSecurityObject();
306     }
307
308     if (scIndex == RX_SECIDX_NULL)
309         ViceLog(0, ("hpr_Initialize: Could not get afs tokens, "
310                     "running unauthenticated. [%d]\n", code));
311
312     memset(serverconns, 0, sizeof(serverconns));        /* terminate list!!! */
313     for (i = 0; i < info.numServers; i++) {
314         serverconns[i] =
315             rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
316                              info.hostAddr[i].sin_port, PRSRV,
317                              sc, scIndex);
318     }
319
320     code = ubik_ClientInit(serverconns, uclient);
321     if (code) {
322         ViceLog(0, ("hpr_Initialize: ubik client init failed. [%d]\n", code));
323     }
324     afsconf_Close(tdir);
325     code2 = rxs_Release(sc);
326
327     if (code == 0) {
328         code = code2;
329     }
330     return code;
331 }
332
333 int
334 hpr_End(struct ubik_client *uclient)
335 {
336     int code = 0;
337
338     if (uclient) {
339         code = ubik_ClientDestroy(uclient);
340     }
341     return code;
342 }
343
344 static_inline int
345 getThreadClient(struct ubik_client **client)
346 {
347     int code;
348
349     *client = pthread_getspecific(viced_uclient_key);
350     if (*client != NULL)
351         return 0;
352
353     code = hpr_Initialize(client);
354     if (code)
355         return code;
356
357     opr_Verify(pthread_setspecific(viced_uclient_key, *client) == 0);
358
359     return 0;
360 }
361
362 int
363 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
364 {
365     afs_int32 code;
366     afs_int32 over;
367     struct ubik_client *uclient;
368
369     code = getThreadClient(&uclient);
370     if (code)
371         return code;
372
373     over = 0;
374     code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
375     if (code != PRSUCCESS)
376         return code;
377     if (over) {
378       /* do something about this, probably make a new call */
379       /* don't forget there's a hard limit in the interface */
380         fprintf(stderr,
381                 "membership list for host id %d exceeds display limit\n",
382                 host);
383     }
384     return 0;
385 }
386
387 int
388 hpr_NameToId(namelist *names, idlist *ids)
389 {
390     afs_int32 code;
391     afs_int32 i;
392     struct ubik_client *uclient;
393
394     code = getThreadClient(&uclient);
395     if (code)
396         return code;
397
398     for (i = 0; i < names->namelist_len; i++)
399         stolower(names->namelist_val[i]);
400     code = ubik_PR_NameToID(uclient, 0, names, ids);
401     return code;
402 }
403
404 int
405 hpr_IdToName(idlist *ids, namelist *names)
406 {
407     afs_int32 code;
408     struct ubik_client *uclient;
409
410     code = getThreadClient(&uclient);
411     if (code)
412         return code;
413
414     code = string_PR_IDToName(uclient, 0, ids, names);
415     return code;
416 }
417
418 int
419 hpr_GetCPS(afs_int32 id, prlist *CPS)
420 {
421     afs_int32 code;
422     afs_int32 over;
423     struct ubik_client *uclient;
424
425     code = getThreadClient(&uclient);
426     if (code)
427         return code;
428
429     over = 0;
430     code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
431     if (code != PRSUCCESS)
432         return code;
433     if (over) {
434       /* do something about this, probably make a new call */
435       /* don't forget there's a hard limit in the interface */
436         fprintf(stderr, "membership list for id %d exceeds display limit\n",
437                 id);
438     }
439     return 0;
440 }
441
442 static short consolePort = 0;
443
444 int
445 h_Lock_r(struct host *host)
446 {
447     H_UNLOCK;
448     h_Lock(host);
449     H_LOCK;
450     return 0;
451 }
452
453 /**
454   * Non-blocking lock
455   * returns 1 if already locked
456   * else returns locks and returns 0
457   */
458
459 int
460 h_NBLock_r(struct host *host)
461 {
462     struct Lock *hostLock = &host->lock;
463     int locked = 0;
464
465     H_UNLOCK;
466     LOCK_LOCK(hostLock);
467     if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
468         hostLock->excl_locked = WRITE_LOCK;
469     else
470         locked = 1;
471
472     LOCK_UNLOCK(hostLock);
473     H_LOCK;
474     if (locked)
475         return 1;
476     else
477         return 0;
478 }
479
480
481 /*------------------------------------------------------------------------
482  * PRIVATE h_AddrInSameNetwork
483  *
484  * Description:
485  *      Given a target IP address and a candidate IP address (both
486  *      in host byte order), return a non-zero value (1) if the
487  *      candidate address is in a different network from the target
488  *      address.
489  *
490  * Arguments:
491  *      a_targetAddr       : Target address.
492  *      a_candAddr         : Candidate address.
493  *
494  * Returns:
495  *      1 if the candidate address is in the same net as the target,
496  *      0 otherwise.
497  *
498  * Environment:
499  *      The target and candidate addresses are both in host byte
500  *      order, NOT network byte order, when passed in.  We return
501  *      our value as a character, since that's the type of field in
502  *      the host structure, where this info will be stored.
503  *
504  * Side Effects:
505  *      As advertised.
506  *------------------------------------------------------------------------*/
507
508 static char
509 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
510 {                               /*h_AddrInSameNetwork */
511
512     afs_uint32 targetNet;
513     afs_uint32 candNet;
514
515     /*
516      * Pull out the network and subnetwork numbers from the target
517      * and candidate addresses.  We can short-circuit this whole
518      * affair if the target and candidate addresses are not of the
519      * same class.
520      */
521     if (IN_CLASSA(a_targetAddr)) {
522         if (!(IN_CLASSA(a_candAddr))) {
523             return (0);
524         }
525         targetNet = a_targetAddr & IN_CLASSA_NET;
526         candNet = a_candAddr & IN_CLASSA_NET;
527     } else if (IN_CLASSB(a_targetAddr)) {
528         if (!(IN_CLASSB(a_candAddr))) {
529             return (0);
530         }
531         targetNet = a_targetAddr & IN_CLASSB_NET;
532         candNet = a_candAddr & IN_CLASSB_NET;
533     } /*Class B target */
534     else if (IN_CLASSC(a_targetAddr)) {
535         if (!(IN_CLASSC(a_candAddr))) {
536             return (0);
537         }
538         targetNet = a_targetAddr & IN_CLASSC_NET;
539         candNet = a_candAddr & IN_CLASSC_NET;
540     } /*Class C target */
541     else {
542         targetNet = a_targetAddr;
543         candNet = a_candAddr;
544     }                           /*Class D address */
545
546     /*
547      * Now, simply compare the extracted net values for the two addresses
548      * (which at this point are known to be of the same class)
549      */
550     if (targetNet == candNet)
551         return (1);
552     else
553         return (0);
554
555 }                               /*h_AddrInSameNetwork */
556
557
558 /* Assumptions: called with held host */
559 void
560 h_gethostcps_r(struct host *host, afs_int32 now)
561 {
562     int code;
563     int slept = 0;
564
565     /* wait if somebody else is already doing the getCPS call */
566     while (host->z.hostFlags & HCPS_INPROGRESS) {
567         slept = 1;              /* I did sleep */
568         host->z.hostFlags |= HCPS_WAITING;      /* I am sleeping now */
569         opr_cv_wait(&host->cond, &host_glock_mutex);
570     }
571
572
573     host->z.hostFlags |= HCPS_INPROGRESS;       /* mark as CPSCall in progress */
574     if (host->z.hcps.prlist_val)
575         free(host->z.hcps.prlist_val);  /* this is for hostaclRefresh */
576     host->z.hcps.prlist_val = NULL;
577     host->z.hcps.prlist_len = 0;
578     host->z.cpsCall = slept ? time(NULL) : (now);
579
580     H_UNLOCK;
581     code = hpr_GetHostCPS(ntohl(host->z.host), &host->z.hcps);
582     H_LOCK;
583     if (code) {
584         char hoststr[16];
585         /*
586          * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
587          * and reevaluates things if no sync server or quorum is found we could still end up
588          * with one of these errors. In such case we would like to reevaluate the rpc call to
589          * find if there's cps for this guy. We treat other errors (except network failures
590          * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
591          * we could like to deal this problem the other way around (i.e. if code == NOCPS
592          * ignore else retry next time) but the problem is that there're other errors (i.e.
593          * EPERM) for which we don't want to retry and we don't know the whole code list!
594          */
595         if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
596             /*
597              * We would have preferred to use a while loop and try again since ops in protected
598              * acls for this host will fail now but they'll be reevaluated on any subsequent
599              * call. The attempt to wait for a quorum/sync site or network error won't work
600              * since this problems really should only occurs during a complete fileserver
601              * restart. Since the fileserver will start before the ptservers (and thus before
602              * quorums are complete) clients will be utilizing all the fileserver's lwps!!
603              */
604             host->z.hcpsfailed = 1;
605             ViceLog(0,
606                     ("Warning:  GetHostCPS failed (%d) for %p (%s:%d); will retry\n",
607                      code, host, afs_inet_ntoa_r(host->z.host, hoststr), ntohs(host->z.port)));
608         } else {
609             host->z.hcpsfailed = 0;
610             ViceLog(1,
611                     ("gethost:  GetHostCPS failed (%d) for %p (%s:%d); ignored\n",
612                      code, host, afs_inet_ntoa_r(host->z.host, hoststr), ntohs(host->z.port)));
613         }
614         if (host->z.hcps.prlist_val)
615             free(host->z.hcps.prlist_val);
616         host->z.hcps.prlist_val = NULL;
617         host->z.hcps.prlist_len = 0;    /* Make sure it's zero */
618     } else
619         host->z.hcpsfailed = 0;
620
621     host->z.hostFlags &= ~HCPS_INPROGRESS;
622     /* signal all who are waiting */
623     if (host->z.hostFlags & HCPS_WAITING) {     /* somebody is waiting */
624         host->z.hostFlags &= ~HCPS_WAITING;
625         opr_cv_broadcast(&host->cond);
626     }
627 }
628
629 /* args in net byte order */
630 void
631 h_flushhostcps(afs_uint32 hostaddr, afs_uint16 hport)
632 {
633     struct host *host;
634
635     H_LOCK;
636     h_Lookup_r(hostaddr, hport, &host);
637     if (host) {
638         host->z.hcpsfailed = 1;
639         h_Release_r(host);
640     }
641     H_UNLOCK;
642     return;
643 }
644
645
646 /*
647  * Allocate a host.  It will be identified by the peer (ip,port) info in the
648  * rx connection provided.  The host is returned held and locked
649  */
650 #define DEF_ROPCONS 2115
651
652 static struct host *
653 h_Alloc_r(struct rx_connection *r_con)
654 {
655     struct servent *serverentry;
656     struct host *host;
657     afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
658
659     host = GetHT();
660     if (!host)
661         return NULL;
662
663     h_Hold_r(host);
664     /* acquire the host lock withot dropping H_LOCK. we can do this here
665      * because we know we will not block; we just created this host and
666      * nobody else knows about it. */
667     ObtainWriteLock(&host->lock);
668
669     host->z.host = rxr_HostOf(r_con);
670     host->z.port = rxr_PortOf(r_con);
671
672     h_AddHostToAddrHashTable_r(host->z.host, host->z.port, host);
673
674     if (consolePort == 0) {     /* find the portal number for console */
675 #if     defined(AFS_OSF_ENV)
676         serverentry = getservbyname("ropcons", "");
677 #else
678         serverentry = getservbyname("ropcons", 0);
679 #endif
680         if (serverentry)
681             consolePort = serverentry->s_port;
682         else
683             consolePort = htons(DEF_ROPCONS);   /* Use a default */
684     }
685     if (host->z.port == consolePort)
686         host->z.Console = 1;
687     /* Make a callback channel even for the console, on the off chance that it
688      * makes a request that causes a break call back.  It shouldn't. */
689     h_SetupCallbackConn_r(host);
690     host->z.LastCall = host->z.cpsCall = host->z.ActiveCall = time(NULL);
691     host->z.hostFlags = 0;
692     host->z.hcps.prlist_val = NULL;
693     host->z.hcps.prlist_len = 0;
694     host->z.interface = NULL;
695 #ifdef undef
696     host->z.hcpsfailed = 0;     /* save cycles */
697     h_gethostcps(host);         /* do this under host hold/lock */
698 #endif
699     host->z.FirstClient = NULL;
700     h_InsertList_r(host);       /* update global host List */
701     /*
702      * Compare the new host's IP address (in host byte order) with ours
703      * (the File Server's), remembering if they are in the same network.
704      */
705     newHostAddr_HBO = (afs_uint32) ntohl(host->z.host);
706     host->z.InSameNetwork =
707         h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
708     return host;
709
710 }                               /*h_Alloc_r */
711
712
713
714 /* Make a callback channel even for the console, on the off chance that it
715  * makes a request that causes a break call back.  It shouldn't. */
716 static void
717 h_SetupCallbackConn_r(struct host * host)
718 {
719     if (!sc)
720         sc = rxnull_NewClientSecurityObject();
721     host->z.callback_rxcon =
722         rx_NewConnection(host->z.host, host->z.port, 1, sc, 0);
723     rx_SetConnDeadTime(host->z.callback_rxcon, 50);
724     rx_SetConnHardDeadTime(host->z.callback_rxcon, AFS_HARDDEADTIME);
725 }
726
727 /* h_Lookup_r
728  * Lookup a host given an IP address and UDP port number.
729  * hostaddr and hport are in network order
730  * hostaddr and hport are in network order
731  * On return, refCount is incremented.
732  */
733 int
734 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, struct host **hostp)
735 {
736     afs_int32 now;
737     struct host *host = NULL;
738     struct h_AddrHashChain *chain;
739     int index = h_HashIndex(haddr);
740     extern int hostaclRefresh;
741
742   restart:
743     for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
744         host = chain->hostPtr;
745         opr_Assert(host);
746         if (!(host->z.hostFlags & HOSTDELETED) && chain->addr == haddr
747             && chain->port == hport) {
748             if ((host->z.hostFlags & HWHO_INPROGRESS) &&
749                 h_threadquota(host->lock.num_waiting)) {
750                 *hostp = 0;
751                 return VBUSY;
752             }
753             h_Hold_r(host);
754             h_Lock_r(host);
755             if (host->z.hostFlags & HOSTDELETED) {
756                 h_Unlock_r(host);
757                 h_Release_r(host);
758                 host = NULL;
759                 goto restart;
760             }
761             h_Unlock_r(host);
762             now = time(NULL);   /* always evaluate "now" */
763             if (host->z.hcpsfailed || (host->z.cpsCall + hostaclRefresh < now)) {
764                 /*
765                  * Every hostaclRefresh period (def 2 hrs) get the new
766                  * membership list for the host.  Note this could be the
767                  * first time that the host is added to a group.  Also
768                  * here we also retry on previous legitimate hcps failures.
769                  *
770                  * If we get here refCount is elevated.
771                  */
772                 h_gethostcps_r(host, now);
773             }
774             break;
775         }
776         host = NULL;
777     }
778     *hostp = host;
779     return 0;
780 }                               /*h_Lookup */
781
782 /* Lookup a host given its UUID. */
783 struct host *
784 h_LookupUuid_r(afsUUID * uuidp)
785 {
786     struct host *host = 0;
787     struct h_UuidHashChain *chain;
788     int index = h_UuidHashIndex(uuidp);
789
790     for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
791         host = chain->hostPtr;
792         opr_Assert(host);
793         if (!(host->z.hostFlags & HOSTDELETED) && host->z.interface
794             && afs_uuid_equal(&host->z.interface->uuid, uuidp)) {
795             return host;
796         }
797     }
798     return NULL;
799 }                               /*h_Lookup */
800
801
802 /* h_TossStuff_r:  Toss anything in the host structure (the host or
803  * clients marked for deletion.  Called from h_Release_r ONLY.
804  * To be called, there must be no holds, and either host->z.deleted
805  * or host->clientDeleted must be set.
806  */
807 void
808 h_TossStuff_r(struct host *host)
809 {
810     struct client **cp, *client;
811     int code;
812     int wasdeleted = 0;
813
814     if ((host->z.hostFlags & HOSTDELETED)) {
815         wasdeleted = 1;
816     }
817
818     /* make sure host doesn't go away over h_NBLock_r */
819     h_Hold_r(host);
820
821     code = h_NBLock_r(host);
822
823     /* don't use h_Release_r, since that may call h_TossStuff_r again */
824     h_Decrement_r(host);
825
826     /* if somebody still has this host locked */
827     if (code != 0) {
828         char hoststr[16];
829         if (wasdeleted) {
830             /* someone locked the host while HOSTDELETED was set; that is bad */
831             ViceLog(0, ("Warning:  h_TossStuff_r failed; Host %" AFS_PTR_FMT
832                         " (%s:%d flags 0x%x) was locked.\n",
833                         host, afs_inet_ntoa_r(host->z.host, hoststr), ntohs(host->z.port),
834                         (unsigned)host->z.hostFlags));
835         }
836         return;
837     } else {
838         h_Unlock_r(host);
839     }
840
841     /* if somebody still has this host held */
842     /* we must check this _after_ h_NBLock_r, since h_NBLock_r can drop and
843      * reacquire H_LOCK */
844     if (host->z.refCount > 0) {
845         char hoststr[16];
846         if (wasdeleted) {
847             /* someone grabbed a ref while HOSTDELETED was set; that is bad */
848             ViceLog(0, ("Warning:  h_TossStuff_r failed; Host %" AFS_PTR_FMT
849                         " (%s:%d flags 0x%x) was held.\n",
850                         host, afs_inet_ntoa_r(host->z.host, hoststr), ntohs(host->z.port),
851                         (unsigned)host->z.hostFlags));
852         }
853         return;
854     }
855
856     /* ASSUMPTION: rxi_FreeConnection() does not yield */
857     for (cp = &host->z.FirstClient; (client = *cp);) {
858         if ((host->z.hostFlags & HOSTDELETED) || client->z.deleted) {
859             int code;
860             ObtainWriteLockNoBlock(&client->lock, code);
861             if (code < 0) {
862                 char hoststr[16];
863                 ViceLog(0,
864                         ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
865                          "client %p was locked.\n",
866                          host, afs_inet_ntoa_r(host->z.host, hoststr),
867                          ntohs(host->z.port), client));
868                 return;
869             }
870
871             if (client->z.refCount) {
872                 char hoststr[16];
873                 ViceLog(0,
874                         ("Warning: h_TossStuff_r failed: Host %p (%s:%d) "
875                          "client %p refcount %d.\n",
876                          host, afs_inet_ntoa_r(host->z.host, hoststr),
877                          ntohs(host->z.port), client, client->z.refCount));
878                 /* This is the same thing we do if the host is locked */
879                 ReleaseWriteLock(&client->lock);
880                 return;
881             }
882             client->z.CPS.prlist_len = 0;
883             if ((client->z.ViceId != ANONYMOUSID) && client->z.CPS.prlist_val)
884                 free(client->z.CPS.prlist_val);
885             client->z.CPS.prlist_val = NULL;
886             CurrentConnections--;
887             *cp = client->z.next;
888             ReleaseWriteLock(&client->lock);
889             FreeCE(client);
890         } else
891             cp = &client->z.next;
892     }
893
894     /* We've just cleaned out all the deleted clients; clear the flag */
895     host->z.hostFlags &= ~CLIENTDELETED;
896
897     if (host->z.hostFlags & HOSTDELETED) {
898         struct rx_connection *rxconn;
899         struct AddrPort hostAddrPort;
900         int i;
901
902         if (host->z.Console & 1)
903             Console--;
904         if ((rxconn = host->z.callback_rxcon)) {
905             host->z.callback_rxcon = (struct rx_connection *)0;
906             rx_DestroyConnection(rxconn);
907         }
908         if (host->z.hcps.prlist_val)
909             free(host->z.hcps.prlist_val);
910         host->z.hcps.prlist_val = NULL;
911         host->z.hcps.prlist_len = 0;
912         free(host->z.tmay_caps.Capabilities_val);
913         host->z.tmay_caps.Capabilities_val = NULL;
914         host->z.tmay_caps.Capabilities_len = 0;
915         DeleteAllCallBacks_r(host, 1);
916         host->z.hostFlags &= ~RESETDONE;        /* just to be safe */
917
918         /* if alternate addresses do not exist */
919         if (!(host->z.interface)) {
920             h_DeleteHostFromAddrHashTable_r(host->z.host, host->z.port, host);
921         } else {
922             h_DeleteHostFromUuidHashTable_r(host);
923             h_DeleteHostFromAddrHashTable_r(host->z.host, host->z.port, host);
924             /* delete the hash entry for each valid alternate addresses */
925             for (i = 0; i < host->z.interface->numberOfInterfaces; i++) {
926                 hostAddrPort = host->z.interface->interface[i];
927                 /*
928                  * if the interface addr/port is the primary, we already
929                  * removed it.  If the addr/port is not valid, its not
930                  * in the hash table.
931                  */
932                 if (hostAddrPort.valid &&
933                     (host->z.host != hostAddrPort.addr ||
934                      host->z.port != hostAddrPort.port))
935                     h_DeleteHostFromAddrHashTable_r(hostAddrPort.addr, hostAddrPort.port, host);
936             }
937             free(host->z.interface);
938             host->z.interface = NULL;
939         }                       /* if alternate address exists */
940
941         h_DeleteList_r(host);   /* remove host from global host List */
942         FreeHT(host);
943     }
944 }                               /*h_TossStuff_r */
945
946
947
948 /* h_Enumerate: Calls (*proc)(host, param) for at least each host in the
949  * system at the start of the enumeration (perhaps more).  Hosts may be deleted
950  * (have delete flag set); ditto for clients.  refCount is always incremented
951  * before (*proc) is called.
952  *
953  * The return value of the proc is a set of flags. The proc should set
954  * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
955  */
956 void
957 h_Enumerate(int (*proc) (struct host*, void *), void *param)
958 {
959     struct host *host, **list;
960     int i, count;
961     int totalCount;
962
963     H_LOCK;
964     if (hostCount == 0) {
965         H_UNLOCK;
966         return;
967     }
968     list = malloc(hostCount * sizeof(struct host *));
969     if (!list) {
970         ViceLogThenPanic(0, ("Failed malloc in h_Enumerate (list)\n"));
971     }
972     for (totalCount = count = 0, host = hostList;
973          host && totalCount < hostCount;
974          host = host->z.next, totalCount++) {
975
976         if (!(host->z.hostFlags & HOSTDELETED)) {
977             list[count] = host;
978             h_Hold_r(host);
979             count++;
980         }
981     }
982     if (totalCount != hostCount) {
983         ViceLog(0, ("h_Enumerate found %d of %d hosts\n", totalCount, hostCount));
984     } else if (host != NULL) {
985         ViceLog(0, ("h_Enumerate found more than %d hosts\n", hostCount));
986         ShutDownAndCore(PANIC);
987     }
988     H_UNLOCK;
989     for (i = 0; i < count; i++) {
990         int flags;
991         flags = (*proc) (list[i], param);
992         H_LOCK;
993         h_Release_r(list[i]);
994         H_UNLOCK;
995         /* bail out of the enumeration early */
996         if (H_ENUMERATE_ISSET_BAIL(flags)) {
997             break;
998         } else if (flags) {
999             ViceLog(0, ("h_Enumerate got back invalid return value %d\n", flags));
1000             ShutDownAndCore(PANIC);
1001         }
1002     }
1003     if (i < count-1) {
1004         /* we bailed out of enumerating hosts early; we still have holds on
1005          * some of the hosts in 'list', so release them */
1006         i++;
1007         H_LOCK;
1008         for ( ; i < count; i++) {
1009             h_Release_r(list[i]);
1010         }
1011         H_UNLOCK;
1012     }
1013     free(list);
1014 }       /* h_Enumerate */
1015
1016
1017 /* h_Enumerate_r (revised):
1018  * Calls (*proc)(host, param) for each host in hostList, starting
1019  * at enumstart. Called only under H_LOCK.  Hosts may be deleted (have
1020  * delete flag set); ditto for clients.  refCount is always incremented
1021  * before (*proc) is called.
1022  *
1023  * @note Assumes that hostList is only prepended to, that a host is never
1024  *       inserted into the middle. Otherwise this would not be guaranteed to
1025  *       terminate.
1026  *
1027  * The return value of the proc is a set of flags. The proc should set
1028  * H_ENUMERATE_BAIL(foo) if the enumeration of hosts should be stopped early.
1029  */
1030 void
1031 h_Enumerate_r(int (*proc) (struct host *, void *),
1032               struct host *enumstart, void *param)
1033 {
1034     struct host *host, *next;
1035     int count;
1036     int origHostCount;
1037
1038     if (hostCount == 0) {
1039         return;
1040     }
1041
1042     host = enumstart;
1043     enumstart = NULL;
1044
1045     /* find the first non-deleted host, so we know where to actually start
1046      * enumerating */
1047     for (count = 0; host && count < hostCount; count++) {
1048         if (!(host->z.hostFlags & HOSTDELETED)) {
1049             enumstart = host;
1050             break;
1051         }
1052         host = host->z.next;
1053     }
1054     if (!enumstart) {
1055         /* we didn't find a non-deleted host... */
1056
1057         if (host && count >= hostCount) {
1058             /* ...because we found a loop */
1059             ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", hostCount));
1060             ShutDownAndCore(PANIC);
1061         }
1062
1063         /* ...because the hostList is full of deleted hosts */
1064         return;
1065     }
1066
1067     h_Hold_r(enumstart);
1068
1069     /* remember hostCount, lest it change over the potential H_LOCK drop in
1070      * h_Release_r */
1071     origHostCount = hostCount;
1072
1073     for (count = 0, host = enumstart; host && count < origHostCount; host = next, count++) {
1074         next = host->z.next;
1075
1076         /* find the next non-deleted host */
1077         while (next && (next->z.hostFlags & HOSTDELETED)) {
1078             next = next->z.next;
1079             /* inc count for the skipped-over host */
1080             if (++count > origHostCount) {
1081                 ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1082                 ShutDownAndCore(PANIC);
1083             }
1084         }
1085         if (next)
1086             h_Hold_r(next);
1087
1088         if (!(host->z.hostFlags & HOSTDELETED)) {
1089             int flags;
1090             flags = (*proc) (host, param);
1091             if (H_ENUMERATE_ISSET_BAIL(flags)) {
1092                 h_Release_r(host); /* this might free up the host */
1093                 if (next) {
1094                     h_Release_r(next);
1095                 }
1096                 break;
1097             } else if (flags) {
1098                 ViceLog(0, ("h_Enumerate_r got back invalid return value %d\n", flags));
1099                 ShutDownAndCore(PANIC);
1100             }
1101         }
1102         h_Release_r(host); /* this might free up the host */
1103     }
1104     if (host != NULL && count >= origHostCount) {
1105         ViceLog(0, ("h_Enumerate_r found more than %d hosts\n", origHostCount));
1106         ShutDownAndCore(PANIC);
1107     }
1108 }       /*h_Enumerate_r */
1109
1110
1111 /* inserts a new HashChain structure corresponding to this UUID */
1112 void
1113 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1114 {
1115     int index;
1116     struct h_UuidHashChain *chain;
1117     char uuid1[128], uuid2[128];
1118     char hoststr[16];
1119
1120     /* hash into proper bucket */
1121     index = h_UuidHashIndex(uuid);
1122
1123     /* don't add the same entry multiple times */
1124     for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
1125         if (!chain->hostPtr)
1126             continue;
1127
1128         if (chain->hostPtr->z.interface &&
1129             afs_uuid_equal(&chain->hostPtr->z.interface->uuid, uuid)) {
1130             if (GetLogLevel() >= 125) {
1131                 afsUUID_to_string(&chain->hostPtr->z.interface->uuid, uuid1,
1132                                   127);
1133                 afsUUID_to_string(uuid, uuid2, 127);
1134                 ViceLog(125, ("h_AddHostToUuidHashTable_r: host %" AFS_PTR_FMT " (uuid %s) exists as %s:%d (uuid %s)\n",
1135                               host, uuid1,
1136                               afs_inet_ntoa_r(chain->hostPtr->z.host, hoststr),
1137                               ntohs(chain->hostPtr->z.port), uuid2));
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, 127);
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));
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      char uuid1[128];
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, 127);
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 %" AFS_PTR_FMT " (uuid %s %s:%d)\n",
1182                       host, uuid1, 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 %" AFS_PTR_FMT " (uuid %s %s:%d) not found\n",
1191               host, uuid1, 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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " 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 %" AFS_PTR_FMT " oldHost %"
1360              AFS_PTR_FMT "\n", 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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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 %" AFS_PTR_FMT " (%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             char uuid1[128], uuid2[128];
2146             if (identP->valid)
2147                 afsUUID_to_string(&identP->uuid, uuid1, 127);
2148             if (host->z.interface)
2149                 afsUUID_to_string(&host->z.interface->uuid, uuid2, 127);
2150             ViceLog(0,
2151                     ("CB: new identity for host %p (%s:%d), "
2152                      "deleting(%x %p %s %s)\n",
2153                      host, afs_inet_ntoa_r(host->z.host, hoststr), ntohs(host->z.port),
2154                      identP->valid, host->z.interface,
2155                      identP->valid ? uuid1 : "no_uuid",
2156                      host->z.interface ? uuid2 : "no_uuid"));
2157
2158             /* The host in the cache is not the host for this connection */
2159             h_Lock_r(host);
2160             host->z.hostFlags |= HOSTDELETED;
2161             h_Unlock_r(host);
2162             h_Release_r(host);
2163             goto retry;
2164         }
2165     } else {
2166         host = h_Alloc_r(tcon); /* returned held and locked */
2167         if (!host)
2168             goto gethost_out;
2169         h_gethostcps_r(host, time(NULL));
2170         if (!(host->z.Console & 1)) {
2171             int pident = 0;
2172             cb_conn = host->z.callback_rxcon;
2173             rx_GetConnection(cb_conn);
2174             host->z.hostFlags |= HWHO_INPROGRESS;
2175             H_UNLOCK;
2176             code =
2177                 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
2178             if (code == RXGEN_OPCODE)
2179                 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
2180             rx_PutConnection(cb_conn);
2181             cb_conn=NULL;
2182             H_LOCK;
2183             if ((code == RXGEN_OPCODE) ||
2184                 ((code == 0) && (afs_uuid_equal(&interf.uuid, &nulluuid)))) {
2185                 if (!identP)
2186                     identP = malloc(sizeof(struct Identity));
2187                 else
2188                     pident = 1;
2189
2190                 if (!identP) {
2191                     ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
2192                 }
2193                 identP->valid = 0;
2194                 if (!pident)
2195                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
2196                 ViceLog(25,
2197                         ("Host %" AFS_PTR_FMT " (%s:%d) does not support WhoAreYou.\n",
2198                          host, afs_inet_ntoa_r(host->z.host, hoststr),
2199                          ntohs(host->z.port)));
2200                 code = 0;
2201             } else if (code == 0) {
2202                 if (!identP)
2203                     identP = malloc(sizeof(struct Identity));
2204                 else
2205                     pident = 1;
2206
2207                 if (!identP) {
2208                     ViceLogThenPanic(0, ("Failed malloc in h_GetHost_r\n"));
2209                 }
2210                 identP->valid = 1;
2211                 interfValid = 1;
2212                 identP->uuid = interf.uuid;
2213                 if (!pident)
2214                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
2215                 ViceLog(25,
2216                         ("WhoAreYou success on host %" AFS_PTR_FMT " (%s:%d)\n",
2217                          host, afs_inet_ntoa_r(host->z.host, hoststr),
2218                          ntohs(host->z.port)));
2219             }
2220             if (code == 0 && !identP->valid) {
2221                 cb_conn = host->z.callback_rxcon;
2222                 rx_GetConnection(cb_conn);
2223                 H_UNLOCK;
2224                 code = RXAFSCB_InitCallBackState(cb_conn);
2225                 rx_PutConnection(cb_conn);
2226                 cb_conn=NULL;
2227                 H_LOCK;
2228             } else if (code == 0) {
2229                 oldHost = h_LookupUuid_r(&identP->uuid);
2230                 if (oldHost) {
2231                     h_Hold_r(oldHost);
2232                     h_Lock_r(oldHost);
2233
2234                     if (oldHost->z.hostFlags & HOSTDELETED) {
2235                         h_Unlock_r(oldHost);
2236                         h_Release_r(oldHost);
2237                         oldHost = NULL;
2238                     }
2239                 }
2240
2241                 if (oldHost) {
2242                     int probefail = 0;
2243
2244                     /* This is a new address for an existing host. Update
2245                      * the list of interfaces for the existing host and
2246                      * delete the host structure we just allocated. */
2247
2248                     /* mark the duplicate host as deleted before we do
2249                      * anything. The probing code below may try to change
2250                      * "oldHost" to the same IP address as "host" currently
2251                      * has, and we do not want a pseudo-"collision" to be
2252                      * noticed. */
2253                     host->z.hostFlags |= HOSTDELETED;
2254
2255                     oldHost->z.hostFlags |= HWHO_INPROGRESS;
2256
2257                     if (oldHost->z.interface) {
2258                         int code2;
2259                         afsUUID uuid = oldHost->z.interface->uuid;
2260                         cb_conn = oldHost->z.callback_rxcon;
2261                         rx_GetConnection(cb_conn);
2262                         rx_SetConnDeadTime(cb_conn, 2);
2263                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2264                         H_UNLOCK;
2265                         code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2266                         H_LOCK;
2267                         rx_SetConnDeadTime(cb_conn, 50);
2268                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
2269                         rx_PutConnection(cb_conn);
2270                         cb_conn=NULL;
2271                         if (code2) {
2272                             /* The primary address is either not responding or
2273                              * is not the client we are looking for.
2274                              * MultiProbeAlternateAddress_r() will remove the
2275                              * alternate interfaces that do not have the same
2276                              * Uuid. */
2277                             ViceLog(0,("CB: ProbeUuid for host %" AFS_PTR_FMT " (%s:%d) failed %d\n",
2278                                          oldHost,
2279                                          afs_inet_ntoa_r(oldHost->z.host, hoststr),
2280                                          ntohs(oldHost->z.port),code2));
2281
2282                             if (MultiProbeAlternateAddress_r(oldHost)) {
2283                                 /* If MultiProbeAlternateAddress_r succeeded,
2284                                  * it updated oldHost->host and oldHost->port
2285                                  * to an address that responded successfully to
2286                                  * a ProbeUuid, so it is as if the ProbeUuid
2287                                  * call above returned success. So, only set
2288                                  * 'probefail' if MultiProbeAlternateAddress_r
2289                                  * fails. */
2290                                 probefail = 1;
2291                             }
2292                         }
2293                     } else {
2294                         probefail = 1;
2295                     }
2296
2297                     if (oldHost->z.host != haddr || oldHost->z.port != hport) {
2298                         struct rx_connection *rxconn;
2299
2300                         ViceLog(25,
2301                                  ("CB: Host %" AFS_PTR_FMT " (%s:%d) has new addr %s:%d\n",
2302                                    oldHost,
2303                                    afs_inet_ntoa_r(oldHost->z.host, hoststr2),
2304                                    ntohs(oldHost->z.port),
2305                                    afs_inet_ntoa_r(haddr, hoststr),
2306                                    ntohs(hport)));
2307                         /*
2308                          * add then remove.  otherwise the host may get marked
2309                          * deleted if we removed the only valid address.
2310                          */
2311                         addInterfaceAddr_r(oldHost, haddr, hport);
2312                         if (probefail || oldHost->z.host == haddr) {
2313                             /*
2314                              * The probe failed which means that the old
2315                              * address is either unreachable or is not the
2316                              * same host we were just contacted by.  We will
2317                              * also remove addresses if only the port has
2318                              * changed because that indicates the client
2319                              * is behind a NAT.
2320                              */
2321                             removeInterfaceAddr_r(oldHost, oldHost->z.host, oldHost->z.port);
2322                         } else {
2323                             int i;
2324                             struct Interface *interface = oldHost->z.interface;
2325                             int number = oldHost->z.interface->numberOfInterfaces;
2326                             for (i = 0; i < number; i++) {
2327                                 if (interface->interface[i].addr == haddr &&
2328                                     interface->interface[i].port != hport) {
2329                                     /*
2330                                      * We have just been contacted by a client
2331                                      * that has been seen from behind a NAT
2332                                      * and at least one other address.
2333                                      */
2334                                     removeInterfaceAddr_r(oldHost, haddr,
2335                                                           interface->interface[i].port);
2336                                     break;
2337                                 }
2338                             }
2339                         }
2340                         oldHost->z.host = haddr;
2341                         oldHost->z.port = hport;
2342                         rxconn = oldHost->z.callback_rxcon;
2343                         oldHost->z.callback_rxcon = host->z.callback_rxcon;
2344                         host->z.callback_rxcon = rxconn;
2345
2346                         /* don't destroy rxconn here; let h_TossStuff_r
2347                          * take care of that via h_Release_r below */
2348                     }
2349                     host->z.hostFlags &= ~HWHO_INPROGRESS;
2350                     h_Unlock_r(host);
2351                     /* release host because it was allocated by h_Alloc_r */
2352                     h_Release_r(host);
2353                     host = oldHost;
2354                     /* the new host is held and locked */
2355                 } else {
2356                     /* This really is a new host */
2357                     opr_Assert(interfValid == 1);
2358                     initInterfaceAddr_r(host, &interf);
2359
2360                     cb_conn = host->z.callback_rxcon;
2361                     rx_GetConnection(cb_conn);
2362                     H_UNLOCK;
2363                     code =
2364                         RXAFSCB_InitCallBackState3(cb_conn,
2365                                                    &FS_HostUUID);
2366                     rx_PutConnection(cb_conn);
2367                     cb_conn=NULL;
2368                     H_LOCK;
2369                     if (code == 0) {
2370                         ViceLog(25,
2371                                 ("InitCallBackState3 success on host %" AFS_PTR_FMT " (%s:%d)\n",
2372                                  host, afs_inet_ntoa_r(host->z.host, hoststr),
2373                                  ntohs(host->z.port)));
2374                     }
2375                 }
2376             }
2377             if (code) {
2378                 ViceLog(0,
2379                         ("CB: RCallBackConnectBack failed for %" AFS_PTR_FMT " (%s:%d)\n",
2380                          host, afs_inet_ntoa_r(host->z.host, hoststr), ntohs(host->z.port)));
2381                 host->z.hostFlags |= VENUSDOWN;
2382             } else {
2383                 ViceLog(125,
2384                         ("CB: RCallBackConnectBack succeeded for %" AFS_PTR_FMT " (%s:%d)\n",
2385                          host, afs_inet_ntoa_r(host->z.host, hoststr), ntohs(host->z.port)));
2386                 host->z.hostFlags |= RESETDONE;
2387             }
2388         }
2389         if (caps.Capabilities_val
2390             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
2391             host->z.hostFlags |= HERRORTRANS;
2392         else
2393             host->z.hostFlags &= ~(HERRORTRANS);
2394         host->z.hostFlags |= ALTADDR;   /* host structure initialization complete */
2395         host->z.hostFlags &= ~HWHO_INPROGRESS;
2396         h_Unlock_r(host);
2397     }
2398
2399  gethost_out:
2400     if (caps.Capabilities_val)
2401         free(caps.Capabilities_val);
2402     caps.Capabilities_val = NULL;
2403     caps.Capabilities_len = 0;
2404     if (cb_in) {
2405         rx_DestroyConnection(cb_in);
2406         cb_in = NULL;
2407     }
2408     return host;
2409
2410 }                               /*h_GetHost_r */
2411
2412
2413 /* not reentrant */
2414 void
2415 h_InitHostPackage(int hquota)
2416 {
2417     opr_Assert(hquota > 0);
2418     h_quota_limit = hquota;
2419
2420     memset(&nulluuid, 0, sizeof(afsUUID));
2421     rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
2422     rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
2423     opr_mutex_init(&host_glock_mutex);
2424 }
2425
2426 static int
2427 MapName_r(char *uname, afs_int32 * aval)
2428 {
2429     namelist lnames;
2430     idlist lids;
2431     afs_int32 code;
2432
2433     lnames.namelist_len = 1;
2434     lnames.namelist_val = (prname *) uname;
2435     lids.idlist_len = 0;
2436     lids.idlist_val = NULL;
2437
2438     H_UNLOCK;
2439     code = hpr_NameToId(&lnames, &lids);
2440     H_LOCK;
2441     if (code == 0) {
2442         if (lids.idlist_val) {
2443             *aval = lids.idlist_val[0];
2444             if (*aval == AnonymousID) {
2445                 ViceLog(2,
2446                         ("MapName: NameToId on %s returns anonymousID\n",
2447                          lnames.namelist_val[0]));
2448             }
2449             free(lids.idlist_val);      /* return parms are not malloced in stub if server proc aborts */
2450         } else {
2451             ViceLog(0,
2452                     ("MapName: NameToId on '%s' is unknown\n",
2453                      lnames.namelist_val[0]));
2454             code = -1;
2455         }
2456     }
2457     return code;
2458 }
2459
2460 /*MapName*/
2461
2462
2463 static int
2464 PerHost_EnumerateClient(struct host *host, void *arock)
2465 {
2466     struct enumclient_args *args = arock;
2467     struct client *client;
2468     int code;
2469
2470     for (client = host->z.FirstClient; client; client = client->z.next) {
2471         if (!client->z.deleted && client->z.ViceId == args->vid) {
2472
2473             client->z.refCount++;
2474             H_UNLOCK;
2475
2476             code = (*args->proc)(client, args->rock);
2477
2478             H_LOCK;
2479             h_ReleaseClient_r(client);
2480
2481             if (code) {
2482                 return H_ENUMERATE_BAIL(0);
2483             }
2484         }
2485     }
2486
2487     return 0;
2488 }
2489
2490 void
2491 h_EnumerateClients(VolumeId vid,
2492                    int (*proc)(struct client *client, void *rock),
2493                    void *rock)
2494 {
2495     struct enumclient_args args;
2496     args.vid = vid;
2497     args.proc = proc;
2498     args.rock = rock;
2499
2500     H_LOCK;
2501     h_Enumerate_r(PerHost_EnumerateClient, hostList, &args);
2502     H_UNLOCK;
2503 }
2504
2505 static int
2506 format_vname(char *vname, int usize, const char *tname, const char *tinst,
2507              const char *tcell, afs_int32 islocal)
2508 {
2509     int len;
2510
2511     len = strlcpy(vname, tname, usize);
2512     if (len >= usize)
2513         return -1;
2514     if (tinst[0]) {
2515         len = strlcat(vname, ".", usize);
2516         if (len >= usize)
2517             return -1;
2518         len = strlcat(vname, tinst, usize);
2519         if (len >= usize)
2520             return -1;
2521     }
2522     if (tcell[0] && !islocal) {
2523         len = strlcat(vname, "@", usize);
2524         if (len >= usize)
2525             return -1;
2526         len = strlcat(vname, tcell, usize);
2527         if (len >= usize)
2528             return -1;
2529     }
2530     return 0;
2531 }
2532
2533 static int
2534 getPeerDetails(struct rx_connection *conn,
2535                afs_int32 *viceid, afs_int32 *expTime, int authClass)
2536 {
2537     int code;
2538 #if (64-MAXKTCNAMELEN)
2539     ticket name length != 64
2540 #endif
2541     char tname[64];
2542     char tinst[64];
2543     char tcell[MAXKTCREALMLEN];
2544     char uname[PR_MAXNAMELEN];
2545
2546     *viceid = AnonymousID;
2547     *expTime = 0x7fffffff;
2548
2549     ViceLog(5,
2550             ("FindClient: authenticating connection: authClass=%d\n",
2551              authClass));
2552     if (authClass == RX_SECIDX_VAB) {
2553         /* A bcrypt tickets, no longer supported */
2554         ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
2555         return 0;
2556     }
2557
2558     if (authClass == RX_SECIDX_KAD) {
2559         /* an rxkad ticket */
2560         afs_int32 kvno;
2561         afs_int32 islocal;
2562
2563         /* kerberos ticket */
2564         code = rxkad_GetServerInfo(conn, /*level */ 0, (afs_uint32 *)expTime,
2565                                    tname, tinst, tcell, &kvno);
2566         if (code) {
2567             ViceLog(1, ("Failed to get rxkad ticket info\n"));
2568             return 0;
2569         }
2570
2571         ViceLog(5,
2572                 ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
2573                  tname, tinst, tcell, *expTime, kvno));
2574         code = afsconf_IsLocalRealmMatch(confDir, &islocal, tname, tinst, tcell);
2575
2576         if (code) {
2577             ViceLog(0, ("FindClient: local realm check failed; code=%d", code));
2578             return 0;
2579         }
2580
2581         code = format_vname(uname, sizeof(uname), tname, tinst, tcell, islocal);
2582         if (code) {
2583             ViceLog(0, ("FindClient: uname truncated."));
2584             return 0;
2585         }
2586
2587         /* translate the name to a vice id */
2588         code = MapName_r(uname, viceid);
2589         if (code) {
2590             ViceLog(1, ("failed to map name=%s -> code=%d\n", uname,
2591                         code));
2592             return code; /* Actually flag this is a failure */
2593         }
2594
2595         return 0;
2596     }
2597
2598     return 0;
2599 }
2600
2601 /*
2602  * Called by the server main loop.  Returns a h_Held client, which must be
2603  * released later the main loop.  Allocates a client if the matching one
2604  * isn't around. The client is returned with its reference count incremented
2605  * by one. The caller must call h_ReleaseClient_r when finished with
2606  * the client.
2607  *
2608  * The refCount on client->z.host is returned incremented.  h_ReleaseClient_r
2609  * does not decrement the refCount on client->z.host.
2610  *
2611  * *a_viceid is set to the user's ViceId, even if we don't return a client
2612  * struct.
2613  */
2614 struct client *
2615 h_FindClient_r(struct rx_connection *tcon, afs_int32 *a_viceid)
2616 {
2617     struct client *client;
2618     struct host *host = NULL;
2619     struct client *oldClient;
2620     afs_int32 viceid = 0;
2621     afs_int32 expTime;
2622     afs_int32 code;
2623     int authClass;
2624
2625     int fail = 0;
2626     int created = 0;
2627
2628     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2629     if (client && client->z.sid == rx_GetConnectionId(tcon)
2630         && client->z.VenusEpoch == rx_GetConnectionEpoch(tcon)
2631         && !(client->z.host->z.hostFlags & HOSTDELETED)
2632         && !client->z.deleted) {
2633
2634         if (a_viceid) {
2635             *a_viceid = client->z.ViceId;
2636         }
2637         client->z.refCount++;
2638         h_Hold_r(client->z.host);
2639         if (client->z.prfail != 2) {
2640             /* Could add shared lock on client here */
2641             /* note that we don't have to lock entry in this path to
2642              * ensure CPS is initialized, since we don't call rx_SetSpecific
2643              * until initialization is done, and we only get here if
2644              * rx_GetSpecific located the client structure.
2645              */
2646             return client;
2647         }
2648         H_UNLOCK;
2649         ObtainWriteLock(&client->lock); /* released at end */
2650         H_LOCK;
2651     } else {
2652         client = NULL;
2653     }
2654
2655     authClass = rx_SecurityClassOf(tcon);
2656
2657     code = getPeerDetails(tcon, &viceid, &expTime, authClass);
2658     if (code)
2659         fail = 1;
2660
2661     if (a_viceid) {
2662         *a_viceid = viceid;
2663     }
2664
2665     if (!client) { /* loop */
2666         host = h_GetHost_r(tcon);       /* Returns with incremented refCount  */
2667
2668         if (!host)
2669             return NULL;
2670
2671     retryfirstclient:
2672         /* First try to find the client structure */
2673         for (client = host->z.FirstClient; client; client = client->z.next) {
2674             if (!client->z.deleted && (client->z.sid == rx_GetConnectionId(tcon))
2675                 && (client->z.VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2676                 client->z.refCount++;
2677                 H_UNLOCK;
2678                 ObtainWriteLock(&client->lock);
2679                 H_LOCK;
2680                 break;
2681             }
2682         }
2683
2684         /* Still no client structure - get one */
2685         if (!client) {
2686             h_Lock_r(host);
2687             if (host->z.hostFlags & HOSTDELETED) {
2688                 h_Unlock_r(host);
2689                 h_Release_r(host);
2690                 return NULL;
2691             }
2692             /* Retry to find the client structure */
2693             for (client = host->z.FirstClient; client; client = client->z.next) {
2694                 if (!client->z.deleted && (client->z.sid == rx_GetConnectionId(tcon))
2695                     && (client->z.VenusEpoch == rx_GetConnectionEpoch(tcon))) {
2696                     h_Unlock_r(host);
2697                     goto retryfirstclient;
2698                 }
2699             }
2700             created = 1;
2701             client = GetCE();
2702             ObtainWriteLock(&client->lock);
2703             client->z.refCount = 1;
2704             client->z.host = host;
2705             client->z.InSameNetwork = host->z.InSameNetwork;
2706             client->z.ViceId = viceid;
2707             client->z.expTime = expTime;        /* rx only */
2708             client->z.authClass = authClass;    /* rx only */
2709             client->z.sid = rx_GetConnectionId(tcon);
2710             client->z.VenusEpoch = rx_GetConnectionEpoch(tcon);
2711             client->z.CPS.prlist_val = NULL;
2712             client->z.CPS.prlist_len = 0;
2713             h_Unlock_r(host);
2714         }
2715     }
2716     client->z.prfail = fail;
2717
2718     if (!(client->z.CPS.prlist_val) || (viceid != client->z.ViceId)) {
2719         client->z.CPS.prlist_len = 0;
2720         if (client->z.CPS.prlist_val && (client->z.ViceId != ANONYMOUSID))
2721             free(client->z.CPS.prlist_val);
2722         client->z.CPS.prlist_val = NULL;
2723         client->z.ViceId = viceid;
2724         client->z.expTime = expTime;
2725
2726         if (viceid == ANONYMOUSID) {
2727             client->z.CPS.prlist_len = AnonCPS.prlist_len;
2728             client->z.CPS.prlist_val = AnonCPS.prlist_val;
2729         } else {
2730             H_UNLOCK;
2731             code = hpr_GetCPS(viceid, &client->z.CPS);
2732             H_LOCK;
2733             if (code) {
2734                 char hoststr[16];
2735                 ViceLog(0,
2736                         ("pr_GetCPS failed(%d) for user %d, host %" AFS_PTR_FMT " (%s:%d)\n",
2737                          code, viceid, client->z.host,
2738                          afs_inet_ntoa_r(client->z.host->z.host,hoststr),
2739                          ntohs(client->z.host->z.port)));
2740
2741                 /* Although ubik_Call (called by pr_GetCPS) traverses thru
2742                  * all protection servers and reevaluates things if no
2743                  * sync server or quorum is found we could still end up
2744                  * with one of these errors. In such case we would like to
2745                  * reevaluate the rpc call to find if there's cps for this
2746                  * guy. We treat other errors (except network failures
2747                  * ones - i.e. code < 0) as an indication that there is no
2748                  * CPS for this host.  Ideally we could like to deal this
2749                  * problem the other way around (i.e.  if code == NOCPS
2750                  * ignore else retry next time) but the problem is that
2751                  * there're other errors (i.e.  EPERM) for which we don't
2752                  * want to retry and we don't know the whole code list!
2753                  */
2754                 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
2755                     client->z.prfail = 1;
2756             }
2757         }
2758         /* the disabling of system:administrators is so iffy and has so many
2759          * possible failure modes that we will disable it again */
2760         /* Turn off System:Administrator for safety
2761          * if (AL_IsAMember(SystemId, client->z.CPS) == 0)
2762          * osi_Assert(AL_DisableGroup(SystemId, client->z.CPS) == 0); */
2763     }
2764
2765     /* Now, tcon may already be set to a rock, since we blocked with no host
2766      * or client locks set above in pr_GetCPS (XXXX some locking is probably
2767      * required).  So, before setting the RPC's rock, we should disconnect
2768      * the RPC from the other client structure's rock.
2769      */
2770     oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2771     if (oldClient && oldClient != client
2772         && oldClient->z.sid == rx_GetConnectionId(tcon)
2773         && oldClient->z.VenusEpoch == rx_GetConnectionEpoch(tcon)
2774         && !(oldClient->z.host->z.hostFlags & HOSTDELETED)) {
2775         char hoststr[16];
2776         if (!oldClient->z.deleted) {
2777             /* if we didn't create it, it's not ours to put back */
2778             if (created) {
2779                 ViceLog(0, ("FindClient: stillborn client %p(%x); "
2780                             "conn %p (host %s:%d) had client %p(%x)\n",
2781                             client, client->z.sid, tcon,
2782                             afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2783                             ntohs(rxr_PortOf(tcon)),
2784                             oldClient, oldClient->z.sid));
2785                 if ((client->z.ViceId != ANONYMOUSID) && client->z.CPS.prlist_val)
2786                     free(client->z.CPS.prlist_val);
2787                 client->z.CPS.prlist_val = NULL;
2788                 client->z.CPS.prlist_len = 0;
2789             }
2790             /* We should perhaps check for 0 here */
2791             client->z.refCount--;
2792             ReleaseWriteLock(&client->lock);
2793             if (created) {
2794                 FreeCE(client);
2795                 created = 0;
2796             }
2797             oldClient->z.refCount++;
2798
2799             h_Hold_r(oldClient->z.host);
2800             h_Release_r(client->z.host);
2801
2802             H_UNLOCK;
2803             ObtainWriteLock(&oldClient->lock);
2804             H_LOCK;
2805             client = oldClient;
2806             host = oldClient->z.host;
2807         } else {
2808             ViceLog(0, ("FindClient: deleted client %p(%x ref %d host %p href "
2809                         "%d) already had conn %p (host %s:%d, cid %x), stolen "
2810                         "by client %p(%x, ref %d host %p href %d)\n",
2811                         oldClient, oldClient->z.sid, oldClient->z.refCount,
2812                         oldClient->z.host, oldClient->z.host->z.refCount, tcon,
2813                         afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2814                         ntohs(rxr_PortOf(tcon)), rx_GetConnectionId(tcon),
2815                         client, client->z.sid, client->z.refCount,
2816                         client->z.host, client->z.host->z.refCount));
2817             /* rx_SetSpecific will be done immediately below */
2818         }
2819     }
2820     /* Avoid chaining in more than once. */
2821     if (created) {
2822         h_Lock_r(host);
2823
2824         if (host->z.hostFlags & HOSTDELETED) {
2825             h_Unlock_r(host);
2826             h_Release_r(host);
2827
2828             host = NULL;
2829             client->z.host = NULL;
2830
2831             if ((client->z.ViceId != ANONYMOUSID) && client->z.CPS.prlist_val)
2832                 free(client->z.CPS.prlist_val);
2833             client->z.CPS.prlist_val = NULL;
2834             client->z.CPS.prlist_len = 0;
2835
2836             client->z.refCount--;
2837             ReleaseWriteLock(&client->lock);
2838             FreeCE(client);
2839             return NULL;
2840         }
2841
2842         client->z.next = host->z.FirstClient;
2843         host->z.FirstClient = client;
2844         h_Unlock_r(host);
2845         CurrentConnections++;   /* increment number of connections */
2846     }
2847     rx_SetSpecific(tcon, rxcon_client_key, client);
2848     ReleaseWriteLock(&client->lock);
2849
2850     return client;
2851
2852 }                               /*h_FindClient_r */
2853
2854 int
2855 h_ReleaseClient_r(struct client *client)
2856 {
2857     opr_Assert(client->z.refCount > 0);
2858     client->z.refCount--;
2859     return 0;
2860 }
2861
2862
2863 /*
2864  * Sigh:  this one is used to get the client AGAIN within the individual
2865  * server routines.  This does not bother h_Holding the host, since
2866  * this is assumed already have been done by the server main loop.
2867  * It does check tokens, since only the server routines can return the
2868  * VICETOKENDEAD error code
2869  */
2870 int
2871 GetClient(struct rx_connection *tcon, struct client **cp)
2872 {
2873     struct client *client;
2874     char hoststr[16];
2875
2876     H_LOCK;
2877     *cp = NULL;
2878     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2879     if (client == NULL) {
2880         ViceLog(0,
2881                 ("GetClient: no client in conn %p (host %s:%d), VBUSYING\n",
2882                  tcon, afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
2883                  ntohs(rxr_PortOf(tcon))));
2884         H_UNLOCK;
2885         return VBUSY;
2886     }
2887     if (rx_GetConnectionId(tcon) != client->z.sid
2888         || rx_GetConnectionEpoch(tcon) != client->z.VenusEpoch) {
2889         ViceLog(0,
2890                 ("GetClient: tcon %p tcon sid %d client sid %d\n",
2891                  tcon, rx_GetConnectionId(tcon), client->z.sid));
2892         H_UNLOCK;
2893         return VBUSY;
2894     }
2895     if (client && client->z.LastCall > client->z.expTime && client->z.expTime) {
2896         ViceLog(1,
2897                 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
2898                  afs_inet_ntoa_r(client->z.host->z.host, hoststr),
2899                  ntohs(client->z.host->z.port), client->z.expTime));
2900         H_UNLOCK;
2901         return VICETOKENDEAD;
2902     }
2903     if (client->z.deleted) {
2904         ViceLog(0, ("GetClient: got deleted client, connection will appear "
2905                     "anonymous; tcon %p cid %x client %p ref %d host %p "
2906                     "(%s:%d) href %d ViceId %d\n",
2907                     tcon, rx_GetConnectionId(tcon), client, client->z.refCount,
2908                     client->z.host,
2909                     afs_inet_ntoa_r(client->z.host->z.host, hoststr),
2910                     (int)ntohs(client->z.host->z.port), client->z.host->z.refCount,
2911                     (int)client->z.ViceId));
2912     }
2913
2914     client->z.refCount++;
2915     *cp = client;
2916     H_UNLOCK;
2917     return 0;
2918 }                               /*GetClient */
2919
2920 int
2921 PutClient(struct client **cp)
2922 {
2923     if (*cp == NULL)
2924         return -1;
2925
2926     H_LOCK;
2927     h_ReleaseClient_r(*cp);
2928     *cp = NULL;
2929     H_UNLOCK;
2930     return 0;
2931 }                               /*PutClient */
2932
2933
2934 /* Client user name for short term use.  Note that this is NOT inexpensive */
2935 char *
2936 h_UserName(struct client *client)
2937 {
2938     static char User[PR_MAXNAMELEN + 1];
2939     namelist lnames;
2940     idlist lids;
2941
2942     lids.idlist_len = 1;
2943     lids.idlist_val = malloc(1 * sizeof(afs_int32));
2944     if (!lids.idlist_val) {
2945         ViceLogThenPanic(0, ("Failed malloc in h_UserName\n"));
2946     }
2947     lnames.namelist_len = 0;
2948     lnames.namelist_val = (prname *) 0;
2949     lids.idlist_val[0] = client->z.ViceId;
2950     if (hpr_IdToName(&lids, &lnames)) {
2951         /* We need to free id we alloced above! */
2952         free(lids.idlist_val);
2953         return "*UNKNOWN USER NAME*";
2954     }
2955     strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
2956     free(lids.idlist_val);
2957     free(lnames.namelist_val);
2958     return User;
2959 }                               /*h_UserName */
2960
2961
2962 void
2963 h_PrintStats(void)
2964 {
2965     ViceLog(0,
2966             ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
2967              CEs, CEBlocks, HTs, HTBlocks));
2968
2969 }                               /*h_PrintStats */
2970
2971
2972 static int
2973 h_PrintClient(struct host *host, void *rock)
2974 {
2975     StreamHandle_t *file = (StreamHandle_t *)rock;
2976     struct client *client;
2977     int i;
2978     char tmpStr[256];
2979     char tbuffer[32];
2980     char hoststr[16];
2981     time_t LastCall, expTime;
2982     struct tm tm;
2983
2984     H_LOCK;
2985     LastCall = host->z.LastCall;
2986     if (host->z.hostFlags & HOSTDELETED) {
2987         H_UNLOCK;
2988         return 0;
2989     }
2990     strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
2991              localtime_r(&LastCall, &tm));
2992     snprintf(tmpStr, sizeof tmpStr, "Host %s:%d down = %d, LastCall %s\n",
2993              afs_inet_ntoa_r(host->z.host, hoststr),
2994              ntohs(host->z.port), (host->z.hostFlags & VENUSDOWN),
2995              tbuffer);
2996     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2997     for (client = host->z.FirstClient; client; client = client->z.next) {
2998         if (!client->z.deleted) {
2999             expTime = client->z.expTime;
3000             strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
3001                      localtime_r(&expTime, &tm));
3002             snprintf(tmpStr, sizeof tmpStr,
3003                      "    user id=%d,  name=%s, sl=%s till %s\n",
3004                      client->z.ViceId, h_UserName(client),
3005                      client->z.authClass ? "Authenticated"
3006                                        : "Not authenticated",
3007                      client->z.authClass ? tbuffer : "No Limit");
3008             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
3009             snprintf(tmpStr, sizeof tmpStr, "      CPS-%d is [",
3010                          client->z.CPS.prlist_len);
3011             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
3012             if (client->z.CPS.prlist_val) {
3013                 for (i = 0; i < client->z.CPS.prlist_len; i++) {
3014                     snprintf(tmpStr, sizeof tmpStr, " %d",
3015                              client->z.CPS.prlist_val[i]);
3016                     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
3017                 }
3018             }
3019             sprintf(tmpStr, "]\n");
3020             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
3021         }
3022     }
3023     H_UNLOCK;
3024     return 0;
3025
3026 }                               /*h_PrintClient */
3027
3028
3029
3030 /*
3031  * Print a list of clients, with last security level and token value seen,
3032  * if known
3033  */
3034 void
3035 h_PrintClients(void)
3036 {
3037     time_t now;
3038     char tmpStr[256];
3039     char tbuffer[32];
3040     struct tm tm;
3041
3042     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
3043
3044     if (file == NULL) {
3045         ViceLog(0,
3046                 ("Couldn't create client dump file %s\n",
3047                  AFSDIR_SERVER_CLNTDUMP_FILEPATH));
3048         return;
3049     }
3050     now = time(NULL);
3051     strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
3052              localtime_r(&now, &tm));
3053     snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n\n",
3054              tbuffer);
3055     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
3056     h_Enumerate(h_PrintClient, (char *)file);
3057     STREAM_REALLYCLOSE(file);
3058     ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
3059 }
3060
3061
3062
3063
3064 static int
3065 h_DumpHost(struct host *host, void *rock)
3066 {
3067     StreamHandle_t *file = (StreamHandle_t *)rock;
3068
3069     int i;
3070     char tmpStr[256];
3071     char hoststr[16];
3072
3073     H_LOCK;
3074     snprintf(tmpStr, sizeof tmpStr,
3075              "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u "
3076              "down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u "
3077              "hcps [",
3078              afs_inet_ntoa_r(host->z.host, hoststr), ntohs(host->z.port),
3079              host->index, host->z.cblist, CheckLock(&host->lock),
3080              host->z.LastCall, host->z.ActiveCall, (host->z.hostFlags & VENUSDOWN),
3081              host->z.hostFlags & HOSTDELETED, host->z.Console,
3082              host->z.hostFlags & CLIENTDELETED, host->z.hcpsfailed,
3083              host->z.cpsCall);
3084     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
3085     if (host->z.hcps.prlist_val)
3086         for (i = 0; i < host->z.hcps.prlist_len; i++) {
3087             snprintf(tmpStr, sizeof tmpStr, " %d", host->z.hcps.prlist_val[i]);
3088             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
3089         }
3090     sprintf(tmpStr, "] [");
3091     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
3092     if (host->z.interface)
3093         for (i = 0; i < host->z.interface->numberOfInterfaces; i++) {
3094             char hoststr[16];
3095             sprintf(tmpStr, " %s:%d",
3096                      afs_inet_ntoa_r(host->z.interface->interface[i].addr, hoststr),
3097                      ntohs(host->z.interface->interface[i].port));
3098             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
3099         }
3100     sprintf(tmpStr, "] refCount:%d hostFlags:%hu\n", host->z.refCount, host->z.hostFlags);
3101     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
3102
3103     H_UNLOCK;
3104     return 0;
3105
3106 }                               /*h_DumpHost */
3107
3108
3109 void
3110 h_DumpHosts(void)
3111 {
3112     time_t now;
3113     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
3114     char tmpStr[256];
3115     char tbuffer[32];
3116     struct tm tm;
3117
3118     if (file == NULL) {
3119         ViceLog(0,
3120                 ("Couldn't create host dump file %s\n",
3121                  AFSDIR_SERVER_HOSTDUMP_FILEPATH));
3122         return;
3123     }
3124     now = time(NULL);
3125     strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y",
3126              localtime_r(&now, &tm));
3127     snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n\n", tbuffer);
3128     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
3129     h_Enumerate(h_DumpHost, (char *)file);
3130     STREAM_REALLYCLOSE(file);
3131     ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
3132
3133 }                               /*h_DumpHosts */
3134
3135 #ifdef AFS_DEMAND_ATTACH_FS
3136 /*
3137  * demand attach fs
3138  * host state serialization
3139  */
3140 static int h_stateFillHeader(struct host_state_header * hdr);
3141 static int h_stateCheckHeader(struct host_state_header * hdr);
3142 static int h_stateAllocMap(struct fs_dump_state * state);
3143 static int h_stateSaveHost(struct host * host, void *rock);
3144 static int h_stateRestoreHost(struct fs_dump_state * state);
3145 static int h_stateRestoreIndex(struct host * h, void *rock);
3146 static int h_stateVerifyHost(struct host * h, void *rock);
3147 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3148                                  afs_uint32 addr, afs_uint16 port, int valid);
3149 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
3150 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
3151 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
3152
3153 /**
3154  * Is this host busy?
3155  *
3156  * This is just a hint and should not be trusted; this should probably only be
3157  * used by the host state serialization code when trying to detect if a host
3158  * can be sanely serialized to disk or not. If this function returns 1, the
3159  * host may be in an invalid state and thus should not be saved to disk.
3160  */
3161 static int
3162 h_isBusy_r(struct host *host)
3163 {
3164     struct Lock *hostLock = &host->lock;
3165     int locked = 0;
3166
3167     LOCK_LOCK(hostLock);
3168     if (hostLock->excl_locked || hostLock->readers_reading) {
3169         locked = 1;
3170     }
3171     LOCK_UNLOCK(hostLock);
3172
3173     if (locked) {
3174         return 1;
3175     }
3176
3177     if ((host->z.hostFlags & HWHO_INPROGRESS) || !(host->z.hostFlags & ALTADDR)) {
3178         /* We shouldn't hit this if the host wasn't locked, but just in case... */
3179         return 1;
3180     }
3181
3182     return 0;
3183 }
3184
3185 /* this procedure saves all host state to disk for fast startup */
3186 int
3187 h_stateSave(struct fs_dump_state * state)
3188 {
3189     AssignInt64(state->eof_offset, &state->hdr->h_offset);
3190
3191     /* XXX debug */
3192     ViceLog(0, ("h_stateSave:  hostCount=%d\n", hostCount));
3193
3194     /* invalidate host state header */
3195     memset(state->h_hdr, 0, sizeof(struct host_state_header));
3196
3197     if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
3198                             sizeof(struct host_state_header))) {
3199         state->bail = 1;
3200         goto done;
3201     }
3202
3203     fs_stateIncEOF(state, sizeof(struct host_state_header));
3204
3205     h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
3206     if (state->bail) {
3207         goto done;
3208     }
3209
3210     h_stateFillHeader(state->h_hdr);
3211
3212     /* write the real header to disk */
3213     state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
3214                                       sizeof(struct host_state_header));
3215
3216  done:
3217     return state->bail;
3218 }
3219
3220 /* demand attach fs
3221  * host state serialization
3222  *
3223  * this procedure restores all host state from a disk for fast startup
3224  */
3225 int
3226 h_stateRestore(struct fs_dump_state * state)
3227 {
3228     int i, records;
3229
3230     /* seek to the right position and read in the host state header */
3231     if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
3232                            sizeof(struct host_state_header))) {
3233         state->bail = 1;
3234         goto done;
3235     }
3236
3237     /* check the validity of the header */
3238     if (h_stateCheckHeader(state->h_hdr)) {
3239         state->bail = 1;
3240         goto done;
3241     }
3242
3243     records = state->h_hdr->records;
3244
3245     if (h_stateAllocMap(state)) {
3246         state->bail = 1;
3247         goto done;
3248     }
3249
3250     /* iterate over records restoring host state */
3251     for (i=0; i < records; i++) {
3252         if (h_stateRestoreHost(state) != 0) {
3253             state->bail = 1;
3254             break;
3255         }
3256     }
3257
3258  done:
3259     return state->bail;
3260 }
3261
3262 int
3263 h_stateRestoreIndices(struct fs_dump_state * state)
3264 {
3265     h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
3266     return state->bail;
3267 }
3268
3269 static int
3270 h_stateRestoreIndex(struct host * h, void *rock)
3271 {
3272     struct fs_dump_state *state = (struct fs_dump_state *)rock;
3273     if (cb_OldToNew(state, h->z.cblist, &h->z.cblist)) {
3274         return H_ENUMERATE_BAIL(0);
3275     }
3276     return 0;
3277 }
3278
3279 int
3280 h_stateVerify(struct fs_dump_state * state)
3281 {
3282     h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
3283     return state->bail;
3284 }
3285
3286 static int
3287 h_stateVerifyHost(struct host * h, void* rock)
3288 {
3289     struct fs_dump_state *state = (struct fs_dump_state *)rock;
3290     int i;
3291
3292     if (h == NULL) {
3293         ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
3294         return H_ENUMERATE_BAIL(0);
3295     }
3296
3297     if (h->z.interface) {
3298         for (i = h->z.interface->numberOfInterfaces-1; i >= 0; i--) {
3299             if (h_stateVerifyAddrHash(state, h, h->z.interface->interface[i].addr,
3300                                       h->z.interface->interface[i].port,
3301                                       h->z.interface->interface[i].valid)) {
3302                 state->bail = 1;
3303             }
3304         }
3305         if (h_stateVerifyUuidHash(state, h)) {
3306             state->bail = 1;
3307         }
3308     } else if (h_stateVerifyAddrHash(state, h, h->z.host, h->z.port, 1)) {
3309         state->bail = 1;
3310     }
3311
3312     if (cb_stateVerifyHCBList(state, h)) {
3313         state->bail = 1;
3314     }
3315
3316     return 0;
3317 }
3318
3319 /**
3320  * verify a host is either in, or absent from, the addr hash table.
3321  *
3322  * @param[in] state  fs dump state
3323  * @param[in] h      host we're dealing with
3324  * @param[in] addr   addr to look for (NBO)
3325  * @param[in] port   port to look for (NBO)
3326  * @param[in] valid  1 if we're verifying that the specified addr and port
3327  *                   in the hash table point to the specified host. 0 if we're
3328  *                   verifying that the specified addr and port do NOT point
3329  *                   to the specified host
3330  *
3331  * @return operation status
3332  *  @retval 1 failed to verify, bail out
3333  *  @retval 0 verified successfully, all is well
3334  */
3335 static int
3336 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h,
3337                       afs_uint32 addr, afs_uint16 port, int valid)
3338 {
3339     int ret = 0, found = 0;
3340     struct host *host = NULL;
3341     struct h_AddrHashChain *chain;
3342     int index = h_HashIndex(addr);
3343     char tmp[16];
3344     int chain_len = 0;
3345
3346     for (chain = hostAddrHashTable[index]; chain; chain = chain->next) {
3347         host = chain->hostPtr;
3348         if (host == NULL) {
3349             afs_inet_ntoa_r(addr, tmp);
3350             ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
3351             ret = 1;
3352             goto done;
3353         }
3354         if ((chain->addr == addr) && (chain->port == port)) {
3355             if (host != h) {
3356                 if (valid) {
3357                     ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry "
3358                                 "points to different host struct (%d, %d)\n",
3359                                 h->index, host->index));
3360                     state->flags.warnings_generated = 1;
3361                 }
3362             } else {
3363                 if (!valid) {
3364                     ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u is "
3365                                 "marked invalid, but points to the containing "
3366                                 "host\n", afs_inet_ntoa_r(addr, tmp),
3367                                 (unsigned)htons(port)));
3368                     ret = 1;
3369                     goto done;
3370                 }
3371             }
3372             found = 1;
3373             break;
3374         }
3375         if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
3376             ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3377                         FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
3378             ret = 1;
3379             goto done;
3380         }
3381         chain_len++;
3382     }
3383
3384     if (!found && valid) {
3385         afs_inet_ntoa_r(addr, tmp);
3386         if (state->mode == FS_STATE_LOAD_MODE) {
3387             ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s:%u not found in hash\n",
3388                         tmp, (unsigned)htons(port)));
3389             ret = 1;
3390             goto done;
3391         } else {
3392             ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s:%u not found in hash\n",
3393                         tmp, (unsigned)htons(port)));
3394             state->flags.warnings_generated = 1;
3395         }
3396     }
3397
3398  done:
3399     return ret;
3400 }
3401
3402 static int
3403 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
3404 {
3405     int ret = 0;
3406     struct host *host = NULL;
3407     struct h_UuidHashChain *chain;
3408     afsUUID * uuidp = &h->z.interface->uuid;
3409     int index = h_UuidHashIndex(uuidp);
3410     char tmp[40];
3411     int chain_len = 0;
3412
3413     for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
3414         host = chain->hostPtr;
3415         if (host == NULL) {
3416             afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3417             ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
3418             ret = 1;
3419             goto done;
3420         }
3421         if (host->z.interface &&
3422             afs_uuid_equal(&host->z.interface->uuid, uuidp)) {
3423             if (host != h) {
3424                 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n",
3425                             h->index, host->index));
3426                 state->flags.warnings_generated = 1;
3427             }
3428             goto done;
3429         }
3430         if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
3431             ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
3432                         FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
3433             ret = 1;
3434             goto done;
3435         }
3436         chain_len++;
3437     }
3438
3439     /* Fall through, so host not found */
3440
3441     afsUUID_to_string(uuidp, tmp, sizeof(tmp));
3442     if (state->mode == FS_STATE_LOAD_MODE) {
3443         ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
3444         ret = 1;
3445         goto done;
3446     } else {
3447         ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
3448         state->flags.warnings_generated = 1;
3449     }
3450
3451  done:
3452     return ret;
3453 }
3454
3455 /* create the host state header structure */
3456 static int
3457 h_stateFillHeader(struct host_state_header * hdr)
3458 {
3459     hdr->stamp.magic = HOST_STATE_MAGIC;
3460     hdr->stamp.version = HOST_STATE_VERSION;
3461     return 0;
3462 }
3463
3464 /* check the contents of the host state header structure */
3465 static int
3466 h_stateCheckHeader(struct host_state_header * hdr)
3467 {
3468     int ret=0;
3469
3470     if (hdr->stamp.magic != HOST_STATE_MAGIC) {
3471         ViceLog(0, ("check_host_state_header: invalid state header\n"));
3472         ret = 1;
3473     }
3474     else if (hdr->stamp.version != HOST_STATE_VERSION) {
3475         ViceLog(0, ("check_host_state_header: unknown version number\n"));
3476         ret = 1;
3477     }
3478     return ret;
3479 }
3480
3481 /* allocate the host id mapping table */
3482 static int
3483 h_stateAllocMap(struct fs_dump_state * state)
3484 {
3485     state->h_map.len = state->h_hdr->index_max + 1;
3486     state->h_map.entries = (struct idx_map_entry_t *)
3487         calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
3488     return (state->h_map.entries != NULL) ? 0 : 1;
3489 }
3490
3491 /* function called by h_Enumerate to save a host to disk */
3492 static int
3493 h_stateSaveHost(struct host * host, void* rock)
3494 {
3495     struct fs_dump_state *state = (struct fs_dump_state *) rock;
3496     int if_len=0, hcps_len=0;
3497     struct hostDiskEntry hdsk;
3498     struct host_state_entry_header hdr;
3499     struct Interface * ifp = NULL;
3500     afs_int32 * hcps = NULL;
3501     struct iovec iov[4];
3502     int iovcnt = 2;
3503
3504     if (h_isBusy_r(host)) {
3505         char hoststr[16];
3506         ViceLog(1, ("Not saving host %s:%d to disk; host appears busy\n",
3507                     afs_inet_ntoa_r(host->z.host, hoststr), (int)ntohs(host->z.port)));
3508         /* Make sure we don't try to save callbacks to disk for this host, or
3509          * we'll get confused on restore */
3510         DeleteAllCallBacks_r(host, 1);
3511         return 0;
3512     }
3513
3514     memset(&hdr, 0, sizeof(hdr));
3515
3516     if (state->h_hdr->index_max < host->index) {
3517         state->h_hdr->index_max = host->index;
3518     }
3519
3520     h_hostToDiskEntry_r(host, &hdsk);
3521     if (host->z.interface) {
3522         if_len = sizeof(struct Interface) +
3523             ((host->z.interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
3524         ifp = malloc(if_len);
3525         opr_Assert(ifp != NULL);
3526         memcpy(ifp, host->z.interface, if_len);
3527         hdr.interfaces = host->z.interface->numberOfInterfaces;
3528         iov[iovcnt].iov_base = (char *) ifp;
3529         iov[iovcnt].iov_len = if_len;
3530         iovcnt++;
3531     }
3532     if (host->z.hcps.prlist_val) {
3533         hdr.hcps = host->z.hcps.prlist_len;
3534         hcps_len = hdr.hcps * sizeof(afs_int32);
3535         hcps = malloc(hcps_len);
3536         opr_Assert(hcps != NULL);
3537         memcpy(hcps, host->z.hcps.prlist_val, hcps_len);
3538         iov[iovcnt].iov_base = (char *) hcps;
3539         iov[iovcnt].iov_len = hcps_len;
3540         iovcnt++;
3541     }
3542
3543     if (hdsk.index > state->h_hdr->index_max)
3544         state->h_hdr->index_max = hdsk.index;
3545
3546     hdr.len = sizeof(struct host_state_entry_header) +
3547         sizeof(struct hostDiskEntry) + if_len + hcps_len;
3548     hdr.magic = HOST_STATE_ENTRY_MAGIC;
3549
3550     iov[0].iov_base = (char *) &hdr;
3551     iov[0].iov_len = sizeof(hdr);
3552     iov[1].iov_base = (char *) &hdsk;
3553     iov[1].iov_len = sizeof(struct hostDiskEntry);
3554
3555     if (fs_stateWriteV(state, iov, iovcnt)) {
3556         ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
3557         state->bail = 1;
3558     }
3559
3560     fs_stateIncEOF(state, hdr.len);
3561
3562     state->h_hdr->records++;
3563
3564     if (ifp)
3565         free(ifp);
3566     if (hcps)
3567         free(hcps);
3568     if (state->bail) {
3569         return H_ENUMERATE_BAIL(0);
3570     }
3571     return 0;
3572 }
3573
3574 /* restores a host from disk */
3575 static int
3576 h_stateRestoreHost(struct fs_dump_state * state)
3577 {
3578     int ifp_len=0, hcps_len=0, bail=0;
3579     struct host_state_entry_header hdr;
3580     struct hostDiskEntry hdsk;
3581     struct host *host = NULL;
3582     struct Interface *ifp = NULL;
3583     afs_int32 * hcps = NULL;
3584     struct iovec iov[3];
3585     int iovcnt = 1;
3586
3587     if (fs_stateRead(state, &hdr, sizeof(hdr))) {
3588         ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
3589                     state->fn));
3590         bail = 1;
3591         goto done;
3592     }
3593
3594     if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
3595         ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
3596                     state->fn));
3597         bail = 1;
3598         goto done;
3599     }
3600
3601     iov[0].iov_base = (char *) &hdsk;
3602     iov[0].iov_len = sizeof(struct hostDiskEntry);
3603
3604     if (hdr.interfaces) {
3605         ifp_len = sizeof(struct Interface) +
3606             ((hdr.interfaces-1) * sizeof(struct AddrPort));
3607         ifp = malloc(ifp_len);
3608         opr_Assert(ifp != NULL);
3609         iov[iovcnt].iov_base = (char *) ifp;
3610         iov[iovcnt].iov_len = ifp_len;
3611         iovcnt++;
3612     }
3613     if (hdr.hcps) {
3614         hcps_len = hdr.hcps * sizeof(afs_int32);
3615         hcps = malloc(hcps_len);
3616         opr_Assert(hcps != NULL);
3617         iov[iovcnt].iov_base = (char *) hcps;
3618         iov[iovcnt].iov_len = hcps_len;
3619         iovcnt++;
3620     }
3621
3622     if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
3623         ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
3624         bail = 1;
3625         goto done;
3626     }
3627
3628     if (fs_stateReadV(state, iov, iovcnt)) {
3629         ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
3630         bail = 1;
3631         goto done;
3632     }
3633
3634     if (!hdr.hcps && hdsk.hcps_valid) {
3635         /* valid, zero-length host cps ; does this ever happen? */
3636         hcps = malloc(sizeof(afs_int32));
3637         opr_Assert(hcps != NULL);
3638     }
3639
3640     if ((hdsk.hostFlags & HWHO_INPROGRESS) || !(hdsk.hostFlags & ALTADDR)) {
3641         char hoststr[16];
3642         ViceLog(0, ("h_stateRestoreHost: skipping host %s:%d due to invalid flags 0x%x\n",
3643                     afs_inet_ntoa_r(hdsk.host, hoststr), (int)ntohs(hdsk.port),
3644                     (unsigned)hdsk.hostFlags));
3645         bail = 0;
3646         state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_SKIPPED;
3647         goto done;
3648     }
3649
3650     /* for restoring state, we better be able to get a host! */
3651     host = GetHT();
3652     opr_Assert(host != NULL);
3653
3654     if (ifp) {
3655         host->z.interface = ifp;
3656     }
3657     if (hcps) {
3658         host->z.hcps.prlist_val = hcps;
3659         host->z.hcps.prlist_len = hdr.hcps;
3660     }
3661
3662     h_diskEntryToHost_r(&hdsk, host);
3663     h_SetupCallbackConn_r(host);
3664
3665     h_AddHostToAddrHashTable_r(host->z.host, host->z.port, host);
3666     if (ifp) {
3667         int i;
3668         for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
3669             if (ifp->interface[i].valid &&
3670                 !(ifp->interface[i].addr == host->z.host &&
3671                   ifp->interface[i].port == host->z.port)) {
3672                 h_AddHostToAddrHashTable_r(ifp->interface[i].addr,
3673                                            ifp->interface[i].port,
3674                                            host);
3675             }
3676         }
3677         h_AddHostToUuidHashTable_r(&ifp->uuid, host);
3678     }
3679     h_InsertList_r(host);
3680
3681     /* setup host id map entry */
3682     state->h_map.entries[hdsk.index].valid = FS_STATE_IDX_VALID;
3683     state->h_map.entries[hdsk.index].old_idx = hdsk.index;
3684     state->h_map.entries[hdsk.index].new_idx = host->index;
3685
3686  done:
3687     if (bail) {
3688         if (ifp)
3689             free(ifp);
3690         if (hcps)
3691             free(hcps);
3692     }
3693     return bail;
3694 }
3695
3696 /* serialize a host structure to disk */
3697 static void
3698 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
3699 {
3700     out->host = in->z.host;
3701     out->port = in->z.port;
3702     out->hostFlags = in->z.hostFlags;
3703     out->Console = in->z.Console;
3704     out->hcpsfailed = in->z.hcpsfailed;
3705     out->LastCall = in->z.LastCall;
3706     out->ActiveCall = in->z.ActiveCall;
3707     out->cpsCall = in->z.cpsCall;
3708     out->cblist = in->z.cblist;
3709     out->InSameNetwork = in->z.InSameNetwork;
3710
3711     /* special fields we save, but are not memcpy'd back on restore */
3712     out->index = in->index;
3713     out->hcps_len = in->z.hcps.prlist_len;
3714     out->hcps_valid = (in->z.hcps.prlist_val == NULL) ? 0 : 1;
3715 }
3716
3717 /* restore a host structure from disk */
3718 static void
3719 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
3720 {
3721     out->z.host = in->host;
3722     out->z.port = in->port;
3723     out->z.hostFlags = in->hostFlags;
3724     out->z.Console = in->Console;
3725     out->z.hcpsfailed = in->hcpsfailed;
3726     out->z.LastCall = in->LastCall;
3727     out->z.ActiveCall = in->ActiveCall;
3728     out->z.cpsCall = in->cpsCall;
3729     out->z.cblist = in->cblist;
3730     out->z.InSameNetwork = in->InSameNetwork;
3731 }
3732
3733 /* index translation routines */
3734 int
3735 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
3736 {
3737     int ret = 0;
3738
3739     /* hosts use a zero-based index, so old==0 is valid */
3740
3741     if (old >= state->h_map.len) {
3742         ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
3743         ret = 1;
3744     } else if (state->h_map.entries[old].valid != FS_STATE_IDX_VALID ||
3745                state->h_map.entries[old].old_idx != old) { /* sanity check */
3746         ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
3747         ret = 1;
3748     } else {
3749         *new = state->h_map.entries[old].new_idx;
3750     }
3751
3752     return ret;
3753 }
3754 #endif /* AFS_DEMAND_ATTACH_FS */
3755
3756
3757 /*
3758  * This counts the number of workstations, the number of active workstations,
3759  * and the number of workstations declared "down" (i.e. not heard from
3760  * recently).  An active workstation has received a call since the cutoff
3761  * time argument passed.
3762  */
3763 void
3764 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
3765 {
3766     struct host *host;
3767     int num = 0, active = 0, del = 0;
3768     int count;
3769
3770     H_LOCK;
3771     for (count = 0, host = hostList; host && count < hostCount; host = host->z.next, count++) {
3772         if (!(host->z.hostFlags & HOSTDELETED)) {
3773             num++;
3774             if (host->z.ActiveCall > cutofftime)
3775                 active++;
3776             if (host->z.hostFlags & VENUSDOWN)
3777                 del++;
3778         }
3779     }
3780     if (count != hostCount) {
3781         ViceLog(0, ("h_GetWorkStats found %d of %d hosts\n", count, hostCount));
3782     } else if (host != NULL) {
3783         ViceLog(0, ("h_GetWorkStats found more than %d hosts\n", hostCount));
3784         ShutDownAndCore(PANIC);
3785     }
3786     H_UNLOCK;
3787     if (nump)
3788         *nump = num;
3789     if (activep)
3790         *activep = active;
3791     if (delp)
3792         *delp = del;
3793
3794 }                               /*h_GetWorkStats */
3795
3796 void
3797 h_GetWorkStats64(afs_uint64 *nump, afs_uint64 *activep, afs_uint64 *delp, 
3798                  afs_int32 cutofftime)
3799 {
3800     int num, active, del;
3801     h_GetWorkStats(&num, &active, &del, cutofftime);
3802     if (nump)
3803         *nump = num;
3804     if (activep)
3805         *activep = active;
3806     if (delp)
3807         *delp = del;
3808 }
3809
3810 /*------------------------------------------------------------------------
3811  * PRIVATE h_ClassifyAddress
3812  *
3813  * Description:
3814  *      Given a target IP address and a candidate IP address (both
3815  *      in host byte order), classify the candidate into one of three
3816  *      buckets in relation to the target by bumping the counters passed
3817  *      in as parameters.
3818  *
3819  * Arguments:
3820  *      a_targetAddr       : Target address.
3821  *      a_candAddr         : Candidate address.
3822  *      a_sameNetOrSubnetP : Ptr to counter to bump when the two
3823  *                           addresses are either in the same network
3824  *                           or the same subnet.
3825  *      a_diffSubnetP      : ...when the candidate is in a different
3826  *                           subnet.
3827  *      a_diffNetworkP     : ...when the candidate is in a different
3828  *                           network.
3829  *
3830  * Returns:
3831  *      Nothing.
3832  *
3833  * Environment:
3834  *      The target and candidate addresses are both in host byte
3835  *      order, NOT network byte order, when passed in.
3836  *
3837  * Side Effects:
3838  *      As advertised.
3839  *------------------------------------------------------------------------*/
3840
3841 static void
3842 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
3843                   afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
3844                   afs_int32 * a_diffNetworkP)
3845 {                               /*h_ClassifyAddress */
3846
3847     afs_uint32 targetNet;
3848     afs_uint32 targetSubnet;
3849     afs_uint32 candNet;
3850     afs_uint32 candSubnet;
3851
3852     /*
3853      * Put bad values into the subnet info to start with.
3854      */
3855     targetSubnet = (afs_uint32) 0;
3856     candSubnet = (afs_uint32) 0;
3857
3858     /*
3859      * Pull out the network and subnetwork numbers from the target
3860      * and candidate addresses.  We can short-circuit this whole
3861      * affair if the target and candidate addresses are not of the
3862      * same class.
3863      */
3864     if (IN_CLASSA(a_targetAddr)) {
3865         if (!(IN_CLASSA(a_candAddr))) {
3866             (*a_diffNetworkP)++;
3867             return;
3868         }
3869         targetNet = a_targetAddr & IN_CLASSA_NET;
3870         candNet = a_candAddr & IN_CLASSA_NET;
3871         if (IN_SUBNETA(a_targetAddr))
3872             targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
3873         if (IN_SUBNETA(a_candAddr))
3874             candSubnet = a_candAddr & IN_CLASSA_SUBNET;
3875     } else if (IN_CLASSB(a_targetAddr)) {
3876         if (!(IN_CLASSB(a_candAddr))) {
3877             (*a_diffNetworkP)++;
3878             return;
3879         }
3880         targetNet = a_targetAddr & IN_CLASSB_NET;
3881         candNet = a_candAddr & IN_CLASSB_NET;
3882         if (IN_SUBNETB(a_targetAddr))
3883             targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
3884         if (IN_SUBNETB(a_candAddr))
3885             candSubnet = a_candAddr & IN_CLASSB_SUBNET;
3886     } /*Class B target */
3887     else if (IN_CLASSC(a_targetAddr)) {
3888         if (!(IN_CLASSC(a_candAddr))) {
3889             (*a_diffNetworkP)++;
3890             return;
3891         }
3892         targetNet = a_targetAddr & IN_CLASSC_NET;
3893         candNet = a_candAddr & IN_CLASSC_NET;
3894
3895         /*
3896          * Note that class C addresses can't have subnets,
3897          * so we leave the defaults untouched.
3898          */
3899     } /*Class C target */
3900     else {
3901         targetNet = a_targetAddr;
3902         candNet = a_candAddr;
3903     }                           /*Class D address */
3904
3905     /*
3906      * Now, simply compare the extracted net and subnet values for
3907      * the two addresses (which at this point are known to be of the
3908      * same class)
3909      */
3910     if (targetNet == candNet) {
3911         if (targetSubnet == candSubnet)
3912             (*a_sameNetOrSubnetP)++;
3913         else
3914             (*a_diffSubnetP)++;
3915     } else
3916         (*a_diffNetworkP)++;
3917
3918 }                               /*h_ClassifyAddress */
3919
3920
3921 /*------------------------------------------------------------------------
3922  * EXPORTED h_GetHostNetStats
3923  *
3924  * Description:
3925  *      Iterate through the host table, and classify each (non-deleted)
3926  *      host entry into ``proximity'' categories (same net or subnet,
3927  *      different subnet, different network).
3928  *
3929  * Arguments:
3930  *      a_numHostsP        : Set to total number of (non-deleted) hosts.
3931  *      a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
3932  *      a_diffSubnetP      : Set to # hosts on diff subnet as server.
3933  *      a_diffNetworkP     : Set to # hosts on diff network as server.
3934  *
3935  * Returns:
3936  *      Nothing.
3937  *
3938  * Environment:
3939  *      We only count non-deleted hosts.  The storage pointed to by our
3940  *      parameters is zeroed upon entry.
3941  *
3942  * Side Effects:
3943  *      As advertised.
3944  *------------------------------------------------------------------------*/
3945
3946 void
3947 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
3948                   afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
3949 {                               /*h_GetHostNetStats */
3950
3951     struct host *hostP; /*Ptr to current host entry */
3952     afs_uint32 currAddr_HBO;    /*Curr host addr, host byte order */
3953     int count;
3954
3955     /*
3956      * Clear out the storage pointed to by our parameters.
3957      */
3958     *a_numHostsP = (afs_int32) 0;
3959     *a_sameNetOrSubnetP = (afs_int32) 0;
3960     *a_diffSubnetP = (afs_int32) 0;
3961     *a_diffNetworkP = (afs_int32) 0;
3962
3963     H_LOCK;
3964     for (count = 0, hostP = hostList; hostP && count < hostCount; hostP = hostP->z.next, count++) {
3965         if (!(hostP->z.hostFlags & HOSTDELETED)) {
3966             /*
3967              * Bump the number of undeleted host entries found.
3968              * In classifying the current entry's address, make
3969              * sure to first convert to host byte order.
3970              */
3971             (*a_numHostsP)++;
3972             currAddr_HBO = (afs_uint32) ntohl(hostP->z.host);
3973             h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
3974                               a_sameNetOrSubnetP, a_diffSubnetP,
3975                               a_diffNetworkP);
3976         }                       /*Only look at non-deleted hosts */
3977     }                           /*For each host record hashed to this index */
3978     if (count != hostCount) {
3979         ViceLog(0, ("h_GetHostNetStats found %d of %d hosts\n", count, hostCount));
3980     } else if (hostP != NULL) {
3981         ViceLog(0, ("h_GetHostNetStats found more than %d hosts\n", hostCount));
3982         ShutDownAndCore(PANIC);
3983     }
3984     H_UNLOCK;
3985 }                               /*h_GetHostNetStats */
3986
3987 static afs_uint32 checktime;
3988 static afs_uint32 clientdeletetime;
3989 static struct AFSFid zerofid;
3990
3991
3992 /*
3993  * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
3994  * Since it can serialize them, and pile up, it should be a separate LWP
3995  * from other events.
3996  */
3997
3998 int
3999 CheckHost_r(struct host *host, void *dummy)
4000 {
4001     struct client *client;
4002     struct rx_connection *cb_conn = NULL;
4003     int code;
4004
4005 #ifdef AFS_DEMAND_ATTACH_FS
4006     /* kill the checkhost lwp ASAP during shutdown */
4007     FS_STATE_RDLOCK;
4008     if (fs_state.mode == FS_MODE_SHUTDOWN) {
4009         FS_STATE_UNLOCK;
4010         return H_ENUMERATE_BAIL(0);
4011     }
4012     FS_STATE_UNLOCK;
4013 #endif
4014
4015     /* Host is held by h_Enumerate_r */
4016     for (client = host->z.FirstClient; client; client = client->z.next) {
4017         if (client->z.refCount == 0 && client->z.LastCall < clientdeletetime) {
4018             client->z.deleted = 1;
4019             host->z.hostFlags |= CLIENTDELETED;
4020         }
4021     }
4022     if (host->z.LastCall < checktime) {
4023         h_Lock_r(host);
4024         if (!(host->z.hostFlags & HOSTDELETED)) {
4025             host->z.hostFlags |= HWHO_INPROGRESS;
4026             cb_conn = host->z.callback_rxcon;
4027             rx_GetConnection(cb_conn);
4028             if (host->z.LastCall < clientdeletetime) {
4029                 host->z.hostFlags |= HOSTDELETED;
4030                 if (!(host->z.hostFlags & VENUSDOWN)) {
4031                     host->z.hostFlags &= ~ALTADDR;      /* alternate address invalid */
4032                     if (host->z.interface) {
4033                         H_UNLOCK;
4034                         code =
4035                             RXAFSCB_InitCallBackState3(cb_conn,
4036                                                        &FS_HostUUID);
4037                         H_LOCK;
4038                     } else {
4039                         H_UNLOCK;
4040                         code =
4041                             RXAFSCB_InitCallBackState(cb_conn);
4042                         H_LOCK;
4043                     }
4044                     host->z.hostFlags |= ALTADDR;       /* alternate addresses valid */
4045                     if (code) {
4046                         char hoststr[16];
4047                         (void)afs_inet_ntoa_r(host->z.host, hoststr);
4048                         ViceLog(0,
4049                                 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
4050                                  hoststr, ntohs(host->z.port)));
4051                         host->z.hostFlags |= VENUSDOWN;
4052                     }
4053                     /* Note:  it's safe to delete hosts even if they have call
4054                      * back state, because break delayed callbacks (called when a
4055                      * message is received from the workstation) will always send a
4056                      * break all call backs to the workstation if there is no
4057                      * callback.
4058                      */
4059                 }
4060             } else {
4061                 if (!(host->z.hostFlags & VENUSDOWN) && host->z.cblist) {
4062                     char hoststr[16];
4063                     (void)afs_inet_ntoa_r(host->z.host, hoststr);
4064                     if (host->z.interface) {
4065                         afsUUID uuid = host->z.interface->uuid;
4066                         H_UNLOCK;
4067                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
4068                         H_LOCK;
4069                         if (code) {
4070                             if (MultiProbeAlternateAddress_r(host)) {
4071                                 ViceLog(0,("CheckHost_r: Probing all interfaces of host %s:%d failed, code %d\n",
4072                                             hoststr, ntohs(host->z.port), code));
4073                                 host->z.hostFlags |= VENUSDOWN;
4074                             }
4075                         }
4076                     } else {
4077                         H_UNLOCK;
4078                         code = RXAFSCB_Probe(cb_conn);
4079                         H_LOCK;
4080                         if (code) {
4081                             ViceLog(0,
4082                                     ("CheckHost_r: Probe failed for host %s:%d, code %d\n",
4083                                      hoststr, ntohs(host->z.port), code));
4084                             host->z.hostFlags |= VENUSDOWN;
4085                         }
4086                     }
4087                 }
4088             }
4089             H_UNLOCK;
4090             rx_PutConnection(cb_conn);
4091             cb_conn=NULL;
4092             H_LOCK;
4093             host->z.hostFlags &= ~HWHO_INPROGRESS;
4094         }
4095         h_Unlock_r(host);
4096     }
4097     return 0;
4098
4099 }                               /*CheckHost_r */
4100
4101
4102 /*
4103  * Set VenusDown for any hosts that have not had a call in 15 minutes and
4104  * don't respond to a probe.  Note that VenusDown can only be cleared if
4105  * a message is received from the host (see ServerLWP in file.c).
4106  * Delete hosts that have not had any calls in 1 hour, clients that
4107  * have not had any calls in 15 minutes.
4108  *
4109  * This routine is called roughly every 5 minutes.
4110  */
4111 void
4112 h_CheckHosts(void)
4113 {
4114     afs_uint32 now = time(NULL);
4115
4116     memset(&zerofid, 0, sizeof(zerofid));
4117     /*
4118      * Send a probe to the workstation if it hasn't been heard from in
4119      * 15 minutes
4120      */
4121     checktime = now - 15 * 60;
4122     clientdeletetime = now - 120 * 60;  /* 2 hours ago */
4123
4124     H_LOCK;
4125     h_Enumerate_r(CheckHost_r, hostList, NULL);
4126     H_UNLOCK;
4127 }                               /*h_CheckHosts */
4128
4129 /*
4130  * This is called with host locked and held. At this point, the
4131  * hostAddrHashTable has an entry for the primary addr/port inserted
4132  * by h_Alloc_r().  No other interfaces should be considered valid.
4133  *
4134  * The addresses in the interfaceAddr list are in host byte order.
4135  */
4136 static int
4137 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
4138 {
4139     int i, j;
4140     int number, count;
4141     afs_uint32 myAddr;
4142     afs_uint16 myPort;
4143     int found;
4144     struct Interface *interface;
4145     char hoststr[16];
4146     char uuidstr[128];
4147     afs_uint16 port7001 = htons(7001);
4148
4149     opr_Assert(host);
4150     opr_Assert(interf);
4151
4152     number = interf->numberOfInterfaces;
4153     myAddr = host->z.host;      /* current interface address */
4154     myPort = host->z.port;      /* current port */
4155
4156     ViceLog(125,
4157             ("initInterfaceAddr : host %s:%d numAddr %d\n",
4158               afs_inet_ntoa_r(myAddr, hoststr), ntohs(myPort), number));
4159
4160     /* validation checks */
4161     if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
4162         ViceLog(0,
4163                 ("Invalid number of alternate addresses is %d\n", number));
4164         return -1;
4165     }
4166
4167     /*
4168      * The client's notion of its own IP addresses is not reliable.
4169      *
4170      * 1. The client list might contain private address ranges which
4171      *    are likely to be re-used by many clients allocated addresses
4172      *    by a NAT.
4173      *
4174      * 2. The client list will not include any public addresses that
4175      *    are hidden by a NAT.
4176      *
4177      * 3. Private address ranges that are exposed to the server will
4178      *    be obtained from the rx connections that use them.
4179      *
4180      * 4. Lists provided by the client are not necessarily truthful.
4181      *    Many existing clients (UNIX) do not refresh the IP address
4182      *    list as the actual assigned addresses change.  The end result
4183      *    is that they report the initial address list for the lifetime
4184      *    of the process.  In other words, a client can report addresses
4185      *    that they are in fact not using.  Adding these addresses to
4186      *    the host interface list without verification is not only
4187      *    pointless, it is downright dangerous.
4188      *
4189      * We therefore do not add alternate addresses to the addr hash table.
4190      * We only use them for multi-rx callback breaks.
4191      */
4192
4193     /*
4194      * Convert IP addresses to network byte order, and remove
4195      * duplicate and loopback IP addresses from the interface list, and
4196      * determine whether or not the incoming addr/port is
4197      * listed.  Note that if the address matches it is not
4198      * truly a match because the port number for the entries
4199      * in the interface list are port 7001 and the port number
4200      * for this connection might not be 7001.
4201      */
4202     for (i = 0, count = 0, found = 0; i < number; i++) {
4203         if (rx_IsLoopbackAddr(interf->addr_in[i])) {
4204             continue;
4205         }
4206         interf->addr_in[i] = htonl(interf->addr_in[i]);
4207         for (j = 0; j < count; j++) {
4208             if (interf->addr_in[j] == interf->addr_in[i])
4209                 break;
4210         }
4211         if (j == count) {
4212             interf->addr_in[count] = interf->addr_in[i];
4213             if (interf->addr_in[count] == myAddr &&
4214                 port7001 == myPort)
4215                 found = 1;
4216             count++;
4217         }
4218     }
4219
4220     /*
4221      * Allocate and initialize an interface structure for this host.
4222      */
4223     if (found) {
4224         interface = malloc(sizeof(struct Interface) +
4225                            (sizeof(struct AddrPort) * (count - 1)));
4226         if (!interface) {
4227             ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 1\n"));
4228         }
4229         interface->numberOfInterfaces = count;
4230     } else {
4231         interface = malloc(sizeof(struct Interface) +
4232                            (sizeof(struct AddrPort) * count));
4233         if (!interface) {
4234             ViceLogThenPanic(0, ("Failed malloc in initInterfaceAddr_r 2\n"));
4235         }
4236         interface->numberOfInterfaces = count + 1;
4237         interface->interface[count].addr = myAddr;
4238         interface->interface[count].port = myPort;
4239         interface->interface[count].valid = 1;
4240     }
4241
4242     for (i = 0; i < count; i++) {
4243
4244         interface->interface[i].addr = interf->addr_in[i];
4245         /* We store the port as 7001 because the addresses reported by
4246          * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
4247          * are coming from fully connected hosts (no NAT/PATs)
4248          */
4249         interface->interface[i].port = port7001;
4250         interface->interface[i].valid =
4251             (interf->addr_in[i] == myAddr && port7001 == myPort) ? 1 : 0;
4252     }
4253
4254     interface->uuid = interf->uuid;
4255
4256     opr_Assert(!host->z.interface);
4257     host->z.interface = interface;
4258
4259     h_AddHostToUuidHashTable_r(&interface->uuid, host);
4260
4261     if (GetLogLevel() >= 125) {
4262         afsUUID_to_string(&interface->uuid, uuidstr, 127);
4263
4264         ViceLog(125, ("--- uuid %s\n", uuidstr));
4265         for (i = 0; i < host->z.interface->numberOfInterfaces; i++) {
4266             ViceLog(125, ("--- alt address %s:%d\n",
4267                           afs_inet_ntoa_r(host->z.interface->interface[i].addr, hoststr),
4268                           ntohs(host->z.interface->interface[i].port)));
4269         }
4270     }
4271
4272     return 0;
4273 }
4274
4275 /* deleted a HashChain structure for this address and host */
4276 /* returns 1 on success */
4277 int
4278 h_DeleteHostFromAddrHashTable_r(afs_uint32 addr, afs_uint16 port,
4279                                 struct host *host)
4280 {
4281     char hoststr[16];
4282     struct h_AddrHashChain **hp, *th;
4283
4284     if (addr == 0 && port == 0)
4285         return 1;
4286
4287     for (hp = &hostAddrHashTable[h_HashIndex(addr)]; (th = *hp);
4288          hp = &th->next) {
4289         opr_Assert(th->hostPtr);
4290         if (th->hostPtr == host && th->addr == addr && th->port == port) {
4291             ViceLog(125, ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d)\n",
4292                           host, afs_inet_ntoa_r(host->z.host, hoststr),
4293                           ntohs(host->z.port)));
4294             *hp = th->next;
4295             free(th);
4296             return 1;
4297         }
4298     }
4299     ViceLog(125,
4300             ("h_DeleteHostFromAddrHashTable_r: host %" AFS_PTR_FMT " (%s:%d) not found\n",
4301              host, afs_inet_ntoa_r(host->z.host, hoststr),
4302              ntohs(host->z.port)));
4303     return 0;
4304 }
4305
4306
4307 /*
4308 ** prints out all alternate interface address for the host. The 'level'
4309 ** parameter indicates what level of debugging sets this output
4310 */
4311 void
4312 printInterfaceAddr(struct host *host, int level)
4313 {
4314     int i, number;
4315     char hoststr[16];
4316
4317     if (host->z.interface) {
4318         /* check alternate addresses */
4319         number = host->z.interface->numberOfInterfaces;
4320         if (number == 0) {
4321             ViceLog(level, ("no-addresses "));
4322         } else {
4323             for (i = 0; i < number; i++)
4324                 ViceLog(level, ("%s:%d ",
4325                     afs_inet_ntoa_r(host->z.interface->interface[i].addr,
4326                         hoststr),
4327                     ntohs(host->z.interface->interface[i].port)));
4328         }
4329     }
4330     ViceLog(level, ("\n"));
4331 }