viced-fix-check-rights-race-20060213
[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             }
726             if (client->tcon) {
727                 rx_SetSpecific(client->tcon, rxcon_client_key, (void *)0);
728             }
729             CurrentConnections--;
730             *cp = client->next;
731             FreeCE(client);
732         } else
733             cp = &client->next;
734     }
735
736     /* We've just cleaned out all the deleted clients; clear the flag */
737     host->hostFlags &= ~CLIENTDELETED;
738
739     if (host->hostFlags & HOSTDELETED) {
740         register struct h_hashChain **hp, *th;
741         register struct rx_connection *rxconn;
742         afsUUID *uuidp;
743         struct AddrPort hostAddrPort;
744         int i;
745
746         if (host->Console & 1)
747             Console--;
748         if ((rxconn = host->callback_rxcon)) {
749             host->callback_rxcon = (struct rx_connection *)0;
750             /*
751              * If rx_DestroyConnection calls h_FreeConnection we will
752              * deadlock on the host_glock_mutex. Work around the problem
753              * by unhooking the client from the connection before
754              * destroying the connection.
755              */
756             client = rx_GetSpecific(rxconn, rxcon_client_key);
757             if (client && client->tcon == rxconn)
758                 client->tcon = NULL;
759             rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
760             rx_DestroyConnection(rxconn);
761         }
762         if (host->hcps.prlist_val)
763             free(host->hcps.prlist_val);
764         host->hcps.prlist_val = NULL;
765         host->hcps.prlist_len = 0;
766         DeleteAllCallBacks_r(host, 1);
767         host->hostFlags &= ~RESETDONE;  /* just to be safe */
768
769         /* if alternate addresses do not exist */
770         if (!(host->interface)) {
771             for (hp = &hostHashTable[h_HashIndex(host->host)]; (th = *hp);
772                  hp = &th->next) {
773                 assert(th->hostPtr);
774                 if (th->hostPtr == host) {
775                     *hp = th->next;
776                     h_DeleteList_r(host);
777                     FreeHT(host);
778                     free(th);
779                     break;
780                 }
781             }
782         } else {
783             /* delete all hash entries for the UUID */
784             uuidp = &host->interface->uuid;
785             for (hp = &hostUuidHashTable[h_UuidHashIndex(uuidp)]; (th = *hp);
786                  hp = &th->next) {
787                 assert(th->hostPtr);
788                 if (th->hostPtr == host) {
789                     *hp = th->next;
790                     free(th);
791                     break;
792                 }
793             }
794             /* delete all hash entries for alternate addresses */
795             assert(host->interface->numberOfInterfaces > 0);
796             for (i = 0; i < host->interface->numberOfInterfaces; i++) {
797                 hostAddrPort = host->interface->interface[i];
798
799                 for (hp = &hostHashTable[h_HashIndex(hostAddrPort.addr)]; (th = *hp);
800                      hp = &th->next) {
801                     assert(th->hostPtr);
802                     if (th->hostPtr == host) {
803                         *hp = th->next;
804                         free(th);
805                         break;
806                     }
807                 }
808             }
809             free(host->interface);
810             host->interface = NULL;
811             h_DeleteList_r(host);       /* remove host from global host List */
812             FreeHT(host);
813         }                       /* if alternate address exists */
814     }
815 }                               /*h_TossStuff_r */
816
817
818 /* Called by rx when a server connection disappears */
819 int
820 h_FreeConnection(struct rx_connection *tcon)
821 {
822     register struct client *client;
823
824     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
825     if (client) {
826         H_LOCK;
827         if (client->tcon == tcon)
828             client->tcon = (struct rx_connection *)0;
829         H_UNLOCK;
830     }
831     return 0;
832 }                               /*h_FreeConnection */
833
834
835 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
836  * system at the start of the enumeration (perhaps more).  Hosts may be deleted
837  * (have delete flag set); ditto for clients.  (*proc) is always called with
838  * host h_held().  The hold state of the host with respect to this lwp is passed
839  * to (*proc) as the param held.  The proc should return 0 if the host should be
840  * released, 1 if it should be held after enumeration.
841  */
842 void
843 h_Enumerate(int (*proc) (), char *param)
844 {
845     register struct host *host, **list;
846     register int *held;
847     register int i, count;
848
849     H_LOCK;
850     if (hostCount == 0) {
851         H_UNLOCK;
852         return;
853     }
854     list = (struct host **)malloc(hostCount * sizeof(struct host *));
855     if (!list) {
856         ViceLog(0, ("Failed malloc in h_Enumerate\n"));
857         assert(0);
858     }
859     held = (int *)malloc(hostCount * sizeof(int));
860     if (!held) {
861         ViceLog(0, ("Failed malloc in h_Enumerate\n"));
862         assert(0);
863     }
864     for (count = 0, host = hostList; host; host = host->next, count++) {
865         list[count] = host;
866         if (!(held[count] = h_Held_r(host)))
867             h_Hold_r(host);
868     }
869     assert(count == hostCount);
870     H_UNLOCK;
871     for (i = 0; i < count; i++) {
872         held[i] = (*proc) (list[i], held[i], param);
873         if (!held[i])
874             h_Release(list[i]); /* this might free up the host */
875     }
876     free((void *)list);
877     free((void *)held);
878 }                               /*h_Enumerate */
879
880 /* h_Enumerate_r (revised):
881  * Calls (*proc)(host, held, param) for each host in hostList, starting
882  * at enumstart
883  * Hosts may be deleted (have delete flag set); ditto for clients.
884  * (*proc) is always called with
885  * host h_held() and the global host lock (H_LOCK) locked.The hold state of the
886  * host with respect to this lwp is passed to (*proc) as the param held.
887  * The proc should return 0 if the host should be released, 1 if it should
888  * be held after enumeration.
889  */
890 void
891 h_Enumerate_r(int (*proc) (), struct host *enumstart, char *param)
892 {
893     register struct host *host, *next;
894     register int held, nheld;
895
896     if (hostCount == 0) {
897         return;
898     }
899     if (enumstart && !(held = h_Held_r(enumstart)))
900         h_Hold_r(enumstart); 
901     for (host = enumstart; host; host = next, held = nheld) {
902         held = (*proc) (host, held, param);
903         next = host->next;
904         if (next && !(nheld = h_Held_r(next)))
905             h_Hold_r(next);
906         if (!held)
907             h_Release_r(host); /* this might free up the host */
908     }
909 }                               /*h_Enumerate_r */
910
911 /* inserts a new HashChain structure corresponding to this UUID */
912 void
913 hashInsertUuid_r(struct afsUUID *uuid, struct host *host)
914 {
915     int index;
916     struct h_hashChain *chain;
917
918     /* hash into proper bucket */
919     index = h_UuidHashIndex(uuid);
920
921     /* insert into beginning of list for this bucket */
922     chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
923     if (!chain) {
924         ViceLog(0, ("Failed malloc in hashInsertUuid_r\n"));
925         assert(0);
926     }
927     assert(chain);
928     chain->hostPtr = host;
929     chain->next = hostUuidHashTable[index];
930     hostUuidHashTable[index] = chain;
931 }
932
933
934 /* inserts a new HashChain structure corresponding to this address */
935 void
936 hashInsert_r(afs_uint32 addr, afs_uint16 port, struct host *host)
937 {
938     int index;
939     struct h_hashChain *chain;
940
941     /* hash into proper bucket */
942     index = h_HashIndex(addr);
943
944     /* insert into beginning of list for this bucket */
945     chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
946     if (!chain) {
947         ViceLog(0, ("Failed malloc in hashInsert_r\n"));
948         assert(0);
949     }
950     chain->hostPtr = host;
951     chain->next = hostHashTable[index];
952     chain->addr = addr;
953     chain->port = port;
954     hostHashTable[index] = chain;
955
956 }
957
958 /*
959  * This is called with host locked and held. At this point, the
960  * hostHashTable should not be having entries for the alternate
961  * interfaces. This function has to insert these entries in the
962  * hostHashTable.
963  *
964  * All addresses are in network byte order.
965  */
966 int
967 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
968 {
969     int i;
970     int number;
971     int found;
972     struct Interface *interface;
973     char hoststr[16], hoststr2[16];
974
975     assert(host);
976     assert(host->interface);
977
978     ViceLog(125, ("addInterfaceAddr : host %s:d addr %s:%d\n", 
979                    afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), 
980                    afs_inet_ntoa_r(addr, hoststr2), ntohs(port)));
981
982     /*
983      * Make sure this address is on the list of known addresses
984      * for this host.
985      */
986     number = host->interface->numberOfInterfaces;
987     for (i = 0, found = 0; i < number && !found; i++) {
988         if (host->interface->interface[i].addr == addr &&
989             host->interface->interface[i].port == port)
990             found = 1;
991     }
992     if (!found) {
993         interface = (struct Interface *)
994             malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
995         if (!interface) {
996             ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
997             assert(0);
998         }
999         interface->numberOfInterfaces = number + 1;
1000         interface->uuid = host->interface->uuid;
1001         for (i = 0; i < number; i++)
1002             interface->interface[i] = host->interface->interface[i];
1003         interface->interface[number].addr = addr;
1004         interface->interface[number].port = port;
1005         free(host->interface);
1006         host->interface = interface;
1007     }
1008
1009     /*
1010      * Create a hash table entry for this address
1011      */
1012     hashInsert_r(addr, port, host);
1013
1014     return 0;
1015 }
1016
1017
1018 /*
1019  * This is called with host locked and held. At this point, the
1020  * hostHashTable should not be having entries for the alternate
1021  * interfaces. This function has to insert these entries in the
1022  * hostHashTable.
1023  *
1024  * All addresses are in network byte order.
1025  */
1026 int
1027 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1028 {
1029     int i;
1030     int number;
1031     int found;
1032     struct Interface *interface;
1033     char hoststr[16], hoststr2[16];
1034
1035     assert(host);
1036     assert(host->interface);
1037
1038     ViceLog(125, ("removeInterfaceAddr : host %s:%d addr %s:%d\n", 
1039                    afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), 
1040                    afs_inet_ntoa_r(addr, hoststr2), ntohs(port)));
1041
1042     /*
1043      * Make sure this address is on the list of known addresses
1044      * for this host.
1045      */
1046     interface = host->interface;
1047     number = host->interface->numberOfInterfaces;
1048     for (i = 0, found = 0; i < number; i++) {
1049         if (interface->interface[i].addr == addr &&
1050             interface->interface[i].port == port) {
1051             found = 1;
1052             break;
1053         }
1054     }
1055     if (found) {
1056         number--;
1057         for (; i < number; i++) {
1058             interface->interface[i].addr = interface->interface[i+1].addr;
1059             interface->interface[i].port = interface->interface[i+1].port;
1060         }
1061         interface->numberOfInterfaces = number;
1062     }
1063
1064     /*
1065      * Remove the hash table entry for this address
1066      */
1067     hashDelete_r(addr, port, host);
1068
1069     return 0;
1070 }
1071
1072
1073 /* Host is returned held */
1074 struct host *
1075 h_GetHost_r(struct rx_connection *tcon)
1076 {
1077     struct host *host;
1078     struct host *oldHost;
1079     int code;
1080     int held, oheld;
1081     struct interfaceAddr interf;
1082     int interfValid = 0;
1083     struct Identity *identP = NULL;
1084     afs_int32 haddr;
1085     afs_int16 hport;
1086     char hoststr[16], hoststr2[16];
1087     Capabilities caps;
1088     struct rx_connection *cb_conn = NULL;
1089
1090     caps.Capabilities_val = NULL;
1091
1092     haddr = rxr_HostOf(tcon);
1093     hport = rxr_PortOf(tcon);
1094   retry:
1095     if (caps.Capabilities_val)
1096         free(caps.Capabilities_val);
1097     caps.Capabilities_val = NULL;
1098     caps.Capabilities_len = 0;
1099
1100     code = 0;
1101     host = h_Lookup_r(haddr, hport, &held);
1102     identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1103     if (host && !identP && !(host->Console & 1)) {
1104         /* This is a new connection, and we already have a host
1105          * structure for this address. Verify that the identity
1106          * of the caller matches the identity in the host structure.
1107          */
1108         h_Lock_r(host);
1109         if (!(host->hostFlags & ALTADDR)) {
1110             /* Another thread is doing initialization */
1111             h_Unlock_r(host);
1112             if (!held)
1113                 h_Release_r(host);
1114             ViceLog(125,
1115                     ("Host %s:%d starting h_Lookup again\n",
1116                      afs_inet_ntoa_r(host->host, hoststr),
1117                      ntohs(host->port)));
1118             goto retry;
1119         }
1120         host->hostFlags &= ~ALTADDR;
1121         cb_conn = host->callback_rxcon;
1122         rx_GetConnection(cb_conn);
1123         H_UNLOCK;
1124         code =
1125             RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1126         if (code == RXGEN_OPCODE)
1127             code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1128         rx_PutConnection(cb_conn);
1129         cb_conn=NULL;
1130         H_LOCK;
1131         if (code == RXGEN_OPCODE) {
1132             identP = (struct Identity *)malloc(sizeof(struct Identity));
1133             if (!identP) {
1134                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1135                 assert(0);
1136             }
1137             identP->valid = 0;
1138             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1139             /* The host on this connection was unable to respond to 
1140              * the WhoAreYou. We will treat this as a new connection
1141              * from the existing host. The worst that can happen is
1142              * that we maintain some extra callback state information */
1143             if (host->interface) {
1144                 ViceLog(0,
1145                         ("Host %s:%d used to support WhoAreYou, deleting.\n",
1146                          afs_inet_ntoa_r(host->host, hoststr),
1147                          ntohs(host->port)));
1148                 host->hostFlags |= HOSTDELETED;
1149                 h_Unlock_r(host);
1150                 if (!held)
1151                     h_Release_r(host);
1152                 host = NULL;
1153                 goto retry;
1154             }
1155         } else if (code == 0) {
1156             interfValid = 1;
1157             identP = (struct Identity *)malloc(sizeof(struct Identity));
1158             if (!identP) {
1159                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1160                 assert(0);
1161             }
1162             identP->valid = 1;
1163             identP->uuid = interf.uuid;
1164             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1165             /* Check whether the UUID on this connection matches
1166              * the UUID in the host structure. If they don't match
1167              * then this is not the same host as before. */
1168             if (!host->interface
1169                 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1170                 ViceLog(25,
1171                         ("Host %s:%d has changed its identity, deleting.\n",
1172                          afs_inet_ntoa_r(host->host, hoststr), host->port));
1173                 host->hostFlags |= HOSTDELETED;
1174                 h_Unlock_r(host);
1175                 if (!held)
1176                     h_Release_r(host);
1177                 host = NULL;
1178                 goto retry;
1179             }
1180         } else {
1181             afs_inet_ntoa_r(host->host, hoststr);
1182             ViceLog(0,
1183                     ("CB: WhoAreYou failed for %s:%d, error %d\n", hoststr,
1184                      ntohs(host->port), code));
1185             host->hostFlags |= VENUSDOWN;
1186         }
1187         if (caps.Capabilities_val
1188             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1189             host->hostFlags |= HERRORTRANS;
1190         else
1191             host->hostFlags &= ~(HERRORTRANS);
1192         host->hostFlags |= ALTADDR;
1193         h_Unlock_r(host);
1194     } else if (host) {
1195         if (!(host->hostFlags & ALTADDR)) {
1196             /* another thread is doing the initialisation */
1197             ViceLog(125,
1198                     ("Host %s:%d waiting for host-init to complete\n",
1199                      afs_inet_ntoa_r(host->host, hoststr),
1200                      ntohs(host->port)));
1201             h_Lock_r(host);
1202             h_Unlock_r(host);
1203             if (!held)
1204                 h_Release_r(host);
1205             ViceLog(125,
1206                     ("Host %s:%d starting h_Lookup again\n",
1207                      afs_inet_ntoa_r(host->host, hoststr),
1208                      ntohs(host->port)));
1209             goto retry;
1210         }
1211         /* We need to check whether the identity in the host structure
1212          * matches the identity on the connection. If they don't match
1213          * then treat this a new host. */
1214         if (!(host->Console & 1)
1215             && ((!identP->valid && host->interface)
1216                 || (identP->valid && !host->interface)
1217                 || (identP->valid
1218                     && !afs_uuid_equal(&identP->uuid,
1219                                        &host->interface->uuid)))) {
1220             char uuid1[128], uuid2[128];
1221             if (identP->valid)
1222                 afsUUID_to_string(&identP->uuid, uuid1, 127);
1223             if (host->interface)
1224                 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1225             ViceLog(0,
1226                     ("CB: new identity for host %s:%d, deleting(%x %x %s %s)\n",
1227                      afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1228                      identP->valid, host->interface,
1229                      identP->valid ? uuid1 : "",
1230                      host->interface ? uuid2 : ""));
1231
1232             /* The host in the cache is not the host for this connection */
1233             host->hostFlags |= HOSTDELETED;
1234             h_Unlock_r(host);
1235             if (!held)
1236                 h_Release_r(host);
1237             goto retry;
1238         }
1239     } else {
1240         host = h_Alloc_r(tcon); /* returned held and locked */
1241         h_gethostcps_r(host, FT_ApproxTime());
1242         if (!(host->Console & 1)) {
1243             int pident = 0;
1244             cb_conn = host->callback_rxcon;
1245             rx_GetConnection(cb_conn);
1246             H_UNLOCK;
1247             code =
1248                 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1249             if (code == RXGEN_OPCODE)
1250                 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1251             rx_PutConnection(cb_conn);
1252             cb_conn=NULL;
1253             H_LOCK;
1254             if (code == RXGEN_OPCODE) {
1255                 if (!identP)
1256                     identP =
1257                         (struct Identity *)malloc(sizeof(struct Identity));
1258                 else
1259                     pident = 1;
1260
1261                 if (!identP) {
1262                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1263                     assert(0);
1264                 }
1265                 identP->valid = 0;
1266                 if (!pident)
1267                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1268                 ViceLog(25,
1269                         ("Host %s:%d does not support WhoAreYou.\n",
1270                          afs_inet_ntoa_r(host->host, hoststr),
1271                          ntohs(host->port)));
1272                 code = 0;
1273             } else if (code == 0) {
1274                 if (!identP)
1275                     identP =
1276                         (struct Identity *)malloc(sizeof(struct Identity));
1277                 else
1278                     pident = 1;
1279
1280                 if (!identP) {
1281                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1282                     assert(0);
1283                 }
1284                 identP->valid = 1;
1285                 interfValid = 1;
1286                 identP->uuid = interf.uuid;
1287                 if (!pident)
1288                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1289                 ViceLog(25,
1290                         ("WhoAreYou success on %s:%d\n",
1291                          afs_inet_ntoa_r(host->host, hoststr),
1292                          ntohs(host->port)));
1293             }
1294             if (code == 0 && !identP->valid) {
1295                 cb_conn = host->callback_rxcon;
1296                 rx_GetConnection(cb_conn);
1297                 H_UNLOCK;
1298                 code = RXAFSCB_InitCallBackState(cb_conn);
1299                 rx_PutConnection(cb_conn);
1300                 cb_conn=NULL;
1301                 H_LOCK;
1302             } else if (code == 0) {
1303                 oldHost = h_LookupUuid_r(&identP->uuid);
1304                 if (oldHost) {
1305                     int probefail = 0;
1306
1307                     if (!(oheld = h_Held_r(oldHost)))
1308                         h_Hold_r(oldHost);
1309                     h_Lock_r(oldHost);
1310
1311                     if (oldHost->interface) {
1312                         afsUUID uuid = oldHost->interface->uuid;
1313                         cb_conn = oldHost->callback_rxcon;
1314                         rx_GetConnection(cb_conn);
1315                         rx_SetConnDeadTime(cb_conn, 2);
1316                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1317                         H_UNLOCK;
1318                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1319                         H_LOCK;
1320                         rx_SetConnDeadTime(cb_conn, 50);
1321                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1322                         rx_PutConnection(cb_conn);
1323                         cb_conn=NULL;
1324                         if (code && MultiProbeAlternateAddress_r(oldHost)) {
1325                             probefail = 1;
1326                         }
1327                     } else {
1328                         probefail = 1;
1329                     }
1330
1331                     if (probefail) {
1332                         /* The old host is either does not have a Uuid,
1333                          * is not responding to Probes, 
1334                          * or does not have a matching Uuid. 
1335                          * Delete it! */
1336                         oldHost->hostFlags |= HOSTDELETED;
1337                         h_Unlock_r(oldHost);
1338                         /* Let the holder be last release */
1339                         if (!oheld) {
1340                             h_Release_r(oldHost);
1341                         }
1342                         oldHost = NULL;
1343                     }
1344                 }
1345                 if (oldHost) {
1346                     /* This is a new address for an existing host. Update
1347                      * the list of interfaces for the existing host and
1348                      * delete the host structure we just allocated. */
1349                     if (oldHost->host != haddr || oldHost->port != hport) {
1350                         ViceLog(25,
1351                                 ("CB: new addr %s:%d for old host %s:%d\n",
1352                                   afs_inet_ntoa_r(haddr, hoststr),
1353                                   ntohs(hport), 
1354                                   afs_inet_ntoa_r(oldHost->host, hoststr2),
1355                                   ntohs(oldHost->port)));
1356                         if (oldHost->host == haddr) {
1357                             /* We have just been contacted by a client behind a NAT */
1358                             removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
1359                         } else {
1360                             int i, found;
1361                             struct Interface *interface = oldHost->interface;
1362                             int number = oldHost->interface->numberOfInterfaces;
1363                             for (i = 0, found = 0; i < number; i++) {
1364                                 if (interface->interface[i].addr == haddr &&
1365                                     interface->interface[i].port != hport) {
1366                                     found = 1;
1367                                     break;
1368                                 }
1369                             }
1370                             if (found) {
1371                                 /* We have just been contacted by a client that has been
1372                                  * seen from behind a NAT and at least one other address.
1373                                  */
1374                                 removeInterfaceAddr_r(oldHost, haddr, interface->interface[i].port);
1375                             }
1376                         }
1377                         addInterfaceAddr_r(oldHost, haddr, hport);
1378                         oldHost->host = haddr;
1379                         oldHost->port = hport;
1380                     }
1381                     host->hostFlags |= HOSTDELETED;
1382                     h_Unlock_r(host);
1383                     if (!held)
1384                         h_Release_r(host);
1385                     host = oldHost;
1386                 } else {
1387                     /* This really is a new host */
1388                     hashInsertUuid_r(&identP->uuid, host);
1389                     cb_conn = host->callback_rxcon;
1390                     rx_GetConnection(cb_conn);          
1391                     H_UNLOCK;
1392                     code =
1393                         RXAFSCB_InitCallBackState3(cb_conn,
1394                                                    &FS_HostUUID);
1395                     rx_PutConnection(cb_conn);
1396                     cb_conn=NULL;
1397                     H_LOCK;
1398                     if (code == 0) {
1399                         ViceLog(25,
1400                                 ("InitCallBackState3 success on %s:%d\n",
1401                                  afs_inet_ntoa_r(host->host, hoststr),
1402                                  ntohs(host->port)));
1403                         assert(interfValid == 1);
1404                         initInterfaceAddr_r(host, &interf);
1405                     }
1406                 }
1407             }
1408             if (code) {
1409                 afs_inet_ntoa_r(host->host, hoststr);
1410                 ViceLog(0,
1411                         ("CB: RCallBackConnectBack failed for %s:%d\n",
1412                          hoststr, ntohs(host->port)));
1413                 host->hostFlags |= VENUSDOWN;
1414             } else {
1415                 ViceLog(125,
1416                         ("CB: RCallBackConnectBack succeeded for %s:%d\n",
1417                          hoststr, ntohs(host->port)));
1418                 host->hostFlags |= RESETDONE;
1419             }
1420         }
1421         if (caps.Capabilities_val
1422             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1423             host->hostFlags |= HERRORTRANS;
1424         else
1425             host->hostFlags &= ~(HERRORTRANS);
1426         host->hostFlags |= ALTADDR;     /* host structure initialization complete */
1427         h_Unlock_r(host);
1428     }
1429     if (caps.Capabilities_val)
1430         free(caps.Capabilities_val);
1431     caps.Capabilities_val = NULL;
1432     caps.Capabilities_len = 0;
1433     return host;
1434
1435 }                               /*h_GetHost_r */
1436
1437
1438 static char localcellname[PR_MAXNAMELEN + 1];
1439 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
1440 int  num_lrealms = -1;
1441
1442 /* not reentrant */
1443 void
1444 h_InitHostPackage()
1445 {
1446     afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
1447     if (num_lrealms == -1) {
1448         int i;
1449         for (i=0; i<AFS_NUM_LREALMS; i++) {
1450             if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
1451                 break;
1452         }
1453
1454         if (i=0) {
1455             ViceLog(0,
1456                     ("afs_krb_get_lrealm failed, using %s.\n",
1457                      localcellname));
1458             strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
1459             num_lrealms = i =1;
1460         } else {
1461             num_lrealms = i;
1462         }
1463
1464         /* initialize the rest of the local realms to nullstring for debugging */
1465         for (; i<AFS_NUM_LREALMS; i++)
1466             local_realms[i][0] = '\0';
1467     }
1468     rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
1469     rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
1470 #ifdef AFS_PTHREAD_ENV
1471     assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
1472 #endif /* AFS_PTHREAD_ENV */
1473 }
1474
1475 static int
1476 MapName_r(char *aname, char *acell, afs_int32 * aval)
1477 {
1478     namelist lnames;
1479     idlist lids;
1480     afs_int32 code;
1481     afs_int32 anamelen, cnamelen;
1482     int foreign = 0;
1483     char *tname;
1484
1485     anamelen = strlen(aname);
1486     if (anamelen >= PR_MAXNAMELEN)
1487         return -1;              /* bad name -- caller interprets this as anonymous, but retries later */
1488
1489     lnames.namelist_len = 1;
1490     lnames.namelist_val = (prname *) aname;     /* don't malloc in the common case */
1491     lids.idlist_len = 0;
1492     lids.idlist_val = NULL;
1493
1494     cnamelen = strlen(acell);
1495     if (cnamelen) {
1496         if (afs_is_foreign_ticket_name(aname, "", acell, localcellname)) {
1497             ViceLog(2,
1498                     ("MapName: cell is foreign.  cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
1499                     acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
1500             if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
1501                 ViceLog(2,
1502                         ("MapName: Name too long, using AnonymousID for %s@%s\n",
1503                          aname, acell));
1504                 *aval = AnonymousID;
1505                 return 0;
1506             }
1507             foreign = 1;        /* attempt cross-cell authentication */
1508             tname = (char *)malloc(PR_MAXNAMELEN);
1509             if (!tname) {
1510                 ViceLog(0, ("Failed malloc in MapName_r\n"));
1511                 assert(0);
1512             }
1513             strcpy(tname, aname);
1514             tname[anamelen] = '@';
1515             strcpy(tname + anamelen + 1, acell);
1516             lnames.namelist_val = (prname *) tname;
1517         }
1518     }
1519
1520     H_UNLOCK;
1521     code = pr_NameToId(&lnames, &lids);
1522     H_LOCK;
1523     if (code == 0) {
1524         if (lids.idlist_val) {
1525             *aval = lids.idlist_val[0];
1526             if (*aval == AnonymousID) {
1527                 ViceLog(2,
1528                         ("MapName: NameToId on %s returns anonymousID\n",
1529                          lnames.namelist_val));
1530             }
1531             free(lids.idlist_val);      /* return parms are not malloced in stub if server proc aborts */
1532         } else {
1533             ViceLog(0,
1534                     ("MapName: NameToId on '%s' is unknown\n",
1535                      lnames.namelist_val));
1536             code = -1;
1537         }
1538     }
1539
1540     if (foreign) {
1541         free(lnames.namelist_val);      /* We allocated this above, so we must free it now. */
1542     }
1543     return code;
1544 }
1545
1546 /*MapName*/
1547
1548
1549 /* NOTE: this returns the client with a Write lock */
1550 struct client *
1551 h_ID2Client(afs_int32 vid)
1552 {
1553     register struct client *client;
1554     register struct host *host;
1555
1556     H_LOCK;
1557     for (host = hostList; host; host = host->next) {
1558         if (host->hostFlags & HOSTDELETED)
1559             continue;
1560         for (client = host->FirstClient; client; client = client->next) {
1561             if (!client->deleted && client->ViceId == vid) {
1562                 client->refCount++;
1563                 H_UNLOCK;
1564                 ObtainWriteLock(&client->lock);
1565                 H_LOCK;
1566                 client->refCount--;
1567                 H_UNLOCK;
1568                 return client;
1569             }
1570         }
1571     }
1572
1573     H_UNLOCK;
1574     return NULL;
1575 }
1576
1577 /*
1578  * Called by the server main loop.  Returns a h_Held client, which must be
1579  * released later the main loop.  Allocates a client if the matching one
1580  * isn't around. The client is returned with its reference count incremented
1581  * by one. The caller must call h_ReleaseClient_r when finished with
1582  * the client.
1583  */
1584 struct client *
1585 h_FindClient_r(struct rx_connection *tcon)
1586 {
1587     register struct client *client;
1588     register struct host *host;
1589     struct client *oldClient;
1590     afs_int32 viceid;
1591     afs_int32 expTime;
1592     afs_int32 code;
1593     int authClass;
1594 #if (64-MAXKTCNAMELEN)
1595     ticket name length != 64
1596 #endif
1597     char tname[64];
1598     char tinst[64];
1599     char uname[PR_MAXNAMELEN];
1600     char tcell[MAXKTCREALMLEN];
1601     int fail = 0;
1602     int created = 0;
1603
1604     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1605     if (client) {
1606         client->refCount++;
1607         h_Hold_r(client->host);
1608         if (!client->deleted && client->prfail != 2) {  
1609             /* Could add shared lock on client here */
1610             /* note that we don't have to lock entry in this path to
1611              * ensure CPS is initialized, since we don't call rx_SetSpecific
1612              * until initialization is done, and we only get here if
1613              * rx_GetSpecific located the client structure.
1614              */
1615             return client;
1616         }
1617         H_UNLOCK;
1618         ObtainWriteLock(&client->lock); /* released at end */
1619         H_LOCK;
1620     }
1621
1622     authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
1623     ViceLog(5,
1624             ("FindClient: authenticating connection: authClass=%d\n",
1625              authClass));
1626     if (authClass == 1) {
1627         /* A bcrypt tickets, no longer supported */
1628         ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
1629         viceid = AnonymousID;
1630         expTime = 0x7fffffff;
1631     } else if (authClass == 2) {
1632         afs_int32 kvno;
1633
1634         /* kerberos ticket */
1635         code = rxkad_GetServerInfo(tcon, /*level */ 0, &expTime,
1636                                    tname, tinst, tcell, &kvno);
1637         if (code) {
1638             ViceLog(1, ("Failed to get rxkad ticket info\n"));
1639             viceid = AnonymousID;
1640             expTime = 0x7fffffff;
1641         } else {
1642             int ilen = strlen(tinst);
1643             ViceLog(5,
1644                     ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
1645                      tname, tinst, tcell, expTime, kvno));
1646             strncpy(uname, tname, sizeof(uname));
1647             if (ilen) {
1648                 if (strlen(uname) + 1 + ilen >= sizeof(uname))
1649                     goto bad_name;
1650                 strcat(uname, ".");
1651                 strcat(uname, tinst);
1652             }
1653             /* translate the name to a vice id */
1654             code = MapName_r(uname, tcell, &viceid);
1655             if (code) {
1656               bad_name:
1657                 ViceLog(1,
1658                         ("failed to map name=%s, cell=%s -> code=%d\n", uname,
1659                          tcell, code));
1660                 fail = 1;
1661                 viceid = AnonymousID;
1662                 expTime = 0x7fffffff;
1663             }
1664         }
1665     } else {
1666         viceid = AnonymousID;   /* unknown security class */
1667         expTime = 0x7fffffff;
1668     }
1669
1670     if (!client) { /* loop */
1671         host = h_GetHost_r(tcon);       /* Returns it h_Held */
1672
1673     retryfirstclient:
1674         /* First try to find the client structure */
1675         for (client = host->FirstClient; client; client = client->next) {
1676             if (!client->deleted && (client->sid == rxr_CidOf(tcon))
1677                 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1678                 if (client->tcon && (client->tcon != tcon)) {
1679                     ViceLog(0,
1680                             ("*** Vid=%d, sid=%x, tcon=%x, Tcon=%x ***\n",
1681                              client->ViceId, client->sid, client->tcon,
1682                              tcon));
1683                     oldClient =
1684                         (struct client *)rx_GetSpecific(client->tcon,
1685                                                         rxcon_client_key);
1686                     if (oldClient) {
1687                         if (oldClient == client)
1688                             rx_SetSpecific(client->tcon, rxcon_client_key,
1689                                            NULL);
1690                         else
1691                             ViceLog(0,
1692                                     ("Client-conn mismatch: CL1=%x, CN=%x, CL2=%x\n",
1693                                      client, client->tcon, oldClient));
1694                     }
1695                     client->tcon = (struct rx_connection *)0;
1696                 }
1697                 client->refCount++;
1698                 H_UNLOCK;
1699                 ObtainWriteLock(&client->lock);
1700                 H_LOCK;
1701                 break;
1702             }
1703         }
1704
1705         /* Still no client structure - get one */
1706         if (!client) {
1707             h_Lock_r(host);
1708             /* Retry to find the client structure */
1709             for (client = host->FirstClient; client; client = client->next) {
1710                 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
1711                     && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1712                     h_Unlock_r(host);
1713                     goto retryfirstclient;
1714                 }
1715             }
1716             created = 1;
1717             client = GetCE();
1718             ObtainWriteLock(&client->lock);
1719             client->refCount = 1;
1720             client->host = host;
1721 #if FS_STATS_DETAILED
1722             client->InSameNetwork = host->InSameNetwork;
1723 #endif /* FS_STATS_DETAILED */
1724             client->ViceId = viceid;
1725             client->expTime = expTime;  /* rx only */
1726             client->authClass = authClass;      /* rx only */
1727             client->sid = rxr_CidOf(tcon);
1728             client->VenusEpoch = rxr_GetEpoch(tcon);
1729             client->CPS.prlist_val = 0;
1730             client->CPS.prlist_len = 0;
1731             h_Unlock_r(host);
1732         }
1733     }
1734     client->prfail = fail;
1735
1736     if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
1737         if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID)) {
1738             free(client->CPS.prlist_val);
1739         }
1740         client->CPS.prlist_val = NULL;
1741         client->CPS.prlist_len = 0;
1742         client->ViceId = viceid;
1743         client->expTime = expTime;
1744
1745         if (viceid == ANONYMOUSID) {
1746             client->CPS.prlist_len = AnonCPS.prlist_len;
1747             client->CPS.prlist_val = AnonCPS.prlist_val;
1748         } else {
1749             H_UNLOCK;
1750             code = pr_GetCPS(viceid, &client->CPS);
1751             H_LOCK;
1752             if (code) {
1753                 char hoststr[16];
1754                 ViceLog(0,
1755                         ("pr_GetCPS failed(%d) for user %d, host %s:%d\n",
1756                          code, viceid, afs_inet_ntoa_r(client->host->host,
1757                                                        hoststr),
1758                          ntohs(client->host->port)));
1759
1760                 /* Although ubik_Call (called by pr_GetCPS) traverses thru
1761                  * all protection servers and reevaluates things if no
1762                  * sync server or quorum is found we could still end up
1763                  * with one of these errors. In such case we would like to
1764                  * reevaluate the rpc call to find if there's cps for this
1765                  * guy. We treat other errors (except network failures
1766                  * ones - i.e. code < 0) as an indication that there is no
1767                  * CPS for this host.  Ideally we could like to deal this
1768                  * problem the other way around (i.e.  if code == NOCPS
1769                  * ignore else retry next time) but the problem is that
1770                  * there're other errors (i.e.  EPERM) for which we don't
1771                  * want to retry and we don't know the whole code list!
1772                  */
1773                 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
1774                     client->prfail = 1;
1775             }
1776         }
1777         /* the disabling of system:administrators is so iffy and has so many
1778          * possible failure modes that we will disable it again */
1779         /* Turn off System:Administrator for safety  
1780          * if (AL_IsAMember(SystemId, client->CPS) == 0)
1781          * assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
1782     }
1783
1784     /* Now, tcon may already be set to a rock, since we blocked with no host
1785      * or client locks set above in pr_GetCPS (XXXX some locking is probably
1786      * required).  So, before setting the RPC's rock, we should disconnect
1787      * the RPC from the other client structure's rock.
1788      */
1789     oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1790     if (oldClient && oldClient->tcon == tcon) {
1791         char hoststr[16];
1792         if (!oldClient->deleted) {
1793             /* if we didn't create it, it's not ours to put back */
1794             if (created) {
1795                 ViceLog(0, ("FindClient: stillborn client %x(%x); conn %x (host %s:%d) had client %x(%x)\n", 
1796                             client, client->sid, tcon, 
1797                             afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
1798                             ntohs(rxr_PortOf(tcon)),
1799                             oldClient, oldClient->sid));
1800                 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val) {
1801                     free(client->CPS.prlist_val);
1802                     client->CPS.prlist_val = NULL;
1803                 }
1804                 client->CPS.prlist_len = 0;
1805                 if (client->tcon) {
1806                     rx_SetSpecific(client->tcon, rxcon_client_key, (void *)0);
1807                 }
1808             }
1809             /* We should perhaps check for 0 here */
1810             client->refCount--;
1811             ReleaseWriteLock(&client->lock);
1812             if (created) {
1813                 FreeCE(client);
1814                 created = 0;
1815             } 
1816             ObtainWriteLock(&oldClient->lock);
1817             oldClient->refCount++;
1818             client = oldClient;
1819         } else {
1820             oldClient->tcon = (struct rx_connection *)0;
1821             ViceLog(0, ("FindClient: deleted client %x(%x) already had conn %x (host %s:%d), stolen by client %x(%x)\n", 
1822                         oldClient, oldClient->sid, tcon, 
1823                         afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
1824                         ntohs(rxr_PortOf(tcon)),
1825                         client, client->sid));
1826             /* rx_SetSpecific will be done immediately below */
1827         }
1828     }
1829     /* Avoid chaining in more than once. */
1830     if (created) {
1831         h_Lock_r(host);
1832         client->next = host->FirstClient;
1833         host->FirstClient = client;
1834         h_Unlock_r(host);
1835         CurrentConnections++;   /* increment number of connections */
1836     }
1837     client->tcon = tcon;
1838     rx_SetSpecific(tcon, rxcon_client_key, client);
1839     ReleaseWriteLock(&client->lock);
1840
1841     return client;
1842
1843 }                               /*h_FindClient_r */
1844
1845 int
1846 h_ReleaseClient_r(struct client *client)
1847 {
1848     assert(client->refCount > 0);
1849     client->refCount--;
1850     return 0;
1851 }
1852
1853
1854 /*
1855  * Sigh:  this one is used to get the client AGAIN within the individual
1856  * server routines.  This does not bother h_Holding the host, since
1857  * this is assumed already have been done by the server main loop.
1858  * It does check tokens, since only the server routines can return the
1859  * VICETOKENDEAD error code
1860  */
1861 int
1862 GetClient(struct rx_connection *tcon, struct client **cp)
1863 {
1864     register struct client *client;
1865
1866     H_LOCK;
1867     *cp = NULL;
1868     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1869     if (client == NULL || client->tcon == NULL) {
1870         ViceLog(0,
1871                 ("GetClient: no client in conn %x (host %x:%d), VBUSYING\n",
1872                  tcon, rxr_HostOf(tcon),ntohs(rxr_PortOf(tcon))));
1873         H_UNLOCK;
1874         return VBUSY;
1875     }
1876     if (rxr_CidOf(client->tcon) != client->sid) {
1877         ViceLog(0,
1878                 ("GetClient: tcon %x tcon sid %d client sid %d\n",
1879                  client->tcon, rxr_CidOf(client->tcon), client->sid));
1880         H_UNLOCK;
1881         return VBUSY;
1882     }
1883     if (!(client && client->tcon && rxr_CidOf(client->tcon) == client->sid)) {
1884         if (!client)
1885             ViceLog(0, ("GetClient: no client in conn %x\n", tcon));
1886         else
1887             ViceLog(0,
1888                     ("GetClient: tcon %x tcon sid %d client sid %d\n",
1889                      client->tcon, client->tcon ? rxr_CidOf(client->tcon)
1890                      : -1, client->sid));
1891         assert(0);
1892     }
1893     if (client && client->LastCall > client->expTime && client->expTime) {
1894         char hoststr[16];
1895         ViceLog(1,
1896                 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
1897                  afs_inet_ntoa_r(client->host->host, hoststr),
1898                  ntohs(client->host->port), client->expTime));
1899         H_UNLOCK;
1900         return VICETOKENDEAD;
1901     }
1902
1903     client->refCount++;
1904     *cp = client;
1905     H_UNLOCK;
1906     return 0;
1907 }                               /*GetClient */
1908
1909 int
1910 PutClient(struct client **cp)
1911 {
1912     if (*cp == NULL) 
1913         return -1;
1914
1915     H_LOCK;
1916     h_ReleaseClient_r(*cp);
1917     *cp = NULL;
1918     H_UNLOCK;
1919     return 0;
1920 }                               /*PutClient */
1921
1922
1923 /* Client user name for short term use.  Note that this is NOT inexpensive */
1924 char *
1925 h_UserName(struct client *client)
1926 {
1927     static char User[PR_MAXNAMELEN + 1];
1928     namelist lnames;
1929     idlist lids;
1930
1931     lids.idlist_len = 1;
1932     lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
1933     if (!lids.idlist_val) {
1934         ViceLog(0, ("Failed malloc in h_UserName\n"));
1935         assert(0);
1936     }
1937     lnames.namelist_len = 0;
1938     lnames.namelist_val = (prname *) 0;
1939     lids.idlist_val[0] = client->ViceId;
1940     if (pr_IdToName(&lids, &lnames)) {
1941         /* We need to free id we alloced above! */
1942         free(lids.idlist_val);
1943         return "*UNKNOWN USER NAME*";
1944     }
1945     strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
1946     free(lids.idlist_val);
1947     free(lnames.namelist_val);
1948     return User;
1949
1950 }                               /*h_UserName */
1951
1952
1953 void
1954 h_PrintStats()
1955 {
1956     ViceLog(0,
1957             ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
1958              CEs, CEBlocks, HTs, HTBlocks));
1959
1960 }                               /*h_PrintStats */
1961
1962
1963 static int
1964 h_PrintClient(register struct host *host, int held, StreamHandle_t * file)
1965 {
1966     register struct client *client;
1967     int i;
1968     char tmpStr[256];
1969     char tbuffer[32];
1970     char hoststr[16];
1971
1972     H_LOCK;
1973     if (host->hostFlags & HOSTDELETED) {
1974         H_UNLOCK;
1975         return held;
1976     }
1977     (void)afs_snprintf(tmpStr, sizeof tmpStr,
1978                        "Host %s:%d down = %d, LastCall %s",
1979                        afs_inet_ntoa_r(host->host, hoststr),
1980                        ntohs(host->port), (host->hostFlags & VENUSDOWN),
1981                        afs_ctime((time_t *) & host->LastCall, tbuffer,
1982                                  sizeof(tbuffer)));
1983     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1984     for (client = host->FirstClient; client; client = client->next) {
1985         if (!client->deleted) {
1986             if (client->tcon) {
1987                 (void)afs_snprintf(tmpStr, sizeof tmpStr,
1988                                    "    user id=%d,  name=%s, sl=%s till %s",
1989                                    client->ViceId, h_UserName(client),
1990                                    client->
1991                                    authClass ? "Authenticated" :
1992                                    "Not authenticated",
1993                                    client->
1994                                    authClass ? afs_ctime((time_t *) & client->
1995                                                          expTime, tbuffer,
1996                                                          sizeof(tbuffer))
1997                                    : "No Limit\n");
1998                 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1999             } else {
2000                 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2001                                    "    user=%s, no current server connection\n",
2002                                    h_UserName(client));
2003                 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2004             }
2005             (void)afs_snprintf(tmpStr, sizeof tmpStr, "      CPS-%d is [",
2006                                client->CPS.prlist_len);
2007             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2008             if (client->CPS.prlist_val) {
2009                 for (i = 0; i > client->CPS.prlist_len; i++) {
2010                     (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2011                                        client->CPS.prlist_val[i]);
2012                     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2013                 }
2014             }
2015             sprintf(tmpStr, "]\n");
2016             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2017         }
2018     }
2019     H_UNLOCK;
2020     return held;
2021
2022 }                               /*h_PrintClient */
2023
2024
2025
2026 /*
2027  * Print a list of clients, with last security level and token value seen,
2028  * if known
2029  */
2030 void
2031 h_PrintClients()
2032 {
2033     time_t now;
2034     char tmpStr[256];
2035     char tbuffer[32];
2036
2037     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2038
2039     if (file == NULL) {
2040         ViceLog(0,
2041                 ("Couldn't create client dump file %s\n",
2042                  AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2043         return;
2044     }
2045     now = FT_ApproxTime();
2046     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
2047                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2048     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2049     h_Enumerate(h_PrintClient, (char *)file);
2050     STREAM_REALLYCLOSE(file);
2051     ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2052 }
2053
2054
2055
2056
2057 static int
2058 h_DumpHost(register struct host *host, int held, StreamHandle_t * file)
2059 {
2060     int i;
2061     char tmpStr[256];
2062     char hoststr[16];
2063
2064     H_LOCK;
2065     (void)afs_snprintf(tmpStr, sizeof tmpStr,
2066                        "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 [",
2067                        afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), host->index,
2068                        host->cblist, CheckLock(&host->lock), host->LastCall,
2069                        host->ActiveCall, (host->hostFlags & VENUSDOWN),
2070                        host->hostFlags & HOSTDELETED, host->Console,
2071                        host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2072                        host->cpsCall);
2073     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2074     if (host->hcps.prlist_val)
2075         for (i = 0; i < host->hcps.prlist_len; i++) {
2076             (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2077                                host->hcps.prlist_val[i]);
2078             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2079         }
2080     sprintf(tmpStr, "] [");
2081     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2082     if (host->interface)
2083         for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2084             char hoststr[16];
2085             sprintf(tmpStr, " %s:%d", 
2086                      afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2087                      ntohs(host->interface->interface[i].port));
2088             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2089         }
2090     sprintf(tmpStr, "] holds: ");
2091     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2092
2093     for (i = 0; i < h_maxSlots; i++) {
2094         sprintf(tmpStr, "%04x", host->holds[i]);
2095         (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2096     }
2097     sprintf(tmpStr, " slot/bit: %d/%d\n", h_holdSlot(), h_holdbit());
2098     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2099
2100     H_UNLOCK;
2101     return held;
2102
2103 }                               /*h_DumpHost */
2104
2105
2106 void
2107 h_DumpHosts()
2108 {
2109     time_t now;
2110     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2111     char tmpStr[256];
2112     char tbuffer[32];
2113
2114     if (file == NULL) {
2115         ViceLog(0,
2116                 ("Couldn't create host dump file %s\n",
2117                  AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2118         return;
2119     }
2120     now = FT_ApproxTime();
2121     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
2122                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2123     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2124     h_Enumerate(h_DumpHost, (char *)file);
2125     STREAM_REALLYCLOSE(file);
2126     ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2127
2128 }                               /*h_DumpHosts */
2129
2130
2131 /*
2132  * This counts the number of workstations, the number of active workstations,
2133  * and the number of workstations declared "down" (i.e. not heard from
2134  * recently).  An active workstation has received a call since the cutoff
2135  * time argument passed.
2136  */
2137 void
2138 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
2139 {
2140     register struct host *host;
2141     register int num = 0, active = 0, del = 0;
2142
2143     H_LOCK;
2144     for (host = hostList; host; host = host->next) {
2145         if (!(host->hostFlags & HOSTDELETED)) {
2146             num++;
2147             if (host->ActiveCall > cutofftime)
2148                 active++;
2149             if (host->hostFlags & VENUSDOWN)
2150                 del++;
2151         }
2152     }
2153     H_UNLOCK;
2154     if (nump)
2155         *nump = num;
2156     if (activep)
2157         *activep = active;
2158     if (delp)
2159         *delp = del;
2160
2161 }                               /*h_GetWorkStats */
2162
2163
2164 /*------------------------------------------------------------------------
2165  * PRIVATE h_ClassifyAddress
2166  *
2167  * Description:
2168  *      Given a target IP address and a candidate IP address (both
2169  *      in host byte order), classify the candidate into one of three
2170  *      buckets in relation to the target by bumping the counters passed
2171  *      in as parameters.
2172  *
2173  * Arguments:
2174  *      a_targetAddr       : Target address.
2175  *      a_candAddr         : Candidate address.
2176  *      a_sameNetOrSubnetP : Ptr to counter to bump when the two
2177  *                           addresses are either in the same network
2178  *                           or the same subnet.
2179  *      a_diffSubnetP      : ...when the candidate is in a different
2180  *                           subnet.
2181  *      a_diffNetworkP     : ...when the candidate is in a different
2182  *                           network.
2183  *
2184  * Returns:
2185  *      Nothing.
2186  *
2187  * Environment:
2188  *      The target and candidate addresses are both in host byte
2189  *      order, NOT network byte order, when passed in.
2190  *
2191  * Side Effects:
2192  *      As advertised.
2193  *------------------------------------------------------------------------*/
2194
2195 static void
2196 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
2197                   afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
2198                   afs_int32 * a_diffNetworkP)
2199 {                               /*h_ClassifyAddress */
2200
2201     afs_uint32 targetNet;
2202     afs_uint32 targetSubnet;
2203     afs_uint32 candNet;
2204     afs_uint32 candSubnet;
2205
2206     /*
2207      * Put bad values into the subnet info to start with.
2208      */
2209     targetSubnet = (afs_uint32) 0;
2210     candSubnet = (afs_uint32) 0;
2211
2212     /*
2213      * Pull out the network and subnetwork numbers from the target
2214      * and candidate addresses.  We can short-circuit this whole
2215      * affair if the target and candidate addresses are not of the
2216      * same class.
2217      */
2218     if (IN_CLASSA(a_targetAddr)) {
2219         if (!(IN_CLASSA(a_candAddr))) {
2220             (*a_diffNetworkP)++;
2221             return;
2222         }
2223         targetNet = a_targetAddr & IN_CLASSA_NET;
2224         candNet = a_candAddr & IN_CLASSA_NET;
2225         if (IN_SUBNETA(a_targetAddr))
2226             targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
2227         if (IN_SUBNETA(a_candAddr))
2228             candSubnet = a_candAddr & IN_CLASSA_SUBNET;
2229     } else if (IN_CLASSB(a_targetAddr)) {
2230         if (!(IN_CLASSB(a_candAddr))) {
2231             (*a_diffNetworkP)++;
2232             return;
2233         }
2234         targetNet = a_targetAddr & IN_CLASSB_NET;
2235         candNet = a_candAddr & IN_CLASSB_NET;
2236         if (IN_SUBNETB(a_targetAddr))
2237             targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
2238         if (IN_SUBNETB(a_candAddr))
2239             candSubnet = a_candAddr & IN_CLASSB_SUBNET;
2240     } /*Class B target */
2241     else if (IN_CLASSC(a_targetAddr)) {
2242         if (!(IN_CLASSC(a_candAddr))) {
2243             (*a_diffNetworkP)++;
2244             return;
2245         }
2246         targetNet = a_targetAddr & IN_CLASSC_NET;
2247         candNet = a_candAddr & IN_CLASSC_NET;
2248
2249         /*
2250          * Note that class C addresses can't have subnets,
2251          * so we leave the defaults untouched.
2252          */
2253     } /*Class C target */
2254     else {
2255         targetNet = a_targetAddr;
2256         candNet = a_candAddr;
2257     }                           /*Class D address */
2258
2259     /*
2260      * Now, simply compare the extracted net and subnet values for
2261      * the two addresses (which at this point are known to be of the
2262      * same class)
2263      */
2264     if (targetNet == candNet) {
2265         if (targetSubnet == candSubnet)
2266             (*a_sameNetOrSubnetP)++;
2267         else
2268             (*a_diffSubnetP)++;
2269     } else
2270         (*a_diffNetworkP)++;
2271
2272 }                               /*h_ClassifyAddress */
2273
2274
2275 /*------------------------------------------------------------------------
2276  * EXPORTED h_GetHostNetStats
2277  *
2278  * Description:
2279  *      Iterate through the host table, and classify each (non-deleted)
2280  *      host entry into ``proximity'' categories (same net or subnet,
2281  *      different subnet, different network).
2282  *
2283  * Arguments:
2284  *      a_numHostsP        : Set to total number of (non-deleted) hosts.
2285  *      a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
2286  *      a_diffSubnetP      : Set to # hosts on diff subnet as server.
2287  *      a_diffNetworkP     : Set to # hosts on diff network as server.
2288  *
2289  * Returns:
2290  *      Nothing.
2291  *
2292  * Environment:
2293  *      We only count non-deleted hosts.  The storage pointed to by our
2294  *      parameters is zeroed upon entry.
2295  *
2296  * Side Effects:
2297  *      As advertised.
2298  *------------------------------------------------------------------------*/
2299
2300 void
2301 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
2302                   afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
2303 {                               /*h_GetHostNetStats */
2304
2305     register struct host *hostP;        /*Ptr to current host entry */
2306     register afs_uint32 currAddr_HBO;   /*Curr host addr, host byte order */
2307
2308     /*
2309      * Clear out the storage pointed to by our parameters.
2310      */
2311     *a_numHostsP = (afs_int32) 0;
2312     *a_sameNetOrSubnetP = (afs_int32) 0;
2313     *a_diffSubnetP = (afs_int32) 0;
2314     *a_diffNetworkP = (afs_int32) 0;
2315
2316     H_LOCK;
2317     for (hostP = hostList; hostP; hostP = hostP->next) {
2318         if (!(hostP->hostFlags & HOSTDELETED)) {
2319             /*
2320              * Bump the number of undeleted host entries found.
2321              * In classifying the current entry's address, make
2322              * sure to first convert to host byte order.
2323              */
2324             (*a_numHostsP)++;
2325             currAddr_HBO = (afs_uint32) ntohl(hostP->host);
2326             h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
2327                               a_sameNetOrSubnetP, a_diffSubnetP,
2328                               a_diffNetworkP);
2329         }                       /*Only look at non-deleted hosts */
2330     }                           /*For each host record hashed to this index */
2331     H_UNLOCK;
2332 }                               /*h_GetHostNetStats */
2333
2334 static afs_uint32 checktime;
2335 static afs_uint32 clientdeletetime;
2336 static struct AFSFid zerofid;
2337
2338
2339 /*
2340  * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
2341  * Since it can serialize them, and pile up, it should be a separate LWP
2342  * from other events.
2343  */
2344 int
2345 CheckHost(register struct host *host, int held)
2346 {
2347     register struct client *client;
2348     struct rx_connection *cb_conn = NULL;
2349     int code;
2350
2351     /* Host is held by h_Enumerate */
2352     H_LOCK;
2353     for (client = host->FirstClient; client; client = client->next) {
2354         if (client->refCount == 0 && client->LastCall < clientdeletetime) {
2355             client->deleted = 1;
2356             host->hostFlags |= CLIENTDELETED;
2357         }
2358     }
2359     if (host->LastCall < checktime) {
2360         h_Lock_r(host);
2361         if (!(host->hostFlags & HOSTDELETED)) {
2362             cb_conn = host->callback_rxcon;
2363             rx_GetConnection(cb_conn);
2364             if (host->LastCall < clientdeletetime) {
2365                 host->hostFlags |= HOSTDELETED;
2366                 if (!(host->hostFlags & VENUSDOWN)) {
2367                     host->hostFlags &= ~ALTADDR;        /* alternate address invalid */
2368                     if (host->interface) {
2369                         H_UNLOCK;
2370                         code =
2371                             RXAFSCB_InitCallBackState3(cb_conn,
2372                                                        &FS_HostUUID);
2373                         H_LOCK;
2374                     } else {
2375                         H_UNLOCK;
2376                         code =
2377                             RXAFSCB_InitCallBackState(cb_conn);
2378                         H_LOCK;
2379                     }
2380                     host->hostFlags |= ALTADDR; /* alternate addresses valid */
2381                     if (code) {
2382                         char hoststr[16];
2383                         (void)afs_inet_ntoa_r(host->host, hoststr);
2384                         ViceLog(0,
2385                                 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
2386                                  hoststr, ntohs(host->port)));
2387                         host->hostFlags |= VENUSDOWN;
2388                     }
2389                     /* Note:  it's safe to delete hosts even if they have call
2390                      * back state, because break delayed callbacks (called when a
2391                      * message is received from the workstation) will always send a 
2392                      * break all call backs to the workstation if there is no
2393                      *callback.
2394                      */
2395                 }
2396             } else {
2397                 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
2398                     if (host->interface) {
2399                         afsUUID uuid = host->interface->uuid;
2400                         H_UNLOCK;
2401                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2402                         H_LOCK;
2403                         if (code) {
2404                             if (MultiProbeAlternateAddress_r(host)) {
2405                                 char hoststr[16];
2406                                 (void)afs_inet_ntoa_r(host->host, hoststr);
2407                                 ViceLog(0,
2408                                         ("ProbeUuid failed for host %s:%d\n",
2409                                          hoststr, ntohs(host->port)));
2410                                 host->hostFlags |= VENUSDOWN;
2411                             }
2412                         }
2413                     } else {
2414                         H_UNLOCK;
2415                         code = RXAFSCB_Probe(cb_conn);
2416                         H_LOCK;
2417                         if (code) {
2418                             char hoststr[16];
2419                             (void)afs_inet_ntoa_r(host->host, hoststr);
2420                             ViceLog(0,
2421                                     ("Probe failed for host %s:%d\n", hoststr,
2422                                      ntohs(host->port)));
2423                             host->hostFlags |= VENUSDOWN;
2424                         }
2425                     }
2426                 }
2427             }
2428             H_UNLOCK;
2429             rx_PutConnection(cb_conn);
2430             cb_conn=NULL;
2431             H_LOCK;
2432         }
2433         h_Unlock_r(host);
2434     }
2435     H_UNLOCK;
2436     return held;
2437
2438 }                               /*CheckHost */
2439
2440
2441 /*
2442  * Set VenusDown for any hosts that have not had a call in 15 minutes and
2443  * don't respond to a probe.  Note that VenusDown can only be cleared if
2444  * a message is received from the host (see ServerLWP in file.c).
2445  * Delete hosts that have not had any calls in 1 hour, clients that
2446  * have not had any calls in 15 minutes.
2447  *
2448  * This routine is called roughly every 5 minutes.
2449  */
2450 void
2451 h_CheckHosts()
2452 {
2453     afs_uint32 now = FT_ApproxTime();
2454
2455     memset((char *)&zerofid, 0, sizeof(zerofid));
2456     /*
2457      * Send a probe to the workstation if it hasn't been heard from in
2458      * 15 minutes
2459      */
2460     checktime = now - 15 * 60;
2461     clientdeletetime = now - 120 * 60;  /* 2 hours ago */
2462     h_Enumerate(CheckHost, NULL);
2463
2464 }                               /*h_CheckHosts */
2465
2466 /*
2467  * This is called with host locked and held. At this point, the
2468  * hostHashTable should not have any entries for the alternate
2469  * interfaces. This function has to insert these entries in the
2470  * hostHashTable.
2471  *
2472  * The addresses in the interfaceAddr list are in host byte order.
2473  */
2474 int
2475 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
2476 {
2477     int i, j;
2478     int number, count;
2479     afs_uint32 myAddr;
2480     afs_uint16 myPort;
2481     int found;
2482     struct Interface *interface;
2483
2484     assert(host);
2485     assert(interf);
2486
2487     ViceLog(125,
2488             ("initInterfaceAddr : host %x numAddr %d\n", host->host,
2489              interf->numberOfInterfaces));
2490
2491     number = interf->numberOfInterfaces;
2492     myAddr = host->host;        /* current interface address */
2493     myPort = host->port;        /* current port */
2494
2495     /* validation checks */
2496     if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
2497         ViceLog(0,
2498                 ("Number of alternate addresses returned is %d\n", number));
2499         return -1;
2500     }
2501
2502     /*
2503      * Convert IP addresses to network byte order, and remove for
2504      * duplicate IP addresses from the interface list.
2505      */
2506     for (i = 0, count = 0, found = 0; i < number; i++) {
2507         interf->addr_in[i] = htonl(interf->addr_in[i]);
2508         for (j = 0; j < count; j++) {
2509             if (interf->addr_in[j] == interf->addr_in[i])
2510                 break;
2511         }
2512         if (j == count) {
2513             interf->addr_in[count] = interf->addr_in[i];
2514             if (interf->addr_in[count] == myAddr)
2515                 found = 1;
2516             count++;
2517         }
2518     }
2519
2520     /*
2521      * Allocate and initialize an interface structure for this host.
2522      */
2523     if (found) {
2524         interface = (struct Interface *)
2525             malloc(sizeof(struct Interface) +
2526                    (sizeof(struct AddrPort) * (count - 1)));
2527         if (!interface) {
2528             ViceLog(0, ("Failed malloc in initInterfaceAddr_r\n"));
2529             assert(0);
2530         }
2531         interface->numberOfInterfaces = count;
2532     } else {
2533         interface = (struct Interface *)
2534             malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
2535         assert(interface);
2536         interface->numberOfInterfaces = count + 1;
2537         interface->interface[count].addr = myAddr;
2538         interface->interface[count].port = myPort;
2539     }
2540     interface->uuid = interf->uuid;
2541     for (i = 0; i < count; i++) {
2542         interface->interface[i].addr = interf->addr_in[i];
2543         /* We store the port as 7001 because the addresses reported by 
2544          * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
2545          * are coming from fully connected hosts (no NAT/PATs)
2546          */
2547         interface->interface[i].port = htons(7001);
2548     }
2549
2550     assert(!host->interface);
2551     host->interface = interface;
2552
2553     for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2554         char hoststr[16];
2555         ViceLog(125, ("--- alt address %s:%d\n", 
2556                        afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2557                        ntohs(host->interface->interface[i].port)));
2558     }
2559
2560     return 0;
2561 }
2562
2563 /* deleted a HashChain structure for this address and host */
2564 /* returns 1 on success */
2565 static int
2566 hashDelete_r(afs_uint32 addr, afs_uint16 port, struct host *host)
2567 {
2568     int flag;
2569     register struct h_hashChain **hp, *th;
2570
2571     for (hp = &hostHashTable[h_HashIndex(addr)]; (th = *hp);) {
2572         assert(th->hostPtr);
2573         if (th->hostPtr == host && th->addr == addr && th->port == port) {
2574             *hp = th->next;
2575             free(th);
2576             flag = 1;
2577             break;
2578         } else {
2579             hp = &th->next;
2580         }
2581     }
2582     return flag;
2583 }
2584
2585
2586 /*
2587 ** prints out all alternate interface address for the host. The 'level'
2588 ** parameter indicates what level of debugging sets this output
2589 */
2590 void
2591 printInterfaceAddr(struct host *host, int level)
2592 {
2593     int i, number;
2594     char hoststr[16];
2595
2596     if (host->interface) {
2597         /* check alternate addresses */
2598         number = host->interface->numberOfInterfaces;
2599         assert(number > 0);
2600         for (i = 0; i < number; i++)
2601             ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2602                              ntohs(host->interface->interface[i].port)));
2603     }
2604     ViceLog(level, ("\n"));
2605 }