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