56af963e266288028d9de3fd9ca8805ac94e4ed2
[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     /* insert into beginning of list for this bucket */
982     chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
983     if (!chain) {
984         ViceLog(0, ("Failed malloc in h_AddHostToHashTable_r\n"));
985         assert(0);
986     }
987     chain->hostPtr = host;
988     chain->next = hostHashTable[index];
989     chain->addr = addr;
990     chain->port = port;
991     hostHashTable[index] = chain;
992
993 }
994
995 /*
996  * This is called with host locked and held. At this point, the
997  * hostHashTable should not be having entries for the alternate
998  * interfaces. This function has to insert these entries in the
999  * hostHashTable.
1000  *
1001  * All addresses are in network byte order.
1002  */
1003 int
1004 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1005 {
1006     int i;
1007     int number;
1008     int found;
1009     struct Interface *interface;
1010     char hoststr[16], hoststr2[16];
1011
1012     assert(host);
1013     assert(host->interface);
1014
1015     ViceLog(125, ("addInterfaceAddr : host %s:%d addr %s:%d\n", 
1016                    afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), 
1017                    afs_inet_ntoa_r(addr, hoststr2), ntohs(port)));
1018
1019     /*
1020      * Make sure this address is on the list of known addresses
1021      * for this host.
1022      */
1023     number = host->interface->numberOfInterfaces;
1024     for (i = 0, found = 0; i < number && !found; i++) {
1025         if (host->interface->interface[i].addr == addr &&
1026             host->interface->interface[i].port == port)
1027             found = 1;
1028     }
1029     if (!found) {
1030         interface = (struct Interface *)
1031             malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1032         if (!interface) {
1033             ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
1034             assert(0);
1035         }
1036         interface->numberOfInterfaces = number + 1;
1037         interface->uuid = host->interface->uuid;
1038         for (i = 0; i < number; i++)
1039             interface->interface[i] = host->interface->interface[i];
1040         interface->interface[number].addr = addr;
1041         interface->interface[number].port = port;
1042         free(host->interface);
1043         host->interface = interface;
1044     }
1045
1046     /*
1047      * Create a hash table entry for this address
1048      */
1049     h_AddHostToHashTable_r(addr, port, host);
1050
1051     return 0;
1052 }
1053
1054
1055 /*
1056  * This is called with host locked and held. At this point, the
1057  * hostHashTable should not be having entries for the alternate
1058  * interfaces. This function has to insert these entries in the
1059  * hostHashTable.
1060  *
1061  * All addresses are in network byte order.
1062  */
1063 int
1064 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1065 {
1066     int i;
1067     int number;
1068     int found;
1069     struct Interface *interface;
1070     char hoststr[16], hoststr2[16];
1071
1072     assert(host);
1073     assert(host->interface);
1074
1075     ViceLog(125, ("removeInterfaceAddr : host %s:%d addr %s:%d\n", 
1076                    afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), 
1077                    afs_inet_ntoa_r(addr, hoststr2), ntohs(port)));
1078
1079     /*
1080      * Make sure this address is on the list of known addresses
1081      * for this host.
1082      */
1083     interface = host->interface;
1084     number = host->interface->numberOfInterfaces;
1085     for (i = 0, found = 0; i < number; i++) {
1086         if (interface->interface[i].addr == addr &&
1087             interface->interface[i].port == port) {
1088             found = 1;
1089             break;
1090         }
1091     }
1092     if (found) {
1093         number--;
1094         for (; i < number; i++) {
1095             interface->interface[i].addr = interface->interface[i+1].addr;
1096             interface->interface[i].port = interface->interface[i+1].port;
1097         }
1098         interface->numberOfInterfaces = number;
1099     }
1100
1101     /*
1102      * Remove the hash table entry for this address
1103      */
1104     h_DeleteHostFromHashTableByAddr_r(addr, port, host);
1105
1106     return 0;
1107 }
1108
1109
1110 /* Host is returned held */
1111 struct host *
1112 h_GetHost_r(struct rx_connection *tcon)
1113 {
1114     struct host *host;
1115     struct host *oldHost;
1116     int code;
1117     int held, oheld;
1118     struct interfaceAddr interf;
1119     int interfValid = 0;
1120     struct Identity *identP = NULL;
1121     afs_uint32 haddr;
1122     afs_uint16 hport;
1123     char hoststr[16], hoststr2[16];
1124     Capabilities caps;
1125     struct rx_connection *cb_conn = NULL;
1126
1127     caps.Capabilities_val = NULL;
1128
1129     haddr = rxr_HostOf(tcon);
1130     hport = rxr_PortOf(tcon);
1131   retry:
1132     if (caps.Capabilities_val)
1133         free(caps.Capabilities_val);
1134     caps.Capabilities_val = NULL;
1135     caps.Capabilities_len = 0;
1136
1137     code = 0;
1138     host = h_Lookup_r(haddr, hport, &held);
1139     identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1140     if (host && !identP && !(host->Console & 1)) {
1141         /* This is a new connection, and we already have a host
1142          * structure for this address. Verify that the identity
1143          * of the caller matches the identity in the host structure.
1144          */
1145         h_Lock_r(host);
1146         if (!(host->hostFlags & ALTADDR)) {
1147             /* Another thread is doing initialization */
1148             h_Unlock_r(host);
1149             if (!held)
1150                 h_Release_r(host);
1151             ViceLog(125,
1152                     ("Host %s:%d starting h_Lookup again\n",
1153                      afs_inet_ntoa_r(host->host, hoststr),
1154                      ntohs(host->port)));
1155             goto retry;
1156         }
1157         host->hostFlags &= ~ALTADDR;
1158         cb_conn = host->callback_rxcon;
1159         rx_GetConnection(cb_conn);
1160         H_UNLOCK;
1161         code =
1162             RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1163         if (code == RXGEN_OPCODE)
1164             code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1165         rx_PutConnection(cb_conn);
1166         cb_conn=NULL;
1167         H_LOCK;
1168         if (code == RXGEN_OPCODE) {
1169             identP = (struct Identity *)malloc(sizeof(struct Identity));
1170             if (!identP) {
1171                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1172                 assert(0);
1173             }
1174             identP->valid = 0;
1175             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1176             /* The host on this connection was unable to respond to 
1177              * the WhoAreYou. We will treat this as a new connection
1178              * from the existing host. The worst that can happen is
1179              * that we maintain some extra callback state information */
1180             if (host->interface) {
1181                 ViceLog(0,
1182                         ("Host %s:%d used to support WhoAreYou, deleting.\n",
1183                          afs_inet_ntoa_r(host->host, hoststr),
1184                          ntohs(host->port)));
1185                 host->hostFlags |= HOSTDELETED;
1186                 h_Unlock_r(host);
1187                 if (!held)
1188                     h_Release_r(host);
1189                 host = NULL;
1190                 goto retry;
1191             }
1192         } else if (code == 0) {
1193             interfValid = 1;
1194             identP = (struct Identity *)malloc(sizeof(struct Identity));
1195             if (!identP) {
1196                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1197                 assert(0);
1198             }
1199             identP->valid = 1;
1200             identP->uuid = interf.uuid;
1201             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1202             /* Check whether the UUID on this connection matches
1203              * the UUID in the host structure. If they don't match
1204              * then this is not the same host as before. */
1205             if (!host->interface
1206                 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1207                 ViceLog(25,
1208                         ("Host %s:%d has changed its identity, deleting.\n",
1209                          afs_inet_ntoa_r(host->host, hoststr), host->port));
1210                 host->hostFlags |= HOSTDELETED;
1211                 h_Unlock_r(host);
1212                 if (!held)
1213                     h_Release_r(host);
1214                 host = NULL;
1215                 goto retry;
1216             }
1217         } else {
1218             afs_inet_ntoa_r(host->host, hoststr);
1219             ViceLog(0,
1220                     ("CB: WhoAreYou failed for %s:%d, error %d\n", hoststr,
1221                      ntohs(host->port), code));
1222             host->hostFlags |= VENUSDOWN;
1223         }
1224         if (caps.Capabilities_val
1225             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1226             host->hostFlags |= HERRORTRANS;
1227         else
1228             host->hostFlags &= ~(HERRORTRANS);
1229         host->hostFlags |= ALTADDR;
1230         h_Unlock_r(host);
1231     } else if (host) {
1232         if (!(host->hostFlags & ALTADDR)) {
1233             /* another thread is doing the initialisation */
1234             ViceLog(125,
1235                     ("Host %s:%d waiting for host-init to complete\n",
1236                      afs_inet_ntoa_r(host->host, hoststr),
1237                      ntohs(host->port)));
1238             h_Lock_r(host);
1239             h_Unlock_r(host);
1240             if (!held)
1241                 h_Release_r(host);
1242             ViceLog(125,
1243                     ("Host %s:%d starting h_Lookup again\n",
1244                      afs_inet_ntoa_r(host->host, hoststr),
1245                      ntohs(host->port)));
1246             goto retry;
1247         }
1248         /* We need to check whether the identity in the host structure
1249          * matches the identity on the connection. If they don't match
1250          * then treat this a new host. */
1251         if (!(host->Console & 1)
1252             && ((!identP->valid && host->interface)
1253                 || (identP->valid && !host->interface)
1254                 || (identP->valid
1255                     && !afs_uuid_equal(&identP->uuid,
1256                                        &host->interface->uuid)))) {
1257             char uuid1[128], uuid2[128];
1258             if (identP->valid)
1259                 afsUUID_to_string(&identP->uuid, uuid1, 127);
1260             if (host->interface)
1261                 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1262             ViceLog(0,
1263                     ("CB: new identity for host %s:%d, deleting(%x %x %s %s)\n",
1264                      afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1265                      identP->valid, host->interface,
1266                      identP->valid ? uuid1 : "",
1267                      host->interface ? uuid2 : ""));
1268
1269             /* The host in the cache is not the host for this connection */
1270             host->hostFlags |= HOSTDELETED;
1271             h_Unlock_r(host);
1272             if (!held)
1273                 h_Release_r(host);
1274             goto retry;
1275         }
1276     } else {
1277         host = h_Alloc_r(tcon); /* returned held and locked */
1278         h_gethostcps_r(host, FT_ApproxTime());
1279         if (!(host->Console & 1)) {
1280             int pident = 0;
1281             cb_conn = host->callback_rxcon;
1282             rx_GetConnection(cb_conn);
1283             H_UNLOCK;
1284             code =
1285                 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1286             if (code == RXGEN_OPCODE)
1287                 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1288             rx_PutConnection(cb_conn);
1289             cb_conn=NULL;
1290             H_LOCK;
1291             if (code == RXGEN_OPCODE) {
1292                 if (!identP)
1293                     identP =
1294                         (struct Identity *)malloc(sizeof(struct Identity));
1295                 else
1296                     pident = 1;
1297
1298                 if (!identP) {
1299                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1300                     assert(0);
1301                 }
1302                 identP->valid = 0;
1303                 if (!pident)
1304                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1305                 ViceLog(25,
1306                         ("Host %s:%d does not support WhoAreYou.\n",
1307                          afs_inet_ntoa_r(host->host, hoststr),
1308                          ntohs(host->port)));
1309                 code = 0;
1310             } else if (code == 0) {
1311                 if (!identP)
1312                     identP =
1313                         (struct Identity *)malloc(sizeof(struct Identity));
1314                 else
1315                     pident = 1;
1316
1317                 if (!identP) {
1318                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1319                     assert(0);
1320                 }
1321                 identP->valid = 1;
1322                 interfValid = 1;
1323                 identP->uuid = interf.uuid;
1324                 if (!pident)
1325                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1326                 ViceLog(25,
1327                         ("WhoAreYou success on %s:%d\n",
1328                          afs_inet_ntoa_r(host->host, hoststr),
1329                          ntohs(host->port)));
1330             }
1331             if (code == 0 && !identP->valid) {
1332                 cb_conn = host->callback_rxcon;
1333                 rx_GetConnection(cb_conn);
1334                 H_UNLOCK;
1335                 code = RXAFSCB_InitCallBackState(cb_conn);
1336                 rx_PutConnection(cb_conn);
1337                 cb_conn=NULL;
1338                 H_LOCK;
1339             } else if (code == 0) {
1340                 oldHost = h_LookupUuid_r(&identP->uuid);
1341                 if (oldHost) {
1342                     int probefail = 0;
1343
1344                     if (!(oheld = h_Held_r(oldHost)))
1345                         h_Hold_r(oldHost);
1346                     h_Lock_r(oldHost);
1347
1348                     if (oldHost->interface) {
1349                         afsUUID uuid = oldHost->interface->uuid;
1350                         cb_conn = oldHost->callback_rxcon;
1351                         rx_GetConnection(cb_conn);
1352                         rx_SetConnDeadTime(cb_conn, 2);
1353                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1354                         H_UNLOCK;
1355                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1356                         H_LOCK;
1357                         rx_SetConnDeadTime(cb_conn, 50);
1358                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1359                         rx_PutConnection(cb_conn);
1360                         cb_conn=NULL;
1361                         if (code && MultiProbeAlternateAddress_r(oldHost)) {
1362                             probefail = 1;
1363                         }
1364                     } else {
1365                         probefail = 1;
1366                     }
1367
1368                     if (probefail) {
1369                         /* The old host is either does not have a Uuid,
1370                          * is not responding to Probes, 
1371                          * or does not have a matching Uuid. 
1372                          * Delete it! */
1373                         oldHost->hostFlags |= HOSTDELETED;
1374                         h_Unlock_r(oldHost);
1375                         /* Let the holder be last release */
1376                         if (!oheld) {
1377                             h_Release_r(oldHost);
1378                         }
1379                         oldHost = NULL;
1380                     }
1381                 }
1382                 if (oldHost) {
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 (oldHost->host == haddr) {
1394                             /* We have just been contacted by a client behind a NAT */
1395                             removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
1396                         } else {
1397                             int i, found;
1398                             struct Interface *interface = oldHost->interface;
1399                             int number = oldHost->interface->numberOfInterfaces;
1400                             for (i = 0, found = 0; i < number; i++) {
1401                                 if (interface->interface[i].addr == haddr &&
1402                                     interface->interface[i].port != hport) {
1403                                     found = 1;
1404                                     break;
1405                                 }
1406                             }
1407                             if (found) {
1408                                 /* We have just been contacted by a client that has been
1409                                  * seen from behind a NAT and at least one other address.
1410                                  */
1411                                 removeInterfaceAddr_r(oldHost, haddr, interface->interface[i].port);
1412                             }
1413                         }
1414                         addInterfaceAddr_r(oldHost, haddr, hport);
1415                         oldHost->host = haddr;
1416                         oldHost->port = hport;
1417                     }
1418                     host->hostFlags |= HOSTDELETED;
1419                     h_Unlock_r(host);
1420                     /* release host because it was allocated by h_Alloc_r */
1421                     h_Release_r(host);
1422                     host = oldHost;
1423                     /* the new host is held and locked */
1424                 } else {
1425                     /* This really is a new host */
1426                     h_AddHostToUuidHashTable_r(&identP->uuid, host);
1427                     cb_conn = host->callback_rxcon;
1428                     rx_GetConnection(cb_conn);          
1429                     H_UNLOCK;
1430                     code =
1431                         RXAFSCB_InitCallBackState3(cb_conn,
1432                                                    &FS_HostUUID);
1433                     rx_PutConnection(cb_conn);
1434                     cb_conn=NULL;
1435                     H_LOCK;
1436                     if (code == 0) {
1437                         ViceLog(25,
1438                                 ("InitCallBackState3 success on %s:%d\n",
1439                                  afs_inet_ntoa_r(host->host, hoststr),
1440                                  ntohs(host->port)));
1441                         assert(interfValid == 1);
1442                         initInterfaceAddr_r(host, &interf);
1443                     }
1444                 }
1445             }
1446             if (code) {
1447                 afs_inet_ntoa_r(host->host, hoststr);
1448                 ViceLog(0,
1449                         ("CB: RCallBackConnectBack failed for %s:%d\n",
1450                          hoststr, ntohs(host->port)));
1451                 host->hostFlags |= VENUSDOWN;
1452             } else {
1453                 ViceLog(125,
1454                         ("CB: RCallBackConnectBack succeeded for %s:%d\n",
1455                          hoststr, ntohs(host->port)));
1456                 host->hostFlags |= RESETDONE;
1457             }
1458         }
1459         if (caps.Capabilities_val
1460             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1461             host->hostFlags |= HERRORTRANS;
1462         else
1463             host->hostFlags &= ~(HERRORTRANS);
1464         host->hostFlags |= ALTADDR;     /* host structure initialization complete */
1465         h_Unlock_r(host);
1466     }
1467     if (caps.Capabilities_val)
1468         free(caps.Capabilities_val);
1469     caps.Capabilities_val = NULL;
1470     caps.Capabilities_len = 0;
1471     return host;
1472
1473 }                               /*h_GetHost_r */
1474
1475
1476 static char localcellname[PR_MAXNAMELEN + 1];
1477 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
1478 int  num_lrealms = -1;
1479
1480 /* not reentrant */
1481 void
1482 h_InitHostPackage()
1483 {
1484     afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
1485     if (num_lrealms == -1) {
1486         int i;
1487         for (i=0; i<AFS_NUM_LREALMS; i++) {
1488             if (afs_krb_get_lrealm(local_realms[i], i) != 0 /*KSUCCESS*/)
1489                 break;
1490         }
1491
1492         if (i=0) {
1493             ViceLog(0,
1494                     ("afs_krb_get_lrealm failed, using %s.\n",
1495                      localcellname));
1496             strncpy(local_realms[0], localcellname, AFS_REALM_SZ);
1497             num_lrealms = i =1;
1498         } else {
1499             num_lrealms = i;
1500         }
1501
1502         /* initialize the rest of the local realms to nullstring for debugging */
1503         for (; i<AFS_NUM_LREALMS; i++)
1504             local_realms[i][0] = '\0';
1505     }
1506     rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
1507     rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
1508 #ifdef AFS_PTHREAD_ENV
1509     assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
1510 #endif /* AFS_PTHREAD_ENV */
1511 }
1512
1513 static int
1514 MapName_r(char *aname, char *acell, afs_int32 * aval)
1515 {
1516     namelist lnames;
1517     idlist lids;
1518     afs_int32 code;
1519     afs_int32 anamelen, cnamelen;
1520     int foreign = 0;
1521     char *tname;
1522
1523     anamelen = strlen(aname);
1524     if (anamelen >= PR_MAXNAMELEN)
1525         return -1;              /* bad name -- caller interprets this as anonymous, but retries later */
1526
1527     lnames.namelist_len = 1;
1528     lnames.namelist_val = (prname *) aname;     /* don't malloc in the common case */
1529     lids.idlist_len = 0;
1530     lids.idlist_val = NULL;
1531
1532     cnamelen = strlen(acell);
1533     if (cnamelen) {
1534         if (afs_is_foreign_ticket_name(aname, NULL, acell, localcellname)) {
1535             ViceLog(2,
1536                     ("MapName: cell is foreign.  cell=%s, localcell=%s, localrealms={%s,%s,%s,%s}\n",
1537                     acell, localcellname, local_realms[0],local_realms[1],local_realms[2],local_realms[3]));
1538             if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
1539                 ViceLog(2,
1540                         ("MapName: Name too long, using AnonymousID for %s@%s\n",
1541                          aname, acell));
1542                 *aval = AnonymousID;
1543                 return 0;
1544             }
1545             foreign = 1;        /* attempt cross-cell authentication */
1546             tname = (char *)malloc(PR_MAXNAMELEN);
1547             if (!tname) {
1548                 ViceLog(0, ("Failed malloc in MapName_r\n"));
1549                 assert(0);
1550             }
1551             strcpy(tname, aname);
1552             tname[anamelen] = '@';
1553             strcpy(tname + anamelen + 1, acell);
1554             lnames.namelist_val = (prname *) tname;
1555         }
1556     }
1557
1558     H_UNLOCK;
1559     code = pr_NameToId(&lnames, &lids);
1560     H_LOCK;
1561     if (code == 0) {
1562         if (lids.idlist_val) {
1563             *aval = lids.idlist_val[0];
1564             if (*aval == AnonymousID) {
1565                 ViceLog(2,
1566                         ("MapName: NameToId on %s returns anonymousID\n",
1567                          lnames.namelist_val));
1568             }
1569             free(lids.idlist_val);      /* return parms are not malloced in stub if server proc aborts */
1570         } else {
1571             ViceLog(0,
1572                     ("MapName: NameToId on '%s' is unknown\n",
1573                      lnames.namelist_val));
1574             code = -1;
1575         }
1576     }
1577
1578     if (foreign) {
1579         free(lnames.namelist_val);      /* We allocated this above, so we must free it now. */
1580     }
1581     return code;
1582 }
1583
1584 /*MapName*/
1585
1586
1587 /* NOTE: this returns the client with a Write lock and a refCount */
1588 struct client *
1589 h_ID2Client(afs_int32 vid)
1590 {
1591     register struct client *client;
1592     register struct host *host;
1593
1594     H_LOCK;
1595     for (host = hostList; host; host = host->next) {
1596         if (host->hostFlags & HOSTDELETED)
1597             continue;
1598         for (client = host->FirstClient; client; client = client->next) {
1599             if (!client->deleted && client->ViceId == vid) {
1600                 client->refCount++;
1601                 H_UNLOCK;
1602                 ObtainWriteLock(&client->lock);
1603                 return client;
1604             }
1605         }
1606     }
1607
1608     H_UNLOCK;
1609     return NULL;
1610 }
1611
1612 /*
1613  * Called by the server main loop.  Returns a h_Held client, which must be
1614  * released later the main loop.  Allocates a client if the matching one
1615  * isn't around. The client is returned with its reference count incremented
1616  * by one. The caller must call h_ReleaseClient_r when finished with
1617  * the client.
1618  *
1619  * the client->host is returned held.  h_ReleaseClient_r does not release
1620  * the hold on client->host.
1621  */
1622 struct client *
1623 h_FindClient_r(struct rx_connection *tcon)
1624 {
1625     register struct client *client;
1626     register struct host *host;
1627     struct client *oldClient;
1628     afs_int32 viceid;
1629     afs_int32 expTime;
1630     afs_int32 code;
1631     int authClass;
1632 #if (64-MAXKTCNAMELEN)
1633     ticket name length != 64
1634 #endif
1635     char tname[64];
1636     char tinst[64];
1637     char uname[PR_MAXNAMELEN];
1638     char tcell[MAXKTCREALMLEN];
1639     int fail = 0;
1640     int created = 0;
1641
1642     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1643     if (client) {
1644         client->refCount++;
1645         h_Hold_r(client->host);
1646         if (!client->deleted && client->prfail != 2) {  
1647             /* Could add shared lock on client here */
1648             /* note that we don't have to lock entry in this path to
1649              * ensure CPS is initialized, since we don't call rx_SetSpecific
1650              * until initialization is done, and we only get here if
1651              * rx_GetSpecific located the client structure.
1652              */
1653             return client;
1654         }
1655         H_UNLOCK;
1656         ObtainWriteLock(&client->lock); /* released at end */
1657         H_LOCK;
1658     }
1659
1660     authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
1661     ViceLog(5,
1662             ("FindClient: authenticating connection: authClass=%d\n",
1663              authClass));
1664     if (authClass == 1) {
1665         /* A bcrypt tickets, no longer supported */
1666         ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
1667         viceid = AnonymousID;
1668         expTime = 0x7fffffff;
1669     } else if (authClass == 2) {
1670         afs_int32 kvno;
1671
1672         /* kerberos ticket */
1673         code = rxkad_GetServerInfo(tcon, /*level */ 0, &expTime,
1674                                    tname, tinst, tcell, &kvno);
1675         if (code) {
1676             ViceLog(1, ("Failed to get rxkad ticket info\n"));
1677             viceid = AnonymousID;
1678             expTime = 0x7fffffff;
1679         } else {
1680             int ilen = strlen(tinst);
1681             ViceLog(5,
1682                     ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
1683                      tname, tinst, tcell, expTime, kvno));
1684             strncpy(uname, tname, sizeof(uname));
1685             if (ilen) {
1686                 if (strlen(uname) + 1 + ilen >= sizeof(uname))
1687                     goto bad_name;
1688                 strcat(uname, ".");
1689                 strcat(uname, tinst);
1690             }
1691             /* translate the name to a vice id */
1692             code = MapName_r(uname, tcell, &viceid);
1693             if (code) {
1694               bad_name:
1695                 ViceLog(1,
1696                         ("failed to map name=%s, cell=%s -> code=%d\n", uname,
1697                          tcell, code));
1698                 fail = 1;
1699                 viceid = AnonymousID;
1700                 expTime = 0x7fffffff;
1701             }
1702         }
1703     } else {
1704         viceid = AnonymousID;   /* unknown security class */
1705         expTime = 0x7fffffff;
1706     }
1707
1708     if (!client) { /* loop */
1709         host = h_GetHost_r(tcon);       /* Returns it h_Held */
1710
1711     retryfirstclient:
1712         /* First try to find the client structure */
1713         for (client = host->FirstClient; client; client = client->next) {
1714             if (!client->deleted && (client->sid == rxr_CidOf(tcon))
1715                 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1716                 if (client->tcon && (client->tcon != tcon)) {
1717                     ViceLog(0,
1718                             ("*** Vid=%d, sid=%x, tcon=%x, Tcon=%x ***\n",
1719                              client->ViceId, client->sid, client->tcon,
1720                              tcon));
1721                     oldClient =
1722                         (struct client *)rx_GetSpecific(client->tcon,
1723                                                         rxcon_client_key);
1724                     if (oldClient) {
1725                         if (oldClient == client) {
1726                             rx_SetSpecific(client->tcon, rxcon_client_key,
1727                                            NULL);
1728                         } else
1729                             ViceLog(0,
1730                                     ("Client-conn mismatch: CL1=%x, CN=%x, CL2=%x\n",
1731                                      client, client->tcon, oldClient));
1732                     }
1733                     rx_PutConnection(client->tcon);
1734                     client->tcon = (struct rx_connection *)0;
1735                 }
1736                 client->refCount++;
1737                 H_UNLOCK;
1738                 ObtainWriteLock(&client->lock);
1739                 H_LOCK;
1740                 break;
1741             }
1742         }
1743
1744         /* Still no client structure - get one */
1745         if (!client) {
1746             h_Lock_r(host);
1747             /* Retry to find the client structure */
1748             for (client = host->FirstClient; client; client = client->next) {
1749                 if (!client->deleted && (client->sid == rxr_CidOf(tcon))
1750                     && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1751                     h_Unlock_r(host);
1752                     goto retryfirstclient;
1753                 }
1754             }
1755             created = 1;
1756             client = GetCE();
1757             ObtainWriteLock(&client->lock);
1758             client->refCount = 1;
1759             client->host = host;
1760 #if FS_STATS_DETAILED
1761             client->InSameNetwork = host->InSameNetwork;
1762 #endif /* FS_STATS_DETAILED */
1763             client->ViceId = viceid;
1764             client->expTime = expTime;  /* rx only */
1765             client->authClass = authClass;      /* rx only */
1766             client->sid = rxr_CidOf(tcon);
1767             client->VenusEpoch = rxr_GetEpoch(tcon);
1768             client->CPS.prlist_val = NULL;
1769             client->CPS.prlist_len = 0;
1770             h_Unlock_r(host);
1771         }
1772     }
1773     client->prfail = fail;
1774
1775     if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
1776         client->CPS.prlist_len = 0;
1777         if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID))
1778             free(client->CPS.prlist_val);
1779         client->CPS.prlist_val = NULL;
1780         client->ViceId = viceid;
1781         client->expTime = expTime;
1782
1783         if (viceid == ANONYMOUSID) {
1784             client->CPS.prlist_len = AnonCPS.prlist_len;
1785             client->CPS.prlist_val = AnonCPS.prlist_val;
1786         } else {
1787             H_UNLOCK;
1788             code = pr_GetCPS(viceid, &client->CPS);
1789             H_LOCK;
1790             if (code) {
1791                 char hoststr[16];
1792                 ViceLog(0,
1793                         ("pr_GetCPS failed(%d) for user %d, host %s:%d\n",
1794                          code, viceid, afs_inet_ntoa_r(client->host->host,
1795                                                        hoststr),
1796                          ntohs(client->host->port)));
1797
1798                 /* Although ubik_Call (called by pr_GetCPS) traverses thru
1799                  * all protection servers and reevaluates things if no
1800                  * sync server or quorum is found we could still end up
1801                  * with one of these errors. In such case we would like to
1802                  * reevaluate the rpc call to find if there's cps for this
1803                  * guy. We treat other errors (except network failures
1804                  * ones - i.e. code < 0) as an indication that there is no
1805                  * CPS for this host.  Ideally we could like to deal this
1806                  * problem the other way around (i.e.  if code == NOCPS
1807                  * ignore else retry next time) but the problem is that
1808                  * there're other errors (i.e.  EPERM) for which we don't
1809                  * want to retry and we don't know the whole code list!
1810                  */
1811                 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
1812                     client->prfail = 1;
1813             }
1814         }
1815         /* the disabling of system:administrators is so iffy and has so many
1816          * possible failure modes that we will disable it again */
1817         /* Turn off System:Administrator for safety  
1818          * if (AL_IsAMember(SystemId, client->CPS) == 0)
1819          * assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
1820     }
1821
1822     /* Now, tcon may already be set to a rock, since we blocked with no host
1823      * or client locks set above in pr_GetCPS (XXXX some locking is probably
1824      * required).  So, before setting the RPC's rock, we should disconnect
1825      * the RPC from the other client structure's rock.
1826      */
1827     oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1828     if (oldClient && oldClient->tcon == tcon) {
1829         char hoststr[16];
1830         if (!oldClient->deleted) {
1831             /* if we didn't create it, it's not ours to put back */
1832             if (created) {
1833                 ViceLog(0, ("FindClient: stillborn client %x(%x); conn %x (host %s:%d) had client %x(%x)\n", 
1834                             client, client->sid, tcon, 
1835                             afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
1836                             ntohs(rxr_PortOf(tcon)),
1837                             oldClient, oldClient->sid));
1838                 if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
1839                     free(client->CPS.prlist_val);
1840                 client->CPS.prlist_val = NULL;
1841                 client->CPS.prlist_len = 0;
1842                 if (client->tcon) {
1843                     rx_SetSpecific(client->tcon, rxcon_client_key, (void *)0);
1844                 }
1845             }
1846             /* We should perhaps check for 0 here */
1847             client->refCount--;
1848             ReleaseWriteLock(&client->lock);
1849             if (created) {
1850                 FreeCE(client);
1851                 created = 0;
1852             } 
1853             ObtainWriteLock(&oldClient->lock);
1854             oldClient->refCount++;
1855             client = oldClient;
1856         } else {
1857             rx_PutConnection(oldClient->tcon);
1858             oldClient->tcon = (struct rx_connection *)0;
1859             ViceLog(0, ("FindClient: deleted client %x(%x) already had conn %x (host %s:%d), stolen by client %x(%x)\n", 
1860                         oldClient, oldClient->sid, tcon, 
1861                         afs_inet_ntoa_r(rxr_HostOf(tcon), hoststr),
1862                         ntohs(rxr_PortOf(tcon)),
1863                         client, client->sid));
1864             /* rx_SetSpecific will be done immediately below */
1865         }
1866     }
1867     /* Avoid chaining in more than once. */
1868     if (created) {
1869         h_Lock_r(host);
1870         client->next = host->FirstClient;
1871         host->FirstClient = client;
1872         h_Unlock_r(host);
1873         CurrentConnections++;   /* increment number of connections */
1874     }
1875     rx_GetConnection(tcon);
1876     client->tcon = tcon;
1877     rx_SetSpecific(tcon, rxcon_client_key, client);
1878     ReleaseWriteLock(&client->lock);
1879
1880     return client;
1881
1882 }                               /*h_FindClient_r */
1883
1884 int
1885 h_ReleaseClient_r(struct client *client)
1886 {
1887     assert(client->refCount > 0);
1888     client->refCount--;
1889     return 0;
1890 }
1891
1892
1893 /*
1894  * Sigh:  this one is used to get the client AGAIN within the individual
1895  * server routines.  This does not bother h_Holding the host, since
1896  * this is assumed already have been done by the server main loop.
1897  * It does check tokens, since only the server routines can return the
1898  * VICETOKENDEAD error code
1899  */
1900 int
1901 GetClient(struct rx_connection *tcon, struct client **cp)
1902 {
1903     register struct client *client;
1904
1905     H_LOCK;
1906     *cp = NULL;
1907     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1908     if (client == NULL || client->tcon == NULL) {
1909         ViceLog(0,
1910                 ("GetClient: no client in conn %x (host %x:%d), VBUSYING\n",
1911                  tcon, rxr_HostOf(tcon),ntohs(rxr_PortOf(tcon))));
1912         H_UNLOCK;
1913         return VBUSY;
1914     }
1915     if (rxr_CidOf(client->tcon) != client->sid) {
1916         ViceLog(0,
1917                 ("GetClient: tcon %x tcon sid %d client sid %d\n",
1918                  client->tcon, rxr_CidOf(client->tcon), client->sid));
1919         H_UNLOCK;
1920         return VBUSY;
1921     }
1922     if (!(client && client->tcon && rxr_CidOf(client->tcon) == client->sid)) {
1923         if (!client)
1924             ViceLog(0, ("GetClient: no client in conn %x\n", tcon));
1925         else
1926             ViceLog(0,
1927                     ("GetClient: tcon %x tcon sid %d client sid %d\n",
1928                      client->tcon, client->tcon ? rxr_CidOf(client->tcon)
1929                      : -1, client->sid));
1930         assert(0);
1931     }
1932     if (client && client->LastCall > client->expTime && client->expTime) {
1933         char hoststr[16];
1934         ViceLog(1,
1935                 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
1936                  afs_inet_ntoa_r(client->host->host, hoststr),
1937                  ntohs(client->host->port), client->expTime));
1938         H_UNLOCK;
1939         return VICETOKENDEAD;
1940     }
1941
1942     client->refCount++;
1943     *cp = client;
1944     H_UNLOCK;
1945     return 0;
1946 }                               /*GetClient */
1947
1948 int
1949 PutClient(struct client **cp)
1950 {
1951     if (*cp == NULL) 
1952         return -1;
1953
1954     H_LOCK;
1955     h_ReleaseClient_r(*cp);
1956     *cp = NULL;
1957     H_UNLOCK;
1958     return 0;
1959 }                               /*PutClient */
1960
1961
1962 /* Client user name for short term use.  Note that this is NOT inexpensive */
1963 char *
1964 h_UserName(struct client *client)
1965 {
1966     static char User[PR_MAXNAMELEN + 1];
1967     namelist lnames;
1968     idlist lids;
1969
1970     lids.idlist_len = 1;
1971     lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
1972     if (!lids.idlist_val) {
1973         ViceLog(0, ("Failed malloc in h_UserName\n"));
1974         assert(0);
1975     }
1976     lnames.namelist_len = 0;
1977     lnames.namelist_val = (prname *) 0;
1978     lids.idlist_val[0] = client->ViceId;
1979     if (pr_IdToName(&lids, &lnames)) {
1980         /* We need to free id we alloced above! */
1981         free(lids.idlist_val);
1982         return "*UNKNOWN USER NAME*";
1983     }
1984     strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
1985     free(lids.idlist_val);
1986     free(lnames.namelist_val);
1987     return User;
1988
1989 }                               /*h_UserName */
1990
1991
1992 void
1993 h_PrintStats()
1994 {
1995     ViceLog(0,
1996             ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
1997              CEs, CEBlocks, HTs, HTBlocks));
1998
1999 }                               /*h_PrintStats */
2000
2001
2002 static int
2003 h_PrintClient(register struct host *host, int held, StreamHandle_t * file)
2004 {
2005     register struct client *client;
2006     int i;
2007     char tmpStr[256];
2008     char tbuffer[32];
2009     char hoststr[16];
2010
2011     H_LOCK;
2012     if (host->hostFlags & HOSTDELETED) {
2013         H_UNLOCK;
2014         return held;
2015     }
2016     (void)afs_snprintf(tmpStr, sizeof tmpStr,
2017                        "Host %s:%d down = %d, LastCall %s",
2018                        afs_inet_ntoa_r(host->host, hoststr),
2019                        ntohs(host->port), (host->hostFlags & VENUSDOWN),
2020                        afs_ctime((time_t *) & host->LastCall, tbuffer,
2021                                  sizeof(tbuffer)));
2022     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2023     for (client = host->FirstClient; client; client = client->next) {
2024         if (!client->deleted) {
2025             if (client->tcon) {
2026                 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2027                                    "    user id=%d,  name=%s, sl=%s till %s",
2028                                    client->ViceId, h_UserName(client),
2029                                    client->
2030                                    authClass ? "Authenticated" :
2031                                    "Not authenticated",
2032                                    client->
2033                                    authClass ? afs_ctime((time_t *) & client->
2034                                                          expTime, tbuffer,
2035                                                          sizeof(tbuffer))
2036                                    : "No Limit\n");
2037                 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2038             } else {
2039                 (void)afs_snprintf(tmpStr, sizeof tmpStr,
2040                                    "    user=%s, no current server connection\n",
2041                                    h_UserName(client));
2042                 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2043             }
2044             (void)afs_snprintf(tmpStr, sizeof tmpStr, "      CPS-%d is [",
2045                                client->CPS.prlist_len);
2046             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2047             if (client->CPS.prlist_val) {
2048                 for (i = 0; i > client->CPS.prlist_len; i++) {
2049                     (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2050                                        client->CPS.prlist_val[i]);
2051                     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2052                 }
2053             }
2054             sprintf(tmpStr, "]\n");
2055             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2056         }
2057     }
2058     H_UNLOCK;
2059     return held;
2060
2061 }                               /*h_PrintClient */
2062
2063
2064
2065 /*
2066  * Print a list of clients, with last security level and token value seen,
2067  * if known
2068  */
2069 void
2070 h_PrintClients()
2071 {
2072     time_t now;
2073     char tmpStr[256];
2074     char tbuffer[32];
2075
2076     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
2077
2078     if (file == NULL) {
2079         ViceLog(0,
2080                 ("Couldn't create client dump file %s\n",
2081                  AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2082         return;
2083     }
2084     now = FT_ApproxTime();
2085     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
2086                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2087     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2088     h_Enumerate(h_PrintClient, (char *)file);
2089     STREAM_REALLYCLOSE(file);
2090     ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
2091 }
2092
2093
2094
2095
2096 static int
2097 h_DumpHost(register struct host *host, int held, StreamHandle_t * file)
2098 {
2099     int i;
2100     char tmpStr[256];
2101     char hoststr[16];
2102
2103     H_LOCK;
2104     (void)afs_snprintf(tmpStr, sizeof tmpStr,
2105                        "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 [",
2106                        afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), host->index,
2107                        host->cblist, CheckLock(&host->lock), host->LastCall,
2108                        host->ActiveCall, (host->hostFlags & VENUSDOWN),
2109                        host->hostFlags & HOSTDELETED, host->Console,
2110                        host->hostFlags & CLIENTDELETED, host->hcpsfailed,
2111                        host->cpsCall);
2112     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2113     if (host->hcps.prlist_val)
2114         for (i = 0; i < host->hcps.prlist_len; i++) {
2115             (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
2116                                host->hcps.prlist_val[i]);
2117             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2118         }
2119     sprintf(tmpStr, "] [");
2120     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2121     if (host->interface)
2122         for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2123             char hoststr[16];
2124             sprintf(tmpStr, " %s:%d", 
2125                      afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
2126                      ntohs(host->interface->interface[i].port));
2127             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2128         }
2129     sprintf(tmpStr, "] holds: ");
2130     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2131
2132     for (i = 0; i < h_maxSlots; i++) {
2133         sprintf(tmpStr, "%04x", host->holds[i]);
2134         (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2135     }
2136     sprintf(tmpStr, " slot/bit: %d/%d\n", h_holdSlot(), h_holdbit());
2137     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2138
2139     H_UNLOCK;
2140     return held;
2141
2142 }                               /*h_DumpHost */
2143
2144
2145 void
2146 h_DumpHosts()
2147 {
2148     time_t now;
2149     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
2150     char tmpStr[256];
2151     char tbuffer[32];
2152
2153     if (file == NULL) {
2154         ViceLog(0,
2155                 ("Couldn't create host dump file %s\n",
2156                  AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2157         return;
2158     }
2159     now = FT_ApproxTime();
2160     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
2161                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
2162     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
2163     h_Enumerate(h_DumpHost, (char *)file);
2164     STREAM_REALLYCLOSE(file);
2165     ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
2166
2167 }                               /*h_DumpHosts */
2168
2169 #ifdef AFS_DEMAND_ATTACH_FS
2170 /*
2171  * demand attach fs
2172  * host state serialization
2173  */
2174 static int h_stateFillHeader(struct host_state_header * hdr);
2175 static int h_stateCheckHeader(struct host_state_header * hdr);
2176 static int h_stateAllocMap(struct fs_dump_state * state);
2177 static int h_stateSaveHost(register struct host * host, int held, struct fs_dump_state * state);
2178 static int h_stateRestoreHost(struct fs_dump_state * state);
2179 static int h_stateRestoreIndex(struct host * h, int held, struct fs_dump_state * state);
2180 static int h_stateVerifyHost(struct host * h, int held, struct fs_dump_state * state);
2181 static int h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port);
2182 static int h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h);
2183 static void h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out);
2184 static void h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out);
2185
2186
2187 /* this procedure saves all host state to disk for fast startup */
2188 int
2189 h_stateSave(struct fs_dump_state * state)
2190 {
2191     AssignInt64(state->eof_offset, &state->hdr->h_offset);
2192
2193     /* XXX debug */
2194     ViceLog(0, ("h_stateSave:  hostCount=%d\n", hostCount));
2195
2196     /* invalidate host state header */
2197     memset(state->h_hdr, 0, sizeof(struct host_state_header));
2198
2199     if (fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2200                             sizeof(struct host_state_header))) {
2201         state->bail = 1;
2202         goto done;
2203     }
2204
2205     fs_stateIncEOF(state, sizeof(struct host_state_header));
2206
2207     h_Enumerate_r(h_stateSaveHost, hostList, (char *)state);
2208     if (state->bail) {
2209         goto done;
2210     }
2211
2212     h_stateFillHeader(state->h_hdr);
2213
2214     /* write the real header to disk */
2215     state->bail = fs_stateWriteHeader(state, &state->hdr->h_offset, state->h_hdr,
2216                                       sizeof(struct host_state_header));
2217
2218  done:
2219     return state->bail;
2220 }
2221
2222 /* demand attach fs
2223  * host state serialization
2224  *
2225  * this procedure restores all host state from a disk for fast startup 
2226  */
2227 int
2228 h_stateRestore(struct fs_dump_state * state)
2229 {
2230     int i, records;
2231
2232     /* seek to the right position and read in the host state header */
2233     if (fs_stateReadHeader(state, &state->hdr->h_offset, state->h_hdr,
2234                            sizeof(struct host_state_header))) {
2235         state->bail = 1;
2236         goto done;
2237     }
2238
2239     /* check the validity of the header */
2240     if (h_stateCheckHeader(state->h_hdr)) {
2241         state->bail = 1;
2242         goto done;
2243     }
2244
2245     records = state->h_hdr->records;
2246
2247     if (h_stateAllocMap(state)) {
2248         state->bail = 1;
2249         goto done;
2250     }
2251
2252     /* iterate over records restoring host state */
2253     for (i=0; i < records; i++) {
2254         if (h_stateRestoreHost(state) != 0) {
2255             state->bail = 1;
2256             break;
2257         }
2258     }
2259
2260  done:
2261     return state->bail;
2262 }
2263
2264 int
2265 h_stateRestoreIndices(struct fs_dump_state * state)
2266 {
2267     h_Enumerate_r(h_stateRestoreIndex, hostList, (char *)state);
2268     return state->bail;
2269 }
2270
2271 static int
2272 h_stateRestoreIndex(struct host * h, int held, struct fs_dump_state * state)
2273 {
2274     if (cb_OldToNew(state, h->cblist, &h->cblist)) {
2275         return H_ENUMERATE_BAIL(held);
2276     }
2277     return held;
2278 }
2279
2280 int
2281 h_stateVerify(struct fs_dump_state * state)
2282 {
2283     h_Enumerate_r(h_stateVerifyHost, hostList, (char *)state);
2284     return state->bail;
2285 }
2286
2287 static int
2288 h_stateVerifyHost(struct host * h, int held, struct fs_dump_state * state)
2289 {
2290     int i;
2291
2292     if (h == NULL) {
2293         ViceLog(0, ("h_stateVerifyHost: error: NULL host pointer in linked list\n"));
2294         return H_ENUMERATE_BAIL(held);
2295     }
2296
2297     if (h->interface) {
2298         for (i = h->interface->numberOfInterfaces-1; i >= 0; i--) {
2299             if (h_stateVerifyAddrHash(state, h, h->interface->interface[i].addr, 
2300                                       h->interface->interface[i].port)) {
2301                 state->bail = 1;
2302             }
2303         }
2304         if (h_stateVerifyUuidHash(state, h)) {
2305             state->bail = 1;
2306         }
2307     } else if (h_stateVerifyAddrHash(state, h, h->host, h->port)) {
2308         state->bail = 1;
2309     }
2310
2311     if (cb_stateVerifyHCBList(state, h)) {
2312         state->bail = 1;
2313     }
2314
2315  done:
2316     return held;
2317 }
2318
2319 static int
2320 h_stateVerifyAddrHash(struct fs_dump_state * state, struct host * h, afs_uint32 addr, afs_uint16 port)
2321 {
2322     int ret = 0, found = 0;
2323     struct host *host = NULL;
2324     struct h_hashChain *chain;
2325     int index = h_HashIndex(addr);
2326     char tmp[16];
2327     int chain_len = 0;
2328
2329     for (chain = hostHashTable[index]; chain; chain = chain->next) {
2330         host = chain->hostPtr;
2331         if (host == NULL) {
2332             afs_inet_ntoa_r(addr, tmp);
2333             ViceLog(0, ("h_stateVerifyAddrHash: error: addr hash chain has NULL host ptr (lookup addr %s)\n", tmp));
2334             ret = 1;
2335             goto done;
2336         }
2337         if ((chain->addr == addr) && (chain->port == port)) {
2338             if (host != h) {
2339                 ViceLog(0, ("h_stateVerifyAddrHash: warning: addr hash entry points to different host struct (%d, %d)\n", 
2340                             h->index, host->index));
2341                 state->flags.warnings_generated = 1;
2342             }
2343             found = 1;
2344             break;
2345         }
2346         if (chain_len > FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN) {
2347             ViceLog(0, ("h_stateVerifyAddrHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2348                         FS_STATE_H_MAX_ADDR_HASH_CHAIN_LEN));
2349             ret = 1;
2350             goto done;
2351         }
2352         chain_len++;
2353     }
2354
2355     if (!found) {
2356         afs_inet_ntoa_r(addr, tmp);
2357         if (state->mode == FS_STATE_LOAD_MODE) {
2358             ViceLog(0, ("h_stateVerifyAddrHash: error: addr %s not found in hash\n", tmp));
2359             ret = 1;
2360             goto done;
2361         } else {
2362             ViceLog(0, ("h_stateVerifyAddrHash: warning: addr %s not found in hash\n", tmp));
2363             state->flags.warnings_generated = 1;
2364         }
2365     }
2366
2367  done:
2368     return ret;
2369 }
2370
2371 static int
2372 h_stateVerifyUuidHash(struct fs_dump_state * state, struct host * h)
2373 {
2374     int ret = 0, found = 0;
2375     struct host *host = NULL;
2376     struct h_hashChain *chain;
2377     afsUUID * uuidp = &h->interface->uuid;
2378     int index = h_UuidHashIndex(uuidp);
2379     char tmp[40];
2380     int chain_len = 0;
2381
2382     for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
2383         host = chain->hostPtr;
2384         if (host == NULL) {
2385             afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2386             ViceLog(0, ("h_stateVerifyUuidHash: error: uuid hash chain has NULL host ptr (lookup uuid %s)\n", tmp));
2387             ret = 1;
2388             goto done;
2389         }
2390         if (host->interface &&
2391             afs_uuid_equal(&host->interface->uuid, uuidp)) {
2392             if (host != h) {
2393                 ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid hash entry points to different host struct (%d, %d)\n", 
2394                             h->index, host->index));
2395                 state->flags.warnings_generated = 1;
2396             }
2397             found = 1;
2398             goto done;
2399         }
2400         if (chain_len > FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN) {
2401             ViceLog(0, ("h_stateVerifyUuidHash: error: hash chain length exceeds %d; assuming there's a loop\n",
2402                         FS_STATE_H_MAX_UUID_HASH_CHAIN_LEN));
2403             ret = 1;
2404             goto done;
2405         }
2406         chain_len++;
2407     }
2408
2409     if (!found) {
2410         afsUUID_to_string(uuidp, tmp, sizeof(tmp));
2411         if (state->mode == FS_STATE_LOAD_MODE) {
2412             ViceLog(0, ("h_stateVerifyUuidHash: error: uuid %s not found in hash\n", tmp));
2413             ret = 1;
2414             goto done;
2415         } else {
2416             ViceLog(0, ("h_stateVerifyUuidHash: warning: uuid %s not found in hash\n", tmp));
2417             state->flags.warnings_generated = 1;
2418         }
2419     }
2420
2421  done:
2422     return ret;
2423 }
2424
2425 /* create the host state header structure */
2426 static int
2427 h_stateFillHeader(struct host_state_header * hdr)
2428 {
2429     hdr->stamp.magic = HOST_STATE_MAGIC;
2430     hdr->stamp.version = HOST_STATE_VERSION;
2431 }
2432
2433 /* check the contents of the host state header structure */
2434 static int
2435 h_stateCheckHeader(struct host_state_header * hdr)
2436 {
2437     int ret=0;
2438
2439     if (hdr->stamp.magic != HOST_STATE_MAGIC) {
2440         ViceLog(0, ("check_host_state_header: invalid state header\n"));
2441         ret = 1;
2442     }
2443     else if (hdr->stamp.version != HOST_STATE_VERSION) {
2444         ViceLog(0, ("check_host_state_header: unknown version number\n"));
2445         ret = 1;
2446     }
2447     return ret;
2448 }
2449
2450 /* allocate the host id mapping table */
2451 static int
2452 h_stateAllocMap(struct fs_dump_state * state)
2453 {
2454     state->h_map.len = state->h_hdr->index_max + 1;
2455     state->h_map.entries = (struct idx_map_entry_t *)
2456         calloc(state->h_map.len, sizeof(struct idx_map_entry_t));
2457     return (state->h_map.entries != NULL) ? 0 : 1;
2458 }
2459
2460 /* function called by h_Enumerate to save a host to disk */
2461 static int
2462 h_stateSaveHost(register struct host * host, int held, struct fs_dump_state * state)
2463 {
2464     int i, if_len=0, hcps_len=0;
2465     struct hostDiskEntry hdsk;
2466     struct host_state_entry_header hdr;
2467     struct Interface * ifp = NULL;
2468     afs_int32 * hcps = NULL;
2469     struct iovec iov[4];
2470     int iovcnt = 2;
2471
2472     memset(&hdr, 0, sizeof(hdr));
2473
2474     if (state->h_hdr->index_max < host->index) {
2475         state->h_hdr->index_max = host->index;
2476     }
2477
2478     h_hostToDiskEntry_r(host, &hdsk);
2479     if (host->interface) {
2480         if_len = sizeof(struct Interface) + 
2481             ((host->interface->numberOfInterfaces-1) * sizeof(struct AddrPort));
2482         ifp = (struct Interface *) malloc(if_len);
2483         assert(ifp != NULL);
2484         memcpy(ifp, host->interface, if_len);
2485         hdr.interfaces = host->interface->numberOfInterfaces;
2486         iov[iovcnt].iov_base = (char *) ifp;
2487         iov[iovcnt].iov_len = if_len;
2488         iovcnt++;
2489     }
2490     if (host->hcps.prlist_val) {
2491         hdr.hcps = host->hcps.prlist_len;
2492         hcps_len = hdr.hcps * sizeof(afs_int32);
2493         hcps = (afs_int32 *) malloc(hcps_len);
2494         assert(hcps != NULL);
2495         memcpy(hcps, host->hcps.prlist_val, hcps_len);
2496         iov[iovcnt].iov_base = (char *) hcps;
2497         iov[iovcnt].iov_len = hcps_len;
2498         iovcnt++;
2499     }
2500
2501     if (hdsk.index > state->h_hdr->index_max)
2502         state->h_hdr->index_max = hdsk.index;
2503
2504     hdr.len = sizeof(struct host_state_entry_header) + 
2505         sizeof(struct hostDiskEntry) + if_len + hcps_len;
2506     hdr.magic = HOST_STATE_ENTRY_MAGIC;
2507
2508     iov[0].iov_base = (char *) &hdr;
2509     iov[0].iov_len = sizeof(hdr);
2510     iov[1].iov_base = (char *) &hdsk;
2511     iov[1].iov_len = sizeof(struct hostDiskEntry);
2512     
2513     if (fs_stateWriteV(state, iov, iovcnt)) {
2514         ViceLog(0, ("h_stateSaveHost: failed to save host %d", host->index));
2515         state->bail = 1;
2516     }
2517
2518     fs_stateIncEOF(state, hdr.len);
2519
2520     state->h_hdr->records++;
2521
2522  done:
2523     if (ifp)
2524         free(ifp);
2525     if (hcps)
2526         free(hcps);
2527     if (state->bail) {
2528         return H_ENUMERATE_BAIL(held);
2529     }
2530     return held;
2531 }
2532
2533 /* restores a host from disk */
2534 static int
2535 h_stateRestoreHost(struct fs_dump_state * state)
2536 {
2537     int ifp_len=0, hcps_len=0, bail=0;
2538     struct host_state_entry_header hdr;
2539     struct hostDiskEntry hdsk;
2540     struct host *host = NULL;
2541     struct Interface *ifp = NULL;
2542     afs_int32 * hcps = NULL;
2543     struct iovec iov[3];
2544     int iovcnt = 1;
2545
2546     if (fs_stateRead(state, &hdr, sizeof(hdr))) {
2547         ViceLog(0, ("h_stateRestoreHost: failed to read host entry header from dump file '%s'\n",
2548                     state->fn));
2549         bail = 1;
2550         goto done;
2551     }
2552
2553     if (hdr.magic != HOST_STATE_ENTRY_MAGIC) {
2554         ViceLog(0, ("h_stateRestoreHost: fileserver state dump file '%s' is corrupt.\n",
2555                     state->fn));
2556         bail = 1;
2557         goto done;
2558     }
2559
2560     iov[0].iov_base = (char *) &hdsk;
2561     iov[0].iov_len = sizeof(struct hostDiskEntry);
2562
2563     if (hdr.interfaces) {
2564         ifp_len = sizeof(struct Interface) +
2565             ((hdr.interfaces-1) * sizeof(struct AddrPort));
2566         ifp = (struct Interface *) malloc(ifp_len);
2567         assert(ifp != NULL);
2568         iov[iovcnt].iov_base = (char *) ifp;
2569         iov[iovcnt].iov_len = ifp_len;
2570         iovcnt++;
2571     }
2572     if (hdr.hcps) {
2573         hcps_len = hdr.hcps * sizeof(afs_int32);
2574         hcps = (afs_int32 *) malloc(hcps_len);
2575         assert(hcps != NULL);
2576         iov[iovcnt].iov_base = (char *) hcps;
2577         iov[iovcnt].iov_len = hcps_len;
2578         iovcnt++;
2579     }
2580
2581     if ((ifp_len + hcps_len + sizeof(hdsk) + sizeof(hdr)) != hdr.len) {
2582         ViceLog(0, ("h_stateRestoreHost: host entry header length fields are inconsistent\n"));
2583         bail = 1;
2584         goto done;
2585     }
2586
2587     if (fs_stateReadV(state, iov, iovcnt)) {
2588         ViceLog(0, ("h_stateRestoreHost: failed to read host entry\n"));
2589         bail = 1;
2590         goto done;
2591     }
2592
2593     if (!hdr.hcps && hdsk.hcps_valid) {
2594         /* valid, zero-length host cps ; does this ever happen? */
2595         hcps = (afs_int32 *) malloc(sizeof(afs_int32));
2596         assert(hcps != NULL);
2597     }
2598
2599     host = GetHT();
2600     assert(host != NULL);
2601
2602     if (ifp) {
2603         host->interface = ifp;
2604     }
2605     if (hcps) {
2606         host->hcps.prlist_val = hcps;
2607         host->hcps.prlist_len = hdr.hcps;
2608     }
2609
2610     h_diskEntryToHost_r(&hdsk, host);
2611     h_SetupCallbackConn_r(host);
2612
2613     if (ifp) {
2614         int i;
2615         for (i = ifp->numberOfInterfaces-1; i >= 0; i--) {
2616             h_AddHostToHashTable_r(ifp->interface[i].addr, 
2617                                    ifp->interface[i].port, host);
2618         }
2619         h_AddHostToUuidHashTable_r(&ifp->uuid, host);
2620     } else {
2621         h_AddHostToHashTable_r(host->host, host->port, host);
2622     }
2623     h_InsertList_r(host);
2624
2625     /* setup host id map entry */
2626     state->h_map.entries[hdsk.index].old_idx = hdsk.index;
2627     state->h_map.entries[hdsk.index].new_idx = host->index;
2628
2629  done:
2630     if (bail) {
2631         if (ifp)
2632             free(ifp);
2633         if (hcps)
2634             free(hcps);
2635     }
2636     return bail;
2637 }
2638
2639 /* serialize a host structure to disk */
2640 static void
2641 h_hostToDiskEntry_r(struct host * in, struct hostDiskEntry * out)
2642 {
2643     out->host = in->host;
2644     out->port = in->port;
2645     out->hostFlags = in->hostFlags;
2646     out->Console = in->Console;
2647     out->hcpsfailed = in->hcpsfailed;
2648     out->LastCall = in->LastCall;
2649     out->ActiveCall = in->ActiveCall;
2650     out->cpsCall = in->cpsCall;
2651     out->cblist = in->cblist;
2652 #ifdef FS_STATS_DETAILED
2653     out->InSameNetwork = in->InSameNetwork;
2654 #endif
2655
2656     /* special fields we save, but are not memcpy'd back on restore */
2657     out->index = in->index;
2658     out->hcps_len = in->hcps.prlist_len;
2659     out->hcps_valid = (in->hcps.prlist_val == NULL) ? 0 : 1;
2660 }
2661
2662 /* restore a host structure from disk */
2663 static void
2664 h_diskEntryToHost_r(struct hostDiskEntry * in, struct host * out)
2665 {
2666     out->host = in->host;
2667     out->port = in->port;
2668     out->hostFlags = in->hostFlags;
2669     out->Console = in->Console;
2670     out->hcpsfailed = in->hcpsfailed;
2671     out->LastCall = in->LastCall;
2672     out->ActiveCall = in->ActiveCall;
2673     out->cpsCall = in->cpsCall;
2674     out->cblist = in->cblist;
2675 #ifdef FS_STATS_DETAILED
2676     out->InSameNetwork = in->InSameNetwork;
2677 #endif
2678 }
2679
2680 /* index translation routines */
2681 int
2682 h_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
2683 {
2684     int ret = 0;
2685
2686     /* hosts use a zero-based index, so old==0 is valid */
2687
2688     if (old >= state->h_map.len) {
2689         ViceLog(0, ("h_OldToNew: index %d is out of range\n", old));
2690         ret = 1;
2691     } else if (state->h_map.entries[old].old_idx != old) { /* sanity check */
2692         ViceLog(0, ("h_OldToNew: index %d points to an invalid host record\n", old));
2693         ret = 1;
2694     } else {
2695         *new = state->h_map.entries[old].new_idx;
2696     }
2697
2698  done:
2699     return ret;
2700 }
2701 #endif /* AFS_DEMAND_ATTACH_FS */
2702
2703
2704 /*
2705  * This counts the number of workstations, the number of active workstations,
2706  * and the number of workstations declared "down" (i.e. not heard from
2707  * recently).  An active workstation has received a call since the cutoff
2708  * time argument passed.
2709  */
2710 void
2711 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
2712 {
2713     register struct host *host;
2714     register int num = 0, active = 0, del = 0;
2715
2716     H_LOCK;
2717     for (host = hostList; host; host = host->next) {
2718         if (!(host->hostFlags & HOSTDELETED)) {
2719             num++;
2720             if (host->ActiveCall > cutofftime)
2721                 active++;
2722             if (host->hostFlags & VENUSDOWN)
2723                 del++;
2724         }
2725     }
2726     H_UNLOCK;
2727     if (nump)
2728         *nump = num;
2729     if (activep)
2730         *activep = active;
2731     if (delp)
2732         *delp = del;
2733
2734 }                               /*h_GetWorkStats */
2735
2736
2737 /*------------------------------------------------------------------------
2738  * PRIVATE h_ClassifyAddress
2739  *
2740  * Description:
2741  *      Given a target IP address and a candidate IP address (both
2742  *      in host byte order), classify the candidate into one of three
2743  *      buckets in relation to the target by bumping the counters passed
2744  *      in as parameters.
2745  *
2746  * Arguments:
2747  *      a_targetAddr       : Target address.
2748  *      a_candAddr         : Candidate address.
2749  *      a_sameNetOrSubnetP : Ptr to counter to bump when the two
2750  *                           addresses are either in the same network
2751  *                           or the same subnet.
2752  *      a_diffSubnetP      : ...when the candidate is in a different
2753  *                           subnet.
2754  *      a_diffNetworkP     : ...when the candidate is in a different
2755  *                           network.
2756  *
2757  * Returns:
2758  *      Nothing.
2759  *
2760  * Environment:
2761  *      The target and candidate addresses are both in host byte
2762  *      order, NOT network byte order, when passed in.
2763  *
2764  * Side Effects:
2765  *      As advertised.
2766  *------------------------------------------------------------------------*/
2767
2768 static void
2769 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
2770                   afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
2771                   afs_int32 * a_diffNetworkP)
2772 {                               /*h_ClassifyAddress */
2773
2774     afs_uint32 targetNet;
2775     afs_uint32 targetSubnet;
2776     afs_uint32 candNet;
2777     afs_uint32 candSubnet;
2778
2779     /*
2780      * Put bad values into the subnet info to start with.
2781      */
2782     targetSubnet = (afs_uint32) 0;
2783     candSubnet = (afs_uint32) 0;
2784
2785     /*
2786      * Pull out the network and subnetwork numbers from the target
2787      * and candidate addresses.  We can short-circuit this whole
2788      * affair if the target and candidate addresses are not of the
2789      * same class.
2790      */
2791     if (IN_CLASSA(a_targetAddr)) {
2792         if (!(IN_CLASSA(a_candAddr))) {
2793             (*a_diffNetworkP)++;
2794             return;
2795         }
2796         targetNet = a_targetAddr & IN_CLASSA_NET;
2797         candNet = a_candAddr & IN_CLASSA_NET;
2798         if (IN_SUBNETA(a_targetAddr))
2799             targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
2800         if (IN_SUBNETA(a_candAddr))
2801             candSubnet = a_candAddr & IN_CLASSA_SUBNET;
2802     } else if (IN_CLASSB(a_targetAddr)) {
2803         if (!(IN_CLASSB(a_candAddr))) {
2804             (*a_diffNetworkP)++;
2805             return;
2806         }
2807         targetNet = a_targetAddr & IN_CLASSB_NET;
2808         candNet = a_candAddr & IN_CLASSB_NET;
2809         if (IN_SUBNETB(a_targetAddr))
2810             targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
2811         if (IN_SUBNETB(a_candAddr))
2812             candSubnet = a_candAddr & IN_CLASSB_SUBNET;
2813     } /*Class B target */
2814     else if (IN_CLASSC(a_targetAddr)) {
2815         if (!(IN_CLASSC(a_candAddr))) {
2816             (*a_diffNetworkP)++;
2817             return;
2818         }
2819         targetNet = a_targetAddr & IN_CLASSC_NET;
2820         candNet = a_candAddr & IN_CLASSC_NET;
2821
2822         /*
2823          * Note that class C addresses can't have subnets,
2824          * so we leave the defaults untouched.
2825          */
2826     } /*Class C target */
2827     else {
2828         targetNet = a_targetAddr;
2829         candNet = a_candAddr;
2830     }                           /*Class D address */
2831
2832     /*
2833      * Now, simply compare the extracted net and subnet values for
2834      * the two addresses (which at this point are known to be of the
2835      * same class)
2836      */
2837     if (targetNet == candNet) {
2838         if (targetSubnet == candSubnet)
2839             (*a_sameNetOrSubnetP)++;
2840         else
2841             (*a_diffSubnetP)++;
2842     } else
2843         (*a_diffNetworkP)++;
2844
2845 }                               /*h_ClassifyAddress */
2846
2847
2848 /*------------------------------------------------------------------------
2849  * EXPORTED h_GetHostNetStats
2850  *
2851  * Description:
2852  *      Iterate through the host table, and classify each (non-deleted)
2853  *      host entry into ``proximity'' categories (same net or subnet,
2854  *      different subnet, different network).
2855  *
2856  * Arguments:
2857  *      a_numHostsP        : Set to total number of (non-deleted) hosts.
2858  *      a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
2859  *      a_diffSubnetP      : Set to # hosts on diff subnet as server.
2860  *      a_diffNetworkP     : Set to # hosts on diff network as server.
2861  *
2862  * Returns:
2863  *      Nothing.
2864  *
2865  * Environment:
2866  *      We only count non-deleted hosts.  The storage pointed to by our
2867  *      parameters is zeroed upon entry.
2868  *
2869  * Side Effects:
2870  *      As advertised.
2871  *------------------------------------------------------------------------*/
2872
2873 void
2874 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
2875                   afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
2876 {                               /*h_GetHostNetStats */
2877
2878     register struct host *hostP;        /*Ptr to current host entry */
2879     register afs_uint32 currAddr_HBO;   /*Curr host addr, host byte order */
2880
2881     /*
2882      * Clear out the storage pointed to by our parameters.
2883      */
2884     *a_numHostsP = (afs_int32) 0;
2885     *a_sameNetOrSubnetP = (afs_int32) 0;
2886     *a_diffSubnetP = (afs_int32) 0;
2887     *a_diffNetworkP = (afs_int32) 0;
2888
2889     H_LOCK;
2890     for (hostP = hostList; hostP; hostP = hostP->next) {
2891         if (!(hostP->hostFlags & HOSTDELETED)) {
2892             /*
2893              * Bump the number of undeleted host entries found.
2894              * In classifying the current entry's address, make
2895              * sure to first convert to host byte order.
2896              */
2897             (*a_numHostsP)++;
2898             currAddr_HBO = (afs_uint32) ntohl(hostP->host);
2899             h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
2900                               a_sameNetOrSubnetP, a_diffSubnetP,
2901                               a_diffNetworkP);
2902         }                       /*Only look at non-deleted hosts */
2903     }                           /*For each host record hashed to this index */
2904     H_UNLOCK;
2905 }                               /*h_GetHostNetStats */
2906
2907 static afs_uint32 checktime;
2908 static afs_uint32 clientdeletetime;
2909 static struct AFSFid zerofid;
2910
2911
2912 /*
2913  * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
2914  * Since it can serialize them, and pile up, it should be a separate LWP
2915  * from other events.
2916  */
2917 static int
2918 CheckHost(register struct host *host, int held)
2919 {
2920     register struct client *client;
2921     struct rx_connection *cb_conn = NULL;
2922     int code;
2923
2924 #ifdef AFS_DEMAND_ATTACH_FS
2925     /* kill the checkhost lwp ASAP during shutdown */
2926     FS_STATE_RDLOCK;
2927     if (fs_state.mode == FS_MODE_SHUTDOWN) {
2928         FS_STATE_UNLOCK;
2929         return H_ENUMERATE_BAIL(held);
2930     }
2931     FS_STATE_UNLOCK;
2932 #endif
2933
2934     /* Host is held by h_Enumerate */
2935     H_LOCK;
2936     for (client = host->FirstClient; client; client = client->next) {
2937         if (client->refCount == 0 && client->LastCall < clientdeletetime) {
2938             client->deleted = 1;
2939             host->hostFlags |= CLIENTDELETED;
2940         }
2941     }
2942     if (host->LastCall < checktime) {
2943         h_Lock_r(host);
2944         if (!(host->hostFlags & HOSTDELETED)) {
2945             cb_conn = host->callback_rxcon;
2946             rx_GetConnection(cb_conn);
2947             if (host->LastCall < clientdeletetime) {
2948                 host->hostFlags |= HOSTDELETED;
2949                 if (!(host->hostFlags & VENUSDOWN)) {
2950                     host->hostFlags &= ~ALTADDR;        /* alternate address invalid */
2951                     if (host->interface) {
2952                         H_UNLOCK;
2953                         code =
2954                             RXAFSCB_InitCallBackState3(cb_conn,
2955                                                        &FS_HostUUID);
2956                         H_LOCK;
2957                     } else {
2958                         H_UNLOCK;
2959                         code =
2960                             RXAFSCB_InitCallBackState(cb_conn);
2961                         H_LOCK;
2962                     }
2963                     host->hostFlags |= ALTADDR; /* alternate addresses valid */
2964                     if (code) {
2965                         char hoststr[16];
2966                         (void)afs_inet_ntoa_r(host->host, hoststr);
2967                         ViceLog(0,
2968                                 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
2969                                  hoststr, ntohs(host->port)));
2970                         host->hostFlags |= VENUSDOWN;
2971                     }
2972                     /* Note:  it's safe to delete hosts even if they have call
2973                      * back state, because break delayed callbacks (called when a
2974                      * message is received from the workstation) will always send a 
2975                      * break all call backs to the workstation if there is no
2976                      *callback.
2977                      */
2978                 }
2979             } else {
2980                 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
2981                     if (host->interface) {
2982                         afsUUID uuid = host->interface->uuid;
2983                         H_UNLOCK;
2984                         code = RXAFSCB_ProbeUuid(cb_conn, &uuid);
2985                         H_LOCK;
2986                         if (code) {
2987                             if (MultiProbeAlternateAddress_r(host)) {
2988                                 char hoststr[16];
2989                                 (void)afs_inet_ntoa_r(host->host, hoststr);
2990                                 ViceLog(0,
2991                                         ("ProbeUuid failed for host %s:%d\n",
2992                                          hoststr, ntohs(host->port)));
2993                                 host->hostFlags |= VENUSDOWN;
2994                             }
2995                         }
2996                     } else {
2997                         H_UNLOCK;
2998                         code = RXAFSCB_Probe(cb_conn);
2999                         H_LOCK;
3000                         if (code) {
3001                             char hoststr[16];
3002                             (void)afs_inet_ntoa_r(host->host, hoststr);
3003                             ViceLog(0,
3004                                     ("Probe failed for host %s:%d\n", hoststr,
3005                                      ntohs(host->port)));
3006                             host->hostFlags |= VENUSDOWN;
3007                         }
3008                     }
3009                 }
3010             }
3011             H_UNLOCK;
3012             rx_PutConnection(cb_conn);
3013             cb_conn=NULL;
3014             H_LOCK;
3015         }
3016         h_Unlock_r(host);
3017     }
3018     H_UNLOCK;
3019     return held;
3020
3021 }                               /*CheckHost */
3022
3023
3024 /*
3025  * Set VenusDown for any hosts that have not had a call in 15 minutes and
3026  * don't respond to a probe.  Note that VenusDown can only be cleared if
3027  * a message is received from the host (see ServerLWP in file.c).
3028  * Delete hosts that have not had any calls in 1 hour, clients that
3029  * have not had any calls in 15 minutes.
3030  *
3031  * This routine is called roughly every 5 minutes.
3032  */
3033 void
3034 h_CheckHosts(void)
3035 {
3036     afs_uint32 now = FT_ApproxTime();
3037
3038     memset((char *)&zerofid, 0, sizeof(zerofid));
3039     /*
3040      * Send a probe to the workstation if it hasn't been heard from in
3041      * 15 minutes
3042      */
3043     checktime = now - 15 * 60;
3044     clientdeletetime = now - 120 * 60;  /* 2 hours ago */
3045     h_Enumerate(CheckHost, NULL);
3046
3047 }                               /*h_CheckHosts */
3048
3049 /*
3050  * This is called with host locked and held. At this point, the
3051  * hostHashTable should not have any entries for the alternate
3052  * interfaces. This function has to insert these entries in the
3053  * hostHashTable.
3054  *
3055  * The addresses in the interfaceAddr list are in host byte order.
3056  */
3057 int
3058 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
3059 {
3060     int i, j;
3061     int number, count;
3062     afs_uint32 myAddr;
3063     afs_uint16 myPort;
3064     int found;
3065     struct Interface *interface;
3066
3067     assert(host);
3068     assert(interf);
3069
3070     ViceLog(125,
3071             ("initInterfaceAddr : host %x numAddr %d\n", host->host,
3072              interf->numberOfInterfaces));
3073
3074     number = interf->numberOfInterfaces;
3075     myAddr = host->host;        /* current interface address */
3076     myPort = host->port;        /* current port */
3077
3078     /* validation checks */
3079     if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
3080         ViceLog(0,
3081                 ("Number of alternate addresses returned is %d\n", number));
3082         return -1;
3083     }
3084
3085     /*
3086      * Convert IP addresses to network byte order, and remove for
3087      * duplicate IP addresses from the interface list.
3088      */
3089     for (i = 0, count = 0, found = 0; i < number; i++) {
3090         interf->addr_in[i] = htonl(interf->addr_in[i]);
3091         for (j = 0; j < count; j++) {
3092             if (interf->addr_in[j] == interf->addr_in[i])
3093                 break;
3094         }
3095         if (j == count) {
3096             interf->addr_in[count] = interf->addr_in[i];
3097             if (interf->addr_in[count] == myAddr)
3098                 found = 1;
3099             count++;
3100         }
3101     }
3102
3103     /*
3104      * Allocate and initialize an interface structure for this host.
3105      */
3106     if (found) {
3107         interface = (struct Interface *)
3108             malloc(sizeof(struct Interface) +
3109                    (sizeof(struct AddrPort) * (count - 1)));
3110         if (!interface) {
3111             ViceLog(0, ("Failed malloc in initInterfaceAddr_r\n"));
3112             assert(0);
3113         }
3114         interface->numberOfInterfaces = count;
3115     } else {
3116         interface = (struct Interface *)
3117             malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * count));
3118         assert(interface);
3119         interface->numberOfInterfaces = count + 1;
3120         interface->interface[count].addr = myAddr;
3121         interface->interface[count].port = myPort;
3122     }
3123     interface->uuid = interf->uuid;
3124     for (i = 0; i < count; i++) {
3125         interface->interface[i].addr = interf->addr_in[i];
3126         /* We store the port as 7001 because the addresses reported by 
3127          * TellMeAboutYourself and WhoAreYou RPCs are only valid if they
3128          * are coming from fully connected hosts (no NAT/PATs)
3129          */
3130         interface->interface[i].port = htons(7001);
3131     }
3132
3133     assert(!host->interface);
3134     host->interface = interface;
3135
3136     for (i = 0; i < host->interface->numberOfInterfaces; i++) {
3137         char hoststr[16];
3138         ViceLog(125, ("--- alt address %s:%d\n", 
3139                        afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3140                        ntohs(host->interface->interface[i].port)));
3141     }
3142
3143     return 0;
3144 }
3145
3146 /* deleted a HashChain structure for this address and host */
3147 /* returns 1 on success */
3148 static int
3149 h_DeleteHostFromHashTableByAddr_r(afs_uint32 addr, afs_uint16 port, struct host *host)
3150 {
3151     int flag;
3152     register struct h_hashChain **hp, *th;
3153
3154     for (hp = &hostHashTable[h_HashIndex(addr)]; (th = *hp);) {
3155         assert(th->hostPtr);
3156         if (th->hostPtr == host && th->addr == addr && th->port == port) {
3157             *hp = th->next;
3158             free(th);
3159             flag = 1;
3160             break;
3161         } else {
3162             hp = &th->next;
3163         }
3164     }
3165     return flag;
3166 }
3167
3168
3169 /*
3170 ** prints out all alternate interface address for the host. The 'level'
3171 ** parameter indicates what level of debugging sets this output
3172 */
3173 void
3174 printInterfaceAddr(struct host *host, int level)
3175 {
3176     int i, number;
3177     char hoststr[16];
3178
3179     if (host->interface) {
3180         /* check alternate addresses */
3181         number = host->interface->numberOfInterfaces;
3182         assert(number > 0);
3183         for (i = 0; i < number; i++)
3184             ViceLog(level, ("%s:%d ", afs_inet_ntoa_r(host->interface->interface[i].addr, hoststr),
3185                              ntohs(host->interface->interface[i].port)));
3186     }
3187     ViceLog(level, ("\n"));
3188 }