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