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