add-missing-return-values-20031207
[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
10 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 RCSID
14     ("$Header$");
15
16 #include <stdio.h>
17 #include <errno.h>
18 #ifdef AFS_NT40_ENV
19 #include <fcntl.h>
20 #include <winsock2.h>
21 #else
22 #include <sys/file.h>
23 #include <netdb.h>
24 #include <netinet/in.h>
25 #endif
26
27 #ifdef HAVE_STRING_H
28 #include <string.h>
29 #else
30 #ifdef HAVE_STRINGS_H
31 #include <strings.h>
32 #endif
33 #endif
34
35 #include <afs/stds.h>
36 #include <rx/xdr.h>
37 #include <afs/assert.h>
38 #include <lwp.h>
39 #include <lock.h>
40 #include <afs/afsint.h>
41 #include <afs/rxgen_consts.h>
42 #include <afs/nfs.h>
43 #include <afs/errors.h>
44 #include <afs/ihandle.h>
45 #include <afs/vnode.h>
46 #include <afs/volume.h>
47 #ifdef AFS_ATHENA_STDENV
48 #include <krb.h>
49 #endif
50 #include <afs/acl.h>
51 #include <afs/ptclient.h>
52 #include <afs/prs_fs.h>
53 #include <afs/auth.h>
54 #include <afs/afsutil.h>
55 #include <rx/rx.h>
56 #include <afs/cellconfig.h>
57 #include <stdlib.h>
58 #include "viced_prototypes.h"
59 #include "viced.h"
60 #include "host.h"
61
62
63 #ifdef AFS_PTHREAD_ENV
64 pthread_mutex_t host_glock_mutex;
65 #endif /* AFS_PTHREAD_ENV */
66
67 extern int Console;
68 extern int CurrentConnections;
69 extern int SystemId;
70 extern int AnonymousID;
71 extern prlist AnonCPS;
72 extern int LogLevel;
73 extern struct afsconf_dir *confDir;     /* config dir object */
74 extern int lwps;                /* the max number of server threads */
75 extern afsUUID FS_HostUUID;
76
77 int CEs = 0;                    /* active clients */
78 int CEBlocks = 0;               /* number of blocks of CEs */
79 struct client *CEFree = 0;      /* first free client */
80 struct host *hostList = 0;      /* linked list of all hosts */
81 int hostCount = 0;              /* number of hosts in hostList */
82 int rxcon_ident_key;
83 int rxcon_client_key;
84
85 #define CESPERBLOCK 73
86 struct CEBlock {                /* block of CESPERBLOCK file entries */
87     struct client entry[CESPERBLOCK];
88 };
89
90 static void h_TossStuff_r(register struct host *host);
91
92 /*
93  * Make sure the subnet macros have been defined.
94  */
95 #ifndef IN_SUBNETA
96 #define IN_SUBNETA(i)           ((((afs_int32)(i))&0x80800000)==0x00800000)
97 #endif
98
99 #ifndef IN_CLASSA_SUBNET
100 #define IN_CLASSA_SUBNET        0xffff0000
101 #endif
102
103 #ifndef IN_SUBNETB
104 #define IN_SUBNETB(i)           ((((afs_int32)(i))&0xc0008000)==0x80008000)
105 #endif
106
107 #ifndef IN_CLASSB_SUBNET
108 #define IN_CLASSB_SUBNET        0xffffff00
109 #endif
110
111 #define rxr_GetEpoch(aconn) (((struct rx_connection *)(aconn))->epoch)
112
113 #define rxr_CidOf(aconn) (((struct rx_connection *)(aconn))->cid)
114
115 #define rxr_PortOf(aconn) \
116     rx_PortOf(rx_PeerOf(((struct rx_connection *)(aconn))))
117
118 #define rxr_HostOf(aconn) \
119     rx_HostOf(rx_PeerOf((struct rx_connection *)(aconn)))
120
121
122 /* get a new block of CEs and chain it on CEFree */
123 static void
124 GetCEBlock()
125 {
126     register struct CEBlock *block;
127     register int i;
128
129     block = (struct CEBlock *)malloc(sizeof(struct CEBlock));
130     if (!block) {
131         ViceLog(0, ("Failed malloc in GetCEBlock\n"));
132         ShutDownAndCore(PANIC);
133     }
134
135     for (i = 0; i < (CESPERBLOCK - 1); i++) {
136         Lock_Init(&block->entry[i].lock);
137         block->entry[i].next = &(block->entry[i + 1]);
138     }
139     block->entry[CESPERBLOCK - 1].next = 0;
140     Lock_Init(&block->entry[CESPERBLOCK - 1].lock);
141     CEFree = (struct client *)block;
142     CEBlocks++;
143
144 }                               /*GetCEBlock */
145
146
147 /* get the next available CE */
148 static struct client *
149 GetCE()
150 {
151     register struct client *entry;
152
153     if (CEFree == 0)
154         GetCEBlock();
155     if (CEFree == 0) {
156         ViceLog(0, ("CEFree NULL in GetCE\n"));
157         ShutDownAndCore(PANIC);
158     }
159
160     entry = CEFree;
161     CEFree = entry->next;
162     CEs++;
163     memset((char *)entry, 0, CLIENT_TO_ZERO(entry));
164     return (entry);
165
166 }                               /*GetCE */
167
168
169 /* return an entry to the free list */
170 static void
171 FreeCE(register struct client *entry)
172 {
173     entry->next = CEFree;
174     CEFree = entry;
175     CEs--;
176
177 }                               /*FreeCE */
178
179 /*
180  * The HTs and HTBlocks variables were formerly static, but they are
181  * now referenced elsewhere in the FileServer.
182  */
183 int HTs = 0;                    /* active file entries */
184 int HTBlocks = 0;               /* number of blocks of HTs */
185 static struct host *HTFree = 0; /* first free file entry */
186
187 /*
188  * Hash tables of host pointers. We need two tables, one
189  * to map IP addresses onto host pointers, and another
190  * to map host UUIDs onto host pointers.
191  */
192 static struct h_hashChain *hostHashTable[h_HASHENTRIES];
193 static struct h_hashChain *hostUuidHashTable[h_HASHENTRIES];
194 #define h_HashIndex(hostip) ((hostip) & (h_HASHENTRIES-1))
195 #define h_UuidHashIndex(uuidp) (((int)(afs_uuid_hash(uuidp))) & (h_HASHENTRIES-1))
196
197 struct HTBlock {                /* block of HTSPERBLOCK file entries */
198     struct host entry[h_HTSPERBLOCK];
199 };
200
201
202 /* get a new block of HTs and chain it on HTFree */
203 static void
204 GetHTBlock()
205 {
206     register struct HTBlock *block;
207     register int i;
208     static int index = 0;
209
210     block = (struct HTBlock *)malloc(sizeof(struct HTBlock));
211     if (!block) {
212         ViceLog(0, ("Failed malloc in GetHTBlock\n"));
213         ShutDownAndCore(PANIC);
214     }
215 #ifdef AFS_PTHREAD_ENV
216     for (i = 0; i < (h_HTSPERBLOCK); i++)
217         assert(pthread_cond_init(&block->entry[i].cond, NULL) == 0);
218 #endif /* AFS_PTHREAD_ENV */
219     for (i = 0; i < (h_HTSPERBLOCK); i++)
220         Lock_Init(&block->entry[i].lock);
221     for (i = 0; i < (h_HTSPERBLOCK - 1); i++)
222         block->entry[i].next = &(block->entry[i + 1]);
223     for (i = 0; i < (h_HTSPERBLOCK); i++)
224         block->entry[i].index = index++;
225     block->entry[h_HTSPERBLOCK - 1].next = 0;
226     HTFree = (struct host *)block;
227     hosttableptrs[HTBlocks++] = block->entry;
228
229 }                               /*GetHTBlock */
230
231
232 /* get the next available HT */
233 static struct host *
234 GetHT()
235 {
236     register struct host *entry;
237
238     if (HTFree == 0)
239         GetHTBlock();
240     assert(HTFree != 0);
241     entry = HTFree;
242     HTFree = entry->next;
243     HTs++;
244     memset((char *)entry, 0, HOST_TO_ZERO(entry));
245     return (entry);
246
247 }                               /*GetHT */
248
249
250 /* return an entry to the free list */
251 static void
252 FreeHT(register struct host *entry)
253 {
254     entry->next = HTFree;
255     HTFree = entry;
256     HTs--;
257
258 }                               /*FreeHT */
259
260
261 static short consolePort = 0;
262
263 int
264 h_Release(register struct host *host)
265 {
266     H_LOCK;
267     h_Release_r(host);
268     H_UNLOCK;
269     return 0;
270 }
271
272 /**
273  * If this thread does not have a hold on this host AND
274  * if other threads also dont have any holds on this host AND
275  * If either the HOSTDELETED or CLIENTDELETED flags are set
276  * then toss the host
277  */
278 int
279 h_Release_r(register struct host *host)
280 {
281
282     if (!((host)->holds[h_holdSlot()] & ~h_holdbit())) {
283         if (!h_OtherHolds_r(host)) {
284             /* must avoid masking this until after h_OtherHolds_r runs
285              * but it should be run before h_TossStuff_r */
286             (host)->holds[h_holdSlot()] &= ~h_holdbit();
287             if ((host->hostFlags & HOSTDELETED)
288                 || (host->hostFlags & CLIENTDELETED)) {
289                 h_TossStuff_r(host);
290             }
291         } else
292             (host)->holds[h_holdSlot()] &= ~h_holdbit();
293     } else
294         (host)->holds[h_holdSlot()] &= ~h_holdbit();
295
296     return 0;
297 }
298
299 int
300 h_OtherHolds_r(register struct host *host)
301 {
302     register int i, bit, slot;
303     bit = h_holdbit();
304     slot = h_holdSlot();
305     for (i = 0; i < h_maxSlots; i++) {
306         if (host->holds[i] != ((i == slot) ? bit : 0)) {
307             return 1;
308         }
309     }
310     return 0;
311 }
312
313 int
314 h_Lock_r(register struct host *host)
315 {
316     H_UNLOCK;
317     h_Lock(host);
318     H_LOCK;
319     return 0;
320 }
321
322 /**
323   * Non-blocking lock
324   * returns 1 if already locked
325   * else returns locks and returns 0
326   */
327
328 int
329 h_NBLock_r(register struct host *host)
330 {
331     struct Lock *hostLock = &host->lock;
332     int locked = 0;
333
334     H_UNLOCK;
335     LOCK_LOCK(hostLock);
336     if (!(hostLock->excl_locked) && !(hostLock->readers_reading))
337         hostLock->excl_locked = WRITE_LOCK;
338     else
339         locked = 1;
340
341     LOCK_UNLOCK(hostLock);
342     H_LOCK;
343     if (locked)
344         return 1;
345     else
346         return 0;
347 }
348
349
350 #if FS_STATS_DETAILED
351 /*------------------------------------------------------------------------
352  * PRIVATE h_AddrInSameNetwork
353  *
354  * Description:
355  *      Given a target IP address and a candidate IP address (both
356  *      in host byte order), return a non-zero value (1) if the
357  *      candidate address is in a different network from the target
358  *      address.
359  *
360  * Arguments:
361  *      a_targetAddr       : Target address.
362  *      a_candAddr         : Candidate address.
363  *
364  * Returns:
365  *      1 if the candidate address is in the same net as the target,
366  *      0 otherwise.
367  *
368  * Environment:
369  *      The target and candidate addresses are both in host byte
370  *      order, NOT network byte order, when passed in.  We return
371  *      our value as a character, since that's the type of field in
372  *      the host structure, where this info will be stored.
373  *
374  * Side Effects:
375  *      As advertised.
376  *------------------------------------------------------------------------*/
377
378 static char
379 h_AddrInSameNetwork(afs_uint32 a_targetAddr, afs_uint32 a_candAddr)
380 {                               /*h_AddrInSameNetwork */
381
382     afs_uint32 targetNet;
383     afs_uint32 candNet;
384
385     /*
386      * Pull out the network and subnetwork numbers from the target
387      * and candidate addresses.  We can short-circuit this whole
388      * affair if the target and candidate addresses are not of the
389      * same class.
390      */
391     if (IN_CLASSA(a_targetAddr)) {
392         if (!(IN_CLASSA(a_candAddr))) {
393             return (0);
394         }
395         targetNet = a_targetAddr & IN_CLASSA_NET;
396         candNet = a_candAddr & IN_CLASSA_NET;
397     } else if (IN_CLASSB(a_targetAddr)) {
398         if (!(IN_CLASSB(a_candAddr))) {
399             return (0);
400         }
401         targetNet = a_targetAddr & IN_CLASSB_NET;
402         candNet = a_candAddr & IN_CLASSB_NET;
403     } /*Class B target */
404     else if (IN_CLASSC(a_targetAddr)) {
405         if (!(IN_CLASSC(a_candAddr))) {
406             return (0);
407         }
408         targetNet = a_targetAddr & IN_CLASSC_NET;
409         candNet = a_candAddr & IN_CLASSC_NET;
410     } /*Class C target */
411     else {
412         targetNet = a_targetAddr;
413         candNet = a_candAddr;
414     }                           /*Class D address */
415
416     /*
417      * Now, simply compare the extracted net values for the two addresses
418      * (which at this point are known to be of the same class)
419      */
420     if (targetNet == candNet)
421         return (1);
422     else
423         return (0);
424
425 }                               /*h_AddrInSameNetwork */
426 #endif /* FS_STATS_DETAILED */
427
428
429 /* Assumptions: called with held host */
430 void
431 h_gethostcps_r(register struct host *host, register afs_int32 now)
432 {
433     register int code;
434     int slept = 0;
435
436     /* wait if somebody else is already doing the getCPS call */
437     while (host->hostFlags & HCPS_INPROGRESS) {
438         slept = 1;              /* I did sleep */
439         host->hostFlags |= HCPS_WAITING;        /* I am sleeping now */
440 #ifdef AFS_PTHREAD_ENV
441         pthread_cond_wait(&host->cond, &host_glock_mutex);
442 #else /* AFS_PTHREAD_ENV */
443         if ((code = LWP_WaitProcess(&(host->hostFlags))) != LWP_SUCCESS)
444             ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
445 #endif /* AFS_PTHREAD_ENV */
446     }
447
448
449     host->hostFlags |= HCPS_INPROGRESS; /* mark as CPSCall in progress */
450     if (host->hcps.prlist_val)
451         free(host->hcps.prlist_val);    /* this is for hostaclRefresh */
452     host->hcps.prlist_val = NULL;
453     host->hcps.prlist_len = 0;
454     slept ? (host->cpsCall = FT_ApproxTime()) : (host->cpsCall = now);
455
456     H_UNLOCK;
457     code = pr_GetHostCPS(htonl(host->host), &host->hcps);
458     H_LOCK;
459     if (code) {
460         /*
461          * Although ubik_Call (called by pr_GetHostCPS) traverses thru all protection servers
462          * and reevaluates things if no sync server or quorum is found we could still end up
463          * with one of these errors. In such case we would like to reevaluate the rpc call to
464          * find if there's cps for this guy. We treat other errors (except network failures
465          * ones - i.e. code < 0) as an indication that there is no CPS for this host. Ideally
466          * we could like to deal this problem the other way around (i.e. if code == NOCPS 
467          * ignore else retry next time) but the problem is that there're other errors (i.e.
468          * EPERM) for which we don't want to retry and we don't know the whole code list!
469          */
470         if (code < 0 || code == UNOQUORUM || code == UNOTSYNC) {
471             /* 
472              * We would have preferred to use a while loop and try again since ops in protected
473              * acls for this host will fail now but they'll be reevaluated on any subsequent
474              * call. The attempt to wait for a quorum/sync site or network error won't work
475              * since this problems really should only occurs during a complete fileserver 
476              * restart. Since the fileserver will start before the ptservers (and thus before
477              * quorums are complete) clients will be utilizing all the fileserver's lwps!!
478              */
479             host->hcpsfailed = 1;
480             ViceLog(0,
481                     ("Warning:  GetHostCPS failed (%d) for %x; will retry\n",
482                      code, host->host));
483         } else {
484             host->hcpsfailed = 0;
485             ViceLog(1,
486                     ("gethost:  GetHostCPS failed (%d) for %x; ignored\n",
487                      code, host->host));
488         }
489         if (host->hcps.prlist_val)
490             free(host->hcps.prlist_val);
491         host->hcps.prlist_val = NULL;
492         host->hcps.prlist_len = 0;      /* Make sure it's zero */
493     } else
494         host->hcpsfailed = 0;
495
496     host->hostFlags &= ~HCPS_INPROGRESS;
497     /* signal all who are waiting */
498     if (host->hostFlags & HCPS_WAITING) {       /* somebody is waiting */
499         host->hostFlags &= ~HCPS_WAITING;
500 #ifdef AFS_PTHREAD_ENV
501         assert(pthread_cond_broadcast(&host->cond) == 0);
502 #else /* AFS_PTHREAD_ENV */
503         if ((code = LWP_NoYieldSignal(&(host->hostFlags))) != LWP_SUCCESS)
504             ViceLog(0, ("LWP_NoYieldSignal returns %d\n", code));
505 #endif /* AFS_PTHREAD_ENV */
506     }
507 }
508
509 /* args in net byte order */
510 void
511 h_flushhostcps(register afs_uint32 hostaddr, register afs_uint32 hport)
512 {
513     register struct host *host;
514     int held = 0;
515
516     H_LOCK;
517     host = h_Lookup_r(hostaddr, hport, &held);
518     if (host) {
519         host->hcpsfailed = 1;
520         if (!held)
521             h_Release_r(host);
522     }
523     H_UNLOCK;
524     return;
525 }
526
527
528 /*
529  * Allocate a host.  It will be identified by the peer (ip,port) info in the
530  * rx connection provided.  The host is returned held and locked
531  */
532 #define DEF_ROPCONS 2115
533
534 struct host *
535 h_Alloc_r(register struct rx_connection *r_con)
536 {
537     struct servent *serverentry;
538     register index = h_HashIndex(rxr_HostOf(r_con));
539     register struct host *host;
540     static struct rx_securityClass *sc = 0;
541     afs_int32 now;
542     struct h_hashChain *h_hashChain;
543 #if FS_STATS_DETAILED
544     afs_uint32 newHostAddr_HBO; /*New host IP addr, in host byte order */
545 #endif /* FS_STATS_DETAILED */
546
547     host = GetHT();
548
549     h_hashChain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
550     if (!h_hashChain) {
551         ViceLog(0, ("Failed malloc in h_Alloc_r\n"));
552         assert(0);
553     }
554     h_hashChain->hostPtr = host;
555     h_hashChain->addr = rxr_HostOf(r_con);
556     h_hashChain->next = hostHashTable[index];
557     hostHashTable[index] = h_hashChain;
558
559     host->host = rxr_HostOf(r_con);
560     host->port = rxr_PortOf(r_con);
561     if (consolePort == 0) {     /* find the portal number for console */
562 #if     defined(AFS_OSF_ENV)
563         serverentry = getservbyname("ropcons", "");
564 #else
565         serverentry = getservbyname("ropcons", 0);
566 #endif
567         if (serverentry)
568             consolePort = serverentry->s_port;
569         else
570             consolePort = htons(DEF_ROPCONS);   /* Use a default */
571     }
572     if (host->port == consolePort)
573         host->Console = 1;
574     /* Make a callback channel even for the console, on the off chance that it
575      * makes a request that causes a break call back.  It shouldn't. */
576     {
577         if (!sc)
578             sc = rxnull_NewClientSecurityObject();
579         host->callback_rxcon =
580             rx_NewConnection(host->host, host->port, 1, sc, 0);
581         rx_SetConnDeadTime(host->callback_rxcon, 50);
582         rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
583     }
584     now = host->LastCall = host->cpsCall = host->ActiveCall = FT_ApproxTime();
585     host->hostFlags = 0;
586     host->hcps.prlist_val = NULL;
587     host->hcps.prlist_len = 0;
588     host->interface = 0;
589 #ifdef undef
590     host->hcpsfailed = 0;       /* save cycles */
591     h_gethostcps(host);         /* do this under host hold/lock */
592 #endif
593     host->FirstClient = 0;
594     h_Hold_r(host);
595     h_Lock_r(host);
596     h_InsertList_r(host);       /* update global host List */
597 #if FS_STATS_DETAILED
598     /*
599      * Compare the new host's IP address (in host byte order) with ours
600      * (the File Server's), remembering if they are in the same network.
601      */
602     newHostAddr_HBO = (afs_uint32) ntohl(host->host);
603     host->InSameNetwork =
604         h_AddrInSameNetwork(FS_HostAddr_HBO, newHostAddr_HBO);
605 #endif /* FS_STATS_DETAILED */
606     return host;
607
608 }                               /*h_Alloc_r */
609
610
611 /* Lookup a host given an IP address and UDP port number. */
612 /* hostaddr and hport are in network order */
613 /* Note: host should be released by caller if 0 == *heldp and non-null */
614 /* hostaddr and hport are in network order */
615 struct host *
616 h_Lookup_r(afs_uint32 hostaddr, afs_uint32 hport, int *heldp)
617 {
618     register afs_int32 now;
619     register struct host *host = 0;
620     register struct h_hashChain *chain;
621     register index = h_HashIndex(hostaddr);
622     extern int hostaclRefresh;
623
624   restart:
625     for (chain = hostHashTable[index]; chain; chain = chain->next) {
626         host = chain->hostPtr;
627         assert(host);
628         if (!(host->hostFlags & HOSTDELETED) && chain->addr == hostaddr
629             && host->port == hport) {
630             *heldp = h_Held_r(host);
631             if (!*heldp)
632                 h_Hold_r(host);
633             h_Lock_r(host);
634             if (host->hostFlags & HOSTDELETED) {
635                 h_Unlock_r(host);
636                 if (!*heldp)
637                     h_Release_r(host);
638                 goto restart;
639             }
640             h_Unlock_r(host);
641             now = FT_ApproxTime();      /* always evaluate "now" */
642             if (host->hcpsfailed || (host->cpsCall + hostaclRefresh < now)) {
643                 /*
644                  * Every hostaclRefresh period (def 2 hrs) get the new
645                  * membership list for the host.  Note this could be the
646                  * first time that the host is added to a group.  Also
647                  * here we also retry on previous legitimate hcps failures.
648                  *
649                  * If we get here we still have a host hold.
650                  */
651                 h_gethostcps_r(host, now);
652             }
653             break;
654         }
655         host = NULL;
656     }
657     return host;
658
659 }                               /*h_Lookup */
660
661 /* Lookup a host given its UUID. */
662 struct host *
663 h_LookupUuid_r(afsUUID * uuidp)
664 {
665     register struct host *host = 0;
666     register struct h_hashChain *chain;
667     register index = h_UuidHashIndex(uuidp);
668
669     for (chain = hostUuidHashTable[index]; chain; chain = chain->next) {
670         host = chain->hostPtr;
671         assert(host);
672         if (!(host->hostFlags & HOSTDELETED) && host->interface
673             && afs_uuid_equal(&host->interface->uuid, uuidp)) {
674             break;
675         }
676         host = NULL;
677     }
678     return host;
679
680 }                               /*h_Lookup */
681
682
683 /*
684  * h_Hold_r: Establish a hold by the current LWP on this host--the host
685  * or its clients will not be physically deleted until all holds have
686  * been released.
687  * NOTE: h_Hold_r is a macro defined in host.h.
688  */
689
690 /* h_TossStuff_r:  Toss anything in the host structure (the host or
691  * clients marked for deletion.  Called from h_Release_r ONLY.
692  * To be called, there must be no holds, and either host->deleted
693  * or host->clientDeleted must be set.
694  */
695 static void
696 h_TossStuff_r(register struct host *host)
697 {
698     register struct client **cp, *client;
699     int i;
700
701     /* if somebody still has this host held */
702     for (i = 0; (i < h_maxSlots) && (!(host)->holds[i]); i++);
703     if (i != h_maxSlots)
704         return;
705
706     /* if somebody still has this host locked */
707     if (h_NBLock_r(host) != 0) {
708         char hoststr[16];
709         ViceLog(0,
710                 ("Warning:  h_TossStuff_r failed; Host %s:%d was locked.\n",
711                  afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
712         return;
713     } else {
714         h_Unlock_r(host);
715     }
716
717     /* ASSUMPTION: rxi_FreeConnection() does not yield */
718     for (cp = &host->FirstClient; (client = *cp);) {
719         if ((host->hostFlags & HOSTDELETED) || client->deleted) {
720             if (client->refCount) {
721                 char hoststr[16];
722                 ViceLog(0,
723                         ("Warning: Host %s:%d client %x refcount %d while deleting.\n",
724                          afs_inet_ntoa_r(host->host, hoststr),
725                          ntohs(host->port), client, client->refCount));
726             }
727             if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val) {
728                 free(client->CPS.prlist_val);
729                 client->CPS.prlist_val = NULL;
730             }
731             client->CPS.prlist_len = 0;
732             if (client->tcon) {
733                 rx_SetSpecific(client->tcon, rxcon_client_key, (void *)0);
734             }
735             CurrentConnections--;
736             *cp = client->next;
737             FreeCE(client);
738         } else
739             cp = &client->next;
740     }
741
742     /* We've just cleaned out all the deleted clients; clear the flag */
743     host->hostFlags &= ~CLIENTDELETED;
744
745     if (host->hostFlags & HOSTDELETED) {
746         register struct h_hashChain **hp, *th;
747         register struct rx_connection *rxconn;
748         afsUUID *uuidp;
749         afs_uint32 hostAddr;
750         int i;
751
752         if (host->Console & 1)
753             Console--;
754         if ((rxconn = host->callback_rxcon)) {
755             host->callback_rxcon = (struct rx_connection *)0;
756             /*
757              * If rx_DestroyConnection calls h_FreeConnection we will
758              * deadlock on the host_glock_mutex. Work around the problem
759              * by unhooking the client from the connection before
760              * destroying the connection.
761              */
762             client = rx_GetSpecific(rxconn, rxcon_client_key);
763             if (client && client->tcon == rxconn)
764                 client->tcon = NULL;
765             rx_SetSpecific(rxconn, rxcon_client_key, (void *)0);
766             rx_DestroyConnection(rxconn);
767         }
768         if (host->hcps.prlist_val)
769             free(host->hcps.prlist_val);
770         host->hcps.prlist_val = NULL;
771         host->hcps.prlist_len = 0;
772         DeleteAllCallBacks_r(host, 1);
773         host->hostFlags &= ~RESETDONE;  /* just to be safe */
774
775         /* if alternate addresses do not exist */
776         if (!(host->interface)) {
777             for (hp = &hostHashTable[h_HashIndex(host->host)]; (th = *hp);
778                  hp = &th->next) {
779                 assert(th->hostPtr);
780                 if (th->hostPtr == host) {
781                     *hp = th->next;
782                     h_DeleteList_r(host);
783                     FreeHT(host);
784                     break;
785                 }
786             }
787         } else {
788             /* delete all hash entries for the UUID */
789             uuidp = &host->interface->uuid;
790             for (hp = &hostUuidHashTable[h_UuidHashIndex(uuidp)]; (th = *hp);
791                  hp = &th->next) {
792                 assert(th->hostPtr);
793                 if (th->hostPtr == host) {
794                     *hp = th->next;
795                     free(th);
796                     break;
797                 }
798             }
799             /* delete all hash entries for alternate addresses */
800             assert(host->interface->numberOfInterfaces > 0);
801             for (i = 0; i < host->interface->numberOfInterfaces; i++) {
802                 hostAddr = host->interface->addr[i];
803                 for (hp = &hostHashTable[h_HashIndex(hostAddr)]; (th = *hp);
804                      hp = &th->next) {
805                     assert(th->hostPtr);
806                     if (th->hostPtr == host) {
807                         *hp = th->next;
808                         free(th);
809                         break;
810                     }
811                 }
812             }
813             free(host->interface);
814             host->interface = NULL;
815             h_DeleteList_r(host);       /* remove host from global host List */
816             FreeHT(host);
817         }                       /* if alternate address exists */
818     }
819 }                               /*h_TossStuff_r */
820
821
822 /* Called by rx when a server connection disappears */
823 int
824 h_FreeConnection(struct rx_connection *tcon)
825 {
826     register struct client *client;
827
828     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
829     if (client) {
830         H_LOCK;
831         if (client->tcon == tcon)
832             client->tcon = (struct rx_connection *)0;
833         H_UNLOCK;
834     }
835     return 0;
836 }                               /*h_FreeConnection */
837
838
839 /* h_Enumerate: Calls (*proc)(host, held, param) for at least each host in the
840  * system at the start of the enumeration (perhaps more).  Hosts may be deleted
841  * (have delete flag set); ditto for clients.  (*proc) is always called with
842  * host h_held().  The hold state of the host with respect to this lwp is passed
843  * to (*proc) as the param held.  The proc should return 0 if the host should be
844  * released, 1 if it should be held after enumeration.
845  */
846 void
847 h_Enumerate(int (*proc) (), char *param)
848 {
849     register struct host *host, **list;
850     register int *held;
851     register int i, count;
852
853     H_LOCK;
854     if (hostCount == 0) {
855         H_UNLOCK;
856         return;
857     }
858     list = (struct host **)malloc(hostCount * sizeof(struct host *));
859     if (!list) {
860         ViceLog(0, ("Failed malloc in h_Enumerate\n"));
861         assert(0);
862     }
863     held = (int *)malloc(hostCount * sizeof(int));
864     if (!held) {
865         ViceLog(0, ("Failed malloc in h_Enumerate\n"));
866         assert(0);
867     }
868     for (count = 0, host = hostList; host; host = host->next, count++) {
869         list[count] = host;
870         if (!(held[count] = h_Held_r(host)))
871             h_Hold_r(host);
872     }
873     assert(count == hostCount);
874     H_UNLOCK;
875     for (i = 0; i < count; i++) {
876         held[i] = (*proc) (list[i], held[i], param);
877         if (!held[i])
878             h_Release(list[i]); /* this might free up the host */
879     }
880     free((void *)list);
881     free((void *)held);
882 }                               /*h_Enumerate */
883
884 /* h_Enumerate_r (revised):
885  * Calls (*proc)(host, held, param) for each host in hostList, starting
886  * at enumstart
887  * Hosts may be deleted (have delete flag set); ditto for clients.
888  * (*proc) is always called with
889  * host h_held() and the global host lock (H_LOCK) locked.The hold state of the
890  * host with respect to this lwp is passed to (*proc) as the param held.
891  * The proc should return 0 if the host should be released, 1 if it should
892  * be held after enumeration.
893  */
894 void
895 h_Enumerate_r(int (*proc) (), struct host *enumstart, char *param)
896 {
897     register struct host *host;
898     register int held;
899
900     if (hostCount == 0) {
901         return;
902     }
903     for (host = enumstart; host; host = host->next) {
904         if (!(held = h_Held_r(host)))
905             h_Hold_r(host);
906         held = (*proc) (host, held, param);
907         if (!held)
908             h_Release_r(host);  /* this might free up the host */
909     }
910 }                               /*h_Enumerate_r */
911
912 /* inserts a new HashChain structure corresponding to this UUID */
913 void
914 hashInsertUuid_r(struct afsUUID *uuid, struct host *host)
915 {
916     int index;
917     struct h_hashChain *chain;
918
919     /* hash into proper bucket */
920     index = h_UuidHashIndex(uuid);
921
922     /* insert into beginning of list for this bucket */
923     chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
924     if (!chain) {
925         ViceLog(0, ("Failed malloc in hashInsertUuid_r\n"));
926         assert(0);
927     }
928     assert(chain);
929     chain->hostPtr = host;
930     chain->next = hostUuidHashTable[index];
931     hostUuidHashTable[index] = chain;
932 }
933
934 /* Host is returned held */
935 struct host *
936 h_GetHost_r(struct rx_connection *tcon)
937 {
938     struct host *host;
939     struct host *oldHost;
940     int code;
941     int held;
942     struct interfaceAddr interf;
943     int interfValid = 0;
944     struct Identity *identP = NULL;
945     afs_int32 haddr;
946     afs_int32 hport;
947     char hoststr[16], hoststr2[16];
948     Capabilities caps;
949
950     caps.Capabilities_val = NULL;
951
952     haddr = rxr_HostOf(tcon);
953     hport = rxr_PortOf(tcon);
954   retry:
955     if (caps.Capabilities_val)
956         free(caps.Capabilities_val);
957     caps.Capabilities_val = NULL;
958     caps.Capabilities_len = 0;
959
960     code = 0;
961     host = h_Lookup_r(haddr, hport, &held);
962     identP = (struct Identity *)rx_GetSpecific(tcon, rxcon_ident_key);
963     if (host && !identP && !(host->Console & 1)) {
964         /* This is a new connection, and we already have a host
965          * structure for this address. Verify that the identity
966          * of the caller matches the identity in the host structure.
967          */
968         h_Lock_r(host);
969         if (!(host->hostFlags & ALTADDR)) {
970             /* Another thread is doing initialization */
971             h_Unlock_r(host);
972             if (!held)
973                 h_Release_r(host);
974             ViceLog(125,
975                     ("Host %s:%d starting h_Lookup again\n",
976                      afs_inet_ntoa_r(host->host, hoststr),
977                      ntohs(host->port)));
978             goto retry;
979         }
980         host->hostFlags &= ~ALTADDR;
981         H_UNLOCK;
982         code =
983             RXAFSCB_TellMeAboutYourself(host->callback_rxcon, &interf, &caps);
984         if (code == RXGEN_OPCODE)
985             code = RXAFSCB_WhoAreYou(host->callback_rxcon, &interf);
986         H_LOCK;
987         if (code == RXGEN_OPCODE) {
988             identP = (struct Identity *)malloc(sizeof(struct Identity));
989             if (!identP) {
990                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
991                 assert(0);
992             }
993             identP->valid = 0;
994             rx_SetSpecific(tcon, rxcon_ident_key, identP);
995             /* The host on this connection was unable to respond to 
996              * the WhoAreYou. We will treat this as a new connection
997              * from the existing host. The worst that can happen is
998              * that we maintain some extra callback state information */
999             if (host->interface) {
1000                 ViceLog(0,
1001                         ("Host %s:%d used to support WhoAreYou, deleting.\n",
1002                          afs_inet_ntoa_r(host->host, hoststr),
1003                          ntohs(host->port)));
1004                 host->hostFlags |= HOSTDELETED;
1005                 h_Unlock_r(host);
1006                 if (!held)
1007                     h_Release_r(host);
1008                 host = NULL;
1009                 goto retry;
1010             }
1011         } else if (code == 0) {
1012             interfValid = 1;
1013             identP = (struct Identity *)malloc(sizeof(struct Identity));
1014             if (!identP) {
1015                 ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1016                 assert(0);
1017             }
1018             identP->valid = 1;
1019             identP->uuid = interf.uuid;
1020             rx_SetSpecific(tcon, rxcon_ident_key, identP);
1021             /* Check whether the UUID on this connection matches
1022              * the UUID in the host structure. If they don't match
1023              * then this is not the same host as before. */
1024             if (!host->interface
1025                 || !afs_uuid_equal(&interf.uuid, &host->interface->uuid)) {
1026                 ViceLog(25,
1027                         ("Host %s:%d has changed its identity, deleting.\n",
1028                          afs_inet_ntoa_r(host->host, hoststr), host->port));
1029                 host->hostFlags |= HOSTDELETED;
1030                 h_Unlock_r(host);
1031                 if (!held)
1032                     h_Release_r(host);
1033                 host = NULL;
1034                 goto retry;
1035             }
1036         } else {
1037             afs_inet_ntoa_r(host->host, hoststr);
1038             ViceLog(0,
1039                     ("CB: WhoAreYou failed for %s:%d, error %d\n", hoststr,
1040                      ntohs(host->port), code));
1041             host->hostFlags |= VENUSDOWN;
1042         }
1043         if (caps.Capabilities_val
1044             && (caps.Capabilities_val[0] & CAPABILITY_ERRORTRANS))
1045             host->hostFlags |= HERRORTRANS;
1046         else
1047             host->hostFlags &= ~(HERRORTRANS);
1048         host->hostFlags |= ALTADDR;
1049         h_Unlock_r(host);
1050     } else if (host) {
1051         if (!(host->hostFlags & ALTADDR)) {
1052             /* another thread is doing the initialisation */
1053             ViceLog(125,
1054                     ("Host %s:%d waiting for host-init to complete\n",
1055                      afs_inet_ntoa_r(host->host, hoststr),
1056                      ntohs(host->port)));
1057             h_Lock_r(host);
1058             h_Unlock_r(host);
1059             if (!held)
1060                 h_Release_r(host);
1061             ViceLog(125,
1062                     ("Host %s:%d starting h_Lookup again\n",
1063                      afs_inet_ntoa_r(host->host, hoststr),
1064                      ntohs(host->port)));
1065             goto retry;
1066         }
1067         /* We need to check whether the identity in the host structure
1068          * matches the identity on the connection. If they don't match
1069          * then treat this a new host. */
1070         if (!(host->Console & 1)
1071             && ((!identP->valid && host->interface)
1072                 || (identP->valid && !host->interface)
1073                 || (identP->valid
1074                     && !afs_uuid_equal(&identP->uuid,
1075                                        &host->interface->uuid)))) {
1076             char uuid1[128], uuid2[128];
1077             if (identP->valid)
1078                 afsUUID_to_string(&identP->uuid, uuid1, 127);
1079             if (host->interface)
1080                 afsUUID_to_string(&host->interface->uuid, uuid2, 127);
1081             ViceLog(0,
1082                     ("CB: new identity for host %s:%d, deleting(%x %x %s %s)\n",
1083                      afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
1084                      identP->valid, host->interface,
1085                      identP->valid ? uuid1 : "",
1086                      host->interface ? uuid2 : ""));
1087
1088             /* The host in the cache is not the host for this connection */
1089             host->hostFlags |= HOSTDELETED;
1090             h_Unlock_r(host);
1091             if (!held)
1092                 h_Release_r(host);
1093             goto retry;
1094         }
1095     } else {
1096         host = h_Alloc_r(tcon); /* returned held and locked */
1097         h_gethostcps_r(host, FT_ApproxTime());
1098         if (!(host->Console & 1)) {
1099             int pident = 0;
1100             H_UNLOCK;
1101             code =
1102                 RXAFSCB_TellMeAboutYourself(host->callback_rxcon, &interf,
1103                                             &caps);
1104             if (code == RXGEN_OPCODE)
1105                 code = RXAFSCB_WhoAreYou(host->callback_rxcon, &interf);
1106             H_LOCK;
1107             if (code == RXGEN_OPCODE) {
1108                 if (!identP)
1109                     identP =
1110                         (struct Identity *)malloc(sizeof(struct Identity));
1111                 else
1112                     pident = 1;
1113
1114                 if (!identP) {
1115                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1116                     assert(0);
1117                 }
1118                 identP->valid = 0;
1119                 if (!pident)
1120                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1121                 ViceLog(25,
1122                         ("Host %s:%d does not support WhoAreYou.\n",
1123                          afs_inet_ntoa_r(host->host, hoststr),
1124                          ntohs(host->port)));
1125                 code = 0;
1126             } else if (code == 0) {
1127                 if (!identP)
1128                     identP =
1129                         (struct Identity *)malloc(sizeof(struct Identity));
1130                 else
1131                     pident = 1;
1132
1133                 if (!identP) {
1134                     ViceLog(0, ("Failed malloc in h_GetHost_r\n"));
1135                     assert(0);
1136                 }
1137                 identP->valid = 1;
1138                 interfValid = 1;
1139                 identP->uuid = interf.uuid;
1140                 if (!pident)
1141                     rx_SetSpecific(tcon, rxcon_ident_key, identP);
1142                 ViceLog(25,
1143                         ("WhoAreYou success on %s:%d\n",
1144                          afs_inet_ntoa_r(host->host, hoststr),
1145                          ntohs(host->port)));
1146             }
1147             if (code == 0 && !identP->valid) {
1148                 H_UNLOCK;
1149                 code = RXAFSCB_InitCallBackState(host->callback_rxcon);
1150                 H_LOCK;
1151             } else if (code == 0) {
1152                 oldHost = h_LookupUuid_r(&identP->uuid);
1153                 if (oldHost) {
1154                     /* This is a new address for an existing host. Update
1155                      * the list of interfaces for the existing host and
1156                      * delete the host structure we just allocated. */
1157                     if (!(held = h_Held_r(oldHost)))
1158                         h_Hold_r(oldHost);
1159                     h_Lock_r(oldHost);
1160                     ViceLog(25,
1161                             ("CB: new addr %s:%d for old host %s:%d\n",
1162                              afs_inet_ntoa_r(host->host, hoststr),
1163                              ntohs(host->port), afs_inet_ntoa_r(oldHost->host,
1164                                                                 hoststr2),
1165                              ntohs(oldHost->port)));
1166                     host->hostFlags |= HOSTDELETED;
1167                     h_Unlock_r(host);
1168                     h_Release_r(host);
1169                     host = oldHost;
1170                     addInterfaceAddr_r(host, haddr);
1171                 } else {
1172                     /* This really is a new host */
1173                     hashInsertUuid_r(&identP->uuid, host);
1174                     H_UNLOCK;
1175                     code =
1176                         RXAFSCB_InitCallBackState3(host->callback_rxcon,
1177                                                    &FS_HostUUID);
1178                     H_LOCK;
1179                     if (code == 0) {
1180                         ViceLog(25,
1181                                 ("InitCallBackState3 success on %s:%d\n",
1182                                  afs_inet_ntoa_r(host->host, hoststr),
1183                                  ntohs(host->port)));
1184                         assert(interfValid == 1);
1185                         initInterfaceAddr_r(host, &interf);
1186                     }
1187                 }
1188             }
1189             if (code) {
1190                 afs_inet_ntoa_r(host->host, hoststr);
1191                 ViceLog(0,
1192                         ("CB: RCallBackConnectBack failed for %s:%d\n",
1193                          hoststr, ntohs(host->port)));
1194                 host->hostFlags |= VENUSDOWN;
1195             } else
1196                 host->hostFlags |= RESETDONE;
1197
1198         }
1199         if (caps.Capabilities_val
1200             && (caps.Capabilities_val[0] & CAPABILITY_ERRORTRANS))
1201             host->hostFlags |= HERRORTRANS;
1202         else
1203             host->hostFlags &= ~(HERRORTRANS);
1204         host->hostFlags |= ALTADDR;     /* host structure iniatilisation complete */
1205         h_Unlock_r(host);
1206     }
1207     if (caps.Capabilities_val)
1208         free(caps.Capabilities_val);
1209     caps.Capabilities_val = NULL;
1210     caps.Capabilities_len = 0;
1211     return host;
1212
1213 }                               /*h_GetHost_r */
1214
1215
1216 static char localcellname[PR_MAXNAMELEN + 1];
1217 char local_realm[AFS_REALM_SZ] = "";
1218
1219 /* not reentrant */
1220 void
1221 h_InitHostPackage()
1222 {
1223     afsconf_GetLocalCell(confDir, localcellname, PR_MAXNAMELEN);
1224     if (!local_realm[0]) {
1225         if (afs_krb_get_lrealm(local_realm, 0) != 0 /*KSUCCESS*/) {
1226             ViceLog(0,
1227                     ("afs_krb_get_lrealm failed, using %s.\n",
1228                      localcellname));
1229             strcpy(local_realm, localcellname);
1230         }
1231     }
1232     rxcon_ident_key = rx_KeyCreate((rx_destructor_t) free);
1233     rxcon_client_key = rx_KeyCreate((rx_destructor_t) 0);
1234 #ifdef AFS_PTHREAD_ENV
1235     assert(pthread_mutex_init(&host_glock_mutex, NULL) == 0);
1236 #endif /* AFS_PTHREAD_ENV */
1237 }
1238
1239 static int
1240 MapName_r(char *aname, char *acell, afs_int32 * aval)
1241 {
1242     namelist lnames;
1243     idlist lids;
1244     afs_int32 code;
1245     afs_int32 anamelen, cnamelen;
1246     int foreign = 0;
1247     char *tname;
1248
1249     anamelen = strlen(aname);
1250     if (anamelen >= PR_MAXNAMELEN)
1251         return -1;              /* bad name -- caller interprets this as anonymous, but retries later */
1252
1253     lnames.namelist_len = 1;
1254     lnames.namelist_val = (prname *) aname;     /* don't malloc in the common case */
1255     lids.idlist_len = 0;
1256     lids.idlist_val = NULL;
1257
1258     cnamelen = strlen(acell);
1259     if (cnamelen) {
1260         if (strcasecmp(local_realm, acell)
1261             && strcasecmp(localcellname, acell)) {
1262             ViceLog(2,
1263                     ("MapName: cell is foreign.  cell=%s, localcell=%s, localrealm=%s\n",
1264                      acell, localcellname, local_realm));
1265             if ((anamelen + cnamelen + 1) >= PR_MAXNAMELEN) {
1266                 ViceLog(2,
1267                         ("MapName: Name too long, using AnonymousID for %s@%s\n",
1268                          aname, acell));
1269                 *aval = AnonymousID;
1270                 return 0;
1271             }
1272             foreign = 1;        /* attempt cross-cell authentication */
1273             tname = (char *)malloc(PR_MAXNAMELEN);
1274             if (!tname) {
1275                 ViceLog(0, ("Failed malloc in MapName_r\n"));
1276                 assert(0);
1277             }
1278             strcpy(tname, aname);
1279             tname[anamelen] = '@';
1280             strcpy(tname + anamelen + 1, acell);
1281             lnames.namelist_val = (prname *) tname;
1282         }
1283     }
1284
1285     H_UNLOCK;
1286     code = pr_NameToId(&lnames, &lids);
1287     H_LOCK;
1288     if (code == 0) {
1289         if (lids.idlist_val) {
1290             *aval = lids.idlist_val[0];
1291             if (*aval == AnonymousID) {
1292                 ViceLog(2,
1293                         ("MapName: NameToId on %s returns anonymousID\n",
1294                          lnames.namelist_val));
1295             }
1296             free(lids.idlist_val);      /* return parms are not malloced in stub if server proc aborts */
1297         } else {
1298             ViceLog(0,
1299                     ("MapName: NameToId on '%s' is unknown\n",
1300                      lnames.namelist_val));
1301             code = -1;
1302         }
1303     }
1304
1305     if (foreign) {
1306         free(lnames.namelist_val);      /* We allocated this above, so we must free it now. */
1307     }
1308     return code;
1309 }
1310
1311 /*MapName*/
1312
1313
1314 /* NOTE: this returns the client with a Shared lock */
1315 struct client *
1316 h_ID2Client(afs_int32 vid)
1317 {
1318     register struct client *client;
1319     register struct host *host;
1320
1321     H_LOCK;
1322     for (host = hostList; host; host = host->next) {
1323         if (host->hostFlags & HOSTDELETED)
1324             continue;
1325         for (client = host->FirstClient; client; client = client->next) {
1326             if (!client->deleted && client->ViceId == vid) {
1327                 client->refCount++;
1328                 H_UNLOCK;
1329                 ObtainSharedLock(&client->lock);
1330                 H_LOCK;
1331                 client->refCount--;
1332                 H_UNLOCK;
1333                 return client;
1334             }
1335         }
1336     }
1337
1338     H_UNLOCK;
1339     return 0;
1340 }
1341
1342 /*
1343  * Called by the server main loop.  Returns a h_Held client, which must be
1344  * released later the main loop.  Allocates a client if the matching one
1345  * isn't around. The client is returned with its reference count incremented
1346  * by one. The caller must call h_ReleaseClient_r when finished with
1347  * the client.
1348  */
1349 struct client *
1350 h_FindClient_r(struct rx_connection *tcon)
1351 {
1352     register struct client *client;
1353     register struct host *host;
1354     struct client *oldClient;
1355     afs_int32 viceid;
1356     afs_int32 expTime;
1357     afs_int32 code;
1358     int authClass;
1359 #if (64-MAXKTCNAMELEN)
1360     ticket name length != 64
1361 #endif
1362     char tname[64];
1363     char tinst[64];
1364     char uname[PR_MAXNAMELEN];
1365     char tcell[MAXKTCREALMLEN];
1366     int fail = 0;
1367
1368     client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1369     if (client && !client->deleted) {
1370         client->refCount++;
1371         h_Hold_r(client->host);
1372         if (client->prfail != 2) {      /* Could add shared lock on client here */
1373             /* note that we don't have to lock entry in this path to
1374              * ensure CPS is initialized, since we don't call rx_SetSpecific
1375              * until initialization is done, and we only get here if
1376              * rx_GetSpecific located the client structure.
1377              */
1378             return client;
1379         }
1380         H_UNLOCK;
1381         ObtainWriteLock(&client->lock); /* released at end */
1382         H_LOCK;
1383     } else if (client) {
1384         client->refCount++;
1385     }
1386
1387     authClass = rx_SecurityClassOf((struct rx_connection *)tcon);
1388     ViceLog(5,
1389             ("FindClient: authenticating connection: authClass=%d\n",
1390              authClass));
1391     if (authClass == 1) {
1392         /* A bcrypt tickets, no longer supported */
1393         ViceLog(1, ("FindClient: bcrypt ticket, using AnonymousID\n"));
1394         viceid = AnonymousID;
1395         expTime = 0x7fffffff;
1396     } else if (authClass == 2) {
1397         afs_int32 kvno;
1398
1399         /* kerberos ticket */
1400         code = rxkad_GetServerInfo(tcon, /*level */ 0, &expTime,
1401                                    tname, tinst, tcell, &kvno);
1402         if (code) {
1403             ViceLog(1, ("Failed to get rxkad ticket info\n"));
1404             viceid = AnonymousID;
1405             expTime = 0x7fffffff;
1406         } else {
1407             int ilen = strlen(tinst);
1408             ViceLog(5,
1409                     ("FindClient: rxkad conn: name=%s,inst=%s,cell=%s,exp=%d,kvno=%d\n",
1410                      tname, tinst, tcell, expTime, kvno));
1411             strncpy(uname, tname, sizeof(uname));
1412             if (ilen) {
1413                 if (strlen(uname) + 1 + ilen >= sizeof(uname))
1414                     goto bad_name;
1415                 strcat(uname, ".");
1416                 strcat(uname, tinst);
1417             }
1418             /* translate the name to a vice id */
1419             code = MapName_r(uname, tcell, &viceid);
1420             if (code) {
1421               bad_name:
1422                 ViceLog(1,
1423                         ("failed to map name=%s, cell=%s -> code=%d\n", uname,
1424                          tcell, code));
1425                 fail = 1;
1426                 viceid = AnonymousID;
1427                 expTime = 0x7fffffff;
1428             }
1429         }
1430     } else {
1431         viceid = AnonymousID;   /* unknown security class */
1432         expTime = 0x7fffffff;
1433     }
1434
1435     if (!client) {
1436         host = h_GetHost_r(tcon);       /* Returns it h_Held */
1437
1438         /* First try to find the client structure */
1439         for (client = host->FirstClient; client; client = client->next) {
1440             if (!client->deleted && (client->sid == rxr_CidOf(tcon))
1441                 && (client->VenusEpoch == rxr_GetEpoch(tcon))) {
1442                 if (client->tcon && (client->tcon != tcon)) {
1443                     ViceLog(0,
1444                             ("*** Vid=%d, sid=%x, tcon=%x, Tcon=%x ***\n",
1445                              client->ViceId, client->sid, client->tcon,
1446                              tcon));
1447                     oldClient =
1448                         (struct client *)rx_GetSpecific(client->tcon,
1449                                                         rxcon_client_key);
1450                     if (oldClient) {
1451                         if (oldClient == client)
1452                             rx_SetSpecific(client->tcon, rxcon_client_key,
1453                                            NULL);
1454                         else
1455                             ViceLog(0,
1456                                     ("Client-conn mismatch: CL1=%x, CN=%x, CL2=%x\n",
1457                                      client, client->tcon, oldClient));
1458                     }
1459                     client->tcon = (struct rx_connection *)0;
1460                 }
1461                 client->refCount++;
1462                 H_UNLOCK;
1463                 ObtainWriteLock(&client->lock);
1464                 H_LOCK;
1465                 break;
1466             }
1467         }
1468
1469         /* Still no client structure - get one */
1470         if (!client) {
1471             client = GetCE();
1472             ObtainWriteLock(&client->lock);
1473             client->refCount = 1;
1474             client->host = host;
1475             client->next = host->FirstClient;
1476             host->FirstClient = client;
1477 #if FS_STATS_DETAILED
1478             client->InSameNetwork = host->InSameNetwork;
1479 #endif /* FS_STATS_DETAILED */
1480             client->ViceId = viceid;
1481             client->expTime = expTime;  /* rx only */
1482             client->authClass = authClass;      /* rx only */
1483             client->sid = rxr_CidOf(tcon);
1484             client->VenusEpoch = rxr_GetEpoch(tcon);
1485             client->CPS.prlist_val = 0;
1486             client->CPS.prlist_len = 0;
1487             CurrentConnections++;       /* increment number of connections */
1488         }
1489     }
1490     client->prfail = fail;
1491
1492     if (!(client->CPS.prlist_val) || (viceid != client->ViceId)) {
1493         if (client->CPS.prlist_val && (client->ViceId != ANONYMOUSID)) {
1494             free(client->CPS.prlist_val);
1495         }
1496         client->CPS.prlist_val = NULL;
1497         client->CPS.prlist_len = 0;
1498         client->ViceId = viceid;
1499         client->expTime = expTime;
1500
1501         if (viceid == ANONYMOUSID) {
1502             client->CPS.prlist_len = AnonCPS.prlist_len;
1503             client->CPS.prlist_val = AnonCPS.prlist_val;
1504         } else {
1505             H_UNLOCK;
1506             code = pr_GetCPS(viceid, &client->CPS);
1507             H_LOCK;
1508             if (code) {
1509                 char hoststr[16];
1510                 ViceLog(0,
1511                         ("pr_GetCPS failed(%d) for user %d, host %s:%d\n",
1512                          code, viceid, afs_inet_ntoa_r(client->host->host,
1513                                                        hoststr),
1514                          ntohs(client->host->port)));
1515
1516                 /* Although ubik_Call (called by pr_GetCPS) traverses thru
1517                  * all protection servers and reevaluates things if no
1518                  * sync server or quorum is found we could still end up
1519                  * with one of these errors. In such case we would like to
1520                  * reevaluate the rpc call to find if there's cps for this
1521                  * guy. We treat other errors (except network failures
1522                  * ones - i.e. code < 0) as an indication that there is no
1523                  * CPS for this host.  Ideally we could like to deal this
1524                  * problem the other way around (i.e.  if code == NOCPS
1525                  * ignore else retry next time) but the problem is that
1526                  * there're other errors (i.e.  EPERM) for which we don't
1527                  * want to retry and we don't know the whole code list!
1528                  */
1529                 if (code < 0 || code == UNOQUORUM || code == UNOTSYNC)
1530                     client->prfail = 1;
1531             }
1532         }
1533         /* the disabling of system:administrators is so iffy and has so many
1534          * possible failure modes that we will disable it again */
1535         /* Turn off System:Administrator for safety  
1536          * if (AL_IsAMember(SystemId, client->CPS) == 0)
1537          * assert(AL_DisableGroup(SystemId, client->CPS) == 0); */
1538     }
1539
1540     /* Now, tcon may already be set to a rock, since we blocked with no host
1541      * or client locks set above in pr_GetCPS (XXXX some locking is probably
1542      * required).  So, before setting the RPC's rock, we should disconnect
1543      * the RPC from the other client structure's rock.
1544      */
1545     oldClient = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1546     if (oldClient && oldClient->tcon == tcon) {
1547         oldClient->tcon = (struct rx_connection *)0;
1548         /* rx_SetSpecific will be done immediately below */
1549     }
1550     client->tcon = tcon;
1551     rx_SetSpecific(tcon, rxcon_client_key, client);
1552     ReleaseWriteLock(&client->lock);
1553
1554     return client;
1555
1556 }                               /*h_FindClient_r */
1557
1558 int
1559 h_ReleaseClient_r(struct client *client)
1560 {
1561     assert(client->refCount > 0);
1562     client->refCount--;
1563     return 0;
1564 }
1565
1566
1567 /*
1568  * Sigh:  this one is used to get the client AGAIN within the individual
1569  * server routines.  This does not bother h_Holding the host, since
1570  * this is assumed already have been done by the server main loop.
1571  * It does check tokens, since only the server routines can return the
1572  * VICETOKENDEAD error code
1573  */
1574 int
1575 GetClient(struct rx_connection *tcon, struct client **cp)
1576 {
1577     register struct client *client;
1578
1579     H_LOCK;
1580     *cp = client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
1581     if (client == NULL || client->tcon == NULL) {
1582         ViceLog(0,
1583                 ("GetClient: no client in conn %x (host %x), VBUSYING\n",
1584                  tcon, rx_HostOf(rx_PeerOf(tcon))));
1585         H_UNLOCK;
1586         return VBUSY;
1587     }
1588     if (rxr_CidOf(client->tcon) != client->sid) {
1589         ViceLog(0,
1590                 ("GetClient: tcon %x tcon sid %d client sid %d\n",
1591                  client->tcon, rxr_CidOf(client->tcon), client->sid));
1592         H_UNLOCK;
1593         return VBUSY;
1594     }
1595     if (!(client && client->tcon && rxr_CidOf(client->tcon) == client->sid)) {
1596         if (!client)
1597             ViceLog(0, ("GetClient: no client in conn %x\n", tcon));
1598         else
1599             ViceLog(0,
1600                     ("GetClient: tcon %x tcon sid %d client sid %d\n",
1601                      client->tcon, client->tcon ? rxr_CidOf(client->tcon)
1602                      : -1, client->sid));
1603         assert(0);
1604     }
1605     if (client && client->LastCall > client->expTime && client->expTime) {
1606         char hoststr[16];
1607         ViceLog(1,
1608                 ("Token for %s at %s:%d expired %d\n", h_UserName(client),
1609                  afs_inet_ntoa_r(client->host->host, hoststr),
1610                  ntohs(client->host->port), client->expTime));
1611         H_UNLOCK;
1612         return VICETOKENDEAD;
1613     }
1614
1615     H_UNLOCK;
1616     return 0;
1617
1618 }                               /*GetClient */
1619
1620
1621 /* Client user name for short term use.  Note that this is NOT inexpensive */
1622 char *
1623 h_UserName(struct client *client)
1624 {
1625     static char User[PR_MAXNAMELEN + 1];
1626     namelist lnames;
1627     idlist lids;
1628
1629     lids.idlist_len = 1;
1630     lids.idlist_val = (afs_int32 *) malloc(1 * sizeof(afs_int32));
1631     if (!lids.idlist_val) {
1632         ViceLog(0, ("Failed malloc in h_UserName\n"));
1633         assert(0);
1634     }
1635     lnames.namelist_len = 0;
1636     lnames.namelist_val = (prname *) 0;
1637     lids.idlist_val[0] = client->ViceId;
1638     if (pr_IdToName(&lids, &lnames)) {
1639         /* We need to free id we alloced above! */
1640         free(lids.idlist_val);
1641         return "*UNKNOWN USER NAME*";
1642     }
1643     strncpy(User, lnames.namelist_val[0], PR_MAXNAMELEN);
1644     free(lids.idlist_val);
1645     free(lnames.namelist_val);
1646     return User;
1647
1648 }                               /*h_UserName */
1649
1650
1651 void
1652 h_PrintStats()
1653 {
1654     ViceLog(0,
1655             ("Total Client entries = %d, blocks = %d; Host entries = %d, blocks = %d\n",
1656              CEs, CEBlocks, HTs, HTBlocks));
1657
1658 }                               /*h_PrintStats */
1659
1660
1661 static int
1662 h_PrintClient(register struct host *host, int held, StreamHandle_t * file)
1663 {
1664     register struct client *client;
1665     int i;
1666     char tmpStr[256];
1667     char tbuffer[32];
1668     char hoststr[16];
1669
1670     H_LOCK;
1671     if (host->hostFlags & HOSTDELETED) {
1672         H_UNLOCK;
1673         return held;
1674     }
1675     (void)afs_snprintf(tmpStr, sizeof tmpStr,
1676                        "Host %s:%d down = %d, LastCall %s",
1677                        afs_inet_ntoa_r(host->host, hoststr),
1678                        ntohs(host->port), (host->hostFlags & VENUSDOWN),
1679                        afs_ctime((time_t *) & host->LastCall, tbuffer,
1680                                  sizeof(tbuffer)));
1681     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1682     for (client = host->FirstClient; client; client = client->next) {
1683         if (!client->deleted) {
1684             if (client->tcon) {
1685                 (void)afs_snprintf(tmpStr, sizeof tmpStr,
1686                                    "    user id=%d,  name=%s, sl=%s till %s",
1687                                    client->ViceId, h_UserName(client),
1688                                    client->
1689                                    authClass ? "Authenticated" :
1690                                    "Not authenticated",
1691                                    client->
1692                                    authClass ? afs_ctime((time_t *) & client->
1693                                                          expTime, tbuffer,
1694                                                          sizeof(tbuffer))
1695                                    : "No Limit\n");
1696                 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1697             } else {
1698                 (void)afs_snprintf(tmpStr, sizeof tmpStr,
1699                                    "    user=%s, no current server connection\n",
1700                                    h_UserName(client));
1701                 (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1702             }
1703             (void)afs_snprintf(tmpStr, sizeof tmpStr, "      CPS-%d is [",
1704                                client->CPS.prlist_len);
1705             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1706             if (client->CPS.prlist_val) {
1707                 for (i = 0; i > client->CPS.prlist_len; i++) {
1708                     (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
1709                                        client->CPS.prlist_val[i]);
1710                     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1711                 }
1712             }
1713             sprintf(tmpStr, "]\n");
1714             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1715         }
1716     }
1717     H_UNLOCK;
1718     return held;
1719
1720 }                               /*h_PrintClient */
1721
1722
1723
1724 /*
1725  * Print a list of clients, with last security level and token value seen,
1726  * if known
1727  */
1728 void
1729 h_PrintClients()
1730 {
1731     time_t now;
1732     char tmpStr[256];
1733     char tbuffer[32];
1734
1735     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_CLNTDUMP_FILEPATH, "w");
1736
1737     if (file == NULL) {
1738         ViceLog(0,
1739                 ("Couldn't create client dump file %s\n",
1740                  AFSDIR_SERVER_CLNTDUMP_FILEPATH));
1741         return;
1742     }
1743     now = FT_ApproxTime();
1744     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active users at %s\n",
1745                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
1746     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1747     h_Enumerate(h_PrintClient, (char *)file);
1748     STREAM_REALLYCLOSE(file);
1749     ViceLog(0, ("Created client dump %s\n", AFSDIR_SERVER_CLNTDUMP_FILEPATH));
1750 }
1751
1752
1753
1754
1755 static int
1756 h_DumpHost(register struct host *host, int held, StreamHandle_t * file)
1757 {
1758     int i;
1759     char tmpStr[256];
1760
1761     H_LOCK;
1762     (void)afs_snprintf(tmpStr, sizeof tmpStr,
1763                        "ip:%x port:%d hidx:%d cbid:%d lock:%x last:%u active:%u down:%d del:%d cons:%d cldel:%d\n\t hpfailed:%d hcpsCall:%u hcps [",
1764                        host->host, ntohs(host->port), host->index,
1765                        host->cblist, CheckLock(&host->lock), host->LastCall,
1766                        host->ActiveCall, (host->hostFlags & VENUSDOWN),
1767                        host->hostFlags & HOSTDELETED, host->Console,
1768                        host->hostFlags & CLIENTDELETED, host->hcpsfailed,
1769                        host->cpsCall);
1770     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1771     if (host->hcps.prlist_val)
1772         for (i = 0; i < host->hcps.prlist_len; i++) {
1773             (void)afs_snprintf(tmpStr, sizeof tmpStr, " %d",
1774                                host->hcps.prlist_val[i]);
1775             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1776         }
1777     sprintf(tmpStr, "] [");
1778     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1779     if (host->interface)
1780         for (i = 0; i < host->interface->numberOfInterfaces; i++) {
1781             sprintf(tmpStr, " %x", host->interface->addr[i]);
1782             (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1783         }
1784     sprintf(tmpStr, "] holds: ");
1785     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1786
1787     for (i = 0; i < h_maxSlots; i++) {
1788         sprintf(tmpStr, "%04x", host->holds[i]);
1789         (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1790     }
1791     sprintf(tmpStr, " slot/bit: %d/%d\n", h_holdSlot(), h_holdbit());
1792     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1793
1794     H_UNLOCK;
1795     return held;
1796
1797 }                               /*h_DumpHost */
1798
1799
1800 void
1801 h_DumpHosts()
1802 {
1803     time_t now;
1804     StreamHandle_t *file = STREAM_OPEN(AFSDIR_SERVER_HOSTDUMP_FILEPATH, "w");
1805     char tmpStr[256];
1806     char tbuffer[32];
1807
1808     if (file == NULL) {
1809         ViceLog(0,
1810                 ("Couldn't create host dump file %s\n",
1811                  AFSDIR_SERVER_HOSTDUMP_FILEPATH));
1812         return;
1813     }
1814     now = FT_ApproxTime();
1815     (void)afs_snprintf(tmpStr, sizeof tmpStr, "List of active hosts at %s\n",
1816                        afs_ctime(&now, tbuffer, sizeof(tbuffer)));
1817     (void)STREAM_WRITE(tmpStr, strlen(tmpStr), 1, file);
1818     h_Enumerate(h_DumpHost, (char *)file);
1819     STREAM_REALLYCLOSE(file);
1820     ViceLog(0, ("Created host dump %s\n", AFSDIR_SERVER_HOSTDUMP_FILEPATH));
1821
1822 }                               /*h_DumpHosts */
1823
1824
1825 /*
1826  * This counts the number of workstations, the number of active workstations,
1827  * and the number of workstations declared "down" (i.e. not heard from
1828  * recently).  An active workstation has received a call since the cutoff
1829  * time argument passed.
1830  */
1831 void
1832 h_GetWorkStats(int *nump, int *activep, int *delp, afs_int32 cutofftime)
1833 {
1834     register struct host *host;
1835     register int num = 0, active = 0, del = 0;
1836
1837     H_LOCK;
1838     for (host = hostList; host; host = host->next) {
1839         if (!(host->hostFlags & HOSTDELETED)) {
1840             num++;
1841             if (host->ActiveCall > cutofftime)
1842                 active++;
1843             if (host->hostFlags & VENUSDOWN)
1844                 del++;
1845         }
1846     }
1847     H_UNLOCK;
1848     if (nump)
1849         *nump = num;
1850     if (activep)
1851         *activep = active;
1852     if (delp)
1853         *delp = del;
1854
1855 }                               /*h_GetWorkStats */
1856
1857
1858 /*------------------------------------------------------------------------
1859  * PRIVATE h_ClassifyAddress
1860  *
1861  * Description:
1862  *      Given a target IP address and a candidate IP address (both
1863  *      in host byte order), classify the candidate into one of three
1864  *      buckets in relation to the target by bumping the counters passed
1865  *      in as parameters.
1866  *
1867  * Arguments:
1868  *      a_targetAddr       : Target address.
1869  *      a_candAddr         : Candidate address.
1870  *      a_sameNetOrSubnetP : Ptr to counter to bump when the two
1871  *                           addresses are either in the same network
1872  *                           or the same subnet.
1873  *      a_diffSubnetP      : ...when the candidate is in a different
1874  *                           subnet.
1875  *      a_diffNetworkP     : ...when the candidate is in a different
1876  *                           network.
1877  *
1878  * Returns:
1879  *      Nothing.
1880  *
1881  * Environment:
1882  *      The target and candidate addresses are both in host byte
1883  *      order, NOT network byte order, when passed in.
1884  *
1885  * Side Effects:
1886  *      As advertised.
1887  *------------------------------------------------------------------------*/
1888
1889 static void
1890 h_ClassifyAddress(afs_uint32 a_targetAddr, afs_uint32 a_candAddr,
1891                   afs_int32 * a_sameNetOrSubnetP, afs_int32 * a_diffSubnetP,
1892                   afs_int32 * a_diffNetworkP)
1893 {                               /*h_ClassifyAddress */
1894
1895     afs_uint32 targetNet;
1896     afs_uint32 targetSubnet;
1897     afs_uint32 candNet;
1898     afs_uint32 candSubnet;
1899
1900     /*
1901      * Put bad values into the subnet info to start with.
1902      */
1903     targetSubnet = (afs_uint32) 0;
1904     candSubnet = (afs_uint32) 0;
1905
1906     /*
1907      * Pull out the network and subnetwork numbers from the target
1908      * and candidate addresses.  We can short-circuit this whole
1909      * affair if the target and candidate addresses are not of the
1910      * same class.
1911      */
1912     if (IN_CLASSA(a_targetAddr)) {
1913         if (!(IN_CLASSA(a_candAddr))) {
1914             (*a_diffNetworkP)++;
1915             return;
1916         }
1917         targetNet = a_targetAddr & IN_CLASSA_NET;
1918         candNet = a_candAddr & IN_CLASSA_NET;
1919         if (IN_SUBNETA(a_targetAddr))
1920             targetSubnet = a_targetAddr & IN_CLASSA_SUBNET;
1921         if (IN_SUBNETA(a_candAddr))
1922             candSubnet = a_candAddr & IN_CLASSA_SUBNET;
1923     } else if (IN_CLASSB(a_targetAddr)) {
1924         if (!(IN_CLASSB(a_candAddr))) {
1925             (*a_diffNetworkP)++;
1926             return;
1927         }
1928         targetNet = a_targetAddr & IN_CLASSB_NET;
1929         candNet = a_candAddr & IN_CLASSB_NET;
1930         if (IN_SUBNETB(a_targetAddr))
1931             targetSubnet = a_targetAddr & IN_CLASSB_SUBNET;
1932         if (IN_SUBNETB(a_candAddr))
1933             candSubnet = a_candAddr & IN_CLASSB_SUBNET;
1934     } /*Class B target */
1935     else if (IN_CLASSC(a_targetAddr)) {
1936         if (!(IN_CLASSC(a_candAddr))) {
1937             (*a_diffNetworkP)++;
1938             return;
1939         }
1940         targetNet = a_targetAddr & IN_CLASSC_NET;
1941         candNet = a_candAddr & IN_CLASSC_NET;
1942
1943         /*
1944          * Note that class C addresses can't have subnets,
1945          * so we leave the defaults untouched.
1946          */
1947     } /*Class C target */
1948     else {
1949         targetNet = a_targetAddr;
1950         candNet = a_candAddr;
1951     }                           /*Class D address */
1952
1953     /*
1954      * Now, simply compare the extracted net and subnet values for
1955      * the two addresses (which at this point are known to be of the
1956      * same class)
1957      */
1958     if (targetNet == candNet) {
1959         if (targetSubnet == candSubnet)
1960             (*a_sameNetOrSubnetP)++;
1961         else
1962             (*a_diffSubnetP)++;
1963     } else
1964         (*a_diffNetworkP)++;
1965
1966 }                               /*h_ClassifyAddress */
1967
1968
1969 /*------------------------------------------------------------------------
1970  * EXPORTED h_GetHostNetStats
1971  *
1972  * Description:
1973  *      Iterate through the host table, and classify each (non-deleted)
1974  *      host entry into ``proximity'' categories (same net or subnet,
1975  *      different subnet, different network).
1976  *
1977  * Arguments:
1978  *      a_numHostsP        : Set to total number of (non-deleted) hosts.
1979  *      a_sameNetOrSubnetP : Set to # hosts on same net/subnet as server.
1980  *      a_diffSubnetP      : Set to # hosts on diff subnet as server.
1981  *      a_diffNetworkP     : Set to # hosts on diff network as server.
1982  *
1983  * Returns:
1984  *      Nothing.
1985  *
1986  * Environment:
1987  *      We only count non-deleted hosts.  The storage pointed to by our
1988  *      parameters is zeroed upon entry.
1989  *
1990  * Side Effects:
1991  *      As advertised.
1992  *------------------------------------------------------------------------*/
1993
1994 void
1995 h_GetHostNetStats(afs_int32 * a_numHostsP, afs_int32 * a_sameNetOrSubnetP,
1996                   afs_int32 * a_diffSubnetP, afs_int32 * a_diffNetworkP)
1997 {                               /*h_GetHostNetStats */
1998
1999     register struct host *hostP;        /*Ptr to current host entry */
2000     register afs_uint32 currAddr_HBO;   /*Curr host addr, host byte order */
2001
2002     /*
2003      * Clear out the storage pointed to by our parameters.
2004      */
2005     *a_numHostsP = (afs_int32) 0;
2006     *a_sameNetOrSubnetP = (afs_int32) 0;
2007     *a_diffSubnetP = (afs_int32) 0;
2008     *a_diffNetworkP = (afs_int32) 0;
2009
2010     H_LOCK;
2011     for (hostP = hostList; hostP; hostP = hostP->next) {
2012         if (!(hostP->hostFlags & HOSTDELETED)) {
2013             /*
2014              * Bump the number of undeleted host entries found.
2015              * In classifying the current entry's address, make
2016              * sure to first convert to host byte order.
2017              */
2018             (*a_numHostsP)++;
2019             currAddr_HBO = (afs_uint32) ntohl(hostP->host);
2020             h_ClassifyAddress(FS_HostAddr_HBO, currAddr_HBO,
2021                               a_sameNetOrSubnetP, a_diffSubnetP,
2022                               a_diffNetworkP);
2023         }                       /*Only look at non-deleted hosts */
2024     }                           /*For each host record hashed to this index */
2025     H_UNLOCK;
2026 }                               /*h_GetHostNetStats */
2027
2028 static afs_uint32 checktime;
2029 static afs_uint32 clientdeletetime;
2030 static struct AFSFid zerofid;
2031
2032
2033 /*
2034  * XXXX: This routine could use Multi-Rx to avoid serializing the timeouts.
2035  * Since it can serialize them, and pile up, it should be a separate LWP
2036  * from other events.
2037  */
2038 int
2039 CheckHost(register struct host *host, int held)
2040 {
2041     register struct client *client;
2042     int code;
2043
2044     /* Host is held by h_Enumerate */
2045     H_LOCK;
2046     for (client = host->FirstClient; client; client = client->next) {
2047         if (client->refCount == 0 && client->LastCall < clientdeletetime) {
2048             client->deleted = 1;
2049             host->hostFlags |= CLIENTDELETED;
2050         }
2051     }
2052     if (host->LastCall < checktime) {
2053         h_Lock_r(host);
2054         if (!(host->hostFlags & HOSTDELETED)) {
2055             if (host->LastCall < clientdeletetime) {
2056                 host->hostFlags |= HOSTDELETED;
2057                 if (!(host->hostFlags & VENUSDOWN)) {
2058                     host->hostFlags &= ~ALTADDR;        /* alternate address invalid */
2059                     if (host->interface) {
2060                         H_UNLOCK;
2061                         code =
2062                             RXAFSCB_InitCallBackState3(host->callback_rxcon,
2063                                                        &FS_HostUUID);
2064                         H_LOCK;
2065                     } else {
2066                         H_UNLOCK;
2067                         code =
2068                             RXAFSCB_InitCallBackState(host->callback_rxcon);
2069                         H_LOCK;
2070                     }
2071                     host->hostFlags |= ALTADDR; /* alternate addresses valid */
2072                     if (code) {
2073                         char hoststr[16];
2074                         (void)afs_inet_ntoa_r(host->host, hoststr);
2075                         ViceLog(0,
2076                                 ("CB: RCallBackConnectBack (host.c) failed for host %s:%d\n",
2077                                  hoststr, ntohs(host->port)));
2078                         host->hostFlags |= VENUSDOWN;
2079                     }
2080                     /* Note:  it's safe to delete hosts even if they have call
2081                      * back state, because break delayed callbacks (called when a
2082                      * message is received from the workstation) will always send a 
2083                      * break all call backs to the workstation if there is no
2084                      *callback.
2085                      */
2086                 }
2087             } else {
2088                 if (!(host->hostFlags & VENUSDOWN) && host->cblist) {
2089                     if (host->interface) {
2090                         afsUUID uuid = host->interface->uuid;
2091                         H_UNLOCK;
2092                         code = RXAFSCB_ProbeUuid(host->callback_rxcon, &uuid);
2093                         H_LOCK;
2094                         if (code) {
2095                             if (MultiProbeAlternateAddress_r(host)) {
2096                                 char hoststr[16];
2097                                 (void)afs_inet_ntoa_r(host->host, hoststr);
2098                                 ViceLog(0,
2099                                         ("ProbeUuid failed for host %s:%d\n",
2100                                          hoststr, ntohs(host->port)));
2101                                 host->hostFlags |= VENUSDOWN;
2102                             }
2103                         }
2104                     } else {
2105                         H_UNLOCK;
2106                         code = RXAFSCB_Probe(host->callback_rxcon);
2107                         H_LOCK;
2108                         if (code) {
2109                             char hoststr[16];
2110                             (void)afs_inet_ntoa_r(host->host, hoststr);
2111                             ViceLog(0,
2112                                     ("Probe failed for host %s:%d\n", hoststr,
2113                                      ntohs(host->port)));
2114                             host->hostFlags |= VENUSDOWN;
2115                         }
2116                     }
2117                 }
2118             }
2119         }
2120         h_Unlock_r(host);
2121     }
2122     H_UNLOCK;
2123     return held;
2124
2125 }                               /*CheckHost */
2126
2127
2128 /*
2129  * Set VenusDown for any hosts that have not had a call in 15 minutes and
2130  * don't respond to a probe.  Note that VenusDown can only be cleared if
2131  * a message is received from the host (see ServerLWP in file.c).
2132  * Delete hosts that have not had any calls in 1 hour, clients that
2133  * have not had any calls in 15 minutes.
2134  *
2135  * This routine is called roughly every 5 minutes.
2136  */
2137 void
2138 h_CheckHosts()
2139 {
2140     afs_uint32 now = FT_ApproxTime();
2141
2142     memset((char *)&zerofid, 0, sizeof(zerofid));
2143     /*
2144      * Send a probe to the workstation if it hasn't been heard from in
2145      * 15 minutes
2146      */
2147     checktime = now - 15 * 60;
2148     clientdeletetime = now - 120 * 60;  /* 2 hours ago */
2149     h_Enumerate(CheckHost, NULL);
2150
2151 }                               /*h_CheckHosts */
2152
2153 /*
2154  * This is called with host locked and held. At this point, the
2155  * hostHashTable should not be having entries for the alternate
2156  * interfaces. This function has to insert these entries in the
2157  * hostHashTable.
2158  *
2159  * The addresses in the ineterfaceAddr list are in host byte order.
2160  */
2161 int
2162 initInterfaceAddr_r(struct host *host, struct interfaceAddr *interf)
2163 {
2164     int i, j;
2165     int number, count;
2166     afs_int32 myHost;
2167     int found;
2168     struct Interface *interface;
2169
2170     assert(host);
2171     assert(interf);
2172
2173     ViceLog(125,
2174             ("initInterfaceAddr : host %x numAddr %d\n", host->host,
2175              interf->numberOfInterfaces));
2176
2177     number = interf->numberOfInterfaces;
2178     myHost = host->host;        /* current interface address */
2179
2180     /* validation checks */
2181     if (number < 0 || number > AFS_MAX_INTERFACE_ADDR) {
2182         ViceLog(0,
2183                 ("Number of alternate addresses returned is %d\n", number));
2184         return -1;
2185     }
2186
2187     /*
2188      * Convert IP addresses to network byte order, and remove for
2189      * duplicate IP addresses from the interface list.
2190      */
2191     for (i = 0, count = 0, found = 0; i < number; i++) {
2192         interf->addr_in[i] = htonl(interf->addr_in[i]);
2193         for (j = 0; j < count; j++) {
2194             if (interf->addr_in[j] == interf->addr_in[i])
2195                 break;
2196         }
2197         if (j == count) {
2198             interf->addr_in[count] = interf->addr_in[i];
2199             if (interf->addr_in[count] == myHost)
2200                 found = 1;
2201             count++;
2202         }
2203     }
2204
2205     /*
2206      * Allocate and initialize an interface structure for this host.
2207      */
2208     if (found) {
2209         interface = (struct Interface *)
2210             malloc(sizeof(struct Interface) +
2211                    (sizeof(afs_int32) * (count - 1)));
2212         if (!interface) {
2213             ViceLog(0, ("Failed malloc in initInterfaceAddr_r\n"));
2214             assert(0);
2215         }
2216         interface->numberOfInterfaces = count;
2217     } else {
2218         interface = (struct Interface *)
2219             malloc(sizeof(struct Interface) + (sizeof(afs_int32) * count));
2220         assert(interface);
2221         interface->numberOfInterfaces = count + 1;
2222         interface->addr[count] = myHost;
2223     }
2224     interface->uuid = interf->uuid;
2225     for (i = 0; i < count; i++)
2226         interface->addr[i] = interf->addr_in[i];
2227
2228     assert(!host->interface);
2229     host->interface = interface;
2230
2231     for (i = 0; i < host->interface->numberOfInterfaces; i++) {
2232         ViceLog(125, ("--- alt address %x\n", host->interface->addr[i]));
2233     }
2234
2235     return 0;
2236 }
2237
2238 /* inserts a new HashChain structure corresponding to this address */
2239 void
2240 hashInsert_r(afs_int32 addr, struct host *host)
2241 {
2242     int index;
2243     struct h_hashChain *chain;
2244
2245     /* hash into proper bucket */
2246     index = h_HashIndex(addr);
2247
2248     /* insert into beginning of list for this bucket */
2249     chain = (struct h_hashChain *)malloc(sizeof(struct h_hashChain));
2250     if (!chain) {
2251         ViceLog(0, ("Failed malloc in hashInsert_r\n"));
2252         assert(0);
2253     }
2254     chain->hostPtr = host;
2255     chain->next = hostHashTable[index];
2256     chain->addr = addr;
2257     hostHashTable[index] = chain;
2258
2259 }
2260
2261 /*
2262  * This is called with host locked and held. At this point, the
2263  * hostHashTable should not be having entries for the alternate
2264  * interfaces. This function has to insert these entries in the
2265  * hostHashTable.
2266  *
2267  * All addresses are in network byte order.
2268  */
2269 int
2270 addInterfaceAddr_r(struct host *host, afs_int32 addr)
2271 {
2272     int i;
2273     int number;
2274     int found;
2275     struct Interface *interface;
2276
2277     assert(host);
2278     assert(host->interface);
2279
2280     ViceLog(125, ("addInterfaceAddr : host %x addr %d\n", host->host, addr));
2281
2282     /*
2283      * Make sure this address is on the list of known addresses
2284      * for this host.
2285      */
2286     number = host->interface->numberOfInterfaces;
2287     for (i = 0, found = 0; i < number && !found; i++) {
2288         if (host->interface->addr[i] == addr)
2289             found = 1;
2290     }
2291     if (!found) {
2292         interface = (struct Interface *)
2293             malloc(sizeof(struct Interface) + (sizeof(afs_int32) * number));
2294         if (!interface) {
2295             ViceLog(0, ("Failed malloc in addInterfaceAddr_r\n"));
2296             assert(0);
2297         }
2298         interface->numberOfInterfaces = number + 1;
2299         interface->uuid = host->interface->uuid;
2300         for (i = 0; i < number; i++)
2301             interface->addr[i] = host->interface->addr[i];
2302         interface->addr[number] = addr;
2303         free(host->interface);
2304         host->interface = interface;
2305     }
2306
2307     /*
2308      * Create a hash table entry for this address
2309      */
2310     hashInsert_r(addr, host);
2311
2312     return 0;
2313 }
2314
2315 /* deleted a HashChain structure for this address and host */
2316 /* returns 1 on success */
2317 int
2318 hashDelete_r(afs_int32 addr, struct host *host)
2319 {
2320     int flag;
2321     register struct h_hashChain **hp, *th;
2322
2323     for (hp = &hostHashTable[h_HashIndex(addr)]; (th = *hp);) {
2324         assert(th->hostPtr);
2325         if (th->hostPtr == host && th->addr == addr) {
2326             *hp = th->next;
2327             free(th);
2328             flag = 1;
2329             break;
2330         } else {
2331             hp = &th->next;
2332         }
2333     }
2334     return flag;
2335 }
2336
2337
2338 /*
2339 ** prints out all alternate interface address for the host. The 'level'
2340 ** parameter indicates what level of debugging sets this output
2341 */
2342 void
2343 printInterfaceAddr(struct host *host, int level)
2344 {
2345     int i, number;
2346     if (host->interface) {
2347         /* check alternate addresses */
2348         number = host->interface->numberOfInterfaces;
2349         assert(number > 0);
2350         for (i = 0; i < number; i++)
2351             ViceLog(level, ("%x ", host->interface->addr[i]));
2352     }
2353     ViceLog(level, ("\n"));
2354 }