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