afs: Use cell for md5 inode numbers
[openafs.git] / src / afs / afs_conn.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 /*
11  * Implements:
12  */
13 #include <afsconfig.h>
14 #include "afs/param.h"
15
16
17 #include "afs/stds.h"
18 #include "afs/sysincludes.h"    /* Standard vendor system headers */
19
20 #if !defined(UKERNEL)
21 #if !defined(AFS_LINUX20_ENV)
22 #include <net/if.h>
23 #endif
24 #include <netinet/in.h>
25
26 #ifdef AFS_SGI62_ENV
27 #include "h/hashing.h"
28 #endif
29 #if !defined(AFS_HPUX110_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV)
30 #include <netinet/in_var.h>
31 #endif /* ! AFS_HPUX110_ENV */
32 #endif /* !defined(UKERNEL) */
33
34 #include "afsincludes.h"        /* Afs-based standard headers */
35 #include "afs/afs_stats.h"      /* afs statistics */
36
37 #if     defined(AFS_SUN5_ENV)
38 #include <inet/led.h>
39 #include <inet/common.h>
40 #include <netinet/ip6.h>
41 #include <inet/ip.h>
42 #endif
43
44 /* Exported variables */
45 afs_rwlock_t afs_xconn;         /* allocation lock for new things */
46 afs_rwlock_t afs_xinterface;    /* for multiple client address */
47 afs_int32 cryptall = 0;         /* encrypt all communications */
48
49 /* some connection macros */
50
51 /* a constructor */
52 #define new_conn_vector(xcv) \
53 do { \
54         xcv = (struct sa_conn_vector *) \
55         afs_osi_Alloc(sizeof(struct sa_conn_vector)); \
56         if (xcv) { \
57                 memset((char *)xcv, 0, sizeof(struct sa_conn_vector)); \
58         } \
59 } while (0);
60
61 /* select a connection to return (if no connection has lower utilization
62  * than any other) */
63 #define conn_vec_select_conn(xcv, bix, conn) \
64 do { \
65     (bix) = ((xcv)->select_index)++ % CVEC_LEN; \
66     (conn) = &((xcv)->cvec[bix]); \
67 } while (0);
68
69 #define struct_conn(s) ((struct afs_conn *)(s))
70
71 #define REPORT_CONNECTIONS_ISSUED 0 /* enable to see utilization */
72
73 /**
74  * Find a connection with call slots available, allocating one
75  * if nothing is available and we find an allocated slot
76  * @param xcv  A connection vector
77  * @param create  If set, a new connection may be created
78  */
79 static struct afs_conn *
80 find_preferred_connection(struct sa_conn_vector *xcv, int create)
81 {
82     afs_int32 cix, bix;
83     struct afs_conn *tc = NULL;
84
85     bix = -1;
86     for(cix = 0; cix < CVEC_LEN; ++cix) {
87         tc = &(xcv->cvec[cix]);
88         if (!tc->id) {
89             if (create) {
90                 tc->parent = xcv;
91                 tc->forceConnectFS = 1;
92                 tc->activated = 1;
93                 bix = cix;
94                 break;
95             } /* create */
96         } else {
97             if (tc->refCount < (RX_MAXCALLS-1)) {
98                 bix = cix;
99                 goto f_conn;
100             } else if (cix == (CVEC_LEN-1))
101                 conn_vec_select_conn(xcv, bix, tc);
102         } /* tc->id */
103     } /* for cix < CVEC_LEN */
104
105     if (bix < 0) {
106         afs_warn("find_preferred_connection: no connection and !create\n");
107         tc = NULL;
108         goto out;
109     }
110
111 f_conn:
112     tc->refCount++;
113     xcv->refCount++;
114
115 #if REPORT_CONNECTIONS_ISSUED
116     afs_warn("Issuing conn %d refCount=%d parent refCount=%d\n", bix,
117              tc->refCount, xcv->refCount);
118 #endif
119
120 out:
121     return (tc);
122
123 }        /* find_preferred_connection */
124
125
126 /**
127  * Release all connections for unix user xu at server xs
128  * @param xu
129  * @param xs
130  */
131 static void
132 release_conns_user_server(struct unixuser *xu, struct server *xs)
133 {
134     int cix, glocked;
135     struct srvAddr *sa;
136     struct afs_conn *tc;
137     struct sa_conn_vector *tcv, **lcv;
138     for (sa = (xs)->addr; sa; sa = sa->next_sa) {
139         lcv = &sa->conns;
140         for (tcv = *lcv; tcv; lcv = &tcv->next, tcv = *lcv) {
141             if (tcv->user == (xu) && tcv->refCount == 0) {
142                 *lcv = tcv->next;
143                 /* our old friend, the GLOCK */
144                 glocked = ISAFS_GLOCK();
145                 if (glocked)
146                     AFS_GUNLOCK();
147                 for(cix = 0; cix < CVEC_LEN; ++cix) {
148                     tc = &(tcv->cvec[cix]);
149                     if (tc->activated)
150                         rx_DestroyConnection(tc->id);
151                 }
152                 if (glocked)
153                     AFS_GLOCK();
154                 afs_osi_Free(tcv, sizeof(struct sa_conn_vector));
155                 break;    /* at most one instance per server */
156             } /*Found unreferenced connection for user */
157         }
158     } /*For each connection on the server */
159
160 }        /* release_conns_user_server */
161
162
163 static void
164 release_conns_vector(struct sa_conn_vector *xcv)
165 {
166     int cix, glocked;
167     struct afs_conn *tc;
168     struct sa_conn_vector *tcv = NULL;
169     struct sa_conn_vector **lcv = NULL;
170     for (tcv = xcv; tcv; lcv = &tcv->next, tcv = *lcv) {
171         *lcv = tcv->next;
172         /* you know it, you love it, the GLOCK */
173         glocked = ISAFS_GLOCK();
174         if (glocked)
175             AFS_GUNLOCK(); \
176         for(cix = 0; cix < CVEC_LEN; ++cix) {
177             tc = &(tcv->cvec[cix]);
178             if (tc->activated)
179                 rx_DestroyConnection( tc->id );
180         }
181         if (glocked)
182             AFS_GLOCK();
183         afs_osi_Free(tcv, sizeof(struct sa_conn_vector));
184     }
185
186 }        /* release_conns_vector */
187
188
189 unsigned int VNOSERVERS = 0;
190
191 /**
192  * Pick a security object to use for a connection to a given server,
193  * by a given user
194  *
195  * @param[in] conn
196  *      The AFS connection for which the security object is required
197  * @param[out] secLevel
198  *      The security level of the returned object
199  *
200  * @return
201  *      An rx security object. This function is guaranteed to return
202  *      an object, although that object may be rxnull (with a secLevel
203  *      of 0)
204  */
205 static struct rx_securityClass *
206 afs_pickSecurityObject(struct afs_conn *conn, int *secLevel)
207 {
208     struct rx_securityClass *secObj = NULL;
209     union tokenUnion *token;
210
211     /* Do we have tokens ? */
212     if (conn->parent->user->states & UHasTokens) {
213         token = afs_FindToken(conn->parent->user->tokens, RX_SECIDX_KAD);
214         if (token) {
215             *secLevel = RX_SECIDX_KAD;
216             /* kerberos tickets on channel 2 */
217             secObj = rxkad_NewClientSecurityObject(
218                          cryptall ? rxkad_crypt : rxkad_clear,
219                          (struct ktc_encryptionKey *)
220                                token->rxkad.clearToken.HandShakeKey,
221                          token->rxkad.clearToken.AuthHandle,
222                          token->rxkad.ticketLen, token->rxkad.ticket);
223             /* We're going to use this token, so populate the viced */
224             conn->parent->user->viceId = token->rxkad.clearToken.ViceId;
225         }
226      }
227      if (secObj == NULL) {
228         *secLevel = 0;
229         secObj = rxnull_NewClientSecurityObject();
230      }
231
232      return secObj;
233 }
234
235
236 /**
237  * Try setting up a connection to the server containing the specified fid.
238  * Gets the volume, checks if it's up and does the connection by server address.
239  *
240  * @param afid
241  * @param areq Request filled in by the caller.
242  * @param locktype Type of lock that will be used.
243  *
244  * @return The conn struct, or NULL.
245  */
246 struct afs_conn *
247 afs_Conn(struct VenusFid *afid, struct vrequest *areq,
248          afs_int32 locktype, struct rx_connection **rxconn)
249 {
250     u_short fsport = AFS_FSPORT;
251     struct volume *tv;
252     struct afs_conn *tconn = NULL;
253     struct srvAddr *lowp = NULL;
254     struct unixuser *tu;
255     int notbusy;
256     int i;
257     struct srvAddr *sa1p;
258
259     *rxconn = NULL;
260
261     AFS_STATCNT(afs_Conn);
262     /* Get fid's volume. */
263     tv = afs_GetVolume(afid, areq, READ_LOCK);
264     if (!tv) {
265         if (areq) {
266             afs_FinalizeReq(areq);
267             areq->volumeError = 1;
268         }
269         return NULL;
270     }
271
272     if (tv->serverHost[0] && tv->serverHost[0]->cell) {
273         fsport = tv->serverHost[0]->cell->fsport;
274     } else {
275         VNOSERVERS++;
276     }
277
278     /* First is always lowest rank, if it's up */
279     if ((tv->status[0] == not_busy) && tv->serverHost[0]
280         && !(tv->serverHost[0]->addr->sa_flags & SRVR_ISDOWN) &&
281         !(((areq->idleError > 0) || (areq->tokenError > 0))
282           && (areq->skipserver[0] == 1)))
283         lowp = tv->serverHost[0]->addr;
284
285     /* Otherwise we look at all of them. There are seven levels of
286      * not_busy. This means we will check a volume seven times before it
287      * is marked offline. Ideally, we only need two levels, but this
288      * serves a second purpose of waiting some number of seconds before
289      * the client decides the volume is offline (ie: a clone could finish
290      * in this time).
291      */
292     for (notbusy = not_busy; (!lowp && (notbusy <= end_not_busy)); notbusy++) {
293         for (i = 0; i < AFS_MAXHOSTS && tv->serverHost[i]; i++) {
294             if (((areq->tokenError > 0)||(areq->idleError > 0))
295                 && (areq->skipserver[i] == 1))
296                 continue;
297             if (tv->status[i] != notbusy) {
298                 if (tv->status[i] == rd_busy || tv->status[i] == rdwr_busy) {
299                     if (!areq->busyCount)
300                         areq->busyCount++;
301                 } else if (tv->status[i] == offline) {
302                     if (!areq->volumeError)
303                         areq->volumeError = VOLMISSING;
304                 }
305                 continue;
306             }
307             for (sa1p = tv->serverHost[i]->addr; sa1p; sa1p = sa1p->next_sa) {
308                 if (sa1p->sa_flags & SRVR_ISDOWN)
309                     continue;
310                 if (!lowp || (lowp->sa_iprank > sa1p->sa_iprank))
311                     lowp = sa1p;
312             }
313         }
314     }
315     afs_PutVolume(tv, READ_LOCK);
316
317     if (lowp) {
318         tu = afs_GetUser(areq->uid, afid->Cell, SHARED_LOCK);
319         tconn = afs_ConnBySA(lowp, fsport, afid->Cell, tu, 0 /*!force */ ,
320                              1 /*create */ , locktype, rxconn);
321
322         afs_PutUser(tu, SHARED_LOCK);
323     }
324
325     return tconn;
326 }                               /*afs_Conn */
327
328
329 /**
330  * Connects to a server by it's server address.
331  *
332  * @param sap Server address.
333  * @param aport Server port.
334  * @param acell
335  * @param tu Connect as this user.
336  * @param force_if_down
337  * @param create
338  * @param locktype Specifies type of lock to be used for this function.
339  *
340  * @return The new connection.
341  */
342 struct afs_conn *
343 afs_ConnBySA(struct srvAddr *sap, unsigned short aport, afs_int32 acell,
344              struct unixuser *tu, int force_if_down, afs_int32 create,
345              afs_int32 locktype, struct rx_connection **rxconn)
346 {
347     int glocked, foundvec;
348     struct afs_conn *tc = NULL;
349     struct sa_conn_vector *tcv = NULL;
350     struct rx_securityClass *csec; /*Security class object */
351     int isec; /*Security index */
352     int service;
353
354     *rxconn = NULL;
355
356     /* find cached connection */
357     ObtainSharedLock(&afs_xconn, 15);
358     foundvec = 0;
359     for (tcv = sap->conns; tcv; tcv = tcv->next) {
360         if (tcv->user == tu && tcv->port == aport) {
361             /* return most eligible conn */
362             if (!foundvec)
363                 foundvec = 1;
364             UpgradeSToWLock(&afs_xconn, 37);
365             tc = find_preferred_connection(tcv, create);
366             ConvertWToSLock(&afs_xconn);
367             break;
368         }
369     }
370
371     if (!tc && !create) {
372         /* Not found and can't create a new one. */
373         ReleaseSharedLock(&afs_xconn);
374         return NULL;
375     }
376
377     if (AFS_IS_DISCONNECTED && !AFS_IN_SYNC) {
378         afs_warnuser("afs_ConnBySA: disconnected\n");
379         ReleaseSharedLock(&afs_xconn);
380         return NULL;
381     }
382
383     if (!foundvec && create) {
384         /* No such connection vector exists.  Create one and splice it in.
385          * Make sure the server record has been marked as used (for the purposes
386          * of calculating up & down times, it's now considered to be an
387          * ``active'' server).  Also make sure the server's lastUpdateEvalTime
388          * gets set, marking the time of its ``birth''.
389          */
390         UpgradeSToWLock(&afs_xconn, 37);
391         new_conn_vector(tcv);
392
393         tcv->user = tu;
394         tcv->port = aport;
395         tcv->srvr = sap;
396         tcv->next = sap->conns;
397         sap->conns = tcv;
398
399         /* all struct afs_conn ptrs come from here */
400         tc = find_preferred_connection(tcv, create);
401
402         afs_ActivateServer(sap);
403
404         ConvertWToSLock(&afs_xconn);
405     } /* end of if (!tcv) */
406
407     if (!tc) {
408         /* Not found and no alternatives. */
409         ReleaseSharedLock(&afs_xconn);
410         return NULL;
411     }
412
413     if (tu->states & UTokensBad) {
414         /* we may still have an authenticated RPC connection here,
415          * we'll have to create a new, unauthenticated, connection.
416          * Perhaps a better way to do this would be to set
417          * conn->forceConnectFS on all conns when the token first goes
418          * bad, but that's somewhat trickier, due to locking
419          * constraints (though not impossible).
420          */
421         if (tc->id && (rx_SecurityClassOf(tc->id) != 0)) {
422             tc->forceConnectFS = 1;     /* force recreation of connection */
423         }
424         tu->states &= ~UHasTokens;      /* remove the authentication info */
425     }
426
427     glocked = ISAFS_GLOCK();
428     if (tc->forceConnectFS) {
429         UpgradeSToWLock(&afs_xconn, 38);
430         csec = (struct rx_securityClass *)0;
431         if (tc->id) {
432             if (glocked)
433                 AFS_GUNLOCK();
434             rx_DestroyConnection(tc->id);
435             if (glocked)
436                 AFS_GLOCK();
437         }
438         /*
439          * Stupid hack to determine if using vldb service or file system
440          * service.
441          */
442         if (aport == sap->server->cell->vlport)
443             service = 52;
444         else
445             service = 1;
446         isec = 0;
447
448         csec = afs_pickSecurityObject(tc, &isec);
449
450         if (glocked)
451             AFS_GUNLOCK();
452         tc->id = rx_NewConnection(sap->sa_ip, aport, service, csec, isec);
453         if (glocked)
454             AFS_GLOCK();
455         if (service == 52) {
456             rx_SetConnHardDeadTime(tc->id, afs_rx_harddead);
457         }
458         /* set to a RX_CALL_TIMEOUT error to allow MTU retry to trigger */
459         rx_SetServerConnIdleDeadErr(tc->id, RX_CALL_DEAD);
460         rx_SetConnIdleDeadTime(tc->id, afs_rx_idledead);
461         rx_SetMsgsizeRetryErr(tc->id, RX_MSGSIZE);
462
463         /*
464          * Only do this for the base connection, not per-user.
465          * Will need to be revisited if/when CB gets security.
466          */
467         if ((isec == 0) && (service != 52) && !(tu->states & UTokensBad) &&
468             (tu->viceId == UNDEFVID))
469             rx_SetConnSecondsUntilNatPing(tc->id, 20);
470
471         tc->forceConnectFS = 0; /* apparently we're appropriately connected now */
472         if (csec)
473             rxs_Release(csec);
474         ConvertWToSLock(&afs_xconn);
475     } /* end of if (tc->forceConnectFS)*/
476
477     *rxconn = tc->id;
478     rx_GetConnection(*rxconn);
479
480     ReleaseSharedLock(&afs_xconn);
481     return tc;
482 }
483
484 /**
485  * forceConnectFS is set whenever we must recompute the connection. UTokensBad
486  * is true only if we know that the tokens are bad.  We thus clear this flag
487  * when we get a new set of tokens..
488  * Having force... true and UTokensBad true simultaneously means that the tokens
489  * went bad and we're supposed to create a new, unauthenticated, connection.
490  *
491  * @param aserver Server to connect to.
492  * @param aport Connection port.
493  * @param acell The cell where all of this happens.
494  * @param areq The request.
495  * @param aforce Force connection?
496  * @param locktype Type of lock to be used.
497  *
498  * @return The established connection.
499  */
500 struct afs_conn *
501 afs_ConnByHost(struct server *aserver, unsigned short aport, afs_int32 acell,
502                struct vrequest *areq, int aforce, afs_int32 locktype,
503                struct rx_connection **rxconn)
504 {
505     struct unixuser *tu;
506     struct afs_conn *tc = NULL;
507     struct srvAddr *sa = NULL;
508
509     *rxconn = NULL;
510
511     AFS_STATCNT(afs_ConnByHost);
512
513     if (AFS_IS_DISCONNECTED && !AFS_IN_SYNC) {
514         afs_warnuser("afs_ConnByHost: disconnected\n");
515         return NULL;
516     }
517
518 /*
519   1.  look for an existing connection
520   2.  create a connection at an address believed to be up
521       (if aforce is true, create a connection at the first address)
522 */
523
524     tu = afs_GetUser(areq->uid, acell, SHARED_LOCK);
525
526     for (sa = aserver->addr; sa; sa = sa->next_sa) {
527         tc = afs_ConnBySA(sa, aport, acell, tu, aforce,
528                           0 /*don't create one */ ,
529                           locktype, rxconn);
530         if (tc)
531             break;
532     }
533
534     if (!tc) {
535         for (sa = aserver->addr; sa; sa = sa->next_sa) {
536             tc = afs_ConnBySA(sa, aport, acell, tu, aforce,
537                               1 /*create one */ ,
538                               locktype, rxconn);
539             if (tc)
540                 break;
541         }
542     }
543
544     afs_PutUser(tu, SHARED_LOCK);
545     return tc;
546
547 }                               /*afs_ConnByHost */
548
549
550 /**
551  * Connect by multiple hosts.
552  * Try to connect to one of the hosts from the ahosts array.
553  *
554  * @param ahosts Multiple hosts to connect to.
555  * @param aport Connection port.
556  * @param acell The cell where all of this happens.
557  * @param areq The request.
558  * @param locktype Type of lock to be used.
559  *
560  * @return The established connection or NULL.
561  */
562 struct afs_conn *
563 afs_ConnByMHosts(struct server *ahosts[], unsigned short aport,
564                  afs_int32 acell, struct vrequest *areq,
565                  afs_int32 locktype, struct rx_connection **rxconn)
566 {
567     afs_int32 i;
568     struct afs_conn *tconn;
569     struct server *ts;
570
571     *rxconn = NULL;
572
573     /* try to find any connection from the set */
574     AFS_STATCNT(afs_ConnByMHosts);
575     for (i = 0; i < AFS_MAXCELLHOSTS; i++) {
576         if ((ts = ahosts[i]) == NULL)
577             break;
578         tconn = afs_ConnByHost(ts, aport, acell, areq, 0, locktype, rxconn);
579         if (tconn) {
580             return tconn;
581         }
582     }
583     return NULL;
584
585 }                               /*afs_ConnByMHosts */
586
587
588 /**
589  * Decrement reference count to this connection.
590  * @param ac
591  * @param locktype
592  */
593 void
594 afs_PutConn(struct afs_conn *ac, struct rx_connection *rxconn,
595             afs_int32 locktype)
596 {
597     AFS_STATCNT(afs_PutConn);
598     ac->refCount--;
599     ac->parent->refCount--;
600     rx_PutConnection(rxconn);
601 }                               /*afs_PutConn */
602
603
604 /**
605  * Free up a connection vector, allowing, eg, code in afs_user.c
606  * to ignore how connections are stored/pooled
607  * @param tcv
608  */
609 void
610 afs_ReleaseConns(struct sa_conn_vector *tcv) {
611     release_conns_vector(tcv);
612 }
613
614
615 /**
616  * Free connection vector(s) for a user
617  * @param au
618  */
619 void
620 afs_ReleaseConnsUser(struct unixuser *au) {
621
622     int i;
623     struct server *ts;
624
625     for (i = 0; i < NSERVERS; i++) {
626         for (ts = afs_servers[i]; ts; ts = ts->next) {
627             release_conns_user_server(au, ts);
628         }       /*For each server on chain */
629     } /*For each chain */
630 }
631
632
633 /**
634  * For multi homed clients, a RPC may timeout because of a
635  * client network interface going down. We need to reopen new
636  * connections in this case.
637  *
638  * @param sap Server address.
639  */
640 void
641 ForceNewConnections(struct srvAddr *sap)
642 {
643     int cix;
644     struct afs_conn *tc = NULL;
645     struct sa_conn_vector *tcv = NULL;
646
647     if (!sap)
648         return; /* defensive check */
649
650     ObtainWriteLock(&afs_xconn, 413);
651     for (tcv = sap->conns; tcv; tcv = tcv->next) {
652         for(cix = 0; cix < CVEC_LEN; ++cix) {
653             tc = &(tcv->cvec[cix]);
654             if (tc->activated)
655                 tc->forceConnectFS = 1;
656         }
657     }
658     ReleaseWriteLock(&afs_xconn);
659 }
660
661