ubik-call-sucks-20060703
[openafs.git] / src / viced / host.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  *
9  * Portions Copyright (c) 2006 Sine Nomine Associates
10  */
11
12 #include <afsconfig.h>
13 #include <afs/param.h>
14
15 RCSID
16     ("$Header$");
17
18 #include <stdio.h>
19 #include <errno.h>
20 #ifdef AFS_NT40_ENV
21 #include <fcntl.h>
22 #include <winsock2.h>
23 #else
24 #include <sys/file.h>
25 #include <netdb.h>
26 #include <netinet/in.h>
27 #endif
28
29 #ifdef HAVE_STRING_H
30 #include <string.h>
31 #else
32 #ifdef HAVE_STRINGS_H
33 #include <strings.h>
34 #endif
35 #endif
36
37 #include <afs/stds.h>
38 #include <rx/xdr.h>
39 #include <afs/assert.h>
40 #include <lwp.h>
41 #include <lock.h>
42 #include <afs/afsint.h>
43 #include <afs/rxgen_consts.h>
44 #include <afs/nfs.h>
45 #include <afs/errors.h>
46 #include <afs/ihandle.h>
47 #include <afs/vnode.h>
48 #include <afs/volume.h>
49 #ifdef AFS_ATHENA_STDENV
50 #include <krb.h>
51 #endif
52 #include <afs/acl.h>
53 #include <afs/ptclient.h>
54 #include <afs/ptuser.h>
55 #include <afs/prs_fs.h>
56 #include <afs/auth.h>
57 #include <afs/afsutil.h>
58 #include <rx/rx.h>
59 #include <afs/cellconfig.h>
60 #include <stdlib.h>
61 #include "viced_prototypes.h"
62 #include "viced.h"
63 #include "host.h"
64 #include "callback.h"
65 #ifdef AFS_DEMAND_ATTACH_FS
66 #include "../util/afsutil_prototypes.h"
67 #include "../tviced/serialize_state.h"
68 #endif /* AFS_DEMAND_ATTACH_FS */
69
70 #ifdef AFS_PTHREAD_ENV
71 pthread_mutex_t host_glock_mutex;
72 #endif /* AFS_PTHREAD_ENV */
73
74 extern int Console;
75 extern int CurrentConnections;
76 extern int SystemId;
77 extern int AnonymousID;
78 extern prlist AnonCPS;
79 extern int LogLevel;
80 extern struct afsconf_dir *confDir;     /* config dir object */
81 extern int lwps;                /* the max number of server threads */
82 extern afsUUID FS_HostUUID;
83
84 int CEs = 0;                    /* active clients */
85 int CEBlocks = 0;               /* number of blocks of CEs */
86 struct client *CEFree = 0;      /* first free client */
87 struct host *hostList = 0;      /* linked list of all hosts */
88 int hostCount = 0;              /* number of hosts in hostList */
89 int rxcon_ident_key;
90 int rxcon_client_key;
91
92 static struct rx_securityClass *sc = NULL;
93
94 static void h_SetupCallbackConn_r(struct host * host);
95 static void h_AddHostToHashTable_r(afs_uint32 addr, afs_uint16 port, struct host * host);
96 static void h_AddHostToUuidHashTable_r(afsUUID * uuid, struct host * host);
97 static int h_DeleteHostFromHashTableByAddr_r(afs_uint32 addr, afs_uint16 port, struct host *host);
98
99 #define CESPERBLOCK 73
100 struct CEBlock {                /* block of CESPERBLOCK file entries */
101     struct client entry[CESPERBLOCK];
102 };
103
104 static void h_TossStuff_r(register struct host *host);
105 static int hashDelete_r(afs_uint32 addr, afs_uint16 port, struct host *host);
106
107 /*
108  * Make sure the subnet macros have been defined.
109  */
110 #ifndef IN_SUBNETA
111 #define IN_SUBNETA(i)           ((((afs_int32)(i))&0x80800000)==0x00800000)
112 #endif
113
114 #ifndef IN_CLASSA_SUBNET
115 #define IN_CLASSA_SUBNET        0xffff0000
116 #endif
117
118 #ifndef IN_SUBNETB
119 #define IN_SUBNETB(i)           ((((afs_int32)(i))&0xc0008000)==0x80008000)
120 #endif
121
122 #ifndef IN_CLASSB_SUBNET
123 #define IN_CLASSB_SUBNET        0xffffff00
124 #endif
125
126
127 /* get a new block of CEs and chain it on CEFree */
128 static void
129 GetCEBlock()
130 {
131     register struct CEBlock *block;
132     register int i;
133
134     block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
135     if (!block) {
136         ViceLog(0, ("Failed malloc in GetCEBlock\n"));
137         ShutDownAndCore(PANIC);
138     }
139
140     for (i = 0; i < (CESPERBLOCK - 1); i++) {
141         Lock_Init(&block->entry[i].lock);
142         block->entry[i].next = &(block->entry[i + 1]);
143     }
144     block->entry[CESPERBLOCK - 1].next = 0;
145     Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
146     CEFree = (struct client *)block;
147     CEBlocks++;
148
149 }                               /*GetCEBlock */
150
151
152 /* get the next available CE */
153 static struct client *
154 GetCE()
155 {
156     register struct client *entry;
157
158     if (CEFree == 0)
159         GetCEBlock();
160     if (CEFree == 0) {
161         ViceLog(0, ("CEFree NULL in GetCE\n"));
162         ShutDownAndCore(PANIC);
163     }
164
165     entry = CEFree;
166     CEFree = entry->next;
167     CEs++;
168     memset((char *)entry, 0, CLIENT_TO_ZERO(entry));
169     return (entry);
170
171 }                               /*GetCE */
172
173
174 /* return an entry to the free list */
175 static void
176 FreeCE(register struct client *entry)
177 {
178     entry->VenusEpoch = 0;
179     entry->sid = 0;
180     entry->next = CEFree;
181     CEFree = entry;
182     CEs--;
183
184 }                               /*FreeCE */
185
186 /*
187  * The HTs and HTBlocks variables were formerly static, but they are
188  * now referenced elsewhere in the FileServer.
189  */
190 int HTs = 0;                    /* active file entries */
191 int HTBlocks = 0;               /* number of blocks of HTs */
192 static struct host *HTFree = 0; /* first free file entry */
193
194 /*
195  * Hash tables of host pointers. We need two tables, one
196  * to map IP addresses onto host pointers, and another
197  * to map host UUIDs onto host pointers.
198  */
199 static struct h_hashChain *hostHashTable[h_HASHENTRIES];
200 static struct h_hashChain *hostUuidHashTable[h_HASHENTRIES];
201 #define h_HashIndex(hostip) ((hostip) & (h_HASHENTRIES-1))
202 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
203
204 struct HTBlock {                /* block of HTSPERBLOCK file entries */
205     struct host entry[h_HTSPERBLOCK];
206 };
207
208
209 /* get a new block of HTs and chain it on HTFree */
210 static void
211 GetHTBlock()
212 {
213     register struct HTBlock *block;
214     register int i;
215     static int index = 0;
216
217     if (HTBlocks == h_MAXHOSTTABLES) {
218         ViceLog(0, ("h_MAXHOSTTABLES reached\n"));
219         ShutDownAndCore(PANIC);
220     }
221
222     block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
223     if (!block) {
224         ViceLog(0, ("Failed malloc in GetHTBlock\n"));
225         ShutDownAndCore(PANIC);
226     }
227 #ifdef AFS_PTHREAD_ENV
228     for (i = 0; i < (h_HTSPERBLOCK); i++)
229         assert(pthread_cond_init(&block->entry[i].cond, NULL) == 0);
230 #endif /* AFS_PTHREAD_ENV */
231     for (i = 0; i < (h_HTSPERBLOCK); i++)
232         Lock_Init(&block->entry[i].lock);
233     for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
234         block->entry[i].next = &(block->entry[i + 1]);
235     for (i = 0; i < (h_HTSPERBLOCK); i++)
236         block->entry[i].index = index++;
237     block->entry[h_HTSPERBLOCK - 1].next = 0;
238     HTFree = (struct host *)block;
239     hosttableptrs[HTBlocks++] = block->entry;
240
241 }                               /*GetHTBlock */
242
243
244 /* get the next available HT */
245 static struct host *
246 GetHT()
247 {
248     register struct host *entry;
249
250     if (HTFree == NULL)
251         GetHTBlock();
252     assert(HTFree != NULL);
253     entry = HTFree;
254     HTFree = entry->next;
255     HTs++;
256     memset((char *)entry, 0, HOST_TO_ZERO(entry));
257     return (entry);
258
259 }                               /*GetHT */
260
261
262 /* return an entry to the free list */
263 static void
264 FreeHT(register struct host *entry)
265 {
266     entry->next = HTFree;
267     HTFree = entry;
268     HTs--;
269
270 }                               /*FreeHT */
271
272 afs_int32
273 hpr_Initialize(struct ubik_client **uclient)
274 {
275     afs_int32 code;
276     struct rx_connection *serverconns[MAXSERVERS];
277     struct rx_securityClass *sc[3];
278     struct afsconf_dir *tdir;
279     char tconfDir[100] = "";
280     char tcell[64] = "";
281     struct ktc_token ttoken;
282     afs_int32 scIndex;
283     struct afsconf_cell info;
284     afs_int32 i;
285     char cellstr[64];
286
287     tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
288     if (!tdir) {
289         fprintf(stderr,
290                 "libprot: Could not open configuration directory: %s.\n",
291                 AFSDIR_SERVER_ETC_DIRPATH);
292       return -1;
293     }
294     
295     code = afsconf_GetLocalCell(tdir, cellstr, sizeof(cellstr));
296     if (code) {
297         fprintf(stderr,
298                 "libprot: Could not get local cell. [%d]\n", code);
299         return code;
300     }
301     
302     code = afsconf_GetCellInfo(tdir, cellstr, "afsprot", &info);
303     if (code) {
304         fprintf(stderr, "libprot: Could not locate cell %s in %s/%s\n",
305                 cellstr, confDir, AFSDIR_CELLSERVDB_FILE);
306         return code;
307     }
308     
309     afsconf_Close(tdir);
310     
311     code = rx_Init(0);
312     if (code) {
313         fprintf(stderr, "libprot:  Could not initialize rx.\n");
314         return code;
315     }
316     
317     scIndex = 2;
318     sc[0] = 0;
319     sc[1] = 0;
320     sc[2] = 0;
321     /* Most callers use secLevel==1, however, the fileserver uses secLevel==2
322      * to force use of the KeyFile.  secLevel == 0 implies -noauth was
323      * specified. */
324     if ((afsconf_GetLatestKey(tdir, 0, 0) == 0)) {
325         code = afsconf_ClientAuthSecure(tdir, &sc[2], &scIndex);
326         if (code)
327             fprintf(stderr,
328                     "libprot: clientauthsecure returns %d %s"
329                     " (so trying noauth)\n", code, error_message(code));
330         if (code)
331             scIndex = 0;        /* use noauth */
332         if (scIndex != 2)
333             /* if there was a problem, an unauthenticated conn is returned */
334             sc[scIndex] = sc[2];
335     } else {
336         struct ktc_principal sname;
337         strcpy(sname.cell, info.name);
338         sname.instance[0] = 0;
339         strcpy(sname.name, "afs");
340         code = ktc_GetToken(&sname, &ttoken, sizeof(ttoken), NULL);
341         if (code)
342             scIndex = 0;
343         else {
344             if (ttoken.kvno >= 0 && ttoken.kvno <= 256)
345                 /* this is a kerberos ticket, set scIndex accordingly */
346                 scIndex = 2;
347             else {
348                 fprintf(stderr,
349                         "libprot: funny kvno (%d) in ticket, proceeding\n",
350                         ttoken.kvno);
351                 scIndex = 2;
352             }
353             sc[2] =
354                 rxkad_NewClientSecurityObject(rxkad_clear, &ttoken.sessionKey,
355                                               ttoken.kvno, ttoken.ticketLen,
356                                               ttoken.ticket);
357         }
358     }
359     if ((scIndex == 0) && (sc[0] == 0))
360         sc[0] = rxnull_NewClientSecurityObject();
361     if ((scIndex == 0))
362         com_err("fileserver", code,
363                 "Could not get afs tokens, running unauthenticated.");
364     
365     memset(serverconns, 0, sizeof(serverconns));        /* terminate list!!! */
366     for (i = 0; i < info.numServers; i++) {
367         serverconns[i] =
368             rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
369                              info.hostAddr[i].sin_port, PRSRV, sc[scIndex],
370                              scIndex);
371     }
372
373     code = ubik_ClientInit(serverconns, uclient);
374     if (code) {
375         com_err("fileserver", code, "ubik client init failed.");
376     }
377
378     code = rxs_Release(sc[scIndex]);
379     return code;
380 }
381
382 int
383 hpr_End(struct ubik_client *uclient)
384 {
385     int code = 0;
386
387     if (uclient) {
388         code = ubik_ClientDestroy(uclient);
389     }
390     return code;
391 }
392
393 int
394 hpr_GetHostCPS(afs_int32 host, prlist *CPS)
395 {
396 #ifdef AFS_PTHREAD_ENV
397     register afs_int32 code;
398     afs_int32 over;
399     struct ubik_client *uclient = 
400         (struct ubik_client *)pthread_getspecific(viced_uclient_key);
401
402     if (!uclient) {
403         code = hpr_Initialize(&uclient);
404         assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
405     }
406
407     over = 0;
408     code = ubik_PR_GetHostCPS(uclient, 0, host, CPS, &over);
409     if (code != PRSUCCESS)
410         return code;
411     if (over) {
412       /* do something about this, probably make a new call */
413       /* don't forget there's a hard limit in the interface */
414         fprintf(stderr,
415                 "membership list for host id %d exceeds display limit\n",
416                 host);
417     }
418     return 0;
419 #else
420     return pr_GetHostCPS(host, CPS);
421 #endif
422 }
423
424 int
425 hpr_NameToId(namelist *names, idlist *ids)
426 {
427 #ifdef AFS_PTHREAD_ENV
428     register afs_int32 code;
429     register afs_int32 i;
430     struct ubik_client *uclient = 
431         (struct ubik_client *)pthread_getspecific(viced_uclient_key);
432
433     if (!uclient) {
434         code = hpr_Initialize(&uclient);
435         assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
436     }
437
438     for (i = 0; i < names->namelist_len; i++)
439         stolower(names->namelist_val[i]);
440     code = ubik_PR_NameToID(uclient, 0, names, ids);
441     return code;
442 #else
443     return pr_NameToId(names, ids);
444 #endif
445 }
446
447 int
448 hpr_IdToName(idlist *ids, namelist *names)
449 {
450 #ifdef AFS_PTHREAD_ENV
451     register afs_int32 code;
452     struct ubik_client *uclient = 
453         (struct ubik_client *)pthread_getspecific(viced_uclient_key);
454     
455     if (!uclient) {
456         code = hpr_Initialize(&uclient);
457         assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
458     }
459
460     code = ubik_PR_IDToName(uclient, 0, ids, names);
461     return code;
462 #else
463     return pr_IdToName(ids, names);
464 #endif
465 }
466
467 int
468 hpr_GetCPS(afs_int32 id, prlist *CPS)
469 {
470 #ifdef AFS_PTHREAD_ENV
471     register afs_int32 code;
472     afs_int32 over;
473     struct ubik_client *uclient = 
474         (struct ubik_client *)pthread_getspecific(viced_uclient_key);
475
476     if (!uclient) {
477         code = hpr_Initialize(&uclient);
478         assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
479     }
480
481     over = 0;
482     code = ubik_PR_GetCPS(uclient, 0, id, CPS, &over);
483     if (code != PRSUCCESS)
484         return code;
485     if (over) {
486       /* do something about this, probably make a new call */
487       /* don't forget there's a hard limit in the interface */
488         fprintf(stderr, "membership list for id %d exceeds display limit\n",
489                 id);
490     }
491     return 0;
492 #else
493     return pr_GetCPS(id, CPS);
494 #endif
495 }
496
497 static short consolePort = 0;
498
499 int
500 h_Release(register struct host *host)
501 {
502     H_LOCK;
503     h_Release_r(host);
504     H_UNLOCK;
505     return 0;
506 }
507
508 /**
509  * If this thread does not have a hold on this host AND
510  * if other threads also dont have any holds on this host AND
511  * If either the HOSTDELETED or CLIENTDELETED flags are set
512  * then toss the host
513  */
514 int
515 h_Release_r(register struct host *host)
516 {
517
518     if (!((host)->holds[h_holdSlot()] & ~h_holdbit())) {
519         if (!h_OtherHolds_r(host)) {
520             /* must avoid masking this until after h_OtherHolds_r runs
521              * but it should be run before h_TossStuff_r */
522             (host)->holds[h_holdSlot()] &= ~h_holdbit();
523             if ((host->hostFlags & HOSTDELETED)
524                 || (host->hostFlags & CLIENTDELETED)) {
525                 h_TossStuff_r(host);
526             }
527         } else
528             (host)->holds[h_holdSlot()] &= ~h_holdbit();
529     } else
530         (host)->holds[h_holdSlot()] &= ~h_holdbit();
531
532     return 0;
533 }
534
535 int
536 h_OtherHolds_r(register struct host *host)
537 {
538     register int i, bit, slot;
539     bit = h_holdbit();
540     slot = h_holdSlot();
541     for (i = 0; i < h_maxSlots; i++) {
542         if (host->holds[i] != ((i == slot) ? bit : 0)) {
543             return 1;
544         }
545     }
546     return 0;
547 }
548
549 int
550 h_Lock_r(register struct host *host)
551 {
552     H_UNLOCK;
553     h_Lock(host);
554     H_LOCK;
555     return 0;
556 }
557
558 /**
559   * Non-blocking lock
560   * returns 1 if already locked
561   * else returns locks and returns 0
562   */
563
564 int
565 h_NBLock_r(register struct host *host)
566 {
567     struct Lock *hostLock = &host->lock;
568     int locked = 0;
569
570     H_UNLOCK;
571     LOCK_LOCK(hostLock);
572     if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
573         hostLock->excl_locked = WRITE_LOCK;
574     else
575         locked = 1;
576
577     LOCK_UNLOCK(hostLock);
578     H_LOCK;
579     if (locked)
580         return 1;
581     else
582         return 0;
583 }
584
585
586 #if FS_STATS_DETAILED
587 /*------------------------------------------------------------------------
588  * PRIVATE h_AddrInSameNetwork
589  *
590  * Description:
591  *      Given a target IP address and a candidate IP address (both
592  *      in host byte order), return a non-zero value (1) if the
593  *      candidate address is in a different network from the target
594  *      address.
595  *
596  * Arguments:
597  *      a_targetAddr       : Target address.
598  *      a_candAddr         : Candidate address.
599  *
600  * Returns:
601  *      1 if the candidate address is in the same net as the target,
602  *      0 otherwise.
603  *
604  * Environment:
605  *      The target and candidate addresses are both in host byte
606  *      order, NOT network byte order, when passed in.  We return
607  *      our value as a character, since that's the type of field in
608  *      the host structure, where this info will be stored.
609  *
610  * Side Effects:
611  *      As advertised.
612  *------------------------------------------------------------------------*/
613
614 static char
615 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
616 {                               /*h_AddrInSameNetwork */
617
618     afs_uint32 targetNet;
619     afs_uint32 candNet;
620
621     /*
622      * Pull out the network and subnetwork numbers from the target
623      * and candidate addresses.  We can short-circuit this whole
624      * affair if the target and candidate addresses are not of the
625      * same class.
626      */
627     if (IN_CLASSA(a_targetAddr)) {
628         if (!(IN_CLASSA(a_candAddr))) {
629             return (0);
630         }
631         targetNet = a_targetAddr & IN_CLASSA_NET;
632         candNet = a_candAddr & IN_CLASSA_NET;
633     } else if (IN_CLASSB(a_targetAddr)) {
634         if (!(IN_CLASSB(a_candAddr))) {
635             return (0);
636         }
637         targetNet = a_targetAddr & IN_CLASSB_NET;
638         candNet = a_candAddr & IN_CLASSB_NET;
639     } /*Class B target */
640     else if (IN_CLASSC(a_targetAddr)) {
641         if (!(IN_CLASSC(a_candAddr))) {
642             return (0);
643         }
644         targetNet = a_targetAddr & IN_CLASSC_NET;
645         candNet = a_candAddr & IN_CLASSC_NET;
646     } /*Class C target */
647     else {
648         targetNet = a_targetAddr;
649         candNet = a_candAddr;
650     }                           /*Class D address */
651
652     /*
653      * Now, simply compare the extracted net values for the two addresses
654      * (which at this point are known to be of the same class)
655      */
656     if (targetNet == candNet)
657         return (1);
658     else
659         return (0);
660
661 }                               /*h_AddrInSameNetwork */
662 #endif /* FS_STATS_DETAILED */
663
664
665 /* Assumptions: called with held host */
666 void
667 h_gethostcps_r(register struct host *host, register afs_int32 now)
668 {
669     register int code;
670     int slept = 0;
671
672     /* wait if somebody else is already doing the getCPS call */
673     while (host->hostFlags & HCPS_INPROGRESS) {
674         slept = 1;              /* I did sleep */
675         host->hostFlags |= HCPS_WAITING;        /* I am sleeping now */
676 #ifdef AFS_PTHREAD_ENV
677         pthread_cond_wait(&host->cond, &host_glock_mutex);
678 #else /* AFS_PTHREAD_ENV */
679         if ((code = LWP_WaitProcess(&(host->hostFlags))) != LWP_SUCCESS)
680             ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
681 #endif /* AFS_PTHREAD_ENV */
682     }
683
684
685     host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
686     if (host->hcps.prlist_val)
687         free(host->hcps.prlist_val);    /* this is for hostaclRefresh */
688     host->hcps.prlist_val = NULL;
689     host->hcps.prlist_len = 0;
690     host->cpsCall = slept ? (FT_ApproxTime()) : (now);
691
692     H_UNLOCK;
693     code = hpr_GetHostCPS(ntohl(host->host), &host->hcps);
694     H_LOCK;
695     if (code) {
696         /*
697          * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
698          * and reevaluates things if no sync server or quorum is found we could still end up
699          * with one of these errors. In such case we would like to reevaluate the rpc call to
700          * find if there's cps for this guy. We treat other errors (except network failures
701          * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
702          * we could like to deal this problem the other way around (i.e. if code == NOCPS 
703          * ignore else retry next time) but the problem is that there're other errors (i.e.
704          * EPERM) for which we don't want to retry and we don't know the whole code list!
705          */
706         if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
707             /* 
708              * We would have preferred to use a while loop and try again since ops in protected
709              * acls for this host will fail now but they'll be reevaluated on any subsequent
710              * call. The attempt to wait for a quorum/sync site or network error won't work
711              * since this problems really should only occurs during a complete fileserver 
712              * restart. Since the fileserver will start before the ptservers (and thus before
713              * quorums are complete) clients will be utilizing all the fileserver's lwps!!
714              */
715             host->hcpsfailed = 1;
716             ViceLog(0,
717                     ("Warning:  GetHostCPS failed (%d) for %x; will retry\n",
718                      code, host->host));
719         } else {
720             host->hcpsfailed = 0;
721             ViceLog(1,
722                     ("gethost:  GetHostCPS failed (%d) for %x; ignored\n",
723                      code, host->host));
724         }
725         if (host->hcps.prlist_val)
726             free(host->hcps.prlist_val);
727         host->hcps.prlist_val = NULL;
728         host->hcps.prlist_len = 0;      /* Make sure it's zero */
729     } else
730         host->hcpsfailed = 0;
731
732     host->hostFlags &= ~HCPS_INPROGRESS;
733     /* signal all who are waiting */
734     if (host->hostFlags & HCPS_WAITING) {       /* somebody is waiting */
735         host->hostFlags &= ~HCPS_WAITING;
736 #ifdef AFS_PTHREAD_ENV
737         assert(pthread_cond_broadcast(&host->cond) == 0);
738 #else /* AFS_PTHREAD_ENV */
739         if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
740             ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
741 #endif /* AFS_PTHREAD_ENV */
742     }
743 }
744
745 /* args in net byte order */
746 void
747 h_flushhostcps(register afs_uint32 hostaddr, register afs_uint16 hport)
748 {
749     register struct host *host;
750     int held = 0;
751
752     H_LOCK;
753     host = h_Lookup_r(hostaddr, hport, &held);
754     if (host) {
755         host->hcpsfailed = 1;
756         if (!held)
757             h_Release_r(host);
758     }
759     H_UNLOCK;
760     return;
761 }
762
763
764 /*
765  * Allocate a host.  It will be identified by the peer (ip,port) info in the
766  * rx connection provided.  The host is returned held and locked
767  */
768 #define DEF_ROPCONS 2115
769
770 struct host *
771 h_Alloc_r(register struct rx_connection *r_con)
772 {
773     struct servent *serverentry;
774     struct host *host;
775     afs_int32 now;
776 #if FS_STATS_DETAILED
777     afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
778 #endif /* FS_STATS_DETAILED */
779
780     host = GetHT();
781
782     host->host = rxr_HostOf(r_con);
783     host->port = rxr_PortOf(r_con);
784
785     h_AddHostToHashTable_r(host->host, host->port, host);
786
787     if (consolePort == 0) {     /* find the portal number for console */
788 #if     defined(AFS_OSF_ENV)
789         serverentry = getservbyname("ropcons", "");
790 #else
791         serverentry = getservbyname("ropcons", 0);
792 #endif
793         if (serverentry)
794             consolePort = serverentry->s_port;
795         else
796             consolePort = htons(DEF_ROPCONS);   /* Use a default */
797     }
798     if (host->port == consolePort)
799         host->Console = 1;
800     /* Make a callback channel even for the console, on the off chance that it
801      * makes a request that causes a break call back.  It shouldn't. */
802     h_SetupCallbackConn_r(host);
803     now = host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
804     host->hostFlags = 0;
805     host->hcps.prlist_val = NULL;
806     host->hcps.prlist_len = 0;
807     host->interface = NULL;
808 #ifdef undef
809     host->hcpsfailed = 0;       /* save cycles */
810     h_gethostcps(host);         /* do this under host hold/lock */
811 #endif
812     host->FirstClient = NULL;
813     h_Hold_r(host);
814     h_Lock_r(host);
815     h_InsertList_r(host);       /* update global host List */
816 #if FS_STATS_DETAILED
817     /*
818      * Compare the new host's IP address (in host byte order) with ours
819      * (the File Server's), remembering if they are in the same network.
820      */
821     newHostAddr_HBO = (afs_uint32) ntohl(host->host);
822     host->InSameNetwork =
823         h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
824 #endif /* FS_STATS_DETAILED */
825     return host;
826
827 }                               /*h_Alloc_r */
828
829
830
831 /* Make a callback channel even for the console, on the off chance that it
832  * makes a request that causes a break call back.  It shouldn't. */
833 static void
834 h_SetupCallbackConn_r(struct host * host)
835 {
836     if (!sc)
837         sc = rxnull_NewClientSecurityObject();
838     host->callback_rxcon =
839         rx_NewConnection(host->host, host->port, 1, sc, 0);
840     rx_SetConnDeadTime(host->callback_rxcon, 50);
841     rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
842 }
843
844 /* Lookup a host given an IP address and UDP port number. */
845 /* hostaddr and hport are in network order */
846 /* Note: host should be released by caller if 0 == *heldp and non-null */
847 /* hostaddr and hport are in network order */
848 struct host *
849 h_Lookup_r(afs_uint32 haddr, afs_uint16 hport, int *heldp)
850 {
851     afs_int32 now;
852     struct host *host = 0;
853     struct h_hashChain *chain;
854     int index = h_HashIndex(haddr);
855     extern int hostaclRefresh;
856
857   restart:
858     for (chain = hostHashTable[index]; chain; chain = chain->next) {
859         host = chain->hostPtr;
860         assert(host);
861         if (!(host->hostFlags & HOSTDELETED) && chain->addr == haddr
862             && chain->port == hport) {
863             *heldp = h_Held_r(host);
864             if (!*heldp)
865                 h_Hold_r(host);
866             h_Lock_r(host);
867             if (host->hostFlags & HOSTDELETED) {
868                 h_Unlock_r(host);
869                 if (!*heldp)
870                     h_Release_r(host);
871                 goto restart;
872             }
873             h_Unlock_r(host);
874             now = FT_ApproxTime();      /* always evaluate "now" */
875             if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
876                 /*
877                  * Every hostaclRefresh period (def 2 hrs) get the new
878                  * membership list for the host.  Note this could be the
879                  * first time that the host is added to a group.  Also
880                  * here we also retry on previous legitimate hcps failures.
881                  *
882                  * If we get here we still have a host hold.
883                  */
884                 h_gethostcps_r(host, now);
885             }
886             break;
887         }
888         host = NULL;
889     }
890     return host;
891
892 }                               /*h_Lookup */
893
894 /* Lookup a host given its UUID. */
895 struct host *
896 h_LookupUuid_r(afsUUID * uuidp)
897 {
898     struct host *host = 0;
899     struct h_hashChain *chain;
900     int index = h_UuidHashIndex(uuidp);
901
902     for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
903         host = chain->hostPtr;
904         assert(host);
905         if (!(host->hostFlags & HOSTDELETED) && host->interface
906             && afs_uuid_equal(&host->interface->uuid, uuidp)) {
907             break;
908         }
909         host = NULL;
910     }
911     return host;
912
913 }                               /*h_Lookup */
914
915
916 /*
917  * h_Hold_r: Establish a hold by the current LWP on this host--the host
918  * or its clients will not be physically deleted until all holds have
919  * been released.
920  * NOTE: h_Hold_r is a macro defined in host.h.
921  */
922
923 /* h_TossStuff_r:  Toss anything in the host structure (the host or
924  * clients marked for deletion.  Called from h_Release_r ONLY.
925  * To be called, there must be no holds, and either host->deleted
926  * or host->clientDeleted must be set.
927  */
928 static void
929 h_TossStuff_r(register struct host *host)
930 {
931     register struct client **cp, *client;
932     int i;
933
934     /* if somebody still has this host held */
935     for (i = 0; (i < h_maxSlots) && (!(host)->holds[i]); i++);
936     if (i != h_maxSlots)
937         return;
938
939     /* if somebody still has this host locked */
940     if (h_NBLock_r(host) != 0) {
941         char hoststr[16];
942         ViceLog(0,
943                 ("Warning:  h_TossStuff_r failed; Host %s:%d was locked.\n",
944                  afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
945         return;
946     } else {
947         h_Unlock_r(host);
948     }
949
950     /* ASSUMPTION: rxi_FreeConnection() does not yield */
951     for (cp = &host->FirstClient; (client = *cp);) {
952         if ((host->hostFlags & HOSTDELETED) || client->deleted) {
953             int code;
954             ObtainWriteLockNoBlock(&client->lock, code);
955             if (code < 0) {
956                 char hoststr[16];
957                 ViceLog(0,
958                         ("Warning: h_TossStuff_r failed: Host %s:%d client %x was locked.\n",
959                          afs_inet_ntoa_r(host->host, hoststr),
960                          ntohs(host->port), client));
961                 return;
962             }
963                  
964             if (client->refCount) {
965                 char hoststr[16];
966                 ViceLog(0,
967                         ("Warning: h_TossStuff_r failed: Host %s:%d client %x refcount %d.\n",
968                          afs_inet_ntoa_r(host->host, hoststr),
969                          ntohs(host->port), client, client->refCount));
970                 /* This is the same thing we do if the host is locked */
971                 ReleaseWriteLock(&client->lock);
972                 return;
973             }
974             client->CPS.prlist_len = 0;
975             if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val)
976                 free(client->CPS.prlist_val);
977             client->CPS.prlist_val = NULL;
978             CurrentConnections--;
979             *cp = client->next;
980             ReleaseWriteLock(&client->lock);
981             FreeCE(client);
982         } else
983             cp = &client->next;
984     }
985
986     /* We've just cleaned out all the deleted clients; clear the flag */
987     host->hostFlags &= ~CLIENTDELETED;
988
989     if (host->hostFlags & HOSTDELETED) {
990         register struct h_hashChain **hp, *th;
991         register struct rx_connection *rxconn;
992         afsUUID *uuidp;
993         struct AddrPort hostAddrPort;
994         int i;
995
996         if (host->Console & 1)
997             Console--;
998         if ((rxconn = host->callback_rxcon)) {
999             host->callback_rxcon = (struct rx_connection *)0;
1000             rx_DestroyConnection(rxconn);
1001         }
1002         if (host->hcps.prlist_val)
1003             free(host->hcps.prlist_val);
1004         host->hcps.prlist_val = NULL;
1005         host->hcps.prlist_len = 0;
1006         DeleteAllCallBacks_r(host, 1);
1007         host->hostFlags &= ~RESETDONE;  /* just to be safe */
1008
1009         /* if alternate addresses do not exist */
1010         if (!(host->interface)) {
1011             for (hp = &hostHashTable[h_HashIndex(host->host)]; (th = *hp);
1012                  hp = &th->next) {
1013                 assert(th->hostPtr);
1014                 if (th->hostPtr == host) {
1015                     *hp = th->next;
1016                     h_DeleteList_r(host);
1017                     FreeHT(host);
1018                     free(th);
1019                     break;
1020                 }
1021             }
1022         } else {
1023             /* delete all hash entries for the UUID */
1024             uuidp = &host->interface->uuid;
1025             for (hp = &hostUuidHashTable[h_UuidHashIndex(uuidp)]; (th = *hp);
1026                  hp = &th->next) {
1027                 assert(th->hostPtr);
1028                 if (th->hostPtr == host) {
1029                     *hp = th->next;
1030                     free(th);
1031                     break;
1032                 }
1033             }
1034             /* delete all hash entries for alternate addresses */
1035             assert(host->interface->numberOfInterfaces > 0);
1036             for (i = 0; i < host->interface->numberOfInterfaces; i++) {
1037                 hostAddrPort = host->interface->interface[i];
1038
1039                 for (hp = &hostHashTable[h_HashIndex(hostAddrPort.addr)]; (th = *hp);
1040                      hp = &th->next) {
1041                     assert(th->hostPtr);
1042                     if (th->hostPtr == host) {
1043                         *hp = th->next;
1044                         free(th);
1045                         break;
1046                     }
1047                 }
1048             }
1049             free(host->interface);
1050             host->interface = NULL;
1051             h_DeleteList_r(host);       /* remove host from global host List */
1052             FreeHT(host);
1053         }                       /* if alternate address exists */
1054     }
1055 }                               /*h_TossStuff_r */
1056
1057
1058 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
1059  * system at the start of the enumeration (perhaps more).  Hosts may be deleted
1060  * (have delete flag set); ditto for clients.  (*proc) is always called with
1061  * host h_held().  The hold state of the host with respect to this lwp is passed
1062  * to (*proc) as the param held.  The proc should return 0 if the host should be
1063  * released, 1 if it should be held after enumeration.
1064  */
1065 void
1066 h_Enumerate(int (*proc) (), char *param)
1067 {
1068     register struct host *host, **list;
1069     register int *held;
1070     register int i, count;
1071
1072     H_LOCK;
1073     if (hostCount == 0) {
1074         H_UNLOCK;
1075         return;
1076     }
1077     list = (struct host **)malloc(hostCount * sizeof(struct host *));
1078     if (!list) {
1079         ViceLog(0, ("Failed malloc in h_Enumerate\n"));
1080         assert(0);
1081     }
1082     held = (int *)malloc(hostCount * sizeof(int));
1083     if (!held) {
1084         ViceLog(0, ("Failed malloc in h_Enumerate\n"));
1085         assert(0);
1086     }
1087     for (count = 0, host = hostList; host; host = host->next, count++) {
1088         list[count] = host;
1089         if (!(held[count] = h_Held_r(host)))
1090             h_Hold_r(host);
1091     }
1092     assert(count == hostCount);
1093     H_UNLOCK;
1094     for (i = 0; i < count; i++) {
1095         held[i] = (*proc) (list[i], held[i], param);
1096         if (!H_ENUMERATE_ISSET_HELD(held[i]))
1097             h_Release(list[i]); /* this might free up the host */
1098         /* bail out of the enumeration early */
1099         if (H_ENUMERATE_ISSET_BAIL(held[i]))
1100             break;
1101     }
1102     free((void *)list);
1103     free((void *)held);
1104 }                               /*h_Enumerate */
1105
1106 /* h_Enumerate_r (revised):
1107  * Calls (*proc)(host, held, param) for each host in hostList, starting
1108  * at enumstart
1109  * Hosts may be deleted (have delete flag set); ditto for clients.
1110  * (*proc) is always called with
1111  * host h_held() and the global host lock (H_LOCK) locked.The hold state of the
1112  * host with respect to this lwp is passed to (*proc) as the param held.
1113  * The proc should return 0 if the host should be released, 1 if it should
1114  * be held after enumeration.
1115  */
1116 void
1117 h_Enumerate_r(int (*proc) (), struct host *enumstart, char *param)
1118 {
1119     register struct host *host, *next;
1120     register int held, nheld;
1121
1122     if (hostCount == 0) {
1123         return;
1124     }
1125     if (enumstart && !(held = h_Held_r(enumstart)))
1126         h_Hold_r(enumstart); 
1127     for (host = enumstart; host; host = next, held = nheld) {
1128         next = host->next;
1129         if (next && !(nheld = h_Held_r(next)) && !H_ENUMERATE_ISSET_BAIL(held))
1130             h_Hold_r(next);
1131         held = (*proc) (host, held, param);
1132         if (!H_ENUMERATE_ISSET_HELD(held))
1133             h_Release_r(host); /* this might free up the host */
1134         if (H_ENUMERATE_ISSET_BAIL(held))
1135             break;
1136     }
1137 }                               /*h_Enumerate_r */
1138
1139 /* inserts a new HashChain structure corresponding to this UUID */
1140 static void
1141 h_AddHostToUuidHashTable_r(struct afsUUID *uuid, struct host *host)
1142 {
1143     int index;
1144     struct h_hashChain *chain;
1145
1146     /* hash into proper bucket */
1147     index = h_UuidHashIndex(uuid);
1148
1149     /* insert into beginning of list for this bucket */
1150     chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
1151     if (!chain) {
1152         ViceLog(0, ("Failed malloc in h_AddHostToUuidHashTable_r\n"));
1153         assert(0);
1154     }
1155     assert(chain);
1156     chain->hostPtr = host;
1157     chain->next = hostUuidHashTable[index];
1158     hostUuidHashTable[index] = chain;
1159 }
1160
1161
1162 /* inserts a new HashChain structure corresponding to this address */
1163 static void
1164 h_AddHostToHashTable_r(afs_uint32 addr, afs_uint16 port, struct host *host)
1165 {
1166     int index;
1167     struct h_hashChain *chain;
1168
1169     /* hash into proper bucket */
1170     index = h_HashIndex(addr);
1171
1172     /* don't add the same entry multiple times */
1173     for (chain = hostHashTable[index]; chain; chain = chain->next) {
1174         if (chain->hostPtr == host && chain->addr == addr && chain->port == port)
1175             return;
1176     }
1177
1178     /* insert into beginning of list for this bucket */
1179     chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
1180     if (!chain) {
1181         ViceLog(0, ("Failed malloc in h_AddHostToHashTable_r\n"));
1182         assert(0);
1183     }
1184     chain->hostPtr = host;
1185     chain->next = hostHashTable[index];
1186     chain->addr = addr;
1187     chain->port = port;
1188     hostHashTable[index] = chain;
1189 }
1190
1191 /*
1192  * This is called with host locked and held. At this point, the
1193  * hostHashTable should not be having entries for the alternate
1194  * interfaces. This function has to insert these entries in the
1195  * hostHashTable.
1196  *
1197  * All addresses are in network byte order.
1198  */
1199 int
1200 addInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1201 {
1202     int i;
1203     int number;
1204     int found;
1205     struct Interface *interface;
1206     char hoststr[16], hoststr2[16];
1207
1208     assert(host);
1209     assert(host->interface);
1210
1211     ViceLog(125, ("addInterfaceAddr : host %s:%d addr %s:%d\n", 
1212                    afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), 
1213                    afs_inet_ntoa_r(addr, hoststr2), ntohs(port)));
1214
1215     /*
1216      * Make sure this address is on the list of known addresses
1217      * for this host.
1218      */
1219     number = host->interface->numberOfInterfaces;
1220     for (i = 0, found = 0; i < number && !found; i++) {
1221         if (host->interface->interface[i].addr == addr &&
1222             host->interface->interface[i].port == port)
1223             found = 1;
1224     }
1225     if (!found) {
1226         interface = (struct Interface *)
1227             malloc(sizeof(struct Interface) + (sizeof(struct AddrPort) * number));
1228         if (!interface) {
1229             ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
1230             assert(0);
1231         }
1232         interface->numberOfInterfaces = number + 1;
1233         interface->uuid = host->interface->uuid;
1234         for (i = 0; i < number; i++)
1235             interface->interface[i] = host->interface->interface[i];
1236         interface->interface[number].addr = addr;
1237         interface->interface[number].port = port;
1238         free(host->interface);
1239         host->interface = interface;
1240     }
1241
1242     /*
1243      * Create a hash table entry for this address
1244      */
1245     h_AddHostToHashTable_r(addr, port, host);
1246
1247     return 0;
1248 }
1249
1250
1251 /*
1252  * This is called with host locked and held. At this point, the
1253  * hostHashTable should not be having entries for the alternate
1254  * interfaces. This function has to insert these entries in the
1255  * hostHashTable.
1256  *
1257  * All addresses are in network byte order.
1258  */
1259 int
1260 removeInterfaceAddr_r(struct host *host, afs_uint32 addr, afs_uint16 port)
1261 {
1262     int i;
1263     int number;
1264     int found;
1265     struct Interface *interface;
1266     char hoststr[16], hoststr2[16];
1267
1268     assert(host);
1269     assert(host->interface);
1270
1271     ViceLog(125, ("removeInterfaceAddr : host %s:%d addr %s:%d\n", 
1272                    afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port), 
1273                    afs_inet_ntoa_r(addr, hoststr2), ntohs(port)));
1274
1275     /*
1276      * Make sure this address is on the list of known addresses
1277      * for this host.
1278      */
1279     interface = host->interface;
1280     number = host->interface->numberOfInterfaces;
1281     for (i = 0, found = 0; i < number; i++) {
1282         if (interface->interface[i].addr == addr &&
1283             interface->interface[i].port == port) {
1284             found = 1;
1285             break;
1286         }
1287     }
1288     if (found) {
1289         number--;
1290         for (; i < number; i++) {
1291             interface->interface[i].addr = interface->interface[i+1].addr;
1292             interface->interface[i].port = interface->interface[i+1].port;
1293         }
1294         interface->numberOfInterfaces = number;
1295     }
1296
1297     /*
1298      * Remove the hash table entry for this address
1299      */
1300     h_DeleteHostFromHashTableByAddr_r(addr, port, host);
1301
1302     return 0;
1303 }
1304
1305
1306 /* Host is returned held */
1307 struct host *
1308 h_GetHost_r(struct rx_connection *tcon)
1309 {
1310     struct host *host;
1311     struct host *oldHost;
1312     int code;
1313     int held, oheld;
1314     struct interfaceAddr interf;
1315     int interfValid = 0;
1316     struct Identity *identP = NULL;
1317     afs_uint32 haddr;
1318     afs_uint16 hport;
1319     char hoststr[16], hoststr2[16];
1320     Capabilities caps;
1321     struct rx_connection *cb_conn = NULL;
1322
1323     caps.Capabilities_val = NULL;
1324
1325     haddr = rxr_HostOf(tcon);
1326     hport = rxr_PortOf(tcon);
1327   retry:
1328     if (caps.Capabilities_val)
1329         free(caps.Capabilities_val);
1330     caps.Capabilities_val = NULL;
1331     caps.Capabilities_len = 0;
1332
1333     code = 0;
1334     host = h_Lookup_r(haddr, hport, &held);
1335     identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
1336     if (host && !identP && !(host->Console & 1)) {
1337         /* This is a new connection, and we already have a host
1338          * structure for this address. Verify that the identity
1339          * of the caller matches the identity in the host structure.
1340          */
1341         h_Lock_r(host);
1342         if (!(host->hostFlags & ALTADDR)) {
1343             /* Another thread is doing initialization */
1344             h_Unlock_r(host);
1345             if (!held)
1346                 h_Release_r(host);
1347             ViceLog(125,
1348                     ("Host %s:%d starting h_Lookup again\n",
1349                      afs_inet_ntoa_r(host->host, hoststr),
1350                      ntohs(host->port)));
1351             goto retry;
1352         }
1353         host->hostFlags &= ~ALTADDR;
1354         cb_conn = host->callback_rxcon;
1355         rx_GetConnection(cb_conn);
1356         H_UNLOCK;
1357         code =
1358             RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1359         if (code == RXGEN_OPCODE)
1360             code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1361         rx_PutConnection(cb_conn);
1362         cb_conn=NULL;
1363         H_LOCK;
1364         if (code == RXGEN_OPCODE) {
1365             identP = (struct Identity *)malloc(sizeof(struct Identity));
1366             if (!identP) {
1367                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1368                 assert(0);
1369             }
1370             identP->valid = 0;
1371             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1372             /* The host on this connection was unable to respond to 
1373              * the WhoAreYou. We will treat this as a new connection
1374              * from the existing host. The worst that can happen is
1375              * that we maintain some extra callback state information */
1376             if (host->interface) {
1377                 ViceLog(0,
1378                         ("Host %s:%d used to support WhoAreYou, deleting.\n",
1379                          afs_inet_ntoa_r(host->host, hoststr),
1380                          ntohs(host->port)));
1381                 host->hostFlags |= HOSTDELETED;
1382                 h_Unlock_r(host);
1383                 if (!held)
1384                     h_Release_r(host);
1385                 host = NULL;
1386                 goto retry;
1387             }
1388         } else if (code == 0) {
1389             interfValid = 1;
1390             identP = (struct Identity *)malloc(sizeof(struct Identity));
1391             if (!identP) {
1392                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1393                 assert(0);
1394             }
1395             identP->valid = 1;
1396             identP->uuid = interf.uuid;
1397             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1398             /* Check whether the UUID on this connection matches
1399              * the UUID in the host structure. If they don't match
1400              * then this is not the same host as before. */
1401             if (!host->interface
1402                 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1403                 ViceLog(25,
1404                         ("Host %s:%d has changed its identity, deleting.\n",
1405                          afs_inet_ntoa_r(host->host, hoststr), host->port));
1406                 host->hostFlags |= HOSTDELETED;
1407                 h_Unlock_r(host);
1408                 if (!held)
1409                     h_Release_r(host);
1410                 host = NULL;
1411                 goto retry;
1412             }
1413         } else {
1414             afs_inet_ntoa_r(host->host, hoststr);
1415             ViceLog(0,
1416                     ("CB: WhoAreYou failed for %s:%d, error %d\n", hoststr,
1417                      ntohs(host->port), code));
1418             host->hostFlags |= VENUSDOWN;
1419         }
1420         if (caps.Capabilities_val
1421             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1422             host->hostFlags |= HERRORTRANS;
1423         else
1424             host->hostFlags &= ~(HERRORTRANS);
1425         host->hostFlags |= ALTADDR;
1426         h_Unlock_r(host);
1427     } else if (host) {
1428         if (!(host->hostFlags & ALTADDR)) {
1429             /* another thread is doing the initialisation */
1430             ViceLog(125,
1431                     ("Host %s:%d waiting for host-init to complete\n",
1432                      afs_inet_ntoa_r(host->host, hoststr),
1433                      ntohs(host->port)));
1434             h_Lock_r(host);
1435             h_Unlock_r(host);
1436             if (!held)
1437                 h_Release_r(host);
1438             ViceLog(125,
1439                     ("Host %s:%d starting h_Lookup again\n",
1440                      afs_inet_ntoa_r(host->host, hoststr),
1441                      ntohs(host->port)));
1442             goto retry;
1443         }
1444         /* We need to check whether the identity in the host structure
1445          * matches the identity on the connection. If they don't match
1446          * then treat this a new host. */
1447         if (!(host->Console & 1)
1448             && ((!identP->valid && host->interface)
1449                 || (identP->valid && !host->interface)
1450                 || (identP->valid
1451                     && !afs_uuid_equal(&identP->uuid,
1452                                        &host->interface->uuid)))) {
1453             char uuid1[128], uuid2[128];
1454             if (identP->valid)
1455                 afsUUID_to_string(&identP->uuid, uuid1, 127);
1456             if (host->interface)
1457                 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1458             ViceLog(0,
1459                     ("CB: new identity for host %s:%d, deleting(%x %x %s %s)\n",
1460                      afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1461                      identP->valid, host->interface,
1462                      identP->valid ? uuid1 : "",
1463                      host->interface ? uuid2 : ""));
1464
1465             /* The host in the cache is not the host for this connection */
1466             host->hostFlags |= HOSTDELETED;
1467             h_Unlock_r(host);
1468             if (!held)
1469                 h_Release_r(host);
1470             goto retry;
1471         }
1472     } else {
1473         host = h_Alloc_r(tcon); /* returned held and locked */
1474         h_gethostcps_r(host, FT_ApproxTime());
1475         if (!(host->Console & 1)) {
1476             int pident = 0;
1477             cb_conn = host->callback_rxcon;
1478             rx_GetConnection(cb_conn);
1479             H_UNLOCK;
1480             code =
1481                 RXAFSCB_TellMeAboutYourself(cb_conn, &interf, &caps);
1482             if (code == RXGEN_OPCODE)
1483                 code = RXAFSCB_WhoAreYou(cb_conn, &interf);
1484             rx_PutConnection(cb_conn);
1485             cb_conn=NULL;
1486             H_LOCK;
1487             if (code == RXGEN_OPCODE) {
1488                 if (!identP)
1489                     identP =
1490                         (struct Identity *)malloc(sizeof(struct Identity));
1491                 else
1492                     pident = 1;
1493
1494                 if (!identP) {
1495                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1496                     assert(0);
1497                 }
1498                 identP->valid = 0;
1499                 if (!pident)
1500                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1501                 ViceLog(25,
1502                         ("Host %s:%d does not support WhoAreYou.\n",
1503                          afs_inet_ntoa_r(host->host, hoststr),
1504                          ntohs(host->port)));
1505                 code = 0;
1506             } else if (code == 0) {
1507                 if (!identP)
1508                     identP =
1509                         (struct Identity *)malloc(sizeof(struct Identity));
1510                 else
1511                     pident = 1;
1512
1513                 if (!identP) {
1514                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1515                     assert(0);
1516                 }
1517                 identP->valid = 1;
1518                 interfValid = 1;
1519                 identP->uuid = interf.uuid;
1520                 if (!pident)
1521                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1522                 ViceLog(25,
1523                         ("WhoAreYou success on %s:%d\n",
1524                          afs_inet_ntoa_r(host->host, hoststr),
1525                          ntohs(host->port)));
1526             }
1527             if (code == 0 && !identP->valid) {
1528                 cb_conn = host->callback_rxcon;
1529                 rx_GetConnection(cb_conn);
1530                 H_UNLOCK;
1531                 code = RXAFSCB_InitCallBackState(cb_conn);
1532                 rx_PutConnection(cb_conn);
1533                 cb_conn=NULL;
1534                 H_LOCK;
1535             } else if (code == 0) {
1536                 oldHost = h_LookupUuid_r(&identP->uuid);
1537                 if (oldHost) {
1538                     int probefail = 0;
1539
1540                     if (!(oheld = h_Held_r(oldHost)))
1541                         h_Hold_r(oldHost);
1542                     h_Lock_r(oldHost);
1543
1544                     if (oldHost->interface) {
1545                         int code2;
1546                         afsUUID uuid = oldHost->interface->uuid;
1547                         cb_conn = oldHost->callback_rxcon;
1548                         rx_GetConnection(cb_conn);
1549                         rx_SetConnDeadTime(cb_conn, 2);
1550                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1551                         H_UNLOCK;
1552                         code2 = RXAFSCB_ProbeUuid(cb_conn, &uuid);
1553                         H_LOCK;
1554                         rx_SetConnDeadTime(cb_conn, 50);
1555                         rx_SetConnHardDeadTime(cb_conn, AFS_HARDDEADTIME);
1556                         rx_PutConnection(cb_conn);
1557                         cb_conn=NULL;
1558                         if (code2) {
1559                             /* The primary address is either not responding or
1560                              * is not the client we are looking for.  
1561                              * MultiProbeAlternateAddress_r() will remove the
1562                              * alternate interfaces that do not have the same
1563                              * Uuid. */
1564                             ViceLog(0,("CB: ProbeUuid for %s:%d failed %d\n",
1565                                          afs_inet_ntoa_r(oldHost->host, hoststr),
1566                                          ntohs(oldHost->port),code2));
1567                             MultiProbeAlternateAddress_r(oldHost);
1568                             probefail = 1;
1569                         }
1570                     } else {
1571                         probefail = 1;
1572                     }
1573
1574                     /* This is a new address for an existing host. Update
1575                      * the list of interfaces for the existing host and
1576                      * delete the host structure we just allocated. */
1577                     if (oldHost->host != haddr || oldHost->port != hport) {
1578                         struct rx_connection *rxconn;
1579
1580                         ViceLog(25,
1581                                 ("CB: new addr %s:%d for old host %s:%d\n",
1582                                   afs_inet_ntoa_r(haddr, hoststr),
1583                                   ntohs(hport), 
1584                                   afs_inet_ntoa_r(oldHost->host, hoststr2),
1585                                   ntohs(oldHost->port)));
1586                         if (probefail || oldHost->host == haddr) {
1587                             /* The probe failed which means that the old address is 
1588                              * either unreachable or is not the same host we were just
1589                              * contacted by.  We will also remove addresses if only
1590                              * the port has changed because that indicates the client
1591                              * is behind a NAT. 
1592                              */
1593                             removeInterfaceAddr_r(oldHost, oldHost->host, oldHost->port);
1594                         } else {
1595                             int i, found;
1596                             struct Interface *interface = oldHost->interface;
1597                             int number = oldHost->interface->numberOfInterfaces;
1598                             for (i = 0, found = 0; i < number; i++) {
1599                                 if (interface->interface[i].addr == haddr &&
1600                                     interface->interface[i].port != hport) {
1601                                     found = 1;
1602                                     break;
1603                                 }
1604                             }
1605                             if (found) {
1606                                 /* We have just been contacted by a client that has been
1607                                  * seen from behind a NAT and at least one other address.
1608                                  */
1609                                 removeInterfaceAddr_r(oldHost, haddr, interface->interface[i].port);
1610                             }
1611                         }
1612                         addInterfaceAddr_r(oldHost, haddr, hport);
1613                         oldHost->host = haddr;
1614                         oldHost->port = hport;
1615                         rxconn = oldHost->callback_rxcon;
1616                         oldHost->callback_rxcon = host->callback_rxcon;
1617                         host->callback_rxcon = NULL;
1618                         
1619                         if (rxconn) {
1620                             struct client *client;
1621                             /*
1622                              * If rx_DestroyConnection calls h_FreeConnection we will
1623                              * deadlock on the host_glock_mutex. Work around the problem
1624                              * by unhooking the client from the connection before
1625                              * destroying the connection.
1626                              */
1627                             client = rx_GetSpecific(rxconn, rxcon_client_key);
1628                             rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
1629                             rx_DestroyConnection(rxconn);
1630                         }
1631                     }
1632                     host->hostFlags |= HOSTDELETED;
1633                     h_Unlock_r(host);
1634                     /* release host because it was allocated by h_Alloc_r */
1635                     h_Release_r(host);
1636                     host = oldHost;
1637                     /* the new host is held and locked */
1638                 } else {
1639                     /* This really is a new host */
1640                     h_AddHostToUuidHashTable_r(&identP->uuid, host);
1641                     cb_conn = host->callback_rxcon;
1642                     rx_GetConnection(cb_conn);          
1643                     H_UNLOCK;
1644                     code =
1645                         RXAFSCB_InitCallBackState3(cb_conn,
1646                                                    &FS_HostUUID);
1647                     rx_PutConnection(cb_conn);
1648                     cb_conn=NULL;
1649                     H_LOCK;
1650                     if (code == 0) {
1651                         ViceLog(25,
1652                                 ("InitCallBackState3 success on %s:%d\n",
1653                                  afs_inet_ntoa_r(host->host, hoststr),
1654                                  ntohs(host->port)));
1655                         assert(interfValid == 1);
1656                         initInterfaceAddr_r(host, &interf);
1657                     }
1658                 }
1659             }
1660             if (code) {
1661                 afs_inet_ntoa_r(host->host, hoststr);
1662                 ViceLog(0,
1663                         ("CB: RCallBackConnectBack failed for %s:%d\n",
1664                          hoststr, ntohs(host->port)));
1665                 host->hostFlags |= VENUSDOWN;
1666             } else {
1667                 ViceLog(125,
1668                         ("CB: RCallBackConnectBack succeeded for %s:%d\n",
1669                          hoststr, ntohs(host->port)));
1670                 host->hostFlags |= RESETDONE;
1671             }
1672         }
1673         if (caps.Capabilities_val
1674             && (caps.Capabilities_val[0] & CLIENT_CAPABILITY_ERRORTRANS))
1675             host->hostFlags |= HERRORTRANS;
1676         else
1677             host->hostFlags &= ~(HERRORTRANS);
1678         host->hostFlags |= ALTADDR;     /* host structure initialization complete */
1679         h_Unlock_r(host);
1680     }
1681     if (caps.Capabilities_val)
1682         free(caps.Capabilities_val);
1683     caps.Capabilities_val = NULL;
1684     caps.Capabilities_len = 0;
1685     return host;
1686
1687 }                               /*h_GetHost_r */
1688
1689
1690 static char localcellname[PR_MAXNAMELEN + 1];
1691 char local_realms[AFS_NUM_LREALMS][AFS_REALM_SZ];
1692 int  num_lrealms = -1;
1693
1694 /* not reentrant */
1695 void
1696 h_InitHostPackage()
1697 {
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                             rxr_AddrStringOf(tcon),
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                         rxr_AddrStringOf(tcon),
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 %s:%d), VBUSYING\n",
2104                  tcon, rxr_AddrStringOf(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 }