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