check-host-optimize-20060123
[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 haddr, 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(haddr);
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 == haddr
629             && chain->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         struct AddrPort hostAddrPort;
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                 hostAddrPort = host->interface->interface[i];
804
805                 for (hp = &hostHashTable[h_HashIndex(hostAddrPort.addr)]; (th = *hp);
806                      hp = &th->next) {
807                     assert(th->hostPtr);
808                     if (th->hostPtr == host) {
809                         *hp = th->next;
810                         free(th);
811                         break;
812                     }
813                 }
814             }
815             free(host->interface);
816             host->interface = NULL;
817             h_DeleteList_r(host);       /* remove host from global host List */
818             FreeHT(host);
819         }                       /* if alternate address exists */
820     }
821 }                               /*h_TossStuff_r */
822
823
824 /* Called by rx when a server connection disappears */
825 int
826 h_FreeConnection(struct rx_connection *tcon)
827 {
828     register struct client *client;
829
830     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
831     if (client) {
832         H_LOCK;
833         if (client->tcon == tcon)
834             client->tcon = (struct rx_connection *)0;
835         H_UNLOCK;
836     }
837     return 0;
838 }                               /*h_FreeConnection */
839
840
841 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
842  * system at the start of the enumeration (perhaps more).  Hosts may be deleted
843  * (have delete flag set); ditto for clients.  (*proc) is always called with
844  * host h_held().  The hold state of the host with respect to this lwp is passed
845  * to (*proc) as the param held.  The proc should return 0 if the host should be
846  * released, 1 if it should be held after enumeration.
847  */
848 void
849 h_Enumerate(int (*proc) (), char *param)
850 {
851     register struct host *host, **list;
852     register int *held;
853     register int i, count;
854
855     H_LOCK;
856     if (hostCount == 0) {
857         H_UNLOCK;
858         return;
859     }
860     list = (struct host **)malloc(hostCount * sizeof(struct host *));
861     if (!list) {
862         ViceLog(0, ("Failed malloc in h_Enumerate\n"));
863         assert(0);
864     }
865     held = (int *)malloc(hostCount * sizeof(int));
866     if (!held) {
867         ViceLog(0, ("Failed malloc in h_Enumerate\n"));
868         assert(0);
869     }
870     for (count = 0, host = hostList; host; host = host->next, count++) {
871         list[count] = host;
872         if (!(held[count] = h_Held_r(host)))
873             h_Hold_r(host);
874     }
875     assert(count == hostCount);
876     H_UNLOCK;
877     for (i = 0; i < count; i++) {
878         held[i] = (*proc) (list[i], held[i], param);
879         if (!held[i])
880             h_Release(list[i]); /* this might free up the host */
881     }
882     free((void *)list);
883     free((void *)held);
884 }                               /*h_Enumerate */
885
886 /* h_Enumerate_r (revised):
887  * Calls (*proc)(host, held, param) for each host in hostList, starting
888  * at enumstart
889  * Hosts may be deleted (have delete flag set); ditto for clients.
890  * (*proc) is always called with
891  * host h_held() and the global host lock (H_LOCK) locked.The hold state of the
892  * host with respect to this lwp is passed to (*proc) as the param held.
893  * The proc should return 0 if the host should be released, 1 if it should
894  * be held after enumeration.
895  */
896 void
897 h_Enumerate_r(int (*proc) (), struct host *enumstart, char *param)
898 {
899     register struct host *host, *next;
900     register int held, nheld;
901
902     if (hostCount == 0) {
903         return;
904     }
905     if (enumstart && !(held = h_Held_r(enumstart)))
906         h_Hold_r(enumstart); 
907     for (host = enumstart; host; host = next, held = nheld) {
908         held = (*proc) (host, held, param);
909         next = host->next;
910         if (next && !(nheld = h_Held_r(next)))
911             h_Hold_r(next);
912         if (!held)
913             h_Release_r(host); /* this might free up the host */
914     }
915 }                               /*h_Enumerate_r */
916
917 /* inserts a new HashChain structure corresponding to this UUID */
918 void
919 hashInsertUuid_r(struct afsUUID *uuid, struct host *host)
920 {
921     int index;
922     struct h_hashChain *chain;
923
924     /* hash into proper bucket */
925     index = h_UuidHashIndex(uuid);
926
927     /* insert into beginning of list for this bucket */
928     chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
929     if (!chain) {
930         ViceLog(0, ("Failed malloc in hashInsertUuid_r\n"));
931         assert(0);
932     }
933     assert(chain);
934     chain->hostPtr = host;
935     chain->next = hostUuidHashTable[index];
936     hostUuidHashTable[index] = chain;
937 }
938
939
940 /* inserts a new HashChain structure corresponding to this address */
941 void
942 hashInsert_r(afs_uint32 addr, afs_uint16 port, struct host *host)
943 {
944     int index;
945     struct h_hashChain *chain;
946
947     /* hash into proper bucket */
948     index = h_HashIndex(addr);
949
950     /* insert into beginning of list for this bucket */
951     chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
952     if (!chain) {
953         ViceLog(0, ("Failed malloc in hashInsert_r\n"));
954         assert(0);
955     }
956     chain->hostPtr = host;
957     chain->next = hostHashTable[index];
958     chain->addr = addr;
959     chain->port = port;
960     hostHashTable[index] = chain;
961
962 }
963
964 /*
965  * This is called with host locked and held. At this point, the
966  * hostHashTable should not be having entries for the alternate
967  * interfaces. This function has to insert these entries in the
968  * hostHashTable.
969  *
970  * All addresses are in network byte order.
971  */
972 int
973 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
974 {
975     int i;
976     int number;
977     int found;
978     struct Interface *interface;
979
980     assert(host);
981     assert(host->interface);
982
983     ViceLog(125, ("addInterfaceAddr : host %x addr %x:%d\n", host->host, addr, ntohs(port)));
984
985     /*
986      * Make sure this address is on the list of known addresses
987      * for this host.
988      */
989     number = host->interface->numberOfInterfaces;
990     for (i = 0, found = 0; i < number && !found; i++) {
991         if (host->interface->interface[i].addr == addr &&
992             host->interface->interface[i].port == port)
993             found = 1;
994     }
995     if (!found) {
996         interface = (struct Interface *)
997             malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
998         if (!interface) {
999             ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
1000             assert(0);
1001         }
1002         interface->numberOfInterfaces = number + 1;
1003         interface->uuid = host->interface->uuid;
1004         for (i = 0; i < number; i++)
1005             interface->interface[i] = host->interface->interface[i];
1006         interface->interface[number].addr = addr;
1007         interface->interface[number].port = port;
1008         free(host->interface);
1009         host->interface = interface;
1010     }
1011
1012     /*
1013      * Create a hash table entry for this address
1014      */
1015     hashInsert_r(addr, port, host);
1016
1017     return 0;
1018 }
1019
1020
1021 /* Host is returned held */
1022 struct host *
1023 h_GetHost_r(struct rx_connection *tcon)
1024 {
1025     struct host *host;
1026     struct host *oldHost;
1027     int code;
1028     int held, oheld;
1029     struct interfaceAddr interf;
1030     int interfValid = 0;
1031     struct Identity *identP = NULL;
1032     afs_int32 haddr;
1033     afs_int16 hport;
1034     char hoststr[16], hoststr2[16];
1035     Capabilities caps;
1036     struct rx_connection *cb_conn = NULL;
1037
1038     caps.Capabilities_val = NULL;
1039
1040     haddr = rxr_HostOf(tcon);
1041     hport = rxr_PortOf(tcon);
1042   retry:
1043     if (caps.Capabilities_val)
1044         free(caps.Capabilities_val);
1045     caps.Capabilities_val = NULL;
1046     caps.Capabilities_len = 0;
1047
1048     code = 0;
1049     host = h_Lookup_r(haddr, hport, &held);
1050     identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1051     if (host && !identP && !(host->Console & 1)) {
1052         /* This is a new connection, and we already have a host
1053          * structure for this address. Verify that the identity
1054          * of the caller matches the identity in the host structure.
1055          */
1056         h_Lock_r(host);
1057         if (!(host->hostFlags & ALTADDR)) {
1058             /* Another thread is doing initialization */
1059             h_Unlock_r(host);
1060             if (!held)
1061                 h_Release_r(host);
1062             ViceLog(125,
1063                     ("Host %s:%d starting h_Lookup again\n",
1064                      afs_inet_ntoa_r(host->host, hoststr),
1065                      ntohs(host->port)));
1066             goto retry;
1067         }
1068         host->hostFlags &= ~ALTADDR;
1069         cb_conn = host->callback_rxcon;
1070         rx_GetConnection(cb_conn);
1071         H_UNLOCK;
1072         code =
1073             RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1074         if (code == RXGEN_OPCODE)
1075             code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1076         rx_PutConnection(cb_conn);
1077         cb_conn=NULL;
1078         H_LOCK;
1079         if (code == RXGEN_OPCODE) {
1080             identP = (struct Identity *)malloc(sizeof(struct Identity));
1081             if (!identP) {
1082                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1083                 assert(0);
1084             }
1085             identP->valid = 0;
1086             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1087             /* The host on this connection was unable to respond to 
1088              * the WhoAreYou. We will treat this as a new connection
1089              * from the existing host. The worst that can happen is
1090              * that we maintain some extra callback state information */
1091             if (host->interface) {
1092                 ViceLog(0,
1093                         ("Host %s:%d used to support WhoAreYou, deleting.\n",
1094                          afs_inet_ntoa_r(host->host, hoststr),
1095                          ntohs(host->port)));
1096                 host->hostFlags |= HOSTDELETED;
1097                 h_Unlock_r(host);
1098                 if (!held)
1099                     h_Release_r(host);
1100                 host = NULL;
1101                 goto retry;
1102             }
1103         } else if (code == 0) {
1104             interfValid = 1;
1105             identP = (struct Identity *)malloc(sizeof(struct Identity));
1106             if (!identP) {
1107                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1108                 assert(0);
1109             }
1110             identP->valid = 1;
1111             identP->uuid = interf.uuid;
1112             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1113             /* Check whether the UUID on this connection matches
1114              * the UUID in the host structure. If they don't match
1115              * then this is not the same host as before. */
1116             if (!host->interface
1117                 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1118                 ViceLog(25,
1119                         ("Host %s:%d has changed its identity, deleting.\n",
1120                          afs_inet_ntoa_r(host->host, hoststr), host->port));
1121                 host->hostFlags |= HOSTDELETED;
1122                 h_Unlock_r(host);
1123                 if (!held)
1124                     h_Release_r(host);
1125                 host = NULL;
1126                 goto retry;
1127             }
1128         } else {
1129             afs_inet_ntoa_r(host->host, hoststr);
1130             ViceLog(0,
1131                     ("CB: WhoAreYou failed for %s:%d, error %d\n", hoststr,
1132                      ntohs(host->port), code));
1133             host->hostFlags |= VENUSDOWN;
1134         }
1135         if (caps.Capabilities_val
1136             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1137             host->hostFlags |= HERRORTRANS;
1138         else
1139             host->hostFlags &= ~(HERRORTRANS);
1140         host->hostFlags |= ALTADDR;
1141         h_Unlock_r(host);
1142     } else if (host) {
1143         if (!(host->hostFlags & ALTADDR)) {
1144             /* another thread is doing the initialisation */
1145             ViceLog(125,
1146                     ("Host %s:%d waiting for host-init to complete\n",
1147                      afs_inet_ntoa_r(host->host, hoststr),
1148                      ntohs(host->port)));
1149             h_Lock_r(host);
1150             h_Unlock_r(host);
1151             if (!held)
1152                 h_Release_r(host);
1153             ViceLog(125,
1154                     ("Host %s:%d starting h_Lookup again\n",
1155                      afs_inet_ntoa_r(host->host, hoststr),
1156                      ntohs(host->port)));
1157             goto retry;
1158         }
1159         /* We need to check whether the identity in the host structure
1160          * matches the identity on the connection. If they don't match
1161          * then treat this a new host. */
1162         if (!(host->Console & 1)
1163             && ((!identP->valid && host->interface)
1164                 || (identP->valid && !host->interface)
1165                 || (identP->valid
1166                     && !afs_uuid_equal(&identP->uuid,
1167                                        &host->interface->uuid)))) {
1168             char uuid1[128], uuid2[128];
1169             if (identP->valid)
1170                 afsUUID_to_string(&identP->uuid, uuid1, 127);
1171             if (host->interface)
1172                 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1173             ViceLog(0,
1174                     ("CB: new identity for host %s:%d, deleting(%x %x %s %s)\n",
1175                      afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1176                      identP->valid, host->interface,
1177                      identP->valid ? uuid1 : "",
1178                      host->interface ? uuid2 : ""));
1179
1180             /* The host in the cache is not the host for this connection */
1181             host->hostFlags |= HOSTDELETED;
1182             h_Unlock_r(host);
1183             if (!held)
1184                 h_Release_r(host);
1185             goto retry;
1186         }
1187     } else {
1188         host = h_Alloc_r(tcon); /* returned held and locked */
1189         h_gethostcps_r(host, FT_ApproxTime());
1190         if (!(host->Console & 1)) {
1191             int pident = 0;
1192             cb_conn = host->callback_rxcon;
1193             rx_GetConnection(cb_conn);
1194             H_UNLOCK;
1195             code =
1196                 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1197             if (code == RXGEN_OPCODE)
1198                 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1199             rx_PutConnection(cb_conn);
1200             cb_conn=NULL;
1201             H_LOCK;
1202             if (code == RXGEN_OPCODE) {
1203                 if (!identP)
1204                     identP =
1205                         (struct Identity *)malloc(sizeof(struct Identity));
1206                 else
1207                     pident = 1;
1208
1209                 if (!identP) {
1210                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1211                     assert(0);
1212                 }
1213                 identP->valid = 0;
1214                 if (!pident)
1215                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1216                 ViceLog(25,
1217                         ("Host %s:%d does not support WhoAreYou.\n",
1218                          afs_inet_ntoa_r(host->host, hoststr),
1219                          ntohs(host->port)));
1220                 code = 0;
1221             } else if (code == 0) {
1222                 if (!identP)
1223                     identP =
1224                         (struct Identity *)malloc(sizeof(struct Identity));
1225                 else
1226                     pident = 1;
1227
1228                 if (!identP) {
1229                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1230                     assert(0);
1231                 }
1232                 identP->valid = 1;
1233                 interfValid = 1;
1234                 identP->uuid = interf.uuid;
1235                 if (!pident)
1236                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1237                 ViceLog(25,
1238                         ("WhoAreYou success on %s:%d\n",
1239                          afs_inet_ntoa_r(host->host, hoststr),
1240                          ntohs(host->port)));
1241             }
1242             if (code == 0 && !identP->valid) {
1243                 cb_conn = host->callback_rxcon;
1244                 rx_GetConnection(cb_conn);
1245                 H_UNLOCK;
1246                 code = RXAFSCB_InitCallBackState(cb_conn);
1247                 rx_PutConnection(cb_conn);
1248                 cb_conn=NULL;
1249                 H_LOCK;
1250             } else if (code == 0) {
1251                 oldHost = h_LookupUuid_r(&identP->uuid);
1252                 if (oldHost) {
1253                     int probefail = 0;
1254
1255                     if (!(oheld = h_Held_r(oldHost)))
1256                         h_Hold_r(oldHost);
1257                     h_Lock_r(oldHost);
1258
1259                     if (oldHost->interface) {
1260                         afsUUID uuid = oldHost->interface->uuid;
1261                         cb_conn = host->callback_rxcon;
1262                         rx_GetConnection(cb_conn);
1263                         H_UNLOCK;
1264                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1265                         rx_PutConnection(cb_conn);
1266                         cb_conn=NULL;
1267                         H_LOCK;
1268                         if (code && MultiProbeAlternateAddress_r(oldHost)) {
1269                             probefail = 1;
1270                         }
1271                     } else {
1272                         probefail = 1;
1273                     }
1274
1275                     if (probefail) {
1276                         /* The old host is either does not have a Uuid,
1277                          * is not responding to Probes, 
1278                          * or does not have a matching Uuid. 
1279                          * Delete it! */
1280                         oldHost->hostFlags |= HOSTDELETED;
1281                         h_Unlock_r(oldHost);
1282                         /* Let the holder be last release */
1283                         if (!oheld) {
1284                             h_Release_r(oldHost);
1285                         }
1286                         oldHost = NULL;
1287                     }
1288                 }
1289                 if (oldHost) {
1290                     /* This is a new address for an existing host. Update
1291                      * the list of interfaces for the existing host and
1292                      * delete the host structure we just allocated. */
1293                     ViceLog(25,
1294                             ("CB: new addr %s:%d for old host %s:%d\n",
1295                              afs_inet_ntoa_r(host->host, hoststr),
1296                              ntohs(host->port), afs_inet_ntoa_r(oldHost->host,
1297                                                                 hoststr2),
1298                              ntohs(oldHost->port)));
1299                     addInterfaceAddr_r(oldHost, haddr, hport);
1300                     host->hostFlags |= HOSTDELETED;
1301                     h_Unlock_r(host);
1302                     if (!held)
1303                         h_Release_r(host);
1304                     host = oldHost;
1305                 } else {
1306                     /* This really is a new host */
1307                     hashInsertUuid_r(&identP->uuid, host);
1308                     cb_conn = host->callback_rxcon;
1309                     rx_GetConnection(cb_conn);          
1310                     H_UNLOCK;
1311                     code =
1312                         RXAFSCB_InitCallBackState3(cb_conn,
1313                                                    &FS_HostUUID);
1314                     rx_PutConnection(cb_conn);
1315                     cb_conn=NULL;
1316                     H_LOCK;
1317                     if (code == 0) {
1318                         ViceLog(25,
1319                                 ("InitCallBackState3 success on %s:%d\n",
1320                                  afs_inet_ntoa_r(host->host, hoststr),
1321                                  ntohs(host->port)));
1322                         assert(interfValid == 1);
1323                         initInterfaceAddr_r(host, &interf);
1324                     }
1325                 }
1326             }
1327             if (code) {
1328                 afs_inet_ntoa_r(host->host, hoststr);
1329                 ViceLog(0,
1330                         ("CB: RCallBackConnectBack failed for %s:%d\n",
1331                          hoststr, ntohs(host->port)));
1332                 host->hostFlags |= VENUSDOWN;
1333             } else
1334                 host->hostFlags |= RESETDONE;
1335
1336         }
1337         if (caps.Capabilities_val
1338             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1339             host->hostFlags |= HERRORTRANS;
1340         else
1341             host->hostFlags &= ~(HERRORTRANS);
1342         host->hostFlags |= ALTADDR;     /* host structure initialization complete */
1343         h_Unlock_r(host);
1344     }
1345     if (caps.Capabilities_val)
1346         free(caps.Capabilities_val);
1347     caps.Capabilities_val = NULL;
1348     caps.Capabilities_len = 0;
1349     return host;
1350
1351 }                               /*h_GetHost_r */
1352
1353
1354 static char localcellname[PR_MAXNAMELEN + 1];
1355 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
1356 int  num_lrealms = -1;
1357
1358 /* not reentrant */
1359 void
1360 h_InitHostPackage()
1361 {
1362     afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
1363     if (num_lrealms == -1) {
1364         int i;
1365         for (i=0; i<AFS_NUM_LREALMS; i++) {
1366             if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
1367                 break;
1368         }
1369
1370         if (i=0) {
1371             ViceLog(0,
1372                     ("afs_krb_get_lrealm failed, using %s.\n",
1373                      localcellname));
1374             strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
1375             num_lrealms = i =1;
1376         } else {
1377             num_lrealms = i;
1378         }
1379
1380         /* initialize the rest of the local realms to nullstring for debugging */
1381         for (; i<AFS_NUM_LREALMS; i++)
1382             local_realms[i][0] = '\0';
1383     }
1384     rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
1385     rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
1386 #ifdef AFS_PTHREAD_ENV
1387     assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
1388 #endif /* AFS_PTHREAD_ENV */
1389 }
1390
1391 static int
1392 MapName_r(char *aname, char *acell, afs_int32 * aval)
1393 {
1394     namelist lnames;
1395     idlist lids;
1396     afs_int32 code;
1397     afs_int32 anamelen, cnamelen;
1398     int foreign = 0;
1399     char *tname;
1400
1401     anamelen = strlen(aname);
1402     if (anamelen >= PR_MAXNAMELEN)
1403         return -1;              /* bad name -- caller interprets this as anonymous, but retries later */
1404
1405     lnames.namelist_len = 1;
1406     lnames.namelist_val = (prname *) aname;     /* don't malloc in the common case */
1407     lids.idlist_len = 0;
1408     lids.idlist_val = NULL;
1409
1410     cnamelen = strlen(acell);
1411     if (cnamelen) {
1412         if (afs_is_foreign_ticket_name(aname, "", acell, localcellname)) {
1413             ViceLog(2,
1414                     ("MapName: cell is foreign.  cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
1415                     acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
1416             if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
1417                 ViceLog(2,
1418                         ("MapName: Name too long, using AnonymousID for %s@%s\n",
1419                          aname, acell));
1420                 *aval = AnonymousID;
1421                 return 0;
1422             }
1423             foreign = 1;        /* attempt cross-cell authentication */
1424             tname = (char *)malloc(PR_MAXNAMELEN);
1425             if (!tname) {
1426                 ViceLog(0, ("Failed malloc in MapName_r\n"));
1427                 assert(0);
1428             }
1429             strcpy(tname, aname);
1430             tname[anamelen] = '@';
1431             strcpy(tname + anamelen + 1, acell);
1432             lnames.namelist_val = (prname *) tname;
1433         }
1434     }
1435
1436     H_UNLOCK;
1437     code = pr_NameToId(&lnames, &lids);
1438     H_LOCK;
1439     if (code == 0) {
1440         if (lids.idlist_val) {
1441             *aval = lids.idlist_val[0];
1442             if (*aval == AnonymousID) {
1443                 ViceLog(2,
1444                         ("MapName: NameToId on %s returns anonymousID\n",
1445                          lnames.namelist_val));
1446             }
1447             free(lids.idlist_val);      /* return parms are not malloced in stub if server proc aborts */
1448         } else {
1449             ViceLog(0,
1450                     ("MapName: NameToId on '%s' is unknown\n",
1451                      lnames.namelist_val));
1452             code = -1;
1453         }
1454     }
1455
1456     if (foreign) {
1457         free(lnames.namelist_val);      /* We allocated this above, so we must free it now. */
1458     }
1459     return code;
1460 }
1461
1462 /*MapName*/
1463
1464
1465 /* NOTE: this returns the client with a Write lock */
1466 struct client *
1467 h_ID2Client(afs_int32 vid)
1468 {
1469     register struct client *client;
1470     register struct host *host;
1471
1472     H_LOCK;
1473     for (host = hostList; host; host = host->next) {
1474         if (host->hostFlags & HOSTDELETED)
1475             continue;
1476         for (client = host->FirstClient; client; client = client->next) {
1477             if (!client->deleted && client->ViceId == vid) {
1478                 client->refCount++;
1479                 H_UNLOCK;
1480                 ObtainWriteLock(&client->lock);
1481                 H_LOCK;
1482                 client->refCount--;
1483                 H_UNLOCK;
1484                 return client;
1485             }
1486         }
1487     }
1488
1489     H_UNLOCK;
1490     return NULL;
1491 }
1492
1493 /*
1494  * Called by the server main loop.  Returns a h_Held client, which must be
1495  * released later the main loop.  Allocates a client if the matching one
1496  * isn't around. The client is returned with its reference count incremented
1497  * by one. The caller must call h_ReleaseClient_r when finished with
1498  * the client.
1499  */
1500 struct client *
1501 h_FindClient_r(struct rx_connection *tcon)
1502 {
1503     register struct client *client;
1504     register struct host *host;
1505     struct client *oldClient;
1506     afs_int32 viceid;
1507     afs_int32 expTime;
1508     afs_int32 code;
1509     int authClass;
1510 #if (64-MAXKTCNAMELEN)
1511     ticket name length != 64
1512 #endif
1513     char tname[64];
1514     char tinst[64];
1515     char uname[PR_MAXNAMELEN];
1516     char tcell[MAXKTCREALMLEN];
1517     int fail = 0;
1518
1519     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1520     if (client && !client->deleted) {
1521         client->refCount++;
1522         h_Hold_r(client->host);
1523         if (client->prfail != 2) {      /* Could add shared lock on client here */
1524             /* note that we don't have to lock entry in this path to
1525              * ensure CPS is initialized, since we don't call rx_SetSpecific
1526              * until initialization is done, and we only get here if
1527              * rx_GetSpecific located the client structure.
1528              */
1529             return client;
1530         }
1531         H_UNLOCK;
1532         ObtainWriteLock(&client->lock); /* released at end */
1533         H_LOCK;
1534     } else if (client) {
1535         client->refCount++;
1536     }
1537
1538     authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
1539     ViceLog(5,
1540             ("FindClient: authenticating connection: authClass=%d\n",
1541              authClass));
1542     if (authClass == 1) {
1543         /* A bcrypt tickets, no longer supported */
1544         ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
1545         viceid = AnonymousID;
1546         expTime = 0x7fffffff;
1547     } else if (authClass == 2) {
1548         afs_int32 kvno;
1549
1550         /* kerberos ticket */
1551         code = rxkad_GetServerInfo(tcon, /*level */ 0, &expTime,
1552                                    tname, tinst, tcell, &kvno);
1553         if (code) {
1554             ViceLog(1, ("Failed to get rxkad ticket info\n"));
1555             viceid = AnonymousID;
1556             expTime = 0x7fffffff;
1557         } else {
1558             int ilen = strlen(tinst);
1559             ViceLog(5,
1560                     ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
1561                      tname, tinst, tcell, expTime, kvno));
1562             strncpy(uname, tname, sizeof(uname));
1563             if (ilen) {
1564                 if (strlen(uname) + 1 + ilen >= sizeof(uname))
1565                     goto bad_name;
1566                 strcat(uname, ".");
1567                 strcat(uname, tinst);
1568             }
1569             /* translate the name to a vice id */
1570             code = MapName_r(uname, tcell, &viceid);
1571             if (code) {
1572               bad_name:
1573                 ViceLog(1,
1574                         ("failed to map name=%s, cell=%s -> code=%d\n", uname,
1575                          tcell, code));
1576                 fail = 1;
1577                 viceid = AnonymousID;
1578                 expTime = 0x7fffffff;
1579             }
1580         }
1581     } else {
1582         viceid = AnonymousID;   /* unknown security class */
1583         expTime = 0x7fffffff;
1584     }
1585
1586     if (!client) {
1587         host = h_GetHost_r(tcon);       /* Returns it h_Held */
1588
1589     retryfirstclient:
1590         /* First try to find the client structure */
1591         for (client = host->FirstClient; client; client = client->next) {
1592             if (!client->deleted && (client->sid == rxr_CidOf(tcon))
1593                 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1594                 if (client->tcon && (client->tcon != tcon)) {
1595                     ViceLog(0,
1596                             ("*** Vid=%d, sid=%x, tcon=%x, Tcon=%x ***\n",
1597                              client->ViceId, client->sid, client->tcon,
1598                              tcon));
1599                     oldClient =
1600                         (struct client *)rx_GetSpecific(client->tcon,
1601                                                         rxcon_client_key);
1602                     if (oldClient) {
1603                         if (oldClient == client)
1604                             rx_SetSpecific(client->tcon, rxcon_client_key,
1605                                            NULL);
1606                         else
1607                             ViceLog(0,
1608                                     ("Client-conn mismatch: CL1=%x, CN=%x, CL2=%x\n",
1609                                      client, client->tcon, oldClient));
1610                     }
1611                     client->tcon = (struct rx_connection *)0;
1612                 }
1613                 client->refCount++;
1614                 H_UNLOCK;
1615                 ObtainWriteLock(&client->lock);
1616                 H_LOCK;
1617                 break;
1618             }
1619         }
1620
1621         /* Still no client structure - get one */
1622         if (!client) {
1623             h_Lock_r(host);
1624             /* Retry to find the client structure */
1625             for (client = host->FirstClient; client; client = client->next) {
1626                 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
1627                     && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1628                     h_Unlock_r(host);
1629                     goto retryfirstclient;
1630                 }
1631             }
1632             client = GetCE();
1633             ObtainWriteLock(&client->lock);
1634             client->refCount = 1;
1635             client->host = host;
1636             client->next = host->FirstClient;
1637             host->FirstClient = client;
1638 #if FS_STATS_DETAILED
1639             client->InSameNetwork = host->InSameNetwork;
1640 #endif /* FS_STATS_DETAILED */
1641             client->ViceId = viceid;
1642             client->expTime = expTime;  /* rx only */
1643             client->authClass = authClass;      /* rx only */
1644             client->sid = rxr_CidOf(tcon);
1645             client->VenusEpoch = rxr_GetEpoch(tcon);
1646             client->CPS.prlist_val = 0;
1647             client->CPS.prlist_len = 0;
1648             h_Unlock_r(host);
1649             CurrentConnections++;       /* increment number of connections */
1650         }
1651     }
1652     client->prfail = fail;
1653
1654     if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
1655         if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID)) {
1656             free(client->CPS.prlist_val);
1657         }
1658         client->CPS.prlist_val = NULL;
1659         client->CPS.prlist_len = 0;
1660         client->ViceId = viceid;
1661         client->expTime = expTime;
1662
1663         if (viceid == ANONYMOUSID) {
1664             client->CPS.prlist_len = AnonCPS.prlist_len;
1665             client->CPS.prlist_val = AnonCPS.prlist_val;
1666         } else {
1667             H_UNLOCK;
1668             code = pr_GetCPS(viceid, &client->CPS);
1669             H_LOCK;
1670             if (code) {
1671                 char hoststr[16];
1672                 ViceLog(0,
1673                         ("pr_GetCPS failed(%d) for user %d, host %s:%d\n",
1674                          code, viceid, afs_inet_ntoa_r(client->host->host,
1675                                                        hoststr),
1676                          ntohs(client->host->port)));
1677
1678                 /* Although ubik_Call (called by pr_GetCPS) traverses thru
1679                  * all protection servers and reevaluates things if no
1680                  * sync server or quorum is found we could still end up
1681                  * with one of these errors. In such case we would like to
1682                  * reevaluate the rpc call to find if there's cps for this
1683                  * guy. We treat other errors (except network failures
1684                  * ones - i.e. code < 0) as an indication that there is no
1685                  * CPS for this host.  Ideally we could like to deal this
1686                  * problem the other way around (i.e.  if code == NOCPS
1687                  * ignore else retry next time) but the problem is that
1688                  * there're other errors (i.e.  EPERM) for which we don't
1689                  * want to retry and we don't know the whole code list!
1690                  */
1691                 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
1692                     client->prfail = 1;
1693             }
1694         }
1695         /* the disabling of system:administrators is so iffy and has so many
1696          * possible failure modes that we will disable it again */
1697         /* Turn off System:Administrator for safety  
1698          * if (AL_IsAMember(SystemId, client->CPS) == 0)
1699          * assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
1700     }
1701
1702     /* Now, tcon may already be set to a rock, since we blocked with no host
1703      * or client locks set above in pr_GetCPS (XXXX some locking is probably
1704      * required).  So, before setting the RPC's rock, we should disconnect
1705      * the RPC from the other client structure's rock.
1706      */
1707     oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1708     if (oldClient && oldClient->tcon == tcon) {
1709         oldClient->tcon = (struct rx_connection *)0;
1710         ViceLog(0, ("FindClient: client %x(%x) already had conn %x (host %x), stolen by client %x(%x)\n", 
1711                     oldClient, oldClient->sid, tcon, 
1712                     rx_HostOf(rx_PeerOf(tcon)), client, client->sid));
1713         /* rx_SetSpecific will be done immediately below */
1714     }
1715     client->tcon = tcon;
1716     rx_SetSpecific(tcon, rxcon_client_key, client);
1717     ReleaseWriteLock(&client->lock);
1718
1719     return client;
1720
1721 }                               /*h_FindClient_r */
1722
1723 int
1724 h_ReleaseClient_r(struct client *client)
1725 {
1726     assert(client->refCount > 0);
1727     client->refCount--;
1728     return 0;
1729 }
1730
1731
1732 /*
1733  * Sigh:  this one is used to get the client AGAIN within the individual
1734  * server routines.  This does not bother h_Holding the host, since
1735  * this is assumed already have been done by the server main loop.
1736  * It does check tokens, since only the server routines can return the
1737  * VICETOKENDEAD error code
1738  */
1739 int
1740 GetClient(struct rx_connection *tcon, struct client **cp)
1741 {
1742     register struct client *client;
1743
1744     H_LOCK;
1745     *cp = client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1746     if (client == NULL || client->tcon == NULL) {
1747         ViceLog(0,
1748                 ("GetClient: no client in conn %x (host %x), VBUSYING\n",
1749                  tcon, rx_HostOf(rx_PeerOf(tcon))));
1750         H_UNLOCK;
1751         return VBUSY;
1752     }
1753     if (rxr_CidOf(client->tcon) != client->sid) {
1754         ViceLog(0,
1755                 ("GetClient: tcon %x tcon sid %d client sid %d\n",
1756                  client->tcon, rxr_CidOf(client->tcon), client->sid));
1757         H_UNLOCK;
1758         return VBUSY;
1759     }
1760     if (!(client && client->tcon && rxr_CidOf(client->tcon) == client->sid)) {
1761         if (!client)
1762             ViceLog(0, ("GetClient: no client in conn %x\n", tcon));
1763         else
1764             ViceLog(0,
1765                     ("GetClient: tcon %x tcon sid %d client sid %d\n",
1766                      client->tcon, client->tcon ? rxr_CidOf(client->tcon)
1767                      : -1, client->sid));
1768         assert(0);
1769     }
1770     if (client && client->LastCall > client->expTime && client->expTime) {
1771         char hoststr[16];
1772         ViceLog(1,
1773                 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
1774                  afs_inet_ntoa_r(client->host->host, hoststr),
1775                  ntohs(client->host->port), client->expTime));
1776         H_UNLOCK;
1777         return VICETOKENDEAD;
1778     }
1779
1780     H_UNLOCK;
1781     return 0;
1782
1783 }                               /*GetClient */
1784
1785
1786 /* Client user name for short term use.  Note that this is NOT inexpensive */
1787 char *
1788 h_UserName(struct client *client)
1789 {
1790     static char User[PR_MAXNAMELEN + 1];
1791     namelist lnames;
1792     idlist lids;
1793
1794     lids.idlist_len = 1;
1795     lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
1796     if (!lids.idlist_val) {
1797         ViceLog(0, ("Failed malloc in h_UserName\n"));
1798         assert(0);
1799     }
1800     lnames.namelist_len = 0;
1801     lnames.namelist_val = (prname *) 0;
1802     lids.idlist_val[0] = client->ViceId;
1803     if (pr_IdToName(&lids, &lnames)) {
1804         /* We need to free id we alloced above! */
1805         free(lids.idlist_val);
1806         return "*UNKNOWN USER NAME*";
1807     }
1808     strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
1809     free(lids.idlist_val);
1810     free(lnames.namelist_val);
1811     return User;
1812
1813 }                               /*h_UserName */
1814
1815
1816 void
1817 h_PrintStats()
1818 {
1819     ViceLog(0,
1820             ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
1821              CEs, CEBlocks, HTs, HTBlocks));
1822
1823 }                               /*h_PrintStats */
1824
1825
1826 static int
1827 h_PrintClient(register struct host *host, int held, StreamHandle_t * file)
1828 {
1829     register struct client *client;
1830     int i;
1831     char tmpStr[256];
1832     char tbuffer[32];
1833     char hoststr[16];
1834
1835     H_LOCK;
1836     if (host->hostFlags & HOSTDELETED) {
1837         H_UNLOCK;
1838         return held;
1839     }
1840     (void)afs_snprintf(tmpStr, sizeof tmpStr,
1841                        "Host %s:%d down = %d, LastCall %s",
1842                        afs_inet_ntoa_r(host->host, hoststr),
1843                        ntohs(host->port), (host->hostFlags & VENUSDOWN),
1844                        afs_ctime((time_t *) & host->LastCall, tbuffer,
1845                                  sizeof(tbuffer)));
1846     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1847     for (client = host->FirstClient; client; client = client->next) {
1848         if (!client->deleted) {
1849             if (client->tcon) {
1850                 (void)afs_snprintf(tmpStr, sizeof tmpStr,
1851                                    "    user id=%d,  name=%s, sl=%s till %s",
1852                                    client->ViceId, h_UserName(client),
1853                                    client->
1854                                    authClass ? "Authenticated" :
1855                                    "Not authenticated",
1856                                    client->
1857                                    authClass ? afs_ctime((time_t *) & client->
1858                                                          expTime, tbuffer,
1859                                                          sizeof(tbuffer))
1860                                    : "No Limit\n");
1861                 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1862             } else {
1863                 (void)afs_snprintf(tmpStr, sizeof tmpStr,
1864                                    "    user=%s, no current server connection\n",
1865                                    h_UserName(client));
1866                 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1867             }
1868             (void)afs_snprintf(tmpStr, sizeof tmpStr, "      CPS-%d is [",
1869                                client->CPS.prlist_len);
1870             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1871             if (client->CPS.prlist_val) {
1872                 for (i = 0; i > client->CPS.prlist_len; i++) {
1873                     (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
1874                                        client->CPS.prlist_val[i]);
1875                     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1876                 }
1877             }
1878             sprintf(tmpStr, "]\n");
1879             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1880         }
1881     }
1882     H_UNLOCK;
1883     return held;
1884
1885 }                               /*h_PrintClient */
1886
1887
1888
1889 /*
1890  * Print a list of clients, with last security level and token value seen,
1891  * if known
1892  */
1893 void
1894 h_PrintClients()
1895 {
1896     time_t now;
1897     char tmpStr[256];
1898     char tbuffer[32];
1899
1900     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
1901
1902     if (file == NULL) {
1903         ViceLog(0,
1904                 ("Couldn't create client dump file %s\n",
1905                  AFSDIR_SERVER_CLNTDUMP_FILEPATH));
1906         return;
1907     }
1908     now = FT_ApproxTime();
1909     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
1910                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
1911     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1912     h_Enumerate(h_PrintClient, (char *)file);
1913     STREAM_REALLYCLOSE(file);
1914     ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
1915 }
1916
1917
1918
1919
1920 static int
1921 h_DumpHost(register struct host *host, int held, StreamHandle_t * file)
1922 {
1923     int i;
1924     char tmpStr[256];
1925
1926     H_LOCK;
1927     (void)afs_snprintf(tmpStr, sizeof tmpStr,
1928                        "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 [",
1929                        host->host, ntohs(host->port), host->index,
1930                        host->cblist, CheckLock(&host->lock), host->LastCall,
1931                        host->ActiveCall, (host->hostFlags & VENUSDOWN),
1932                        host->hostFlags & HOSTDELETED, host->Console,
1933                        host->hostFlags & CLIENTDELETED, host->hcpsfailed,
1934                        host->cpsCall);
1935     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1936     if (host->hcps.prlist_val)
1937         for (i = 0; i < host->hcps.prlist_len; i++) {
1938             (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
1939                                host->hcps.prlist_val[i]);
1940             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1941         }
1942     sprintf(tmpStr, "] [");
1943     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1944     if (host->interface)
1945         for (i = 0; i < host->interface->numberOfInterfaces; i++) {
1946             sprintf(tmpStr, " %x:%d", host->interface->interface[i].addr,
1947                      ntohs(host->interface->interface[i].port));
1948             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1949         }
1950     sprintf(tmpStr, "] holds: ");
1951     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1952
1953     for (i = 0; i < h_maxSlots; i++) {
1954         sprintf(tmpStr, "%04x", host->holds[i]);
1955         (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1956     }
1957     sprintf(tmpStr, " slot/bit: %d/%d\n", h_holdSlot(), h_holdbit());
1958     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1959
1960     H_UNLOCK;
1961     return held;
1962
1963 }                               /*h_DumpHost */
1964
1965
1966 void
1967 h_DumpHosts()
1968 {
1969     time_t now;
1970     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
1971     char tmpStr[256];
1972     char tbuffer[32];
1973
1974     if (file == NULL) {
1975         ViceLog(0,
1976                 ("Couldn't create host dump file %s\n",
1977                  AFSDIR_SERVER_HOSTDUMP_FILEPATH));
1978         return;
1979     }
1980     now = FT_ApproxTime();
1981     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
1982                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
1983     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1984     h_Enumerate(h_DumpHost, (char *)file);
1985     STREAM_REALLYCLOSE(file);
1986     ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
1987
1988 }                               /*h_DumpHosts */
1989
1990
1991 /*
1992  * This counts the number of workstations, the number of active workstations,
1993  * and the number of workstations declared "down" (i.e. not heard from
1994  * recently).  An active workstation has received a call since the cutoff
1995  * time argument passed.
1996  */
1997 void
1998 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
1999 {
2000     register struct host *host;
2001     register int num = 0, active = 0, del = 0;
2002
2003     H_LOCK;
2004     for (host = hostList; host; host = host->next) {
2005         if (!(host->hostFlags & HOSTDELETED)) {
2006             num++;
2007             if (host->ActiveCall > cutofftime)
2008                 active++;
2009             if (host->hostFlags & VENUSDOWN)
2010                 del++;
2011         }
2012     }
2013     H_UNLOCK;
2014     if (nump)
2015         *nump = num;
2016     if (activep)
2017         *activep = active;
2018     if (delp)
2019         *delp = del;
2020
2021 }                               /*h_GetWorkStats */
2022
2023
2024 /*------------------------------------------------------------------------
2025  * PRIVATE h_ClassifyAddress
2026  *
2027  * Description:
2028  *      Given a target IP address and a candidate IP address (both
2029  *      in host byte order), classify the candidate into one of three
2030  *      buckets in relation to the target by bumping the counters passed
2031  *      in as parameters.
2032  *
2033  * Arguments:
2034  *      a_targetAddr       : Target address.
2035  *      a_candAddr         : Candidate address.
2036  *      a_sameNetOrSubnetP : Ptr to counter to bump when the two
2037  *                           addresses are either in the same network
2038  *                           or the same subnet.
2039  *      a_diffSubnetP      : ...when the candidate is in a different
2040  *                           subnet.
2041  *      a_diffNetworkP     : ...when the candidate is in a different
2042  *                           network.
2043  *
2044  * Returns:
2045  *      Nothing.
2046  *
2047  * Environment:
2048  *      The target and candidate addresses are both in host byte
2049  *      order, NOT network byte order, when passed in.
2050  *
2051  * Side Effects:
2052  *      As advertised.
2053  *------------------------------------------------------------------------*/
2054
2055 static void
2056 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
2057                   afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
2058                   afs_int32 * a_diffNetworkP)
2059 {                               /*h_ClassifyAddress */
2060
2061     afs_uint32 targetNet;
2062     afs_uint32 targetSubnet;
2063     afs_uint32 candNet;
2064     afs_uint32 candSubnet;
2065
2066     /*
2067      * Put bad values into the subnet info to start with.
2068      */
2069     targetSubnet = (afs_uint32) 0;
2070     candSubnet = (afs_uint32) 0;
2071
2072     /*
2073      * Pull out the network and subnetwork numbers from the target
2074      * and candidate addresses.  We can short-circuit this whole
2075      * affair if the target and candidate addresses are not of the
2076      * same class.
2077      */
2078     if (IN_CLASSA(a_targetAddr)) {
2079         if (!(IN_CLASSA(a_candAddr))) {
2080             (*a_diffNetworkP)++;
2081             return;
2082         }
2083         targetNet = a_targetAddr & IN_CLASSA_NET;
2084         candNet = a_candAddr & IN_CLASSA_NET;
2085         if (IN_SUBNETA(a_targetAddr))
2086             targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
2087         if (IN_SUBNETA(a_candAddr))
2088             candSubnet = a_candAddr & IN_CLASSA_SUBNET;
2089     } else if (IN_CLASSB(a_targetAddr)) {
2090         if (!(IN_CLASSB(a_candAddr))) {
2091             (*a_diffNetworkP)++;
2092             return;
2093         }
2094         targetNet = a_targetAddr & IN_CLASSB_NET;
2095         candNet = a_candAddr & IN_CLASSB_NET;
2096         if (IN_SUBNETB(a_targetAddr))
2097             targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
2098         if (IN_SUBNETB(a_candAddr))
2099             candSubnet = a_candAddr & IN_CLASSB_SUBNET;
2100     } /*Class B target */
2101     else if (IN_CLASSC(a_targetAddr)) {
2102         if (!(IN_CLASSC(a_candAddr))) {
2103             (*a_diffNetworkP)++;
2104             return;
2105         }
2106         targetNet = a_targetAddr & IN_CLASSC_NET;
2107         candNet = a_candAddr & IN_CLASSC_NET;
2108
2109         /*
2110          * Note that class C addresses can't have subnets,
2111          * so we leave the defaults untouched.
2112          */
2113     } /*Class C target */
2114     else {
2115         targetNet = a_targetAddr;
2116         candNet = a_candAddr;
2117     }                           /*Class D address */
2118
2119     /*
2120      * Now, simply compare the extracted net and subnet values for
2121      * the two addresses (which at this point are known to be of the
2122      * same class)
2123      */
2124     if (targetNet == candNet) {
2125         if (targetSubnet == candSubnet)
2126             (*a_sameNetOrSubnetP)++;
2127         else
2128             (*a_diffSubnetP)++;
2129     } else
2130         (*a_diffNetworkP)++;
2131
2132 }                               /*h_ClassifyAddress */
2133
2134
2135 /*------------------------------------------------------------------------
2136  * EXPORTED h_GetHostNetStats
2137  *
2138  * Description:
2139  *      Iterate through the host table, and classify each (non-deleted)
2140  *      host entry into ``proximity'' categories (same net or subnet,
2141  *      different subnet, different network).
2142  *
2143  * Arguments:
2144  *      a_numHostsP        : Set to total number of (non-deleted) hosts.
2145  *      a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
2146  *      a_diffSubnetP      : Set to # hosts on diff subnet as server.
2147  *      a_diffNetworkP     : Set to # hosts on diff network as server.
2148  *
2149  * Returns:
2150  *      Nothing.
2151  *
2152  * Environment:
2153  *      We only count non-deleted hosts.  The storage pointed to by our
2154  *      parameters is zeroed upon entry.
2155  *
2156  * Side Effects:
2157  *      As advertised.
2158  *------------------------------------------------------------------------*/
2159
2160 void
2161 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
2162                   afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
2163 {                               /*h_GetHostNetStats */
2164
2165     register struct host *hostP;        /*Ptr to current host entry */
2166     register afs_uint32 currAddr_HBO;   /*Curr host addr, host byte order */
2167
2168     /*
2169      * Clear out the storage pointed to by our parameters.
2170      */
2171     *a_numHostsP = (afs_int32) 0;
2172     *a_sameNetOrSubnetP = (afs_int32) 0;
2173     *a_diffSubnetP = (afs_int32) 0;
2174     *a_diffNetworkP = (afs_int32) 0;
2175
2176     H_LOCK;
2177     for (hostP = hostList; hostP; hostP = hostP->next) {
2178         if (!(hostP->hostFlags & HOSTDELETED)) {
2179             /*
2180              * Bump the number of undeleted host entries found.
2181              * In classifying the current entry's address, make
2182              * sure to first convert to host byte order.
2183              */
2184             (*a_numHostsP)++;
2185             currAddr_HBO = (afs_uint32) ntohl(hostP->host);
2186             h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
2187                               a_sameNetOrSubnetP, a_diffSubnetP,
2188                               a_diffNetworkP);
2189         }                       /*Only look at non-deleted hosts */
2190     }                           /*For each host record hashed to this index */
2191     H_UNLOCK;
2192 }                               /*h_GetHostNetStats */
2193
2194 static afs_uint32 checktime;
2195 static afs_uint32 clientdeletetime;
2196 static struct AFSFid zerofid;
2197
2198
2199 /*
2200  * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
2201  * Since it can serialize them, and pile up, it should be a separate LWP
2202  * from other events.
2203  */
2204 int
2205 CheckHost(register struct host *host, int held)
2206 {
2207     register struct client *client;
2208     struct rx_connection *cb_conn = NULL;
2209     int code;
2210
2211     /* Host is held by h_Enumerate */
2212     H_LOCK;
2213     for (client = host->FirstClient; client; client = client->next) {
2214         if (client->refCount == 0 && client->LastCall < clientdeletetime) {
2215             client->deleted = 1;
2216             host->hostFlags |= CLIENTDELETED;
2217         }
2218     }
2219     if (host->LastCall < checktime) {
2220         h_Lock_r(host);
2221         if (!(host->hostFlags & HOSTDELETED)) {
2222             cb_conn = host->callback_rxcon;
2223             rx_GetConnection(cb_conn);
2224             if (host->LastCall < clientdeletetime) {
2225                 host->hostFlags |= HOSTDELETED;
2226                 if (!(host->hostFlags & VENUSDOWN)) {
2227                     host->hostFlags &= ~ALTADDR;        /* alternate address invalid */
2228                     if (host->interface) {
2229                         H_UNLOCK;
2230                         code =
2231                             RXAFSCB_InitCallBackState3(cb_conn,
2232                                                        &FS_HostUUID);
2233                         H_LOCK;
2234                     } else {
2235                         H_UNLOCK;
2236                         code =
2237                             RXAFSCB_InitCallBackState(cb_conn);
2238                         H_LOCK;
2239                     }
2240                     host->hostFlags |= ALTADDR; /* alternate addresses valid */
2241                     if (code) {
2242                         char hoststr[16];
2243                         (void)afs_inet_ntoa_r(host->host, hoststr);
2244                         ViceLog(0,
2245                                 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
2246                                  hoststr, ntohs(host->port)));
2247                         host->hostFlags |= VENUSDOWN;
2248                     }
2249                     /* Note:  it's safe to delete hosts even if they have call
2250                      * back state, because break delayed callbacks (called when a
2251                      * message is received from the workstation) will always send a 
2252                      * break all call backs to the workstation if there is no
2253                      *callback.
2254                      */
2255                 }
2256             } else {
2257                 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
2258                     if (host->interface) {
2259                         afsUUID uuid = host->interface->uuid;
2260                         H_UNLOCK;
2261                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2262                         H_LOCK;
2263                         if (code) {
2264                             if (MultiProbeAlternateAddress_r(host)) {
2265                                 char hoststr[16];
2266                                 (void)afs_inet_ntoa_r(host->host, hoststr);
2267                                 ViceLog(0,
2268                                         ("ProbeUuid failed for host %s:%d\n",
2269                                          hoststr, ntohs(host->port)));
2270                                 host->hostFlags |= VENUSDOWN;
2271                             }
2272                         }
2273                     } else {
2274                         H_UNLOCK;
2275                         code = RXAFSCB_Probe(cb_conn);
2276                         H_LOCK;
2277                         if (code) {
2278                             char hoststr[16];
2279                             (void)afs_inet_ntoa_r(host->host, hoststr);
2280                             ViceLog(0,
2281                                     ("Probe failed for host %s:%d\n", hoststr,
2282                                      ntohs(host->port)));
2283                             host->hostFlags |= VENUSDOWN;
2284                         }
2285                     }
2286                 }
2287             }
2288             H_UNLOCK;
2289             rx_PutConnection(cb_conn);
2290             cb_conn=NULL;
2291             H_LOCK;
2292         }
2293         h_Unlock_r(host);
2294     }
2295     H_UNLOCK;
2296     return held;
2297
2298 }                               /*CheckHost */
2299
2300
2301 /*
2302  * Set VenusDown for any hosts that have not had a call in 15 minutes and
2303  * don't respond to a probe.  Note that VenusDown can only be cleared if
2304  * a message is received from the host (see ServerLWP in file.c).
2305  * Delete hosts that have not had any calls in 1 hour, clients that
2306  * have not had any calls in 15 minutes.
2307  *
2308  * This routine is called roughly every 5 minutes.
2309  */
2310 void
2311 h_CheckHosts()
2312 {
2313     afs_uint32 now = FT_ApproxTime();
2314
2315     memset((char *)&zerofid, 0, sizeof(zerofid));
2316     /*
2317      * Send a probe to the workstation if it hasn't been heard from in
2318      * 15 minutes
2319      */
2320     checktime = now - 15 * 60;
2321     clientdeletetime = now - 120 * 60;  /* 2 hours ago */
2322     h_Enumerate(CheckHost, NULL);
2323
2324 }                               /*h_CheckHosts */
2325
2326 /*
2327  * This is called with host locked and held. At this point, the
2328  * hostHashTable should not have any entries for the alternate
2329  * interfaces. This function has to insert these entries in the
2330  * hostHashTable.
2331  *
2332  * The addresses in the interfaceAddr list are in host byte order.
2333  */
2334 int
2335 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
2336 {
2337     int i, j;
2338     int number, count;
2339     afs_uint32 myAddr;
2340     afs_uint16 myPort;
2341     int found;
2342     struct Interface *interface;
2343
2344     assert(host);
2345     assert(interf);
2346
2347     ViceLog(125,
2348             ("initInterfaceAddr : host %x numAddr %d\n", host->host,
2349              interf->numberOfInterfaces));
2350
2351     number = interf->numberOfInterfaces;
2352     myAddr = host->host;        /* current interface address */
2353     myPort = host->port;        /* current port */
2354
2355     /* validation checks */
2356     if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
2357         ViceLog(0,
2358                 ("Number of alternate addresses returned is %d\n", number));
2359         return -1;
2360     }
2361
2362     /*
2363      * Convert IP addresses to network byte order, and remove for
2364      * duplicate IP addresses from the interface list.
2365      */
2366     for (i = 0, count = 0, found = 0; i < number; i++) {
2367         interf->addr_in[i] = htonl(interf->addr_in[i]);
2368         for (j = 0; j < count; j++) {
2369             if (interf->addr_in[j] == interf->addr_in[i])
2370                 break;
2371         }
2372         if (j == count) {
2373             interf->addr_in[count] = interf->addr_in[i];
2374             if (interf->addr_in[count] == myAddr)
2375                 found = 1;
2376             count++;
2377         }
2378     }
2379
2380     /*
2381      * Allocate and initialize an interface structure for this host.
2382      */
2383     if (found) {
2384         interface = (struct Interface *)
2385             malloc(sizeof(struct Interface) +
2386                    (sizeof(struct AddrPort) * (count - 1)));
2387         if (!interface) {
2388             ViceLog(0, ("Failed malloc in initInterfaceAddr_r\n"));
2389             assert(0);
2390         }
2391         interface->numberOfInterfaces = count;
2392     } else {
2393         interface = (struct Interface *)
2394             malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
2395         assert(interface);
2396         interface->numberOfInterfaces = count + 1;
2397         interface->interface[count].addr = myAddr;
2398         interface->interface[count].port = myPort;
2399     }
2400     interface->uuid = interf->uuid;
2401     for (i = 0; i < count; i++) {
2402         interface->interface[i].addr = interf->addr_in[i];
2403         /* We store the port as 7001 because the addresses reported by 
2404          * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
2405          * are coming from fully connected hosts (no NAT/PATs)
2406          */
2407         interface->interface[i].port = htons(7001);
2408     }
2409
2410     assert(!host->interface);
2411     host->interface = interface;
2412
2413     for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2414         ViceLog(125, ("--- alt address %x:%d\n", host->interface->interface[i].addr,
2415                        ntohs(host->interface->interface[i].port)));
2416     }
2417
2418     return 0;
2419 }
2420
2421 /* deleted a HashChain structure for this address and host */
2422 /* returns 1 on success */
2423 int
2424 hashDelete_r(afs_uint32 addr, afs_uint16 port, struct host *host)
2425 {
2426     int flag;
2427     register struct h_hashChain **hp, *th;
2428
2429     for (hp = &hostHashTable[h_HashIndex(addr)]; (th = *hp);) {
2430         assert(th->hostPtr);
2431         if (th->hostPtr == host && th->addr == addr && th->port == port) {
2432             *hp = th->next;
2433             free(th);
2434             flag = 1;
2435             break;
2436         } else {
2437             hp = &th->next;
2438         }
2439     }
2440     return flag;
2441 }
2442
2443
2444 /*
2445 ** prints out all alternate interface address for the host. The 'level'
2446 ** parameter indicates what level of debugging sets this output
2447 */
2448 void
2449 printInterfaceAddr(struct host *host, int level)
2450 {
2451     int i, number;
2452     if (host->interface) {
2453         /* check alternate addresses */
2454         number = host->interface->numberOfInterfaces;
2455         assert(number > 0);
2456         for (i = 0; i < number; i++)
2457             ViceLog(level, ("%x:%d ", host->interface->interface[i].addr,
2458                              ntohs(host->interface->interface[i].port)));
2459     }
2460     ViceLog(level, ("\n"));
2461 }