viced-client-cps-race-fix-20060220
[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
10 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 RCSID
14     ("$Header$");
15
16 #include <stdio.h>
17 #include <errno.h>
18 #ifdef AFS_NT40_ENV
19 #include <fcntl.h>
20 #include <winsock2.h>
21 #else
22 #include <sys/file.h>
23 #include <netdb.h>
24 #include <netinet/in.h>
25 #endif
26
27 #ifdef HAVE_STRING_H
28 #include <string.h>
29 #else
30 #ifdef HAVE_STRINGS_H
31 #include <strings.h>
32 #endif
33 #endif
34
35 #include <afs/stds.h>
36 #include <rx/xdr.h>
37 #include <afs/assert.h>
38 #include <lwp.h>
39 #include <lock.h>
40 #include <afs/afsint.h>
41 #include <afs/rxgen_consts.h>
42 #include <afs/nfs.h>
43 #include <afs/errors.h>
44 #include <afs/ihandle.h>
45 #include <afs/vnode.h>
46 #include <afs/volume.h>
47 #ifdef AFS_ATHENA_STDENV
48 #include <krb.h>
49 #endif
50 #include <afs/acl.h>
51 #include <afs/ptclient.h>
52 #include <afs/prs_fs.h>
53 #include <afs/auth.h>
54 #include <afs/afsutil.h>
55 #include <rx/rx.h>
56 #include <afs/cellconfig.h>
57 #include <stdlib.h>
58 #include "viced_prototypes.h"
59 #include "viced.h"
60 #include "host.h"
61
62
63 #ifdef AFS_PTHREAD_ENV
64 pthread_mutex_t host_glock_mutex;
65 #endif /* AFS_PTHREAD_ENV */
66
67 extern int Console;
68 extern int CurrentConnections;
69 extern int SystemId;
70 extern int AnonymousID;
71 extern prlist AnonCPS;
72 extern int LogLevel;
73 extern struct afsconf_dir *confDir;     /* config dir object */
74 extern int lwps;                /* the max number of server threads */
75 extern afsUUID FS_HostUUID;
76
77 int CEs = 0;                    /* active clients */
78 int CEBlocks = 0;               /* number of blocks of CEs */
79 struct client *CEFree = 0;      /* first free client */
80 struct host *hostList = 0;      /* linked list of all hosts */
81 int hostCount = 0;              /* number of hosts in hostList */
82 int rxcon_ident_key;
83 int rxcon_client_key;
84
85 #define CESPERBLOCK 73
86 struct CEBlock {                /* block of CESPERBLOCK file entries */
87     struct client entry[CESPERBLOCK];
88 };
89
90 static void h_TossStuff_r(register struct host *host);
91 static int hashDelete_r(afs_uint32 addr, afs_uint16 port, struct host *host);
92
93 /*
94  * Make sure the subnet macros have been defined.
95  */
96 #ifndef IN_SUBNETA
97 #define IN_SUBNETA(i)           ((((afs_int32)(i))&0x80800000)==0x00800000)
98 #endif
99
100 #ifndef IN_CLASSA_SUBNET
101 #define IN_CLASSA_SUBNET        0xffff0000
102 #endif
103
104 #ifndef IN_SUBNETB
105 #define IN_SUBNETB(i)           ((((afs_int32)(i))&0xc0008000)==0x80008000)
106 #endif
107
108 #ifndef IN_CLASSB_SUBNET
109 #define IN_CLASSB_SUBNET        0xffffff00
110 #endif
111
112
113 /* get a new block of CEs and chain it on CEFree */
114 static void
115 GetCEBlock()
116 {
117     register struct CEBlock *block;
118     register int i;
119
120     block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
121     if (!block) {
122         ViceLog(0, ("Failed malloc in GetCEBlock\n"));
123         ShutDownAndCore(PANIC);
124     }
125
126     for (i = 0; i < (CESPERBLOCK - 1); i++) {
127         Lock_Init(&block->entry[i].lock);
128         block->entry[i].next = &(block->entry[i + 1]);
129     }
130     block->entry[CESPERBLOCK - 1].next = 0;
131     Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
132     CEFree = (struct client *)block;
133     CEBlocks++;
134
135 }                               /*GetCEBlock */
136
137
138 /* get the next available CE */
139 static struct client *
140 GetCE()
141 {
142     register struct client *entry;
143
144     if (CEFree == 0)
145         GetCEBlock();
146     if (CEFree == 0) {
147         ViceLog(0, ("CEFree NULL in GetCE\n"));
148         ShutDownAndCore(PANIC);
149     }
150
151     entry = CEFree;
152     CEFree = entry->next;
153     CEs++;
154     memset((char *)entry, 0, CLIENT_TO_ZERO(entry));
155     return (entry);
156
157 }                               /*GetCE */
158
159
160 /* return an entry to the free list */
161 static void
162 FreeCE(register struct client *entry)
163 {
164     entry->next = CEFree;
165     CEFree = entry;
166     CEs--;
167
168 }                               /*FreeCE */
169
170 /*
171  * The HTs and HTBlocks variables were formerly static, but they are
172  * now referenced elsewhere in the FileServer.
173  */
174 int HTs = 0;                    /* active file entries */
175 int HTBlocks = 0;               /* number of blocks of HTs */
176 static struct host *HTFree = 0; /* first free file entry */
177
178 /*
179  * Hash tables of host pointers. We need two tables, one
180  * to map IP addresses onto host pointers, and another
181  * to map host UUIDs onto host pointers.
182  */
183 static struct h_hashChain *hostHashTable[h_HASHENTRIES];
184 static struct h_hashChain *hostUuidHashTable[h_HASHENTRIES];
185 #define h_HashIndex(hostip) ((hostip) & (h_HASHENTRIES-1))
186 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
187
188 struct HTBlock {                /* block of HTSPERBLOCK file entries */
189     struct host entry[h_HTSPERBLOCK];
190 };
191
192
193 /* get a new block of HTs and chain it on HTFree */
194 static void
195 GetHTBlock()
196 {
197     register struct HTBlock *block;
198     register int i;
199     static int index = 0;
200
201     block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
202     if (!block) {
203         ViceLog(0, ("Failed malloc in GetHTBlock\n"));
204         ShutDownAndCore(PANIC);
205     }
206 #ifdef AFS_PTHREAD_ENV
207     for (i = 0; i < (h_HTSPERBLOCK); i++)
208         assert(pthread_cond_init(&block->entry[i].cond, NULL) == 0);
209 #endif /* AFS_PTHREAD_ENV */
210     for (i = 0; i < (h_HTSPERBLOCK); i++)
211         Lock_Init(&block->entry[i].lock);
212     for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
213         block->entry[i].next = &(block->entry[i + 1]);
214     for (i = 0; i < (h_HTSPERBLOCK); i++)
215         block->entry[i].index = index++;
216     block->entry[h_HTSPERBLOCK - 1].next = 0;
217     HTFree = (struct host *)block;
218     hosttableptrs[HTBlocks++] = block->entry;
219
220 }                               /*GetHTBlock */
221
222
223 /* get the next available HT */
224 static struct host *
225 GetHT()
226 {
227     register struct host *entry;
228
229     if (HTFree == 0)
230         GetHTBlock();
231     assert(HTFree != 0);
232     entry = HTFree;
233     HTFree = entry->next;
234     HTs++;
235     memset((char *)entry, 0, HOST_TO_ZERO(entry));
236     return (entry);
237
238 }                               /*GetHT */
239
240
241 /* return an entry to the free list */
242 static void
243 FreeHT(register struct host *entry)
244 {
245     entry->next = HTFree;
246     HTFree = entry;
247     HTs--;
248
249 }                               /*FreeHT */
250
251
252 static short consolePort = 0;
253
254 int
255 h_Release(register struct host *host)
256 {
257     H_LOCK;
258     h_Release_r(host);
259     H_UNLOCK;
260     return 0;
261 }
262
263 /**
264  * If this thread does not have a hold on this host AND
265  * if other threads also dont have any holds on this host AND
266  * If either the HOSTDELETED or CLIENTDELETED flags are set
267  * then toss the host
268  */
269 int
270 h_Release_r(register struct host *host)
271 {
272
273     if (!((host)->holds[h_holdSlot()] & ~h_holdbit())) {
274         if (!h_OtherHolds_r(host)) {
275             /* must avoid masking this until after h_OtherHolds_r runs
276              * but it should be run before h_TossStuff_r */
277             (host)->holds[h_holdSlot()] &= ~h_holdbit();
278             if ((host->hostFlags & HOSTDELETED)
279                 || (host->hostFlags & CLIENTDELETED)) {
280                 h_TossStuff_r(host);
281             }
282         } else
283             (host)->holds[h_holdSlot()] &= ~h_holdbit();
284     } else
285         (host)->holds[h_holdSlot()] &= ~h_holdbit();
286
287     return 0;
288 }
289
290 int
291 h_OtherHolds_r(register struct host *host)
292 {
293     register int i, bit, slot;
294     bit = h_holdbit();
295     slot = h_holdSlot();
296     for (i = 0; i < h_maxSlots; i++) {
297         if (host->holds[i] != ((i == slot) ? bit : 0)) {
298             return 1;
299         }
300     }
301     return 0;
302 }
303
304 int
305 h_Lock_r(register struct host *host)
306 {
307     H_UNLOCK;
308     h_Lock(host);
309     H_LOCK;
310     return 0;
311 }
312
313 /**
314   * Non-blocking lock
315   * returns 1 if already locked
316   * else returns locks and returns 0
317   */
318
319 int
320 h_NBLock_r(register struct host *host)
321 {
322     struct Lock *hostLock = &host->lock;
323     int locked = 0;
324
325     H_UNLOCK;
326     LOCK_LOCK(hostLock);
327     if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
328         hostLock->excl_locked = WRITE_LOCK;
329     else
330         locked = 1;
331
332     LOCK_UNLOCK(hostLock);
333     H_LOCK;
334     if (locked)
335         return 1;
336     else
337         return 0;
338 }
339
340
341 #if FS_STATS_DETAILED
342 /*------------------------------------------------------------------------
343  * PRIVATE h_AddrInSameNetwork
344  *
345  * Description:
346  *      Given a target IP address and a candidate IP address (both
347  *      in host byte order), return a non-zero value (1) if the
348  *      candidate address is in a different network from the target
349  *      address.
350  *
351  * Arguments:
352  *      a_targetAddr       : Target address.
353  *      a_candAddr         : Candidate address.
354  *
355  * Returns:
356  *      1 if the candidate address is in the same net as the target,
357  *      0 otherwise.
358  *
359  * Environment:
360  *      The target and candidate addresses are both in host byte
361  *      order, NOT network byte order, when passed in.  We return
362  *      our value as a character, since that's the type of field in
363  *      the host structure, where this info will be stored.
364  *
365  * Side Effects:
366  *      As advertised.
367  *------------------------------------------------------------------------*/
368
369 static char
370 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
371 {                               /*h_AddrInSameNetwork */
372
373     afs_uint32 targetNet;
374     afs_uint32 candNet;
375
376     /*
377      * Pull out the network and subnetwork numbers from the target
378      * and candidate addresses.  We can short-circuit this whole
379      * affair if the target and candidate addresses are not of the
380      * same class.
381      */
382     if (IN_CLASSA(a_targetAddr)) {
383         if (!(IN_CLASSA(a_candAddr))) {
384             return (0);
385         }
386         targetNet = a_targetAddr & IN_CLASSA_NET;
387         candNet = a_candAddr & IN_CLASSA_NET;
388     } else if (IN_CLASSB(a_targetAddr)) {
389         if (!(IN_CLASSB(a_candAddr))) {
390             return (0);
391         }
392         targetNet = a_targetAddr & IN_CLASSB_NET;
393         candNet = a_candAddr & IN_CLASSB_NET;
394     } /*Class B target */
395     else if (IN_CLASSC(a_targetAddr)) {
396         if (!(IN_CLASSC(a_candAddr))) {
397             return (0);
398         }
399         targetNet = a_targetAddr & IN_CLASSC_NET;
400         candNet = a_candAddr & IN_CLASSC_NET;
401     } /*Class C target */
402     else {
403         targetNet = a_targetAddr;
404         candNet = a_candAddr;
405     }                           /*Class D address */
406
407     /*
408      * Now, simply compare the extracted net values for the two addresses
409      * (which at this point are known to be of the same class)
410      */
411     if (targetNet == candNet)
412         return (1);
413     else
414         return (0);
415
416 }                               /*h_AddrInSameNetwork */
417 #endif /* FS_STATS_DETAILED */
418
419
420 /* Assumptions: called with held host */
421 void
422 h_gethostcps_r(register struct host *host, register afs_int32 now)
423 {
424     register int code;
425     int slept = 0;
426
427     /* wait if somebody else is already doing the getCPS call */
428     while (host->hostFlags & HCPS_INPROGRESS) {
429         slept = 1;              /* I did sleep */
430         host->hostFlags |= HCPS_WAITING;        /* I am sleeping now */
431 #ifdef AFS_PTHREAD_ENV
432         pthread_cond_wait(&host->cond, &host_glock_mutex);
433 #else /* AFS_PTHREAD_ENV */
434         if ((code = LWP_WaitProcess(&(host->hostFlags))) != LWP_SUCCESS)
435             ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
436 #endif /* AFS_PTHREAD_ENV */
437     }
438
439
440     host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
441     if (host->hcps.prlist_val)
442         free(host->hcps.prlist_val);    /* this is for hostaclRefresh */
443     host->hcps.prlist_val = NULL;
444     host->hcps.prlist_len = 0;
445     slept ? (host->cpsCall = FT_ApproxTime()) : (host->cpsCall = now);
446
447     H_UNLOCK;
448     code = pr_GetHostCPS(htonl(host->host), &host->hcps);
449     H_LOCK;
450     if (code) {
451         /*
452          * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
453          * and reevaluates things if no sync server or quorum is found we could still end up
454          * with one of these errors. In such case we would like to reevaluate the rpc call to
455          * find if there's cps for this guy. We treat other errors (except network failures
456          * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
457          * we could like to deal this problem the other way around (i.e. if code == NOCPS 
458          * ignore else retry next time) but the problem is that there're other errors (i.e.
459          * EPERM) for which we don't want to retry and we don't know the whole code list!
460          */
461         if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
462             /* 
463              * We would have preferred to use a while loop and try again since ops in protected
464              * acls for this host will fail now but they'll be reevaluated on any subsequent
465              * call. The attempt to wait for a quorum/sync site or network error won't work
466              * since this problems really should only occurs during a complete fileserver 
467              * restart. Since the fileserver will start before the ptservers (and thus before
468              * quorums are complete) clients will be utilizing all the fileserver's lwps!!
469              */
470             host->hcpsfailed = 1;
471             ViceLog(0,
472                     ("Warning:  GetHostCPS failed (%d) for %x; will retry\n",
473                      code, host->host));
474         } else {
475             host->hcpsfailed = 0;
476             ViceLog(1,
477                     ("gethost:  GetHostCPS failed (%d) for %x; ignored\n",
478                      code, host->host));
479         }
480         if (host->hcps.prlist_val)
481             free(host->hcps.prlist_val);
482         host->hcps.prlist_val = NULL;
483         host->hcps.prlist_len = 0;      /* Make sure it's zero */
484     } else
485         host->hcpsfailed = 0;
486
487     host->hostFlags &= ~HCPS_INPROGRESS;
488     /* signal all who are waiting */
489     if (host->hostFlags & HCPS_WAITING) {       /* somebody is waiting */
490         host->hostFlags &= ~HCPS_WAITING;
491 #ifdef AFS_PTHREAD_ENV
492         assert(pthread_cond_broadcast(&host->cond) == 0);
493 #else /* AFS_PTHREAD_ENV */
494         if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
495             ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
496 #endif /* AFS_PTHREAD_ENV */
497     }
498 }
499
500 /* args in net byte order */
501 void
502 h_flushhostcps(register afs_uint32 hostaddr, register afs_uint32 hport)
503 {
504     register struct host *host;
505     int held = 0;
506
507     H_LOCK;
508     host = h_Lookup_r(hostaddr, hport, &held);
509     if (host) {
510         host->hcpsfailed = 1;
511         if (!held)
512             h_Release_r(host);
513     }
514     H_UNLOCK;
515     return;
516 }
517
518
519 /*
520  * Allocate a host.  It will be identified by the peer (ip,port) info in the
521  * rx connection provided.  The host is returned held and locked
522  */
523 #define DEF_ROPCONS 2115
524
525 struct host *
526 h_Alloc_r(register struct rx_connection *r_con)
527 {
528     struct servent *serverentry;
529     register index = h_HashIndex(rxr_HostOf(r_con));
530     register struct host *host;
531     static struct rx_securityClass *sc = 0;
532     afs_int32 now;
533     struct h_hashChain *h_hashChain;
534 #if FS_STATS_DETAILED
535     afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
536 #endif /* FS_STATS_DETAILED */
537
538     host = GetHT();
539
540     h_hashChain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
541     if (!h_hashChain) {
542         ViceLog(0, ("Failed malloc in h_Alloc_r\n"));
543         assert(0);
544     }
545     h_hashChain->hostPtr = host;
546     h_hashChain->addr = rxr_HostOf(r_con);
547     h_hashChain->next = hostHashTable[index];
548     hostHashTable[index] = h_hashChain;
549
550     host->host = rxr_HostOf(r_con);
551     host->port = rxr_PortOf(r_con);
552     if (consolePort == 0) {     /* find the portal number for console */
553 #if     defined(AFS_OSF_ENV)
554         serverentry = getservbyname("ropcons", "");
555 #else
556         serverentry = getservbyname("ropcons", 0);
557 #endif
558         if (serverentry)
559             consolePort = serverentry->s_port;
560         else
561             consolePort = htons(DEF_ROPCONS);   /* Use a default */
562     }
563     if (host->port == consolePort)
564         host->Console = 1;
565     /* Make a callback channel even for the console, on the off chance that it
566      * makes a request that causes a break call back.  It shouldn't. */
567     {
568         if (!sc)
569             sc = rxnull_NewClientSecurityObject();
570         host->callback_rxcon =
571             rx_NewConnection(host->host, host->port, 1, sc, 0);
572         rx_SetConnDeadTime(host->callback_rxcon, 50);
573         rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
574     }
575     now = host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
576     host->hostFlags = 0;
577     host->hcps.prlist_val = NULL;
578     host->hcps.prlist_len = 0;
579     host->interface = 0;
580 #ifdef undef
581     host->hcpsfailed = 0;       /* save cycles */
582     h_gethostcps(host);         /* do this under host hold/lock */
583 #endif
584     host->FirstClient = 0;
585     h_Hold_r(host);
586     h_Lock_r(host);
587     h_InsertList_r(host);       /* update global host List */
588 #if FS_STATS_DETAILED
589     /*
590      * Compare the new host's IP address (in host byte order) with ours
591      * (the File Server's), remembering if they are in the same network.
592      */
593     newHostAddr_HBO = (afs_uint32) ntohl(host->host);
594     host->InSameNetwork =
595         h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
596 #endif /* FS_STATS_DETAILED */
597     return host;
598
599 }                               /*h_Alloc_r */
600
601
602 /* Lookup a host given an IP address and UDP port number. */
603 /* hostaddr and hport are in network order */
604 /* Note: host should be released by caller if 0 == *heldp and non-null */
605 /* hostaddr and hport are in network order */
606 struct host *
607 h_Lookup_r(afs_uint32 haddr, afs_uint32 hport, int *heldp)
608 {
609     register afs_int32 now;
610     register struct host *host = 0;
611     register struct h_hashChain *chain;
612     register index = h_HashIndex(haddr);
613     extern int hostaclRefresh;
614
615   restart:
616     for (chain = hostHashTable[index]; chain; chain = chain->next) {
617         host = chain->hostPtr;
618         assert(host);
619         if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
620             && chain->port == hport) {
621             *heldp = h_Held_r(host);
622             if (!*heldp)
623                 h_Hold_r(host);
624             h_Lock_r(host);
625             if (host->hostFlags & HOSTDELETED) {
626                 h_Unlock_r(host);
627                 if (!*heldp)
628                     h_Release_r(host);
629                 goto restart;
630             }
631             h_Unlock_r(host);
632             now = FT_ApproxTime();      /* always evaluate "now" */
633             if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
634                 /*
635                  * Every hostaclRefresh period (def 2 hrs) get the new
636                  * membership list for the host.  Note this could be the
637                  * first time that the host is added to a group.  Also
638                  * here we also retry on previous legitimate hcps failures.
639                  *
640                  * If we get here we still have a host hold.
641                  */
642                 h_gethostcps_r(host, now);
643             }
644             break;
645         }
646         host = NULL;
647     }
648     return host;
649
650 }                               /*h_Lookup */
651
652 /* Lookup a host given its UUID. */
653 struct host *
654 h_LookupUuid_r(afsUUID * uuidp)
655 {
656     register struct host *host = 0;
657     register struct h_hashChain *chain;
658     register index = h_UuidHashIndex(uuidp);
659
660     for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
661         host = chain->hostPtr;
662         assert(host);
663         if (!(host->hostFlags & HOSTDELETED) && host->interface
664             && afs_uuid_equal(&host->interface->uuid, uuidp)) {
665             break;
666         }
667         host = NULL;
668     }
669     return host;
670
671 }                               /*h_Lookup */
672
673
674 /*
675  * h_Hold_r: Establish a hold by the current LWP on this host--the host
676  * or its clients will not be physically deleted until all holds have
677  * been released.
678  * NOTE: h_Hold_r is a macro defined in host.h.
679  */
680
681 /* h_TossStuff_r:  Toss anything in the host structure (the host or
682  * clients marked for deletion.  Called from h_Release_r ONLY.
683  * To be called, there must be no holds, and either host->deleted
684  * or host->clientDeleted must be set.
685  */
686 static void
687 h_TossStuff_r(register struct host *host)
688 {
689     register struct client **cp, *client;
690     int i;
691
692     /* if somebody still has this host held */
693     for (i = 0; (i < h_maxSlots) && (!(host)->holds[i]); i++);
694     if (i != h_maxSlots)
695         return;
696
697     /* if somebody still has this host locked */
698     if (h_NBLock_r(host) != 0) {
699         char hoststr[16];
700         ViceLog(0,
701                 ("Warning:  h_TossStuff_r failed; Host %s:%d was locked.\n",
702                  afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
703         return;
704     } else {
705         h_Unlock_r(host);
706     }
707
708     /* ASSUMPTION: rxi_FreeConnection() does not yield */
709     for (cp = &host->FirstClient; (client = *cp);) {
710         if ((host->hostFlags & HOSTDELETED) || client->deleted) {
711             if (client->refCount) {
712                 char hoststr[16];
713                 ViceLog(0,
714                         ("Warning: Host %s:%d client %x refcount %d while deleting, failing.\n",
715                          afs_inet_ntoa_r(host->host, hoststr),
716                          ntohs(host->port), client, client->refCount));
717                 /* This is the same thing we do if the host is locked */
718                 return;
719             }
720             /* We can't protect this without dropping the H_LOCK */
721             client->CPS.prlist_len = 0;
722             if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
723                 free(client->CPS.prlist_val);
724             client->CPS.prlist_val = NULL;
725             if (client->tcon) {
726                 rx_SetSpecific(client->tcon, rxcon_client_key, (void *)0);
727             }
728             CurrentConnections--;
729             *cp = client->next;
730             FreeCE(client);
731         } else
732             cp = &client->next;
733     }
734
735     /* We've just cleaned out all the deleted clients; clear the flag */
736     host->hostFlags &= ~CLIENTDELETED;
737
738     if (host->hostFlags & HOSTDELETED) {
739         register struct h_hashChain **hp, *th;
740         register struct rx_connection *rxconn;
741         afsUUID *uuidp;
742         struct AddrPort hostAddrPort;
743         int i;
744
745         if (host->Console & 1)
746             Console--;
747         if ((rxconn = host->callback_rxcon)) {
748             host->callback_rxcon = (struct rx_connection *)0;
749             /*
750              * If rx_DestroyConnection calls h_FreeConnection we will
751              * deadlock on the host_glock_mutex. Work around the problem
752              * by unhooking the client from the connection before
753              * destroying the connection.
754              */
755             client = rx_GetSpecific(rxconn, rxcon_client_key);
756             if (client && client->tcon == rxconn)
757                 client->tcon = NULL;
758             rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
759             rx_DestroyConnection(rxconn);
760         }
761         if (host->hcps.prlist_val)
762             free(host->hcps.prlist_val);
763         host->hcps.prlist_val = NULL;
764         host->hcps.prlist_len = 0;
765         DeleteAllCallBacks_r(host, 1);
766         host->hostFlags &= ~RESETDONE;  /* just to be safe */
767
768         /* if alternate addresses do not exist */
769         if (!(host->interface)) {
770             for (hp = &hostHashTable[h_HashIndex(host->host)]; (th = *hp);
771                  hp = &th->next) {
772                 assert(th->hostPtr);
773                 if (th->hostPtr == host) {
774                     *hp = th->next;
775                     h_DeleteList_r(host);
776                     FreeHT(host);
777                     free(th);
778                     break;
779                 }
780             }
781         } else {
782             /* delete all hash entries for the UUID */
783             uuidp = &host->interface->uuid;
784             for (hp = &hostUuidHashTable[h_UuidHashIndex(uuidp)]; (th = *hp);
785                  hp = &th->next) {
786                 assert(th->hostPtr);
787                 if (th->hostPtr == host) {
788                     *hp = th->next;
789                     free(th);
790                     break;
791                 }
792             }
793             /* delete all hash entries for alternate addresses */
794             assert(host->interface->numberOfInterfaces > 0);
795             for (i = 0; i < host->interface->numberOfInterfaces; i++) {
796                 hostAddrPort = host->interface->interface[i];
797
798                 for (hp = &hostHashTable[h_HashIndex(hostAddrPort.addr)]; (th = *hp);
799                      hp = &th->next) {
800                     assert(th->hostPtr);
801                     if (th->hostPtr == host) {
802                         *hp = th->next;
803                         free(th);
804                         break;
805                     }
806                 }
807             }
808             free(host->interface);
809             host->interface = NULL;
810             h_DeleteList_r(host);       /* remove host from global host List */
811             FreeHT(host);
812         }                       /* if alternate address exists */
813     }
814 }                               /*h_TossStuff_r */
815
816
817 /* Called by rx when a server connection disappears */
818 int
819 h_FreeConnection(struct rx_connection *tcon)
820 {
821     register struct client *client;
822
823     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
824     if (client) {
825         H_LOCK;
826         if (client->tcon == tcon)
827             client->tcon = (struct rx_connection *)0;
828         H_UNLOCK;
829     }
830     return 0;
831 }                               /*h_FreeConnection */
832
833
834 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
835  * system at the start of the enumeration (perhaps more).  Hosts may be deleted
836  * (have delete flag set); ditto for clients.  (*proc) is always called with
837  * host h_held().  The hold state of the host with respect to this lwp is passed
838  * to (*proc) as the param held.  The proc should return 0 if the host should be
839  * released, 1 if it should be held after enumeration.
840  */
841 void
842 h_Enumerate(int (*proc) (), char *param)
843 {
844     register struct host *host, **list;
845     register int *held;
846     register int i, count;
847
848     H_LOCK;
849     if (hostCount == 0) {
850         H_UNLOCK;
851         return;
852     }
853     list = (struct host **)malloc(hostCount * sizeof(struct host *));
854     if (!list) {
855         ViceLog(0, ("Failed malloc in h_Enumerate\n"));
856         assert(0);
857     }
858     held = (int *)malloc(hostCount * sizeof(int));
859     if (!held) {
860         ViceLog(0, ("Failed malloc in h_Enumerate\n"));
861         assert(0);
862     }
863     for (count = 0, host = hostList; host; host = host->next, count++) {
864         list[count] = host;
865         if (!(held[count] = h_Held_r(host)))
866             h_Hold_r(host);
867     }
868     assert(count == hostCount);
869     H_UNLOCK;
870     for (i = 0; i < count; i++) {
871         held[i] = (*proc) (list[i], held[i], param);
872         if (!held[i])
873             h_Release(list[i]); /* this might free up the host */
874     }
875     free((void *)list);
876     free((void *)held);
877 }                               /*h_Enumerate */
878
879 /* h_Enumerate_r (revised):
880  * Calls (*proc)(host, held, param) for each host in hostList, starting
881  * at enumstart
882  * Hosts may be deleted (have delete flag set); ditto for clients.
883  * (*proc) is always called with
884  * host h_held() and the global host lock (H_LOCK) locked.The hold state of the
885  * host with respect to this lwp is passed to (*proc) as the param held.
886  * The proc should return 0 if the host should be released, 1 if it should
887  * be held after enumeration.
888  */
889 void
890 h_Enumerate_r(int (*proc) (), struct host *enumstart, char *param)
891 {
892     register struct host *host, *next;
893     register int held, nheld;
894
895     if (hostCount == 0) {
896         return;
897     }
898     if (enumstart && !(held = h_Held_r(enumstart)))
899         h_Hold_r(enumstart); 
900     for (host = enumstart; host; host = next, held = nheld) {
901         held = (*proc) (host, held, param);
902         next = host->next;
903         if (next && !(nheld = h_Held_r(next)))
904             h_Hold_r(next);
905         if (!held)
906             h_Release_r(host); /* this might free up the host */
907     }
908 }                               /*h_Enumerate_r */
909
910 /* inserts a new HashChain structure corresponding to this UUID */
911 void
912 hashInsertUuid_r(struct afsUUID *uuid, struct host *host)
913 {
914     int index;
915     struct h_hashChain *chain;
916
917     /* hash into proper bucket */
918     index = h_UuidHashIndex(uuid);
919
920     /* insert into beginning of list for this bucket */
921     chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
922     if (!chain) {
923         ViceLog(0, ("Failed malloc in hashInsertUuid_r\n"));
924         assert(0);
925     }
926     assert(chain);
927     chain->hostPtr = host;
928     chain->next = hostUuidHashTable[index];
929     hostUuidHashTable[index] = chain;
930 }
931
932
933 /* inserts a new HashChain structure corresponding to this address */
934 void
935 hashInsert_r(afs_uint32 addr, afs_uint16 port, struct host *host)
936 {
937     int index;
938     struct h_hashChain *chain;
939
940     /* hash into proper bucket */
941     index = h_HashIndex(addr);
942
943     /* insert into beginning of list for this bucket */
944     chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
945     if (!chain) {
946         ViceLog(0, ("Failed malloc in hashInsert_r\n"));
947         assert(0);
948     }
949     chain->hostPtr = host;
950     chain->next = hostHashTable[index];
951     chain->addr = addr;
952     chain->port = port;
953     hostHashTable[index] = chain;
954
955 }
956
957 /*
958  * This is called with host locked and held. At this point, the
959  * hostHashTable should not be having entries for the alternate
960  * interfaces. This function has to insert these entries in the
961  * hostHashTable.
962  *
963  * All addresses are in network byte order.
964  */
965 int
966 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
967 {
968     int i;
969     int number;
970     int found;
971     struct Interface *interface;
972     char hoststr[16], hoststr2[16];
973
974     assert(host);
975     assert(host->interface);
976
977     ViceLog(125, ("addInterfaceAddr : host %s:d addr %s:%d\n", 
978                    afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), 
979                    afs_inet_ntoa_r(addr, hoststr2), ntohs(port)));
980
981     /*
982      * Make sure this address is on the list of known addresses
983      * for this host.
984      */
985     number = host->interface->numberOfInterfaces;
986     for (i = 0, found = 0; i < number && !found; i++) {
987         if (host->interface->interface[i].addr == addr &&
988             host->interface->interface[i].port == port)
989             found = 1;
990     }
991     if (!found) {
992         interface = (struct Interface *)
993             malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
994         if (!interface) {
995             ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
996             assert(0);
997         }
998         interface->numberOfInterfaces = number + 1;
999         interface->uuid = host->interface->uuid;
1000         for (i = 0; i < number; i++)
1001             interface->interface[i] = host->interface->interface[i];
1002         interface->interface[number].addr = addr;
1003         interface->interface[number].port = port;
1004         free(host->interface);
1005         host->interface = interface;
1006     }
1007
1008     /*
1009      * Create a hash table entry for this address
1010      */
1011     hashInsert_r(addr, port, host);
1012
1013     return 0;
1014 }
1015
1016
1017 /*
1018  * This is called with host locked and held. At this point, the
1019  * hostHashTable should not be having entries for the alternate
1020  * interfaces. This function has to insert these entries in the
1021  * hostHashTable.
1022  *
1023  * All addresses are in network byte order.
1024  */
1025 int
1026 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1027 {
1028     int i;
1029     int number;
1030     int found;
1031     struct Interface *interface;
1032     char hoststr[16], hoststr2[16];
1033
1034     assert(host);
1035     assert(host->interface);
1036
1037     ViceLog(125, ("removeInterfaceAddr : host %s:%d addr %s:%d\n", 
1038                    afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), 
1039                    afs_inet_ntoa_r(addr, hoststr2), ntohs(port)));
1040
1041     /*
1042      * Make sure this address is on the list of known addresses
1043      * for this host.
1044      */
1045     interface = host->interface;
1046     number = host->interface->numberOfInterfaces;
1047     for (i = 0, found = 0; i < number; i++) {
1048         if (interface->interface[i].addr == addr &&
1049             interface->interface[i].port == port) {
1050             found = 1;
1051             break;
1052         }
1053     }
1054     if (found) {
1055         number--;
1056         for (; i < number; i++) {
1057             interface->interface[i].addr = interface->interface[i+1].addr;
1058             interface->interface[i].port = interface->interface[i+1].port;
1059         }
1060         interface->numberOfInterfaces = number;
1061     }
1062
1063     /*
1064      * Remove the hash table entry for this address
1065      */
1066     hashDelete_r(addr, port, host);
1067
1068     return 0;
1069 }
1070
1071
1072 /* Host is returned held */
1073 struct host *
1074 h_GetHost_r(struct rx_connection *tcon)
1075 {
1076     struct host *host;
1077     struct host *oldHost;
1078     int code;
1079     int held, oheld;
1080     struct interfaceAddr interf;
1081     int interfValid = 0;
1082     struct Identity *identP = NULL;
1083     afs_int32 haddr;
1084     afs_int16 hport;
1085     char hoststr[16], hoststr2[16];
1086     Capabilities caps;
1087     struct rx_connection *cb_conn = NULL;
1088
1089     caps.Capabilities_val = NULL;
1090
1091     haddr = rxr_HostOf(tcon);
1092     hport = rxr_PortOf(tcon);
1093   retry:
1094     if (caps.Capabilities_val)
1095         free(caps.Capabilities_val);
1096     caps.Capabilities_val = NULL;
1097     caps.Capabilities_len = 0;
1098
1099     code = 0;
1100     host = h_Lookup_r(haddr, hport, &held);
1101     identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1102     if (host && !identP && !(host->Console & 1)) {
1103         /* This is a new connection, and we already have a host
1104          * structure for this address. Verify that the identity
1105          * of the caller matches the identity in the host structure.
1106          */
1107         h_Lock_r(host);
1108         if (!(host->hostFlags & ALTADDR)) {
1109             /* Another thread is doing initialization */
1110             h_Unlock_r(host);
1111             if (!held)
1112                 h_Release_r(host);
1113             ViceLog(125,
1114                     ("Host %s:%d starting h_Lookup again\n",
1115                      afs_inet_ntoa_r(host->host, hoststr),
1116                      ntohs(host->port)));
1117             goto retry;
1118         }
1119         host->hostFlags &= ~ALTADDR;
1120         cb_conn = host->callback_rxcon;
1121         rx_GetConnection(cb_conn);
1122         H_UNLOCK;
1123         code =
1124             RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1125         if (code == RXGEN_OPCODE)
1126             code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1127         rx_PutConnection(cb_conn);
1128         cb_conn=NULL;
1129         H_LOCK;
1130         if (code == RXGEN_OPCODE) {
1131             identP = (struct Identity *)malloc(sizeof(struct Identity));
1132             if (!identP) {
1133                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1134                 assert(0);
1135             }
1136             identP->valid = 0;
1137             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1138             /* The host on this connection was unable to respond to 
1139              * the WhoAreYou. We will treat this as a new connection
1140              * from the existing host. The worst that can happen is
1141              * that we maintain some extra callback state information */
1142             if (host->interface) {
1143                 ViceLog(0,
1144                         ("Host %s:%d used to support WhoAreYou, deleting.\n",
1145                          afs_inet_ntoa_r(host->host, hoststr),
1146                          ntohs(host->port)));
1147                 host->hostFlags |= HOSTDELETED;
1148                 h_Unlock_r(host);
1149                 if (!held)
1150                     h_Release_r(host);
1151                 host = NULL;
1152                 goto retry;
1153             }
1154         } else if (code == 0) {
1155             interfValid = 1;
1156             identP = (struct Identity *)malloc(sizeof(struct Identity));
1157             if (!identP) {
1158                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1159                 assert(0);
1160             }
1161             identP->valid = 1;
1162             identP->uuid = interf.uuid;
1163             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1164             /* Check whether the UUID on this connection matches
1165              * the UUID in the host structure. If they don't match
1166              * then this is not the same host as before. */
1167             if (!host->interface
1168                 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1169                 ViceLog(25,
1170                         ("Host %s:%d has changed its identity, deleting.\n",
1171                          afs_inet_ntoa_r(host->host, hoststr), host->port));
1172                 host->hostFlags |= HOSTDELETED;
1173                 h_Unlock_r(host);
1174                 if (!held)
1175                     h_Release_r(host);
1176                 host = NULL;
1177                 goto retry;
1178             }
1179         } else {
1180             afs_inet_ntoa_r(host->host, hoststr);
1181             ViceLog(0,
1182                     ("CB: WhoAreYou failed for %s:%d, error %d\n", hoststr,
1183                      ntohs(host->port), code));
1184             host->hostFlags |= VENUSDOWN;
1185         }
1186         if (caps.Capabilities_val
1187             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1188             host->hostFlags |= HERRORTRANS;
1189         else
1190             host->hostFlags &= ~(HERRORTRANS);
1191         host->hostFlags |= ALTADDR;
1192         h_Unlock_r(host);
1193     } else if (host) {
1194         if (!(host->hostFlags & ALTADDR)) {
1195             /* another thread is doing the initialisation */
1196             ViceLog(125,
1197                     ("Host %s:%d waiting for host-init to complete\n",
1198                      afs_inet_ntoa_r(host->host, hoststr),
1199                      ntohs(host->port)));
1200             h_Lock_r(host);
1201             h_Unlock_r(host);
1202             if (!held)
1203                 h_Release_r(host);
1204             ViceLog(125,
1205                     ("Host %s:%d starting h_Lookup again\n",
1206                      afs_inet_ntoa_r(host->host, hoststr),
1207                      ntohs(host->port)));
1208             goto retry;
1209         }
1210         /* We need to check whether the identity in the host structure
1211          * matches the identity on the connection. If they don't match
1212          * then treat this a new host. */
1213         if (!(host->Console & 1)
1214             && ((!identP->valid && host->interface)
1215                 || (identP->valid && !host->interface)
1216                 || (identP->valid
1217                     && !afs_uuid_equal(&identP->uuid,
1218                                        &host->interface->uuid)))) {
1219             char uuid1[128], uuid2[128];
1220             if (identP->valid)
1221                 afsUUID_to_string(&identP->uuid, uuid1, 127);
1222             if (host->interface)
1223                 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1224             ViceLog(0,
1225                     ("CB: new identity for host %s:%d, deleting(%x %x %s %s)\n",
1226                      afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1227                      identP->valid, host->interface,
1228                      identP->valid ? uuid1 : "",
1229                      host->interface ? uuid2 : ""));
1230
1231             /* The host in the cache is not the host for this connection */
1232             host->hostFlags |= HOSTDELETED;
1233             h_Unlock_r(host);
1234             if (!held)
1235                 h_Release_r(host);
1236             goto retry;
1237         }
1238     } else {
1239         host = h_Alloc_r(tcon); /* returned held and locked */
1240         h_gethostcps_r(host, FT_ApproxTime());
1241         if (!(host->Console & 1)) {
1242             int pident = 0;
1243             cb_conn = host->callback_rxcon;
1244             rx_GetConnection(cb_conn);
1245             H_UNLOCK;
1246             code =
1247                 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1248             if (code == RXGEN_OPCODE)
1249                 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1250             rx_PutConnection(cb_conn);
1251             cb_conn=NULL;
1252             H_LOCK;
1253             if (code == RXGEN_OPCODE) {
1254                 if (!identP)
1255                     identP =
1256                         (struct Identity *)malloc(sizeof(struct Identity));
1257                 else
1258                     pident = 1;
1259
1260                 if (!identP) {
1261                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1262                     assert(0);
1263                 }
1264                 identP->valid = 0;
1265                 if (!pident)
1266                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1267                 ViceLog(25,
1268                         ("Host %s:%d does not support WhoAreYou.\n",
1269                          afs_inet_ntoa_r(host->host, hoststr),
1270                          ntohs(host->port)));
1271                 code = 0;
1272             } else if (code == 0) {
1273                 if (!identP)
1274                     identP =
1275                         (struct Identity *)malloc(sizeof(struct Identity));
1276                 else
1277                     pident = 1;
1278
1279                 if (!identP) {
1280                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1281                     assert(0);
1282                 }
1283                 identP->valid = 1;
1284                 interfValid = 1;
1285                 identP->uuid = interf.uuid;
1286                 if (!pident)
1287                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1288                 ViceLog(25,
1289                         ("WhoAreYou success on %s:%d\n",
1290                          afs_inet_ntoa_r(host->host, hoststr),
1291                          ntohs(host->port)));
1292             }
1293             if (code == 0 && !identP->valid) {
1294                 cb_conn = host->callback_rxcon;
1295                 rx_GetConnection(cb_conn);
1296                 H_UNLOCK;
1297                 code = RXAFSCB_InitCallBackState(cb_conn);
1298                 rx_PutConnection(cb_conn);
1299                 cb_conn=NULL;
1300                 H_LOCK;
1301             } else if (code == 0) {
1302                 oldHost = h_LookupUuid_r(&identP->uuid);
1303                 if (oldHost) {
1304                     int probefail = 0;
1305
1306                     if (!(oheld = h_Held_r(oldHost)))
1307                         h_Hold_r(oldHost);
1308                     h_Lock_r(oldHost);
1309
1310                     if (oldHost->interface) {
1311                         afsUUID uuid = oldHost->interface->uuid;
1312                         cb_conn = oldHost->callback_rxcon;
1313                         rx_GetConnection(cb_conn);
1314                         rx_SetConnDeadTime(cb_conn, 2);
1315                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1316                         H_UNLOCK;
1317                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1318                         H_LOCK;
1319                         rx_SetConnDeadTime(cb_conn, 50);
1320                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1321                         rx_PutConnection(cb_conn);
1322                         cb_conn=NULL;
1323                         if (code && MultiProbeAlternateAddress_r(oldHost)) {
1324                             probefail = 1;
1325                         }
1326                     } else {
1327                         probefail = 1;
1328                     }
1329
1330                     if (probefail) {
1331                         /* The old host is either does not have a Uuid,
1332                          * is not responding to Probes, 
1333                          * or does not have a matching Uuid. 
1334                          * Delete it! */
1335                         oldHost->hostFlags |= HOSTDELETED;
1336                         h_Unlock_r(oldHost);
1337                         /* Let the holder be last release */
1338                         if (!oheld) {
1339                             h_Release_r(oldHost);
1340                         }
1341                         oldHost = NULL;
1342                     }
1343                 }
1344                 if (oldHost) {
1345                     /* This is a new address for an existing host. Update
1346                      * the list of interfaces for the existing host and
1347                      * delete the host structure we just allocated. */
1348                     if (oldHost->host != haddr || oldHost->port != hport) {
1349                         ViceLog(25,
1350                                 ("CB: new addr %s:%d for old host %s:%d\n",
1351                                   afs_inet_ntoa_r(haddr, hoststr),
1352                                   ntohs(hport), 
1353                                   afs_inet_ntoa_r(oldHost->host, hoststr2),
1354                                   ntohs(oldHost->port)));
1355                         if (oldHost->host == haddr) {
1356                             /* We have just been contacted by a client behind a NAT */
1357                             removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
1358                         } else {
1359                             int i, found;
1360                             struct Interface *interface = oldHost->interface;
1361                             int number = oldHost->interface->numberOfInterfaces;
1362                             for (i = 0, found = 0; i < number; i++) {
1363                                 if (interface->interface[i].addr == haddr &&
1364                                     interface->interface[i].port != hport) {
1365                                     found = 1;
1366                                     break;
1367                                 }
1368                             }
1369                             if (found) {
1370                                 /* We have just been contacted by a client that has been
1371                                  * seen from behind a NAT and at least one other address.
1372                                  */
1373                                 removeInterfaceAddr_r(oldHost, haddr, interface->interface[i].port);
1374                             }
1375                         }
1376                         addInterfaceAddr_r(oldHost, haddr, hport);
1377                         oldHost->host = haddr;
1378                         oldHost->port = hport;
1379                     }
1380                     host->hostFlags |= HOSTDELETED;
1381                     h_Unlock_r(host);
1382                     if (!held)
1383                         h_Release_r(host);
1384                     host = oldHost;
1385                 } else {
1386                     /* This really is a new host */
1387                     hashInsertUuid_r(&identP->uuid, host);
1388                     cb_conn = host->callback_rxcon;
1389                     rx_GetConnection(cb_conn);          
1390                     H_UNLOCK;
1391                     code =
1392                         RXAFSCB_InitCallBackState3(cb_conn,
1393                                                    &FS_HostUUID);
1394                     rx_PutConnection(cb_conn);
1395                     cb_conn=NULL;
1396                     H_LOCK;
1397                     if (code == 0) {
1398                         ViceLog(25,
1399                                 ("InitCallBackState3 success on %s:%d\n",
1400                                  afs_inet_ntoa_r(host->host, hoststr),
1401                                  ntohs(host->port)));
1402                         assert(interfValid == 1);
1403                         initInterfaceAddr_r(host, &interf);
1404                     }
1405                 }
1406             }
1407             if (code) {
1408                 afs_inet_ntoa_r(host->host, hoststr);
1409                 ViceLog(0,
1410                         ("CB: RCallBackConnectBack failed for %s:%d\n",
1411                          hoststr, ntohs(host->port)));
1412                 host->hostFlags |= VENUSDOWN;
1413             } else {
1414                 ViceLog(125,
1415                         ("CB: RCallBackConnectBack succeeded for %s:%d\n",
1416                          hoststr, ntohs(host->port)));
1417                 host->hostFlags |= RESETDONE;
1418             }
1419         }
1420         if (caps.Capabilities_val
1421             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1422             host->hostFlags |= HERRORTRANS;
1423         else
1424             host->hostFlags &= ~(HERRORTRANS);
1425         host->hostFlags |= ALTADDR;     /* host structure initialization complete */
1426         h_Unlock_r(host);
1427     }
1428     if (caps.Capabilities_val)
1429         free(caps.Capabilities_val);
1430     caps.Capabilities_val = NULL;
1431     caps.Capabilities_len = 0;
1432     return host;
1433
1434 }                               /*h_GetHost_r */
1435
1436
1437 static char localcellname[PR_MAXNAMELEN + 1];
1438 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
1439 int  num_lrealms = -1;
1440
1441 /* not reentrant */
1442 void
1443 h_InitHostPackage()
1444 {
1445     afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
1446     if (num_lrealms == -1) {
1447         int i;
1448         for (i=0; i<AFS_NUM_LREALMS; i++) {
1449             if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
1450                 break;
1451         }
1452
1453         if (i=0) {
1454             ViceLog(0,
1455                     ("afs_krb_get_lrealm failed, using %s.\n",
1456                      localcellname));
1457             strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
1458             num_lrealms = i =1;
1459         } else {
1460             num_lrealms = i;
1461         }
1462
1463         /* initialize the rest of the local realms to nullstring for debugging */
1464         for (; i<AFS_NUM_LREALMS; i++)
1465             local_realms[i][0] = '\0';
1466     }
1467     rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
1468     rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
1469 #ifdef AFS_PTHREAD_ENV
1470     assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
1471 #endif /* AFS_PTHREAD_ENV */
1472 }
1473
1474 static int
1475 MapName_r(char *aname, char *acell, afs_int32 * aval)
1476 {
1477     namelist lnames;
1478     idlist lids;
1479     afs_int32 code;
1480     afs_int32 anamelen, cnamelen;
1481     int foreign = 0;
1482     char *tname;
1483
1484     anamelen = strlen(aname);
1485     if (anamelen >= PR_MAXNAMELEN)
1486         return -1;              /* bad name -- caller interprets this as anonymous, but retries later */
1487
1488     lnames.namelist_len = 1;
1489     lnames.namelist_val = (prname *) aname;     /* don't malloc in the common case */
1490     lids.idlist_len = 0;
1491     lids.idlist_val = NULL;
1492
1493     cnamelen = strlen(acell);
1494     if (cnamelen) {
1495         if (afs_is_foreign_ticket_name(aname, "", acell, localcellname)) {
1496             ViceLog(2,
1497                     ("MapName: cell is foreign.  cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
1498                     acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
1499             if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
1500                 ViceLog(2,
1501                         ("MapName: Name too long, using AnonymousID for %s@%s\n",
1502                          aname, acell));
1503                 *aval = AnonymousID;
1504                 return 0;
1505             }
1506             foreign = 1;        /* attempt cross-cell authentication */
1507             tname = (char *)malloc(PR_MAXNAMELEN);
1508             if (!tname) {
1509                 ViceLog(0, ("Failed malloc in MapName_r\n"));
1510                 assert(0);
1511             }
1512             strcpy(tname, aname);
1513             tname[anamelen] = '@';
1514             strcpy(tname + anamelen + 1, acell);
1515             lnames.namelist_val = (prname *) tname;
1516         }
1517     }
1518
1519     H_UNLOCK;
1520     code = pr_NameToId(&lnames, &lids);
1521     H_LOCK;
1522     if (code == 0) {
1523         if (lids.idlist_val) {
1524             *aval = lids.idlist_val[0];
1525             if (*aval == AnonymousID) {
1526                 ViceLog(2,
1527                         ("MapName: NameToId on %s returns anonymousID\n",
1528                          lnames.namelist_val));
1529             }
1530             free(lids.idlist_val);      /* return parms are not malloced in stub if server proc aborts */
1531         } else {
1532             ViceLog(0,
1533                     ("MapName: NameToId on '%s' is unknown\n",
1534                      lnames.namelist_val));
1535             code = -1;
1536         }
1537     }
1538
1539     if (foreign) {
1540         free(lnames.namelist_val);      /* We allocated this above, so we must free it now. */
1541     }
1542     return code;
1543 }
1544
1545 /*MapName*/
1546
1547
1548 /* NOTE: this returns the client with a Write lock and a refCount */
1549 struct client *
1550 h_ID2Client(afs_int32 vid)
1551 {
1552     register struct client *client;
1553     register struct host *host;
1554
1555     H_LOCK;
1556     for (host = hostList; host; host = host->next) {
1557         if (host->hostFlags & HOSTDELETED)
1558             continue;
1559         for (client = host->FirstClient; client; client = client->next) {
1560             if (!client->deleted && client->ViceId == vid) {
1561                 client->refCount++;
1562                 H_UNLOCK;
1563                 ObtainWriteLock(&client->lock);
1564                 return client;
1565             }
1566         }
1567     }
1568
1569     H_UNLOCK;
1570     return NULL;
1571 }
1572
1573 /*
1574  * Called by the server main loop.  Returns a h_Held client, which must be
1575  * released later the main loop.  Allocates a client if the matching one
1576  * isn't around. The client is returned with its reference count incremented
1577  * by one. The caller must call h_ReleaseClient_r when finished with
1578  * the client.
1579  */
1580 struct client *
1581 h_FindClient_r(struct rx_connection *tcon)
1582 {
1583     register struct client *client;
1584     register struct host *host;
1585     struct client *oldClient;
1586     afs_int32 viceid;
1587     afs_int32 expTime;
1588     afs_int32 code;
1589     int authClass;
1590 #if (64-MAXKTCNAMELEN)
1591     ticket name length != 64
1592 #endif
1593     char tname[64];
1594     char tinst[64];
1595     char uname[PR_MAXNAMELEN];
1596     char tcell[MAXKTCREALMLEN];
1597     int fail = 0;
1598     int created = 0;
1599
1600     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1601     if (client) {
1602         client->refCount++;
1603         h_Hold_r(client->host);
1604         if (!client->deleted && client->prfail != 2) {  
1605             /* Could add shared lock on client here */
1606             /* note that we don't have to lock entry in this path to
1607              * ensure CPS is initialized, since we don't call rx_SetSpecific
1608              * until initialization is done, and we only get here if
1609              * rx_GetSpecific located the client structure.
1610              */
1611             return client;
1612         }
1613         H_UNLOCK;
1614         ObtainWriteLock(&client->lock); /* released at end */
1615         H_LOCK;
1616     }
1617
1618     authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
1619     ViceLog(5,
1620             ("FindClient: authenticating connection: authClass=%d\n",
1621              authClass));
1622     if (authClass == 1) {
1623         /* A bcrypt tickets, no longer supported */
1624         ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
1625         viceid = AnonymousID;
1626         expTime = 0x7fffffff;
1627     } else if (authClass == 2) {
1628         afs_int32 kvno;
1629
1630         /* kerberos ticket */
1631         code = rxkad_GetServerInfo(tcon, /*level */ 0, &expTime,
1632                                    tname, tinst, tcell, &kvno);
1633         if (code) {
1634             ViceLog(1, ("Failed to get rxkad ticket info\n"));
1635             viceid = AnonymousID;
1636             expTime = 0x7fffffff;
1637         } else {
1638             int ilen = strlen(tinst);
1639             ViceLog(5,
1640                     ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
1641                      tname, tinst, tcell, expTime, kvno));
1642             strncpy(uname, tname, sizeof(uname));
1643             if (ilen) {
1644                 if (strlen(uname) + 1 + ilen >= sizeof(uname))
1645                     goto bad_name;
1646                 strcat(uname, ".");
1647                 strcat(uname, tinst);
1648             }
1649             /* translate the name to a vice id */
1650             code = MapName_r(uname, tcell, &viceid);
1651             if (code) {
1652               bad_name:
1653                 ViceLog(1,
1654                         ("failed to map name=%s, cell=%s -> code=%d\n", uname,
1655                          tcell, code));
1656                 fail = 1;
1657                 viceid = AnonymousID;
1658                 expTime = 0x7fffffff;
1659             }
1660         }
1661     } else {
1662         viceid = AnonymousID;   /* unknown security class */
1663         expTime = 0x7fffffff;
1664     }
1665
1666     if (!client) { /* loop */
1667         host = h_GetHost_r(tcon);       /* Returns it h_Held */
1668
1669     retryfirstclient:
1670         /* First try to find the client structure */
1671         for (client = host->FirstClient; client; client = client->next) {
1672             if (!client->deleted && (client->sid == rxr_CidOf(tcon))
1673                 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1674                 if (client->tcon && (client->tcon != tcon)) {
1675                     ViceLog(0,
1676                             ("*** Vid=%d, sid=%x, tcon=%x, Tcon=%x ***\n",
1677                              client->ViceId, client->sid, client->tcon,
1678                              tcon));
1679                     oldClient =
1680                         (struct client *)rx_GetSpecific(client->tcon,
1681                                                         rxcon_client_key);
1682                     if (oldClient) {
1683                         if (oldClient == client)
1684                             rx_SetSpecific(client->tcon, rxcon_client_key,
1685                                            NULL);
1686                         else
1687                             ViceLog(0,
1688                                     ("Client-conn mismatch: CL1=%x, CN=%x, CL2=%x\n",
1689                                      client, client->tcon, oldClient));
1690                     }
1691                     client->tcon = (struct rx_connection *)0;
1692                 }
1693                 client->refCount++;
1694                 H_UNLOCK;
1695                 ObtainWriteLock(&client->lock);
1696                 H_LOCK;
1697                 break;
1698             }
1699         }
1700
1701         /* Still no client structure - get one */
1702         if (!client) {
1703             h_Lock_r(host);
1704             /* Retry to find the client structure */
1705             for (client = host->FirstClient; client; client = client->next) {
1706                 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
1707                     && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1708                     h_Unlock_r(host);
1709                     goto retryfirstclient;
1710                 }
1711             }
1712             created = 1;
1713             client = GetCE();
1714             ObtainWriteLock(&client->lock);
1715             client->refCount = 1;
1716             client->host = host;
1717 #if FS_STATS_DETAILED
1718             client->InSameNetwork = host->InSameNetwork;
1719 #endif /* FS_STATS_DETAILED */
1720             client->ViceId = viceid;
1721             client->expTime = expTime;  /* rx only */
1722             client->authClass = authClass;      /* rx only */
1723             client->sid = rxr_CidOf(tcon);
1724             client->VenusEpoch = rxr_GetEpoch(tcon);
1725             client->CPS.prlist_val = 0;
1726             client->CPS.prlist_len = 0;
1727             h_Unlock_r(host);
1728         }
1729     }
1730     client->prfail = fail;
1731
1732     if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
1733         client->CPS.prlist_len = 0;
1734         if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
1735             free(client->CPS.prlist_val);
1736         client->CPS.prlist_val = NULL;
1737         client->ViceId = viceid;
1738         client->expTime = expTime;
1739
1740         if (viceid == ANONYMOUSID) {
1741             client->CPS.prlist_len = AnonCPS.prlist_len;
1742             client->CPS.prlist_val = AnonCPS.prlist_val;
1743         } else {
1744             H_UNLOCK;
1745             code = pr_GetCPS(viceid, &client->CPS);
1746             H_LOCK;
1747             if (code) {
1748                 char hoststr[16];
1749                 ViceLog(0,
1750                         ("pr_GetCPS failed(%d) for user %d, host %s:%d\n",
1751                          code, viceid, afs_inet_ntoa_r(client->host->host,
1752                                                        hoststr),
1753                          ntohs(client->host->port)));
1754
1755                 /* Although ubik_Call (called by pr_GetCPS) traverses thru
1756                  * all protection servers and reevaluates things if no
1757                  * sync server or quorum is found we could still end up
1758                  * with one of these errors. In such case we would like to
1759                  * reevaluate the rpc call to find if there's cps for this
1760                  * guy. We treat other errors (except network failures
1761                  * ones - i.e. code < 0) as an indication that there is no
1762                  * CPS for this host.  Ideally we could like to deal this
1763                  * problem the other way around (i.e.  if code == NOCPS
1764                  * ignore else retry next time) but the problem is that
1765                  * there're other errors (i.e.  EPERM) for which we don't
1766                  * want to retry and we don't know the whole code list!
1767                  */
1768                 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
1769                     client->prfail = 1;
1770             }
1771         }
1772         /* the disabling of system:administrators is so iffy and has so many
1773          * possible failure modes that we will disable it again */
1774         /* Turn off System:Administrator for safety  
1775          * if (AL_IsAMember(SystemId, client->CPS) == 0)
1776          * assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
1777     }
1778
1779     /* Now, tcon may already be set to a rock, since we blocked with no host
1780      * or client locks set above in pr_GetCPS (XXXX some locking is probably
1781      * required).  So, before setting the RPC's rock, we should disconnect
1782      * the RPC from the other client structure's rock.
1783      */
1784     oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1785     if (oldClient && oldClient->tcon == tcon) {
1786         char hoststr[16];
1787         if (!oldClient->deleted) {
1788             /* if we didn't create it, it's not ours to put back */
1789             if (created) {
1790                 ViceLog(0, ("FindClient: stillborn client %x(%x); conn %x (host %s:%d) had client %x(%x)\n", 
1791                             client, client->sid, tcon, 
1792                             afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
1793                             ntohs(rxr_PortOf(tcon)),
1794                             oldClient, oldClient->sid));
1795                 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
1796                     free(client->CPS.prlist_val);
1797                 client->CPS.prlist_val = NULL;
1798                 client->CPS.prlist_len = 0;
1799                 if (client->tcon) {
1800                     rx_SetSpecific(client->tcon, rxcon_client_key, (void *)0);
1801                 }
1802             }
1803             /* We should perhaps check for 0 here */
1804             client->refCount--;
1805             ReleaseWriteLock(&client->lock);
1806             if (created) {
1807                 FreeCE(client);
1808                 created = 0;
1809             } 
1810             ObtainWriteLock(&oldClient->lock);
1811             oldClient->refCount++;
1812             client = oldClient;
1813         } else {
1814             oldClient->tcon = (struct rx_connection *)0;
1815             ViceLog(0, ("FindClient: deleted client %x(%x) already had conn %x (host %s:%d), stolen by client %x(%x)\n", 
1816                         oldClient, oldClient->sid, tcon, 
1817                         afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
1818                         ntohs(rxr_PortOf(tcon)),
1819                         client, client->sid));
1820             /* rx_SetSpecific will be done immediately below */
1821         }
1822     }
1823     /* Avoid chaining in more than once. */
1824     if (created) {
1825         h_Lock_r(host);
1826         client->next = host->FirstClient;
1827         host->FirstClient = client;
1828         h_Unlock_r(host);
1829         CurrentConnections++;   /* increment number of connections */
1830     }
1831     client->tcon = tcon;
1832     rx_SetSpecific(tcon, rxcon_client_key, client);
1833     ReleaseWriteLock(&client->lock);
1834
1835     return client;
1836
1837 }                               /*h_FindClient_r */
1838
1839 int
1840 h_ReleaseClient_r(struct client *client)
1841 {
1842     assert(client->refCount > 0);
1843     client->refCount--;
1844     return 0;
1845 }
1846
1847
1848 /*
1849  * Sigh:  this one is used to get the client AGAIN within the individual
1850  * server routines.  This does not bother h_Holding the host, since
1851  * this is assumed already have been done by the server main loop.
1852  * It does check tokens, since only the server routines can return the
1853  * VICETOKENDEAD error code
1854  */
1855 int
1856 GetClient(struct rx_connection *tcon, struct client **cp)
1857 {
1858     register struct client *client;
1859
1860     H_LOCK;
1861     *cp = NULL;
1862     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1863     if (client == NULL || client->tcon == NULL) {
1864         ViceLog(0,
1865                 ("GetClient: no client in conn %x (host %x:%d), VBUSYING\n",
1866                  tcon, rxr_HostOf(tcon),ntohs(rxr_PortOf(tcon))));
1867         H_UNLOCK;
1868         return VBUSY;
1869     }
1870     if (rxr_CidOf(client->tcon) != client->sid) {
1871         ViceLog(0,
1872                 ("GetClient: tcon %x tcon sid %d client sid %d\n",
1873                  client->tcon, rxr_CidOf(client->tcon), client->sid));
1874         H_UNLOCK;
1875         return VBUSY;
1876     }
1877     if (!(client && client->tcon && rxr_CidOf(client->tcon) == client->sid)) {
1878         if (!client)
1879             ViceLog(0, ("GetClient: no client in conn %x\n", tcon));
1880         else
1881             ViceLog(0,
1882                     ("GetClient: tcon %x tcon sid %d client sid %d\n",
1883                      client->tcon, client->tcon ? rxr_CidOf(client->tcon)
1884                      : -1, client->sid));
1885         assert(0);
1886     }
1887     if (client && client->LastCall > client->expTime && client->expTime) {
1888         char hoststr[16];
1889         ViceLog(1,
1890                 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
1891                  afs_inet_ntoa_r(client->host->host, hoststr),
1892                  ntohs(client->host->port), client->expTime));
1893         H_UNLOCK;
1894         return VICETOKENDEAD;
1895     }
1896
1897     client->refCount++;
1898     *cp = client;
1899     H_UNLOCK;
1900     return 0;
1901 }                               /*GetClient */
1902
1903 int
1904 PutClient(struct client **cp)
1905 {
1906     if (*cp == NULL) 
1907         return -1;
1908
1909     H_LOCK;
1910     h_ReleaseClient_r(*cp);
1911     *cp = NULL;
1912     H_UNLOCK;
1913     return 0;
1914 }                               /*PutClient */
1915
1916
1917 /* Client user name for short term use.  Note that this is NOT inexpensive */
1918 char *
1919 h_UserName(struct client *client)
1920 {
1921     static char User[PR_MAXNAMELEN + 1];
1922     namelist lnames;
1923     idlist lids;
1924
1925     lids.idlist_len = 1;
1926     lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
1927     if (!lids.idlist_val) {
1928         ViceLog(0, ("Failed malloc in h_UserName\n"));
1929         assert(0);
1930     }
1931     lnames.namelist_len = 0;
1932     lnames.namelist_val = (prname *) 0;
1933     lids.idlist_val[0] = client->ViceId;
1934     if (pr_IdToName(&lids, &lnames)) {
1935         /* We need to free id we alloced above! */
1936         free(lids.idlist_val);
1937         return "*UNKNOWN USER NAME*";
1938     }
1939     strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
1940     free(lids.idlist_val);
1941     free(lnames.namelist_val);
1942     return User;
1943
1944 }                               /*h_UserName */
1945
1946
1947 void
1948 h_PrintStats()
1949 {
1950     ViceLog(0,
1951             ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
1952              CEs, CEBlocks, HTs, HTBlocks));
1953
1954 }                               /*h_PrintStats */
1955
1956
1957 static int
1958 h_PrintClient(register struct host *host, int held, StreamHandle_t * file)
1959 {
1960     register struct client *client;
1961     int i;
1962     char tmpStr[256];
1963     char tbuffer[32];
1964     char hoststr[16];
1965
1966     H_LOCK;
1967     if (host->hostFlags & HOSTDELETED) {
1968         H_UNLOCK;
1969         return held;
1970     }
1971     (void)afs_snprintf(tmpStr, sizeof tmpStr,
1972                        "Host %s:%d down = %d, LastCall %s",
1973                        afs_inet_ntoa_r(host->host, hoststr),
1974                        ntohs(host->port), (host->hostFlags & VENUSDOWN),
1975                        afs_ctime((time_t *) & host->LastCall, tbuffer,
1976                                  sizeof(tbuffer)));
1977     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1978     for (client = host->FirstClient; client; client = client->next) {
1979         if (!client->deleted) {
1980             if (client->tcon) {
1981                 (void)afs_snprintf(tmpStr, sizeof tmpStr,
1982                                    "    user id=%d,  name=%s, sl=%s till %s",
1983                                    client->ViceId, h_UserName(client),
1984                                    client->
1985                                    authClass ? "Authenticated" :
1986                                    "Not authenticated",
1987                                    client->
1988                                    authClass ? afs_ctime((time_t *) & client->
1989                                                          expTime, tbuffer,
1990                                                          sizeof(tbuffer))
1991                                    : "No Limit\n");
1992                 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1993             } else {
1994                 (void)afs_snprintf(tmpStr, sizeof tmpStr,
1995                                    "    user=%s, no current server connection\n",
1996                                    h_UserName(client));
1997                 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1998             }
1999             (void)afs_snprintf(tmpStr, sizeof tmpStr, "      CPS-%d is [",
2000                                client->CPS.prlist_len);
2001             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2002             if (client->CPS.prlist_val) {
2003                 for (i = 0; i > client->CPS.prlist_len; i++) {
2004                     (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2005                                        client->CPS.prlist_val[i]);
2006                     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2007                 }
2008             }
2009             sprintf(tmpStr, "]\n");
2010             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2011         }
2012     }
2013     H_UNLOCK;
2014     return held;
2015
2016 }                               /*h_PrintClient */
2017
2018
2019
2020 /*
2021  * Print a list of clients, with last security level and token value seen,
2022  * if known
2023  */
2024 void
2025 h_PrintClients()
2026 {
2027     time_t now;
2028     char tmpStr[256];
2029     char tbuffer[32];
2030
2031     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2032
2033     if (file == NULL) {
2034         ViceLog(0,
2035                 ("Couldn't create client dump file %s\n",
2036                  AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2037         return;
2038     }
2039     now = FT_ApproxTime();
2040     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
2041                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2042     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2043     h_Enumerate(h_PrintClient, (char *)file);
2044     STREAM_REALLYCLOSE(file);
2045     ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2046 }
2047
2048
2049
2050
2051 static int
2052 h_DumpHost(register struct host *host, int held, StreamHandle_t * file)
2053 {
2054     int i;
2055     char tmpStr[256];
2056     char hoststr[16];
2057
2058     H_LOCK;
2059     (void)afs_snprintf(tmpStr, sizeof tmpStr,
2060                        "ip:%s port:%d hidx:%d cbid:%d lock:%x last:%u active:%u down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u hcps [",
2061                        afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), host->index,
2062                        host->cblist, CheckLock(&host->lock), host->LastCall,
2063                        host->ActiveCall, (host->hostFlags & VENUSDOWN),
2064                        host->hostFlags & HOSTDELETED, host->Console,
2065                        host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2066                        host->cpsCall);
2067     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2068     if (host->hcps.prlist_val)
2069         for (i = 0; i < host->hcps.prlist_len; i++) {
2070             (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2071                                host->hcps.prlist_val[i]);
2072             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2073         }
2074     sprintf(tmpStr, "] [");
2075     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2076     if (host->interface)
2077         for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2078             char hoststr[16];
2079             sprintf(tmpStr, " %s:%d", 
2080                      afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2081                      ntohs(host->interface->interface[i].port));
2082             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2083         }
2084     sprintf(tmpStr, "] holds: ");
2085     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2086
2087     for (i = 0; i < h_maxSlots; i++) {
2088         sprintf(tmpStr, "%04x", host->holds[i]);
2089         (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2090     }
2091     sprintf(tmpStr, " slot/bit: %d/%d\n", h_holdSlot(), h_holdbit());
2092     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2093
2094     H_UNLOCK;
2095     return held;
2096
2097 }                               /*h_DumpHost */
2098
2099
2100 void
2101 h_DumpHosts()
2102 {
2103     time_t now;
2104     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2105     char tmpStr[256];
2106     char tbuffer[32];
2107
2108     if (file == NULL) {
2109         ViceLog(0,
2110                 ("Couldn't create host dump file %s\n",
2111                  AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2112         return;
2113     }
2114     now = FT_ApproxTime();
2115     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
2116                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2117     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2118     h_Enumerate(h_DumpHost, (char *)file);
2119     STREAM_REALLYCLOSE(file);
2120     ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2121
2122 }                               /*h_DumpHosts */
2123
2124
2125 /*
2126  * This counts the number of workstations, the number of active workstations,
2127  * and the number of workstations declared "down" (i.e. not heard from
2128  * recently).  An active workstation has received a call since the cutoff
2129  * time argument passed.
2130  */
2131 void
2132 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
2133 {
2134     register struct host *host;
2135     register int num = 0, active = 0, del = 0;
2136
2137     H_LOCK;
2138     for (host = hostList; host; host = host->next) {
2139         if (!(host->hostFlags & HOSTDELETED)) {
2140             num++;
2141             if (host->ActiveCall > cutofftime)
2142                 active++;
2143             if (host->hostFlags & VENUSDOWN)
2144                 del++;
2145         }
2146     }
2147     H_UNLOCK;
2148     if (nump)
2149         *nump = num;
2150     if (activep)
2151         *activep = active;
2152     if (delp)
2153         *delp = del;
2154
2155 }                               /*h_GetWorkStats */
2156
2157
2158 /*------------------------------------------------------------------------
2159  * PRIVATE h_ClassifyAddress
2160  *
2161  * Description:
2162  *      Given a target IP address and a candidate IP address (both
2163  *      in host byte order), classify the candidate into one of three
2164  *      buckets in relation to the target by bumping the counters passed
2165  *      in as parameters.
2166  *
2167  * Arguments:
2168  *      a_targetAddr       : Target address.
2169  *      a_candAddr         : Candidate address.
2170  *      a_sameNetOrSubnetP : Ptr to counter to bump when the two
2171  *                           addresses are either in the same network
2172  *                           or the same subnet.
2173  *      a_diffSubnetP      : ...when the candidate is in a different
2174  *                           subnet.
2175  *      a_diffNetworkP     : ...when the candidate is in a different
2176  *                           network.
2177  *
2178  * Returns:
2179  *      Nothing.
2180  *
2181  * Environment:
2182  *      The target and candidate addresses are both in host byte
2183  *      order, NOT network byte order, when passed in.
2184  *
2185  * Side Effects:
2186  *      As advertised.
2187  *------------------------------------------------------------------------*/
2188
2189 static void
2190 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
2191                   afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
2192                   afs_int32 * a_diffNetworkP)
2193 {                               /*h_ClassifyAddress */
2194
2195     afs_uint32 targetNet;
2196     afs_uint32 targetSubnet;
2197     afs_uint32 candNet;
2198     afs_uint32 candSubnet;
2199
2200     /*
2201      * Put bad values into the subnet info to start with.
2202      */
2203     targetSubnet = (afs_uint32) 0;
2204     candSubnet = (afs_uint32) 0;
2205
2206     /*
2207      * Pull out the network and subnetwork numbers from the target
2208      * and candidate addresses.  We can short-circuit this whole
2209      * affair if the target and candidate addresses are not of the
2210      * same class.
2211      */
2212     if (IN_CLASSA(a_targetAddr)) {
2213         if (!(IN_CLASSA(a_candAddr))) {
2214             (*a_diffNetworkP)++;
2215             return;
2216         }
2217         targetNet = a_targetAddr & IN_CLASSA_NET;
2218         candNet = a_candAddr & IN_CLASSA_NET;
2219         if (IN_SUBNETA(a_targetAddr))
2220             targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
2221         if (IN_SUBNETA(a_candAddr))
2222             candSubnet = a_candAddr & IN_CLASSA_SUBNET;
2223     } else if (IN_CLASSB(a_targetAddr)) {
2224         if (!(IN_CLASSB(a_candAddr))) {
2225             (*a_diffNetworkP)++;
2226             return;
2227         }
2228         targetNet = a_targetAddr & IN_CLASSB_NET;
2229         candNet = a_candAddr & IN_CLASSB_NET;
2230         if (IN_SUBNETB(a_targetAddr))
2231             targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
2232         if (IN_SUBNETB(a_candAddr))
2233             candSubnet = a_candAddr & IN_CLASSB_SUBNET;
2234     } /*Class B target */
2235     else if (IN_CLASSC(a_targetAddr)) {
2236         if (!(IN_CLASSC(a_candAddr))) {
2237             (*a_diffNetworkP)++;
2238             return;
2239         }
2240         targetNet = a_targetAddr & IN_CLASSC_NET;
2241         candNet = a_candAddr & IN_CLASSC_NET;
2242
2243         /*
2244          * Note that class C addresses can't have subnets,
2245          * so we leave the defaults untouched.
2246          */
2247     } /*Class C target */
2248     else {
2249         targetNet = a_targetAddr;
2250         candNet = a_candAddr;
2251     }                           /*Class D address */
2252
2253     /*
2254      * Now, simply compare the extracted net and subnet values for
2255      * the two addresses (which at this point are known to be of the
2256      * same class)
2257      */
2258     if (targetNet == candNet) {
2259         if (targetSubnet == candSubnet)
2260             (*a_sameNetOrSubnetP)++;
2261         else
2262             (*a_diffSubnetP)++;
2263     } else
2264         (*a_diffNetworkP)++;
2265
2266 }                               /*h_ClassifyAddress */
2267
2268
2269 /*------------------------------------------------------------------------
2270  * EXPORTED h_GetHostNetStats
2271  *
2272  * Description:
2273  *      Iterate through the host table, and classify each (non-deleted)
2274  *      host entry into ``proximity'' categories (same net or subnet,
2275  *      different subnet, different network).
2276  *
2277  * Arguments:
2278  *      a_numHostsP        : Set to total number of (non-deleted) hosts.
2279  *      a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
2280  *      a_diffSubnetP      : Set to # hosts on diff subnet as server.
2281  *      a_diffNetworkP     : Set to # hosts on diff network as server.
2282  *
2283  * Returns:
2284  *      Nothing.
2285  *
2286  * Environment:
2287  *      We only count non-deleted hosts.  The storage pointed to by our
2288  *      parameters is zeroed upon entry.
2289  *
2290  * Side Effects:
2291  *      As advertised.
2292  *------------------------------------------------------------------------*/
2293
2294 void
2295 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
2296                   afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
2297 {                               /*h_GetHostNetStats */
2298
2299     register struct host *hostP;        /*Ptr to current host entry */
2300     register afs_uint32 currAddr_HBO;   /*Curr host addr, host byte order */
2301
2302     /*
2303      * Clear out the storage pointed to by our parameters.
2304      */
2305     *a_numHostsP = (afs_int32) 0;
2306     *a_sameNetOrSubnetP = (afs_int32) 0;
2307     *a_diffSubnetP = (afs_int32) 0;
2308     *a_diffNetworkP = (afs_int32) 0;
2309
2310     H_LOCK;
2311     for (hostP = hostList; hostP; hostP = hostP->next) {
2312         if (!(hostP->hostFlags & HOSTDELETED)) {
2313             /*
2314              * Bump the number of undeleted host entries found.
2315              * In classifying the current entry's address, make
2316              * sure to first convert to host byte order.
2317              */
2318             (*a_numHostsP)++;
2319             currAddr_HBO = (afs_uint32) ntohl(hostP->host);
2320             h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
2321                               a_sameNetOrSubnetP, a_diffSubnetP,
2322                               a_diffNetworkP);
2323         }                       /*Only look at non-deleted hosts */
2324     }                           /*For each host record hashed to this index */
2325     H_UNLOCK;
2326 }                               /*h_GetHostNetStats */
2327
2328 static afs_uint32 checktime;
2329 static afs_uint32 clientdeletetime;
2330 static struct AFSFid zerofid;
2331
2332
2333 /*
2334  * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
2335  * Since it can serialize them, and pile up, it should be a separate LWP
2336  * from other events.
2337  */
2338 int
2339 CheckHost(register struct host *host, int held)
2340 {
2341     register struct client *client;
2342     struct rx_connection *cb_conn = NULL;
2343     int code;
2344
2345     /* Host is held by h_Enumerate */
2346     H_LOCK;
2347     for (client = host->FirstClient; client; client = client->next) {
2348         if (client->refCount == 0 && client->LastCall < clientdeletetime) {
2349             client->deleted = 1;
2350             host->hostFlags |= CLIENTDELETED;
2351         }
2352     }
2353     if (host->LastCall < checktime) {
2354         h_Lock_r(host);
2355         if (!(host->hostFlags & HOSTDELETED)) {
2356             cb_conn = host->callback_rxcon;
2357             rx_GetConnection(cb_conn);
2358             if (host->LastCall < clientdeletetime) {
2359                 host->hostFlags |= HOSTDELETED;
2360                 if (!(host->hostFlags & VENUSDOWN)) {
2361                     host->hostFlags &= ~ALTADDR;        /* alternate address invalid */
2362                     if (host->interface) {
2363                         H_UNLOCK;
2364                         code =
2365                             RXAFSCB_InitCallBackState3(cb_conn,
2366                                                        &FS_HostUUID);
2367                         H_LOCK;
2368                     } else {
2369                         H_UNLOCK;
2370                         code =
2371                             RXAFSCB_InitCallBackState(cb_conn);
2372                         H_LOCK;
2373                     }
2374                     host->hostFlags |= ALTADDR; /* alternate addresses valid */
2375                     if (code) {
2376                         char hoststr[16];
2377                         (void)afs_inet_ntoa_r(host->host, hoststr);
2378                         ViceLog(0,
2379                                 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
2380                                  hoststr, ntohs(host->port)));
2381                         host->hostFlags |= VENUSDOWN;
2382                     }
2383                     /* Note:  it's safe to delete hosts even if they have call
2384                      * back state, because break delayed callbacks (called when a
2385                      * message is received from the workstation) will always send a 
2386                      * break all call backs to the workstation if there is no
2387                      *callback.
2388                      */
2389                 }
2390             } else {
2391                 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
2392                     if (host->interface) {
2393                         afsUUID uuid = host->interface->uuid;
2394                         H_UNLOCK;
2395                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2396                         H_LOCK;
2397                         if (code) {
2398                             if (MultiProbeAlternateAddress_r(host)) {
2399                                 char hoststr[16];
2400                                 (void)afs_inet_ntoa_r(host->host, hoststr);
2401                                 ViceLog(0,
2402                                         ("ProbeUuid failed for host %s:%d\n",
2403                                          hoststr, ntohs(host->port)));
2404                                 host->hostFlags |= VENUSDOWN;
2405                             }
2406                         }
2407                     } else {
2408                         H_UNLOCK;
2409                         code = RXAFSCB_Probe(cb_conn);
2410                         H_LOCK;
2411                         if (code) {
2412                             char hoststr[16];
2413                             (void)afs_inet_ntoa_r(host->host, hoststr);
2414                             ViceLog(0,
2415                                     ("Probe failed for host %s:%d\n", hoststr,
2416                                      ntohs(host->port)));
2417                             host->hostFlags |= VENUSDOWN;
2418                         }
2419                     }
2420                 }
2421             }
2422             H_UNLOCK;
2423             rx_PutConnection(cb_conn);
2424             cb_conn=NULL;
2425             H_LOCK;
2426         }
2427         h_Unlock_r(host);
2428     }
2429     H_UNLOCK;
2430     return held;
2431
2432 }                               /*CheckHost */
2433
2434
2435 /*
2436  * Set VenusDown for any hosts that have not had a call in 15 minutes and
2437  * don't respond to a probe.  Note that VenusDown can only be cleared if
2438  * a message is received from the host (see ServerLWP in file.c).
2439  * Delete hosts that have not had any calls in 1 hour, clients that
2440  * have not had any calls in 15 minutes.
2441  *
2442  * This routine is called roughly every 5 minutes.
2443  */
2444 void
2445 h_CheckHosts()
2446 {
2447     afs_uint32 now = FT_ApproxTime();
2448
2449     memset((char *)&zerofid, 0, sizeof(zerofid));
2450     /*
2451      * Send a probe to the workstation if it hasn't been heard from in
2452      * 15 minutes
2453      */
2454     checktime = now - 15 * 60;
2455     clientdeletetime = now - 120 * 60;  /* 2 hours ago */
2456     h_Enumerate(CheckHost, NULL);
2457
2458 }                               /*h_CheckHosts */
2459
2460 /*
2461  * This is called with host locked and held. At this point, the
2462  * hostHashTable should not have any entries for the alternate
2463  * interfaces. This function has to insert these entries in the
2464  * hostHashTable.
2465  *
2466  * The addresses in the interfaceAddr list are in host byte order.
2467  */
2468 int
2469 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
2470 {
2471     int i, j;
2472     int number, count;
2473     afs_uint32 myAddr;
2474     afs_uint16 myPort;
2475     int found;
2476     struct Interface *interface;
2477
2478     assert(host);
2479     assert(interf);
2480
2481     ViceLog(125,
2482             ("initInterfaceAddr : host %x numAddr %d\n", host->host,
2483              interf->numberOfInterfaces));
2484
2485     number = interf->numberOfInterfaces;
2486     myAddr = host->host;        /* current interface address */
2487     myPort = host->port;        /* current port */
2488
2489     /* validation checks */
2490     if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
2491         ViceLog(0,
2492                 ("Number of alternate addresses returned is %d\n", number));
2493         return -1;
2494     }
2495
2496     /*
2497      * Convert IP addresses to network byte order, and remove for
2498      * duplicate IP addresses from the interface list.
2499      */
2500     for (i = 0, count = 0, found = 0; i < number; i++) {
2501         interf->addr_in[i] = htonl(interf->addr_in[i]);
2502         for (j = 0; j < count; j++) {
2503             if (interf->addr_in[j] == interf->addr_in[i])
2504                 break;
2505         }
2506         if (j == count) {
2507             interf->addr_in[count] = interf->addr_in[i];
2508             if (interf->addr_in[count] == myAddr)
2509                 found = 1;
2510             count++;
2511         }
2512     }
2513
2514     /*
2515      * Allocate and initialize an interface structure for this host.
2516      */
2517     if (found) {
2518         interface = (struct Interface *)
2519             malloc(sizeof(struct Interface) +
2520                    (sizeof(struct AddrPort) * (count - 1)));
2521         if (!interface) {
2522             ViceLog(0, ("Failed malloc in initInterfaceAddr_r\n"));
2523             assert(0);
2524         }
2525         interface->numberOfInterfaces = count;
2526     } else {
2527         interface = (struct Interface *)
2528             malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
2529         assert(interface);
2530         interface->numberOfInterfaces = count + 1;
2531         interface->interface[count].addr = myAddr;
2532         interface->interface[count].port = myPort;
2533     }
2534     interface->uuid = interf->uuid;
2535     for (i = 0; i < count; i++) {
2536         interface->interface[i].addr = interf->addr_in[i];
2537         /* We store the port as 7001 because the addresses reported by 
2538          * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
2539          * are coming from fully connected hosts (no NAT/PATs)
2540          */
2541         interface->interface[i].port = htons(7001);
2542     }
2543
2544     assert(!host->interface);
2545     host->interface = interface;
2546
2547     for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2548         char hoststr[16];
2549         ViceLog(125, ("--- alt address %s:%d\n", 
2550                        afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2551                        ntohs(host->interface->interface[i].port)));
2552     }
2553
2554     return 0;
2555 }
2556
2557 /* deleted a HashChain structure for this address and host */
2558 /* returns 1 on success */
2559 static int
2560 hashDelete_r(afs_uint32 addr, afs_uint16 port, struct host *host)
2561 {
2562     int flag;
2563     register struct h_hashChain **hp, *th;
2564
2565     for (hp = &hostHashTable[h_HashIndex(addr)]; (th = *hp);) {
2566         assert(th->hostPtr);
2567         if (th->hostPtr == host && th->addr == addr && th->port == port) {
2568             *hp = th->next;
2569             free(th);
2570             flag = 1;
2571             break;
2572         } else {
2573             hp = &th->next;
2574         }
2575     }
2576     return flag;
2577 }
2578
2579
2580 /*
2581 ** prints out all alternate interface address for the host. The 'level'
2582 ** parameter indicates what level of debugging sets this output
2583 */
2584 void
2585 printInterfaceAddr(struct host *host, int level)
2586 {
2587     int i, number;
2588     char hoststr[16];
2589
2590     if (host->interface) {
2591         /* check alternate addresses */
2592         number = host->interface->numberOfInterfaces;
2593         assert(number > 0);
2594         for (i = 0; i < number; i++)
2595             ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2596                              ntohs(host->interface->interface[i].port)));
2597     }
2598     ViceLog(level, ("\n"));
2599 }