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