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