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