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