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