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