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