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