pull-prototypes-to-head-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: Calls (*proc)(host, held, param) for at least each host in
921  * the at the start of the enumeration (perhaps more).  Hosts may be deleted
922  * (have delete flag set); ditto for clients.  (*proc) is always called with
923  * host h_held() and the global host lock (H_LOCK) locked.The hold state of the
924  * host with respect to this lwp is passed to (*proc) as the param held.
925  * The proc should return 0 if the host should be released, 1 if it should
926  * be held after enumeration.
927  */
928 h_Enumerate_r(proc, param)
929     int (*proc)();
930     char *param;
931
932 {
933     register struct host *host;
934     register int held;
935     
936     if (hostCount == 0) {
937         return;
938     }
939     for (host = hostList ; host ; host = host->next) {
940         if (!(held = h_Held_r(host)))
941             h_Hold_r(host);
942         held = (*proc)(host, held, param);
943         if (!held)
944             h_Release_r(host);/* this might free up the host */
945     }
946 } /*h_Enumerate*/
947
948
949 /* Host is returned held */
950 struct host *h_GetHost_r(tcon)
951     struct rx_connection *tcon;
952
953 {
954     struct host *host;
955     struct host *oldHost;
956     int code;
957     int held;
958     struct interfaceAddr interf;
959     int interfValid = 0;
960     afs_int32   buffer[AFS_MAX_INTERFACE_ADDR];
961     struct Identity *identP = NULL;
962     afs_int32 haddr;
963     afs_int32 hport;
964     int i, j, count;
965     char hoststr[16], hoststr2[16];
966
967     haddr = rxr_HostOf(tcon);
968     hport = rxr_PortOf(tcon);
969 retry:
970     code = 0;
971     identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
972     host = h_Lookup_r(haddr, hport, &held);
973     if (host && !identP && !(host->Console&1)) {
974         /* This is a new connection, and we already have a host
975          * structure for this address. Verify that the identity
976          * of the caller matches the identity in the host structure.
977          */
978         h_Lock_r(host);
979         if ( !(host->hostFlags & ALTADDR) )
980         {
981                 /* Another thread is doing initialization */
982                 h_Unlock_r(host);
983                 if ( !held) h_Release_r(host);
984                 ViceLog(125, ("Host %s:%d starting h_Lookup again\n",
985                              afs_inet_ntoa_r(host->host, hoststr), host->port));
986                 goto retry;
987         }
988         host->hostFlags &= ~ALTADDR;
989         H_UNLOCK
990         code = RXAFSCB_WhoAreYou(host->callback_rxcon, &interf);
991         H_LOCK
992         if ( code == RXGEN_OPCODE ) {
993                 identP = (struct Identity *)malloc(sizeof(struct Identity));
994                 identP->valid = 0;
995                 rx_SetSpecific(tcon, rxcon_ident_key, identP);
996                 /* The host on this connection was unable to respond to 
997                  * the WhoAreYou. We will treat this as a new connection
998                  * from the existing host. The worst that can happen is
999                  * that we maintain some extra callback state information */
1000                 if (host->interface) {
1001                     ViceLog(0,
1002                             ("Host %s:%d used to support WhoAreYou, deleting.\n",
1003                             afs_inet_ntoa_r(host->host, hoststr), host->port));
1004                     host->hostFlags |= HOSTDELETED;
1005                     h_Unlock_r(host);
1006                     if (!held) h_Release_r(host);
1007                     host = NULL;
1008                     goto retry;
1009                 }
1010         } else if (code == 0) {
1011                 interfValid = 1;
1012                 identP = (struct Identity *)malloc(sizeof(struct Identity));
1013                 identP->valid = 1;
1014                 identP->uuid = interf.uuid;
1015                 rx_SetSpecific(tcon, rxcon_ident_key, identP);
1016                 /* Check whether the UUID on this connection matches
1017                  * the UUID in the host structure. If they don't match
1018                  * then this is not the same host as before. */
1019                 if ( !host->interface
1020                   || !afs_uuid_equal(&interf.uuid, &host->interface->uuid) ) {
1021                     ViceLog(25,
1022                             ("Host %s:%d has changed its identity, deleting.\n",
1023                             afs_inet_ntoa_r(host->host, hoststr), host->port));
1024                     host->hostFlags |= HOSTDELETED;
1025                     h_Unlock_r(host);
1026                     if (!held) h_Release_r(host);
1027                     host = NULL;
1028                     goto retry;
1029                 }
1030         } else {
1031             afs_inet_ntoa_r(host->host, hoststr);
1032             ViceLog(0,("CB: WhoAreYou failed for %s:%d, error %d\n", 
1033                        hoststr, ntohs(host->port), code));
1034             host->hostFlags |= VENUSDOWN;
1035         }
1036         host->hostFlags |= ALTADDR;
1037         h_Unlock_r(host);
1038     } else if (host) {
1039         if ( ! (host->hostFlags & ALTADDR) ) 
1040         {
1041                 /* another thread is doing the initialisation */
1042                 ViceLog(125, ("Host %s:%d waiting for host-init to complete\n",
1043                              afs_inet_ntoa_r(host->host, hoststr), host->port));
1044                 h_Lock_r(host);
1045                 h_Unlock_r(host);
1046                 if ( !held) h_Release_r(host);
1047                 ViceLog(125, ("Host %s:%d starting h_Lookup again\n",
1048                              afs_inet_ntoa_r(host->host, hoststr), host->port));
1049                 goto retry;
1050         }
1051         /* We need to check whether the identity in the host structure
1052          * matches the identity on the connection. If they don't match
1053          * then treat this a new host. */
1054         if ( !(host->Console&1)
1055           && ( ( !identP->valid && host->interface )
1056             || ( identP->valid && !host->interface )
1057             || ( identP->valid
1058               && !afs_uuid_equal(&identP->uuid, &host->interface->uuid) ) ) ) {
1059                 /* The host in the cache is not the host for this connection */
1060                 host->hostFlags |= HOSTDELETED;
1061                 h_Unlock_r(host);
1062                 if (!held) h_Release_r(host);
1063                 ViceLog(0, ("CB: new identity for host %s:%d, deleting\n",
1064                            afs_inet_ntoa_r(host->host, hoststr), host->port));
1065                 goto retry;
1066         }
1067     } else {
1068         host = h_Alloc_r(tcon);
1069         h_Hold_r(host);
1070         h_Lock_r(host);
1071         h_gethostcps_r(host,FT_ApproxTime());
1072         if (!(host->Console&1)) {
1073             if (!identP || !interfValid) {
1074                 H_UNLOCK
1075                 code = RXAFSCB_WhoAreYou(host->callback_rxcon, &interf);
1076                 H_LOCK
1077                 if ( code == RXGEN_OPCODE ) {
1078                   identP = (struct Identity *)malloc(sizeof(struct Identity));
1079                     identP->valid = 0;
1080                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1081                     ViceLog(25,
1082                             ("Host %s:%d does not support WhoAreYou.\n",
1083                             afs_inet_ntoa_r(host->host, hoststr), host->port));
1084                     code = 0;
1085                 } else if (code == 0) {
1086                     interfValid = 1;
1087                     identP = (struct Identity *)malloc(sizeof(struct Identity));
1088                     identP->valid = 1;
1089                     identP->uuid = interf.uuid;
1090                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1091                     ViceLog(25, ("WhoAreYou success on %s:%d\n",
1092                                 afs_inet_ntoa_r(host->host, hoststr), host->port));
1093                 }
1094             }
1095             if (code == 0 && !identP->valid) {
1096                 H_UNLOCK
1097                 code = RXAFSCB_InitCallBackState(host->callback_rxcon);
1098                 H_LOCK
1099             } else if (code == 0) {
1100                 oldHost = h_LookupUuid_r(&identP->uuid);
1101                 if (oldHost) {
1102                     /* This is a new address for an existing host. Update
1103                      * the list of interfaces for the existing host and
1104                      * delete the host structure we just allocated. */
1105                     if (!(held = h_Held_r(oldHost)))
1106                         h_Hold_r(oldHost);
1107                     h_Lock_r(oldHost);
1108                     ViceLog(25, ("CB: new addr %s:%d for old host %s:%d\n",
1109                                 afs_inet_ntoa_r(host->host, hoststr), host->port,
1110                                 afs_inet_ntoa_r(oldHost->host, hoststr2), oldHost->port));
1111                     host->hostFlags |= HOSTDELETED;
1112                     h_Unlock_r(host);
1113                     h_Release_r(host);
1114                     host = oldHost;
1115                     addInterfaceAddr_r(host, haddr);
1116                 } else {
1117                     /* This really is a new host */
1118                     hashInsertUuid_r(&identP->uuid, host);
1119                     H_UNLOCK
1120                     code = RXAFSCB_InitCallBackState3(host->callback_rxcon,
1121                                                       &FS_HostUUID);
1122                     H_LOCK
1123                     if (code == 0) {
1124                         ViceLog(25, ("InitCallBackState3 success on %s:%d\n",
1125                                     afs_inet_ntoa_r(host->host, hoststr), host->port));
1126                         assert(interfValid == 1);
1127                         initInterfaceAddr_r(host, &interf);
1128                     }
1129                 }
1130            }
1131            if (code) {
1132                afs_inet_ntoa_r(host->host, hoststr);
1133                ViceLog(0,("CB: RCallBackConnectBack failed for %s:%d\n", 
1134                           hoststr, ntohs(host->port)));
1135                host->hostFlags |= VENUSDOWN;
1136             }
1137             else
1138                 host->hostFlags |= RESETDONE;
1139
1140         }
1141         host->hostFlags |= ALTADDR;/* host structure iniatilisation complete */
1142         h_Unlock_r(host);
1143     }
1144     return host;
1145
1146 } /*h_GetHost_r*/
1147
1148
1149 static char localcellname[PR_MAXNAMELEN+1];
1150 char local_realm[AFS_REALM_SZ] = "";
1151
1152 /* not reentrant */
1153 void h_InitHostPackage()
1154 {
1155     afsconf_GetLocalCell (confDir, localcellname, PR_MAXNAMELEN);
1156     if (!local_realm[0]) {
1157         if (afs_krb_get_lrealm(local_realm, 0) != 0/*KSUCCESS*/) {
1158             ViceLog(0, ("afs_krb_get_lrealm failed, using %s.\n",localcellname));
1159             strcpy (local_realm, localcellname);
1160         }
1161     }
1162     rxcon_ident_key = rx_KeyCreate((rx_destructor_t)free);
1163     rxcon_client_key = rx_KeyCreate((rx_destructor_t)0);
1164 #ifdef AFS_PTHREAD_ENV
1165     assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
1166 #endif /* AFS_PTHREAD_ENV */
1167 }
1168
1169 static MapName_r(aname, acell, aval)
1170     char *aname;
1171     char *acell;
1172     afs_int32 *aval;
1173
1174 {
1175     namelist lnames;
1176     idlist lids;
1177     afs_int32 code;
1178     afs_int32 anamelen, cnamelen;
1179     int foreign = 0;
1180     char *tname;
1181
1182     anamelen=strlen(aname);
1183     if (anamelen >= PR_MAXNAMELEN)
1184         return -1; /* bad name -- caller interprets this as anonymous, but retries later */
1185
1186     lnames.namelist_len = 1;
1187     lnames.namelist_val = (prname *) aname;  /* don't malloc in the common case */
1188     lids.idlist_len = 0;
1189     lids.idlist_val = NULL;
1190
1191     cnamelen=strlen(acell);
1192     if (cnamelen) {
1193         if (strcasecmp(local_realm, acell) && strcasecmp(localcellname, acell))  {
1194             ViceLog(2, ("MapName: cell is foreign.  cell=%s, localcell=%s, localrealm=%s\n",
1195                         acell, localcellname, local_realm));
1196             if ((anamelen+cnamelen+1) >= PR_MAXNAMELEN) {
1197                 ViceLog(2, ("MapName: Name too long, using AnonymousID for %s@%s\n",
1198                             aname, acell));
1199                 *aval = AnonymousID;
1200                 return 0;
1201             }               
1202             foreign = 1;  /* attempt cross-cell authentication */
1203             tname = (char *) malloc(anamelen+cnamelen+2);
1204             strcpy(tname, aname);
1205             tname[anamelen] = '@';
1206             strcpy(tname+anamelen+1, acell);
1207             lnames.namelist_val = (prname *) tname;
1208         }
1209     }
1210
1211     H_UNLOCK
1212     code = pr_NameToId(&lnames, &lids); 
1213     H_LOCK
1214     if (code == 0) {
1215        if (lids.idlist_val) {
1216           *aval = lids.idlist_val[0];
1217           if (*aval == AnonymousID) {
1218              ViceLog(2, ("MapName: NameToId on %s returns anonymousID\n", lnames.namelist_val));
1219           }
1220           free(lids.idlist_val);  /* return parms are not malloced in stub if server proc aborts */
1221        } else {
1222           ViceLog(0, ("MapName: NameToId on '%s' is unknown\n", lnames.namelist_val));
1223           code = -1;
1224        }
1225     }
1226
1227     if (foreign) {
1228         free(lnames.namelist_val);  /* We allocated this above, so we must free it now. */
1229     }
1230     return code;
1231 }
1232 /*MapName*/
1233
1234
1235 /* NOTE: this returns the client with a Shared lock */
1236 struct client *h_ID2Client(vid)
1237 afs_int32 vid;
1238 {
1239     register struct client *client;
1240     register struct host *host;
1241
1242     H_LOCK
1243
1244       for (host=hostList; host; host=host->next) {
1245         if (host->hostFlags & HOSTDELETED)
1246           continue;
1247         for (client = host->FirstClient; client; client = client->next) {
1248           if (!client->deleted && client->ViceId == vid) {
1249             client->refCount++;
1250             H_UNLOCK
1251             ObtainSharedLock(&client->lock);
1252             H_LOCK
1253             client->refCount--;
1254             H_UNLOCK
1255             return client;
1256           }
1257         }
1258       }
1259
1260     H_UNLOCK
1261 return 0;
1262 }
1263
1264 /*
1265  * Called by the server main loop.  Returns a h_Held client, which must be
1266  * released later the main loop.  Allocates a client if the matching one
1267  * isn't around. The client is returned with its reference count incremented
1268  * by one. The caller must call h_ReleaseClient_r when finished with
1269  * the client.
1270  */
1271 struct client *h_FindClient_r(tcon)
1272     struct rx_connection *tcon;
1273
1274 {
1275     register struct client *client;
1276     register struct host *host;
1277     struct client *oldClient;
1278     afs_int32 viceid;
1279     afs_int32 expTime;
1280     afs_int32 code;
1281     int authClass;
1282 #if (64-MAXKTCNAMELEN)
1283 ticket name length != 64
1284 #endif
1285     char tname[64];
1286     char tinst[64];
1287     char uname[PR_MAXNAMELEN];
1288     char tcell[MAXKTCREALMLEN];
1289     int fail = 0;
1290
1291     client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key);
1292     if (client && !client->deleted) {
1293        client->refCount++;
1294        h_Hold_r(client->host);
1295        if (client->prfail != 2) {  /* Could add shared lock on client here */
1296           /* note that we don't have to lock entry in this path to
1297            * ensure CPS is initialized, since we don't call rxr_SetSpecific
1298            * until initialization is done, and we only get here if
1299            * rx_GetSpecific located the client structure.
1300            */
1301           return client;
1302        }
1303        H_UNLOCK
1304        ObtainWriteLock(&client->lock); /* released at end */
1305        H_LOCK
1306     } else if (client) {
1307        client->refCount++;
1308     }
1309
1310     authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
1311     ViceLog(5,("FindClient: authenticating connection: authClass=%d\n",
1312                authClass));
1313     if (authClass == 1) {
1314        /* A bcrypt tickets, no longer supported */
1315        ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
1316        viceid = AnonymousID;
1317        expTime = 0x7fffffff;
1318     } else if (authClass == 2) {
1319        afs_int32 kvno;
1320
1321        /* kerberos ticket */
1322        code = rxkad_GetServerInfo (tcon, /*level*/0, &expTime,
1323                                    tname, tinst, tcell, &kvno);
1324        if (code) {
1325           ViceLog(1, ("Failed to get rxkad ticket info\n"));
1326           viceid = AnonymousID;
1327           expTime = 0x7fffffff;
1328        } else {
1329           int ilen = strlen(tinst);
1330           ViceLog(5,
1331                   ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
1332                    tname, tinst, tcell, expTime, kvno));
1333           strncpy (uname, tname, sizeof(uname));
1334           if (ilen) {
1335              if (strlen(uname) + 1 + ilen >= sizeof(uname))
1336                 goto bad_name;
1337              strcat (uname, ".");
1338              strcat (uname, tinst);
1339           }
1340           /* translate the name to a vice id */
1341           code = MapName_r(uname, tcell, &viceid);
1342           if (code) {
1343           bad_name:
1344              ViceLog(1, ("failed to map name=%s, cell=%s -> code=%d\n",
1345                          uname, tcell, code));
1346              fail = 1;
1347              viceid = AnonymousID;
1348              expTime = 0x7fffffff;
1349           }
1350        }
1351     } else {
1352        viceid = AnonymousID;    /* unknown security class */
1353        expTime = 0x7fffffff;
1354     }
1355
1356     if (!client) {
1357        host = h_GetHost_r(tcon); /* Returns it h_Held */
1358
1359        /* First try to find the client structure */
1360        for (client = host->FirstClient; client; client = client->next) {
1361           if (!client->deleted && (client->sid == rxr_CidOf(tcon)) &&
1362                                   (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1363              if (client->tcon && (client->tcon != tcon)) {
1364                 ViceLog(0, ("*** Vid=%d, sid=%x, tcon=%x, Tcon=%x ***\n", 
1365                             client->ViceId, client->sid, client->tcon, tcon));
1366                 client->tcon = (struct rx_connection *)0;
1367              }
1368              client->refCount++;
1369              H_UNLOCK
1370              ObtainWriteLock(&client->lock);
1371              H_LOCK
1372              break;
1373           }
1374        }
1375
1376        /* Still no client structure - get one */
1377        if (!client) {
1378           client = GetCE();
1379           ObtainWriteLock(&client->lock);
1380           client->host = host;
1381           client->next = host->FirstClient;
1382           host->FirstClient = client;
1383 #if FS_STATS_DETAILED
1384           client->InSameNetwork = host->InSameNetwork;
1385 #endif /* FS_STATS_DETAILED */
1386           client->ViceId = viceid;
1387           client->expTime       = expTime;      /* rx only */
1388           client->authClass = authClass;        /* rx only */
1389           client->sid = rxr_CidOf(tcon);
1390           client->VenusEpoch = rxr_GetEpoch(tcon);
1391           client->CPS.prlist_val = 0;
1392           client->refCount = 1;
1393           CurrentConnections++; /* increment number of connections */
1394        }
1395     }
1396     client->prfail = fail;
1397
1398     if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
1399         if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID)) {
1400            free(client->CPS.prlist_val);
1401         }
1402         client->CPS.prlist_val = NULL;
1403         client->ViceId = viceid;
1404         client->expTime = expTime;
1405
1406         if (viceid == ANONYMOUSID) {
1407           client->CPS.prlist_len = AnonCPS.prlist_len;
1408           client->CPS.prlist_val = AnonCPS.prlist_val;
1409         } else {
1410           H_UNLOCK
1411           code = pr_GetCPS(viceid, &client->CPS);
1412           H_LOCK
1413           if (code) {
1414             char hoststr[16];
1415             ViceLog(0, ("pr_GetCPS failed(%d) for user %d, host %s:%d\n",
1416                        code, viceid,
1417                        afs_inet_ntoa_r(client->host->host, hoststr),
1418                        client->host->port));
1419
1420             /* Although ubik_Call (called by pr_GetCPS) traverses thru
1421              * all protection servers and reevaluates things if no
1422              * sync server or quorum is found we could still end up
1423              * with one of these errors. In such case we would like to
1424              * reevaluate the rpc call to find if there's cps for this
1425              * guy. We treat other errors (except network failures
1426              * ones - i.e. code < 0) as an indication that there is no
1427              * CPS for this host.  Ideally we could like to deal this
1428              * problem the other way around (i.e.  if code == NOCPS
1429              * ignore else retry next time) but the problem is that
1430              * there're other errors (i.e.  EPERM) for which we don't
1431              * want to retry and we don't know the whole code list!
1432              */
1433             if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) 
1434                 client->prfail = 1;
1435           }
1436         }
1437         /* the disabling of system:administrators is so iffy and has so many
1438          * possible failure modes that we will disable it again */
1439         /* Turn off System:Administrator for safety  
1440            if (AL_IsAMember(SystemId, client->CPS) == 0)
1441            assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
1442     }
1443
1444     /* Now, tcon may already be set to a rock, since we blocked with no host
1445      * or client locks set above in pr_GetCPS (XXXX some locking is probably
1446      * required).  So, before setting the RPC's rock, we should disconnect
1447      * the RPC from the other client structure's rock.
1448      */
1449     if ((oldClient = (struct client *) rx_GetSpecific(tcon, rxcon_client_key))) {
1450         oldClient->tcon = (struct rx_connection *) 0;
1451         /* rx_SetSpecific will be done immediately below */
1452     }
1453     client->tcon = tcon;
1454     rx_SetSpecific(tcon, rxcon_client_key, client);
1455     ReleaseWriteLock(&client->lock);
1456
1457     return client;
1458
1459 } /*h_FindClient_r*/
1460
1461 int h_ReleaseClient_r(client)
1462     struct client *client;
1463 {
1464     assert(client->refCount > 0);
1465     client->refCount--;
1466     return 0;
1467 }
1468
1469
1470 /*
1471  * Sigh:  this one is used to get the client AGAIN within the individual
1472  * server routines.  This does not bother h_Holding the host, since
1473  * this is assumed already have been done by the server main loop.
1474  * It does check tokens, since only the server routines can return the
1475  * VICETOKENDEAD error code
1476  */
1477 int GetClient(tcon, cp)
1478     struct rx_connection * tcon;
1479     struct client **cp;
1480
1481 {
1482     register struct client *client;
1483
1484     H_LOCK
1485
1486     *cp = client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key);
1487     /* XXXX debug */
1488     assert(client && client->tcon && rxr_CidOf(client->tcon) == client->sid);
1489     if (client &&
1490         client->LastCall > client->expTime && client->expTime) {
1491         char hoststr[16];
1492         ViceLog(1, ("Token for %s at %s:%d expired %d\n",
1493                 h_UserName(client),
1494                 afs_inet_ntoa_r(client->host->host, hoststr),
1495                 client->host->port, client->expTime));
1496         H_UNLOCK
1497         return VICETOKENDEAD;
1498     }
1499
1500     H_UNLOCK
1501     return 0;
1502
1503 } /*GetClient*/
1504
1505
1506 /* Client user name for short term use.  Note that this is NOT inexpensive */
1507 char *h_UserName(client)
1508     struct client *client;
1509
1510 {
1511     static char User[PR_MAXNAMELEN+1];
1512     namelist lnames;
1513     idlist lids;
1514
1515     lids.idlist_len = 1;
1516     lids.idlist_val = (afs_int32 *)malloc(1*sizeof(afs_int32));
1517     lnames.namelist_len = 0;
1518     lnames.namelist_val = (prname *)0;
1519     lids.idlist_val[0] = client->ViceId;
1520     if (pr_IdToName(&lids,&lnames)) {
1521         /* We need to free id we alloced above! */
1522         free(lids.idlist_val);
1523         return "*UNKNOWN USER NAME*";
1524     }
1525     strncpy(User,lnames.namelist_val[0],PR_MAXNAMELEN);
1526     free(lids.idlist_val);
1527     free(lnames.namelist_val);
1528     return User;
1529
1530 } /*h_UserName*/
1531
1532
1533 h_PrintStats()
1534
1535 {
1536     ViceLog(0,
1537             ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
1538             CEs, CEBlocks, HTs, HTBlocks));
1539
1540 } /*h_PrintStats*/
1541
1542
1543 static int h_PrintClient(host, held, file)
1544     register struct host *host;
1545     int held;
1546     StreamHandle_t *file;
1547 {
1548     register struct client *client;
1549     int i;
1550     char tmpStr[256];
1551     char tbuffer[32];
1552     char hoststr[16];
1553
1554     H_LOCK
1555     if (host->hostFlags & HOSTDELETED) {
1556         H_UNLOCK
1557         return held;
1558     }
1559     sprintf(tmpStr,"Host %s:%d down = %d, LastCall %s",
1560             afs_inet_ntoa_r(host->host, hoststr), host->port,
1561             (host->hostFlags & VENUSDOWN),
1562             afs_ctime((time_t *)&host->LastCall, tbuffer, sizeof(tbuffer)));
1563     STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1564     for (client = host->FirstClient; client; client=client->next) {
1565         if (!client->deleted) {
1566             if (client->tcon) {
1567                 sprintf(tmpStr, "    user id=%d,  name=%s, sl=%s till %s",
1568                         client->ViceId, h_UserName(client),
1569                         client->authClass ? "Authenticated" : "Not authenticated",
1570                         client->authClass ?
1571                         afs_ctime((time_t *)&client->expTime, tbuffer, sizeof(tbuffer))
1572                         : "No Limit\n");
1573                 STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1574             }
1575             else {
1576                 sprintf(tmpStr, "    user=%s, no current server connection\n",
1577                         h_UserName(client));
1578                 STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1579             }
1580             sprintf(tmpStr, "      CPS-%d is [", client->CPS.prlist_len);
1581             STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1582             if (client->CPS.prlist_val) {
1583                 for (i=0; i > client->CPS.prlist_len; i++) {
1584                     sprintf(tmpStr, " %d", client->CPS.prlist_val[i]);
1585                     STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1586                 }
1587             }
1588             sprintf(tmpStr, "]\n");         
1589             STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1590         }
1591     }
1592     H_UNLOCK
1593     return held;
1594
1595 } /*h_PrintClient*/
1596
1597
1598
1599 /*
1600  * Print a list of clients, with last security level and token value seen,
1601  * if known
1602  */
1603 h_PrintClients()
1604
1605 {
1606     time_t now;
1607     char tmpStr[256];
1608     char tbuffer[32];
1609
1610     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
1611
1612     if (file == NULL) {
1613         ViceLog(0, ("Couldn't create client dump file %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
1614         return;
1615     }
1616     now = FT_ApproxTime();
1617     sprintf(tmpStr, "List of active users at %s\n",
1618             afs_ctime(&now, tbuffer, sizeof(tbuffer)));
1619     STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1620     h_Enumerate(h_PrintClient, (char *)file);
1621     STREAM_REALLYCLOSE(file);
1622     ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
1623 }
1624
1625
1626
1627
1628 static int h_DumpHost(host, held, file)
1629     register struct host *host;
1630     int held;
1631     StreamHandle_t *file;
1632
1633 {
1634     int i;
1635     char tmpStr[256];
1636
1637     H_LOCK
1638     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 [",
1639             host->host, host->port, host->index, host->cblist,
1640             CheckLock(&host->lock), host->LastCall, host->ActiveCall, 
1641             (host->hostFlags & VENUSDOWN), host->hostFlags&HOSTDELETED, 
1642             host->Console, host->hostFlags & CLIENTDELETED, 
1643             host->hcpsfailed, host->cpsCall);
1644     STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1645     if (host->hcps.prlist_val)
1646         for (i=0; i < host->hcps.prlist_len; i++) {
1647             sprintf(tmpStr, " %d", host->hcps.prlist_val[i]);
1648             STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1649         }
1650     sprintf(tmpStr, "] [");
1651     STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1652     if ( host->interface)
1653         for (i=0; i < host->interface->numberOfInterfaces; i++) {
1654             sprintf(tmpStr, " %x", host->interface->addr[i]);
1655             STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1656         }
1657     sprintf(tmpStr, "] holds: ");
1658     STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1659
1660     for (i = 0 ; i < h_maxSlots ; i++) {
1661       sprintf(tmpStr, "%04x", host->holds[i]);
1662       STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1663     }
1664     sprintf(tmpStr, " slot/bit: %d/%d\n", h_holdSlot(), h_holdbit());
1665     STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1666
1667     H_UNLOCK
1668     return held;
1669
1670 } /*h_DumpHost*/
1671
1672
1673 h_DumpHosts()
1674
1675 {
1676     time_t now;
1677     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
1678     char tmpStr[256];
1679     char tbuffer[32];
1680
1681     if (file == NULL) {
1682         ViceLog(0, ("Couldn't create host dump file %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
1683         return;
1684     }
1685     now = FT_ApproxTime();
1686     sprintf(tmpStr, "List of active hosts at %s\n",
1687             afs_ctime(&now, tbuffer, sizeof(tbuffer)));
1688     STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1689     h_Enumerate(h_DumpHost, (char *) file);
1690     STREAM_REALLYCLOSE(file);
1691     ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
1692
1693 } /*h_DumpHosts*/
1694
1695
1696 /*
1697  * This counts the number of workstations, the number of active workstations,
1698  * and the number of workstations declared "down" (i.e. not heard from
1699  * recently).  An active workstation has received a call since the cutoff
1700  * time argument passed.
1701  */
1702 h_GetWorkStats(nump, activep, delp, cutofftime)
1703     int *nump;
1704     int *activep;
1705     int *delp;
1706     afs_int32 cutofftime;
1707
1708 {
1709     register int i;
1710     register struct host *host;
1711     register int num=0, active=0, del=0;
1712
1713     H_LOCK
1714     for (host = hostList; host; host = host->next) {
1715             if (!(host->hostFlags & HOSTDELETED)) {
1716                 num++;
1717                 if (host->ActiveCall > cutofftime)
1718                     active++;
1719                 if (host->hostFlags & VENUSDOWN)
1720                     del++;
1721             }
1722     }
1723     H_UNLOCK
1724     if (nump)
1725         *nump = num;
1726     if (activep)
1727         *activep = active;
1728     if (delp)
1729         *delp = del;
1730
1731 } /*h_GetWorkStats*/
1732
1733
1734 /*------------------------------------------------------------------------
1735  * PRIVATE h_ClassifyAddress
1736  *
1737  * Description:
1738  *      Given a target IP address and a candidate IP address (both
1739  *      in host byte order), classify the candidate into one of three
1740  *      buckets in relation to the target by bumping the counters passed
1741  *      in as parameters.
1742  *
1743  * Arguments:
1744  *      a_targetAddr       : Target address.
1745  *      a_candAddr         : Candidate address.
1746  *      a_sameNetOrSubnetP : Ptr to counter to bump when the two
1747  *                           addresses are either in the same network
1748  *                           or the same subnet.
1749  *      a_diffSubnetP      : ...when the candidate is in a different
1750  *                           subnet.
1751  *      a_diffNetworkP     : ...when the candidate is in a different
1752  *                           network.
1753  *
1754  * Returns:
1755  *      Nothing.
1756  *
1757  * Environment:
1758  *      The target and candidate addresses are both in host byte
1759  *      order, NOT network byte order, when passed in.
1760  *
1761  * Side Effects:
1762  *      As advertised.
1763  *------------------------------------------------------------------------*/
1764
1765 static void h_ClassifyAddress(a_targetAddr, a_candAddr, a_sameNetOrSubnetP,
1766                        a_diffSubnetP, a_diffNetworkP)
1767     afs_uint32 a_targetAddr;
1768     afs_uint32 a_candAddr;
1769     afs_int32 *a_sameNetOrSubnetP;
1770     afs_int32 *a_diffSubnetP;
1771     afs_int32 *a_diffNetworkP;
1772
1773 { /*h_ClassifyAddress*/
1774
1775     register int i;                      /*Iterator thru host hash table*/
1776     register struct host *hostP;         /*Ptr to current host entry*/
1777     register afs_uint32 currHostAddr; /*Current host address*/
1778     afs_uint32 targetNet;
1779     afs_uint32 targetSubnet;
1780     afs_uint32 candNet;
1781     afs_uint32 candSubnet;
1782
1783     /*
1784      * Put bad values into the subnet info to start with.
1785      */
1786     targetSubnet = (afs_uint32) 0;
1787     candSubnet   = (afs_uint32) 0;
1788
1789     /*
1790      * Pull out the network and subnetwork numbers from the target
1791      * and candidate addresses.  We can short-circuit this whole
1792      * affair if the target and candidate addresses are not of the
1793      * same class.
1794      */
1795     if (IN_CLASSA(a_targetAddr)) {
1796         if (!(IN_CLASSA(a_candAddr))) {
1797             (*a_diffNetworkP)++;
1798             return;
1799         }
1800         targetNet = a_targetAddr & IN_CLASSA_NET;
1801         candNet   = a_candAddr   & IN_CLASSA_NET;
1802         if (IN_SUBNETA(a_targetAddr))
1803             targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
1804         if (IN_SUBNETA(a_candAddr))
1805             candSubnet = a_candAddr & IN_CLASSA_SUBNET;
1806     }
1807     else
1808         if (IN_CLASSB(a_targetAddr)) {
1809             if (!(IN_CLASSB(a_candAddr))) {
1810                 (*a_diffNetworkP)++;
1811                 return;
1812             }
1813             targetNet = a_targetAddr & IN_CLASSB_NET;
1814             candNet   = a_candAddr   & IN_CLASSB_NET;
1815             if (IN_SUBNETB(a_targetAddr))
1816                 targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
1817             if (IN_SUBNETB(a_candAddr))
1818                 candSubnet = a_candAddr & IN_CLASSB_SUBNET;
1819         } /*Class B target*/
1820         else
1821             if (IN_CLASSC(a_targetAddr)) {
1822                 if (!(IN_CLASSC(a_candAddr))) {
1823                     (*a_diffNetworkP)++;
1824                     return;
1825                 }
1826                 targetNet = a_targetAddr & IN_CLASSC_NET;
1827                 candNet   = a_candAddr   & IN_CLASSC_NET;
1828
1829                 /*
1830                  * Note that class C addresses can't have subnets,
1831                  * so we leave the defaults untouched.
1832                  */
1833             } /*Class C target*/
1834             else {
1835                 targetNet = a_targetAddr;
1836                 candNet = a_candAddr;
1837             } /*Class D address*/
1838     
1839     /*
1840      * Now, simply compare the extracted net and subnet values for
1841      * the two addresses (which at this point are known to be of the
1842      * same class)
1843      */
1844     if (targetNet == candNet) {
1845         if (targetSubnet == candSubnet)
1846             (*a_sameNetOrSubnetP)++;
1847         else
1848             (*a_diffSubnetP)++;
1849     }
1850     else
1851         (*a_diffNetworkP)++;
1852
1853 } /*h_ClassifyAddress*/
1854
1855
1856 /*------------------------------------------------------------------------
1857  * EXPORTED h_GetHostNetStats
1858  *
1859  * Description:
1860  *      Iterate through the host table, and classify each (non-deleted)
1861  *      host entry into ``proximity'' categories (same net or subnet,
1862  *      different subnet, different network).
1863  *
1864  * Arguments:
1865  *      a_numHostsP        : Set to total number of (non-deleted) hosts.
1866  *      a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
1867  *      a_diffSubnetP      : Set to # hosts on diff subnet as server.
1868  *      a_diffNetworkP     : Set to # hosts on diff network as server.
1869  *
1870  * Returns:
1871  *      Nothing.
1872  *
1873  * Environment:
1874  *      We only count non-deleted hosts.  The storage pointed to by our
1875  *      parameters is zeroed upon entry.
1876  *
1877  * Side Effects:
1878  *      As advertised.
1879  *------------------------------------------------------------------------*/
1880
1881 void h_GetHostNetStats(a_numHostsP, a_sameNetOrSubnetP, a_diffSubnetP,
1882                        a_diffNetworkP)
1883     afs_int32 *a_numHostsP;
1884     afs_int32 *a_sameNetOrSubnetP;
1885     afs_int32 *a_diffSubnetP;
1886     afs_int32 *a_diffNetworkP;
1887
1888 { /*h_GetHostNetStats*/
1889
1890     register struct host *hostP;         /*Ptr to current host entry*/
1891     register afs_uint32 currAddr_HBO; /*Curr host addr, host byte order*/
1892
1893     /*
1894      * Clear out the storage pointed to by our parameters.
1895      */
1896     *a_numHostsP        = (afs_int32) 0;
1897     *a_sameNetOrSubnetP = (afs_int32) 0;
1898     *a_diffSubnetP      = (afs_int32) 0;
1899     *a_diffNetworkP     = (afs_int32) 0;
1900
1901     H_LOCK
1902     for (hostP = hostList; hostP; hostP = hostP->next) {
1903             if (!(hostP->hostFlags & HOSTDELETED)) {
1904                 /*
1905                  * Bump the number of undeleted host entries found.
1906                  * In classifying the current entry's address, make
1907                  * sure to first convert to host byte order.
1908                  */
1909                 (*a_numHostsP)++;
1910                 currAddr_HBO = (afs_uint32)ntohl(hostP->host);
1911                 h_ClassifyAddress(FS_HostAddr_HBO,
1912                                   currAddr_HBO,
1913                                   a_sameNetOrSubnetP,
1914                                   a_diffSubnetP,
1915                                   a_diffNetworkP);
1916             } /*Only look at non-deleted hosts*/
1917     } /*For each host record hashed to this index*/
1918     H_UNLOCK
1919
1920 } /*h_GetHostNetStats*/
1921
1922 static afs_uint32       checktime;
1923 static afs_uint32    clientdeletetime;
1924 static struct AFSFid zerofid;
1925
1926
1927 /*
1928  * XXXX: This routine could use Multi-R to avoid serializing the timeouts.
1929  * Since it can serialize them, and pile up, it should be a separate LWP
1930  * from other events.
1931  */
1932 int CheckHost(host, held)
1933     register struct host *host;
1934     int held;
1935
1936 {
1937     register struct client *client;
1938     struct interfaceAddr interf;
1939     int code;
1940
1941     /* Host is held by h_Enumerate */
1942     H_LOCK
1943     for (client = host->FirstClient; client; client = client->next) {
1944         if (client->refCount == 0 && client->LastCall < clientdeletetime) {
1945             client->deleted = 1;
1946             host->hostFlags  |= CLIENTDELETED;
1947         }
1948     }
1949     if (host->LastCall < checktime) {
1950         h_Lock_r(host);
1951         if (!(host->hostFlags & HOSTDELETED)) {
1952             if (host->LastCall < clientdeletetime) {
1953                 host->hostFlags |= HOSTDELETED;
1954                 if (!(host->hostFlags & VENUSDOWN)) {
1955                     host->hostFlags &= ~ALTADDR; /* alternate address invalid*/
1956                     if (host->interface) {
1957                         H_UNLOCK
1958                         code = RXAFSCB_InitCallBackState3(host->callback_rxcon,
1959                                                           &FS_HostUUID);
1960                         H_LOCK
1961                     } else {
1962                         H_UNLOCK
1963                         code = RXAFSCB_InitCallBackState(host->callback_rxcon);
1964                         H_LOCK
1965                     }
1966                     host->hostFlags |= ALTADDR; /* alternate addresses valid */
1967                     if ( code )
1968                     {
1969                         char hoststr[16];
1970                         afs_inet_ntoa_r(host->host, hoststr);
1971                         ViceLog(0,
1972                                 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
1973                                  hoststr, ntohs(host->port)));
1974                         host->hostFlags |= VENUSDOWN;
1975                     }
1976                     /* Note:  it's safe to delete hosts even if they have call
1977                      * back state, because break delayed callbacks (called when a
1978                      * message is received from the workstation) will always send a 
1979                      * break all call backs to the workstation if there is no
1980                      *callback.
1981                      */
1982                 }
1983             }
1984             else {
1985                 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
1986                     if (host->interface) {
1987                         afsUUID uuid = host->interface->uuid;
1988                         H_UNLOCK
1989                         code = RXAFSCB_ProbeUuid(host->callback_rxcon, &uuid);
1990                         H_LOCK
1991                         if(code) {
1992                             if ( MultiProbeAlternateAddress_r(host) ) {
1993                                 char hoststr[16];
1994                                 afs_inet_ntoa_r(host->host, hoststr);
1995                                 ViceLog(0,
1996                                         ("ProbeUuid failed for host %s:%d\n",
1997                                          hoststr, ntohs(host->port)));
1998                                 host->hostFlags |= VENUSDOWN;
1999                             }
2000                         }
2001                     } else {
2002                         H_UNLOCK
2003                         code = RXAFSCB_Probe(host->callback_rxcon);
2004                         H_LOCK
2005                         if (code) {
2006                             char hoststr[16];
2007                             afs_inet_ntoa_r(host->host, hoststr);
2008                             ViceLog(0, ("ProbeUuid failed for host %s:%d\n",
2009                                         hoststr, ntohs(host->port)));
2010                             host->hostFlags |= VENUSDOWN;
2011                         }
2012                     }
2013                 }
2014             }
2015         }
2016         h_Unlock_r(host);
2017     }
2018     H_UNLOCK
2019     return held;
2020
2021 } /*CheckHost*/
2022
2023
2024 /*
2025  * Set VenusDown for any hosts that have not had a call in 15 minutes and
2026  * don't respond to a probe.  Note that VenusDown can only be cleared if
2027  * a message is received from the host (see ServerLWP in file.c).
2028  * Delete hosts that have not had any calls in 1 hour, clients that
2029  * have not had any calls in 15 minutes.
2030  *
2031  * This routine is called roughly every 5 minutes.
2032  */
2033 h_CheckHosts() {
2034
2035     afs_uint32 now = FT_ApproxTime();
2036
2037     memset((char *)&zerofid, 0, sizeof(zerofid));
2038     /*
2039      * Send a probe to the workstation if it hasn't been heard from in
2040      * 15 minutes
2041      */
2042     checktime = now - 15*60;
2043     clientdeletetime = now - 120*60;    /* 2 hours ago */
2044     h_Enumerate(CheckHost, NULL);
2045
2046 } /*h_CheckHosts*/
2047
2048 /*
2049  * This is called with host locked and held. At this point, the
2050  * hostHashTable should not be having entries for the alternate
2051  * interfaces. This function has to insert these entries in the
2052  * hostHashTable.
2053  *
2054  * The addresses in the ineterfaceAddr list are in host byte order.
2055  */
2056 int
2057 initInterfaceAddr_r(host, interf)
2058 struct host*    host;
2059 struct interfaceAddr *interf;
2060 {
2061         int i, j;
2062         int number, count;
2063         afs_int32               myPort, myHost;
2064         int found;
2065         struct Interface *interface;
2066
2067         assert(host);
2068         assert(interf);
2069
2070         ViceLog(125,("initInterfaceAddr : host %x numAddr %d\n",
2071                 host->host, interf->numberOfInterfaces));
2072
2073         number = interf->numberOfInterfaces;
2074         myPort   = host->port;
2075         myHost   = host->host; /* current interface address */
2076
2077         /* validation checks */
2078         if ( number < 0 )
2079         {
2080                 ViceLog(0,("Number of alternate addresses returned is %d\n",
2081                          number));
2082                 return  -1;
2083         }
2084
2085         /*
2086          * Convert IP addresses to network byte order, and remove for
2087          * duplicate IP addresses from the interface list.
2088          */
2089         for (i = 0, count = 0, found = 0; i < number; i++)
2090         {
2091             interf->addr_in[i] = htonl(interf->addr_in[i]);
2092             for (j = 0 ; j < count ; j++) {
2093                 if (interf->addr_in[j] == interf->addr_in[i])
2094                     break;
2095             }
2096             if (j == count) {
2097                 interf->addr_in[count] = interf->addr_in[i];
2098                 if (interf->addr_in[count] == myHost)
2099                     found = 1;
2100                 count++;
2101             }
2102         }
2103
2104         /*
2105          * Allocate and initialize an interface structure for this host.
2106          */
2107         if (found) {
2108             interface = (struct Interface *)
2109                         malloc(sizeof(struct Interface) +
2110                                (sizeof(afs_int32) * (count-1)));
2111             assert(interface);
2112             interface->numberOfInterfaces = count;
2113         } else {
2114             interface = (struct Interface *)
2115                         malloc(sizeof(struct Interface) +
2116                                (sizeof(afs_int32) * count));
2117             assert(interface);
2118             interface->numberOfInterfaces = count + 1;
2119             interface->addr[count] = myHost;
2120         }
2121         interface->uuid = interf->uuid;
2122         for (i = 0 ; i < count ; i++)
2123             interface->addr[i] = interf->addr_in[i];
2124
2125         assert(!host->interface);
2126         host->interface = interface;
2127
2128         for ( i=0; i < host->interface->numberOfInterfaces; i++)
2129         {
2130                 ViceLog(125,("--- alt address %x\n", host->interface->addr[i]));
2131         }
2132
2133         return 0;
2134 }
2135
2136 /*
2137  * This is called with host locked and held. At this point, the
2138  * hostHashTable should not be having entries for the alternate
2139  * interfaces. This function has to insert these entries in the
2140  * hostHashTable.
2141  *
2142  * All addresses are in network byte order.
2143  */
2144 int
2145 addInterfaceAddr_r(host, addr)
2146 struct host*    host;
2147 afs_int32 addr;
2148 {
2149         int i;
2150         int number;
2151         int found;
2152         struct Interface *interface;
2153
2154         assert(host);
2155         assert(host->interface);
2156
2157         ViceLog(125,("addInterfaceAddr : host %x addr %d\n",
2158                 host->host, addr));
2159
2160         /*
2161          * Make sure this address is on the list of known addresses
2162          * for this host.
2163          */
2164         number = host->interface->numberOfInterfaces;
2165         for ( i=0, found=0; i < number && !found; i++)
2166         {
2167             if ( host->interface->addr[i] == addr)
2168                 found = 1;
2169         }
2170         if (!found) {
2171             interface = (struct Interface *)
2172                         malloc(sizeof(struct Interface) +
2173                                (sizeof(afs_int32) * number));
2174             interface->numberOfInterfaces = number + 1;
2175             interface->uuid = host->interface->uuid;
2176             for (i = 0 ; i < number ; i++)
2177                 interface->addr[i] = host->interface->addr[i];
2178             interface->addr[number] = addr;
2179             free(host->interface);
2180             host->interface = interface;
2181         }
2182
2183         /*
2184          * Create a hash table entry for this address
2185          */
2186         hashInsert_r(addr, host);
2187
2188         return 0;
2189 }
2190
2191 /* inserts  a new HashChain structure corresponding to this address */
2192 hashInsert_r(addr, host)
2193 afs_int32 addr;
2194 struct host* host;
2195 {
2196         int index;
2197         struct h_hashChain*     chain;
2198
2199         /* hash into proper bucket */
2200         index = h_HashIndex(addr);
2201
2202         /* insert into beginning of list for this bucket */
2203         chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
2204         assert(chain);
2205         chain->hostPtr = host;
2206         chain->next = hostHashTable[index];
2207         chain->addr = addr;
2208         hostHashTable[index] = chain;
2209
2210 }
2211
2212 /* inserts  a new HashChain structure corresponding to this UUID */
2213 hashInsertUuid_r(uuid, host)
2214 struct afsUUID *uuid;
2215 struct host* host;
2216 {
2217         int index;
2218         struct h_hashChain*     chain;
2219
2220         /* hash into proper bucket */
2221         index = h_UuidHashIndex(uuid);
2222
2223         /* insert into beginning of list for this bucket */
2224         chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
2225         assert(chain);
2226         chain->hostPtr = host;
2227         chain->next = hostUuidHashTable[index];
2228         hostUuidHashTable[index] = chain;
2229 }
2230
2231 /* deleted a HashChain structure for this address and host */
2232 /* returns 1 on success */
2233 int
2234 hashDelete_r(addr, host)
2235 afs_int32 addr;
2236 struct host* host;
2237 {
2238         int flag;
2239         int index;
2240         register struct h_hashChain **hp, *th;
2241
2242         for (hp = &hostHashTable[h_HashIndex(addr)]; (th = *hp); )
2243         {
2244                 assert(th->hostPtr);
2245                 if (th->hostPtr == host && th->addr == addr)
2246                 {
2247                         *hp = th->next;
2248                         free(th);
2249                         flag = 1;
2250                         break;
2251                 } else {
2252                         hp = &th->next;
2253                 }
2254         }
2255         return flag;
2256 }
2257
2258
2259 /*
2260 ** prints out all alternate interface address for the host. The 'level'
2261 ** parameter indicates what level of debugging sets this output
2262 */
2263 printInterfaceAddr(host, level)
2264 struct host*    host;
2265 int             level;
2266 {
2267         int i, number;
2268         if ( host-> interface )
2269         {
2270                 /* check alternate addresses */
2271                 number = host->interface->numberOfInterfaces;
2272                 assert( number > 0 );
2273                 for ( i=0; i < number; i++)
2274                         ViceLog(level, ("%x ", host->interface->addr[i]));
2275         }
2276          ViceLog(level, ("\n"));
2277 }
2278