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