a136c8d1382505bf8d05d42f27088156cbac2df4
[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_SetConnSecondsUntilNatPing(tc->id, 0);
151                         rx_DestroyConnection(tc->id);
152                     }
153                 }
154                 if (glocked)
155                     AFS_GLOCK();
156                 afs_osi_Free(tcv, sizeof(struct sa_conn_vector));
157                 break;    /* at most one instance per server */
158             } /*Found unreferenced connection for user */
159         }
160     } /*For each connection on the server */
161
162 }        /* release_conns_user_server */
163
164
165 static void
166 release_conns_vector(struct sa_conn_vector *xcv)
167 {
168     int cix, glocked;
169     struct afs_conn *tc;
170     struct sa_conn_vector *tcv = NULL;
171     struct sa_conn_vector **lcv = NULL;
172     for (tcv = xcv; tcv; lcv = &tcv->next, tcv = *lcv) {
173         *lcv = tcv->next;
174         /* you know it, you love it, the GLOCK */
175         glocked = ISAFS_GLOCK();
176         if (glocked)
177             AFS_GUNLOCK(); \
178         for(cix = 0; cix < CVEC_LEN; ++cix) {
179             tc = &(tcv->cvec[cix]);
180             if (tc->activated) {
181                 rx_SetConnSecondsUntilNatPing(tc->id, 0);
182                 rx_DestroyConnection(tc->id);
183             }
184         }
185         if (glocked)
186             AFS_GLOCK();
187         afs_osi_Free(tcv, sizeof(struct sa_conn_vector));
188     }
189
190 }        /* release_conns_vector */
191
192
193 unsigned int VNOSERVERS = 0;
194
195 /**
196  * Pick a security object to use for a connection to a given server,
197  * by a given user
198  *
199  * @param[in] conn
200  *      The AFS connection for which the security object is required
201  * @param[out] secLevel
202  *      The security level of the returned object
203  *
204  * @return
205  *      An rx security object. This function is guaranteed to return
206  *      an object, although that object may be rxnull (with a secLevel
207  *      of 0)
208  */
209 static struct rx_securityClass *
210 afs_pickSecurityObject(struct afs_conn *conn, int *secLevel)
211 {
212     struct rx_securityClass *secObj = NULL;
213     union tokenUnion *token;
214
215     /* Do we have tokens ? */
216     if (conn->parent->user->states & UHasTokens) {
217         token = afs_FindToken(conn->parent->user->tokens, RX_SECIDX_KAD);
218         if (token) {
219             *secLevel = RX_SECIDX_KAD;
220             /* kerberos tickets on channel 2 */
221             secObj = rxkad_NewClientSecurityObject(
222                          cryptall ? rxkad_crypt : rxkad_clear,
223                          (struct ktc_encryptionKey *)
224                                token->rxkad.clearToken.HandShakeKey,
225                          token->rxkad.clearToken.AuthHandle,
226                          token->rxkad.ticketLen, token->rxkad.ticket);
227             /* We're going to use this token, so populate the viced */
228             conn->parent->user->viceId = token->rxkad.clearToken.ViceId;
229         }
230      }
231      if (secObj == NULL) {
232         *secLevel = 0;
233         secObj = rxnull_NewClientSecurityObject();
234      }
235
236      return secObj;
237 }
238
239
240 /**
241  * Try setting up a connection to the server containing the specified fid.
242  * Gets the volume, checks if it's up and does the connection by server address.
243  *
244  * @param afid
245  * @param areq Request filled in by the caller.
246  * @param locktype Type of lock that will be used.
247  *
248  * @return The conn struct, or NULL.
249  */
250 struct afs_conn *
251 afs_Conn(struct VenusFid *afid, struct vrequest *areq,
252          afs_int32 locktype, struct rx_connection **rxconn)
253 {
254     u_short fsport = AFS_FSPORT;
255     struct volume *tv;
256     struct afs_conn *tconn = NULL;
257     struct srvAddr *lowp = NULL;
258     struct unixuser *tu;
259     int notbusy;
260     int i;
261     struct srvAddr *sa1p;
262
263     *rxconn = NULL;
264
265     AFS_STATCNT(afs_Conn);
266     /* Get fid's volume. */
267     tv = afs_GetVolume(afid, areq, READ_LOCK);
268     if (!tv) {
269         if (areq) {
270             afs_FinalizeReq(areq);
271             areq->volumeError = 1;
272         }
273         return NULL;
274     }
275
276     if (tv->serverHost[0] && tv->serverHost[0]->cell) {
277         fsport = tv->serverHost[0]->cell->fsport;
278     } else {
279         VNOSERVERS++;
280     }
281
282     /* First is always lowest rank, if it's up */
283     if ((tv->status[0] == not_busy) && tv->serverHost[0]
284         && !(tv->serverHost[0]->addr->sa_flags & SRVR_ISDOWN) &&
285         !(((areq->idleError > 0) || (areq->tokenError > 0))
286           && (areq->skipserver[0] == 1)))
287         lowp = tv->serverHost[0]->addr;
288
289     /* Otherwise we look at all of them. There are seven levels of
290      * not_busy. This means we will check a volume seven times before it
291      * is marked offline. Ideally, we only need two levels, but this
292      * serves a second purpose of waiting some number of seconds before
293      * the client decides the volume is offline (ie: a clone could finish
294      * in this time).
295      */
296     for (notbusy = not_busy; (!lowp && (notbusy <= end_not_busy)); notbusy++) {
297         for (i = 0; i < AFS_MAXHOSTS && tv->serverHost[i]; i++) {
298             if (((areq->tokenError > 0)||(areq->idleError > 0))
299                 && (areq->skipserver[i] == 1))
300                 continue;
301             if (tv->status[i] != notbusy) {
302                 if (tv->status[i] == rd_busy || tv->status[i] == rdwr_busy) {
303                     if (!areq->busyCount)
304                         areq->busyCount++;
305                 } else if (tv->status[i] == offline) {
306                     if (!areq->volumeError)
307                         areq->volumeError = VOLMISSING;
308                 }
309                 continue;
310             }
311             for (sa1p = tv->serverHost[i]->addr; sa1p; sa1p = sa1p->next_sa) {
312                 if (sa1p->sa_flags & SRVR_ISDOWN)
313                     continue;
314                 if (!lowp || (lowp->sa_iprank > sa1p->sa_iprank))
315                     lowp = sa1p;
316             }
317         }
318     }
319     afs_PutVolume(tv, READ_LOCK);
320
321     if (lowp) {
322         tu = afs_GetUser(areq->uid, afid->Cell, SHARED_LOCK);
323         tconn = afs_ConnBySA(lowp, fsport, afid->Cell, tu, 0 /*!force */ ,
324                              1 /*create */ , locktype, rxconn);
325
326         afs_PutUser(tu, SHARED_LOCK);
327     }
328
329     return tconn;
330 }                               /*afs_Conn */
331
332
333 /**
334  * Connects to a server by it's server address.
335  *
336  * @param sap Server address.
337  * @param aport Server port.
338  * @param acell
339  * @param tu Connect as this user.
340  * @param force_if_down
341  * @param create
342  * @param locktype Specifies type of lock to be used for this function.
343  *
344  * @return The new connection.
345  */
346 struct afs_conn *
347 afs_ConnBySA(struct srvAddr *sap, unsigned short aport, afs_int32 acell,
348              struct unixuser *tu, int force_if_down, afs_int32 create,
349              afs_int32 locktype, struct rx_connection **rxconn)
350 {
351     int glocked, foundvec;
352     struct afs_conn *tc = NULL;
353     struct sa_conn_vector *tcv = NULL;
354     struct rx_securityClass *csec; /*Security class object */
355     int isec; /*Security index */
356     int service;
357
358     *rxconn = NULL;
359
360     /* find cached connection */
361     ObtainSharedLock(&afs_xconn, 15);
362     foundvec = 0;
363     for (tcv = sap->conns; tcv; tcv = tcv->next) {
364         if (tcv->user == tu && tcv->port == aport) {
365             /* return most eligible conn */
366             if (!foundvec)
367                 foundvec = 1;
368             UpgradeSToWLock(&afs_xconn, 37);
369             tc = find_preferred_connection(tcv, create);
370             ConvertWToSLock(&afs_xconn);
371             break;
372         }
373     }
374
375     if (!tc && !create) {
376         /* Not found and can't create a new one. */
377         ReleaseSharedLock(&afs_xconn);
378         return NULL;
379     }
380
381     if (AFS_IS_DISCONNECTED && !AFS_IN_SYNC) {
382         afs_warnuser("afs_ConnBySA: disconnected\n");
383         ReleaseSharedLock(&afs_xconn);
384         return NULL;
385     }
386
387     if (!foundvec && create) {
388         /* No such connection vector exists.  Create one and splice it in.
389          * Make sure the server record has been marked as used (for the purposes
390          * of calculating up & down times, it's now considered to be an
391          * ``active'' server).  Also make sure the server's lastUpdateEvalTime
392          * gets set, marking the time of its ``birth''.
393          */
394         UpgradeSToWLock(&afs_xconn, 37);
395         new_conn_vector(tcv);
396
397         tcv->user = tu;
398         tcv->port = aport;
399         tcv->srvr = sap;
400         tcv->next = sap->conns;
401         sap->conns = tcv;
402
403         /* all struct afs_conn ptrs come from here */
404         tc = find_preferred_connection(tcv, create);
405
406         afs_ActivateServer(sap);
407
408         ConvertWToSLock(&afs_xconn);
409     } /* end of if (!tcv) */
410
411     if (!tc) {
412         /* Not found and no alternatives. */
413         ReleaseSharedLock(&afs_xconn);
414         return NULL;
415     }
416
417     if (tu->states & UTokensBad) {
418         /* we may still have an authenticated RPC connection here,
419          * we'll have to create a new, unauthenticated, connection.
420          * Perhaps a better way to do this would be to set
421          * conn->forceConnectFS on all conns when the token first goes
422          * bad, but that's somewhat trickier, due to locking
423          * constraints (though not impossible).
424          */
425         if (tc->id && (rx_SecurityClassOf(tc->id) != 0)) {
426             tc->forceConnectFS = 1;     /* force recreation of connection */
427         }
428         tu->states &= ~UHasTokens;      /* remove the authentication info */
429     }
430
431     glocked = ISAFS_GLOCK();
432     if (tc->forceConnectFS) {
433         UpgradeSToWLock(&afs_xconn, 38);
434         csec = (struct rx_securityClass *)0;
435         if (tc->id) {
436             if (glocked)
437                 AFS_GUNLOCK();
438             rx_SetConnSecondsUntilNatPing(tc->id, 0);
439             rx_DestroyConnection(tc->id);
440             if (glocked)
441                 AFS_GLOCK();
442         }
443         /*
444          * Stupid hack to determine if using vldb service or file system
445          * service.
446          */
447         if (aport == sap->server->cell->vlport)
448             service = 52;
449         else
450             service = 1;
451         isec = 0;
452
453         csec = afs_pickSecurityObject(tc, &isec);
454
455         if (glocked)
456             AFS_GUNLOCK();
457         tc->id = rx_NewConnection(sap->sa_ip, aport, service, csec, isec);
458         if (glocked)
459             AFS_GLOCK();
460         if (service == 52) {
461             rx_SetConnHardDeadTime(tc->id, afs_rx_harddead);
462         }
463         /* set to a RX_CALL_TIMEOUT error to allow MTU retry to trigger */
464         rx_SetServerConnIdleDeadErr(tc->id, RX_CALL_DEAD);
465         rx_SetConnIdleDeadTime(tc->id, afs_rx_idledead);
466         rx_SetMsgsizeRetryErr(tc->id, RX_MSGSIZE);
467
468         /*
469          * Only do this for the base connection, not per-user.
470          * Will need to be revisited if/when CB gets security.
471          */
472         if ((isec == 0) && (service != 52) && !(tu->states & UTokensBad) &&
473             (tu->viceId == UNDEFVID))
474             rx_SetConnSecondsUntilNatPing(tc->id, 20);
475
476         tc->forceConnectFS = 0; /* apparently we're appropriately connected now */
477         if (csec)
478             rxs_Release(csec);
479         ConvertWToSLock(&afs_xconn);
480     } /* end of if (tc->forceConnectFS)*/
481
482     *rxconn = tc->id;
483     rx_GetConnection(*rxconn);
484
485     ReleaseSharedLock(&afs_xconn);
486     return tc;
487 }
488
489 /**
490  * forceConnectFS is set whenever we must recompute the connection. UTokensBad
491  * is true only if we know that the tokens are bad.  We thus clear this flag
492  * when we get a new set of tokens..
493  * Having force... true and UTokensBad true simultaneously means that the tokens
494  * went bad and we're supposed to create a new, unauthenticated, connection.
495  *
496  * @param aserver Server to connect to.
497  * @param aport Connection port.
498  * @param acell The cell where all of this happens.
499  * @param areq The request.
500  * @param aforce Force connection?
501  * @param locktype Type of lock to be used.
502  *
503  * @return The established connection.
504  */
505 struct afs_conn *
506 afs_ConnByHost(struct server *aserver, unsigned short aport, afs_int32 acell,
507                struct vrequest *areq, int aforce, afs_int32 locktype,
508                struct rx_connection **rxconn)
509 {
510     struct unixuser *tu;
511     struct afs_conn *tc = NULL;
512     struct srvAddr *sa = NULL;
513
514     *rxconn = NULL;
515
516     AFS_STATCNT(afs_ConnByHost);
517
518     if (AFS_IS_DISCONNECTED && !AFS_IN_SYNC) {
519         afs_warnuser("afs_ConnByHost: disconnected\n");
520         return NULL;
521     }
522
523 /*
524   1.  look for an existing connection
525   2.  create a connection at an address believed to be up
526       (if aforce is true, create a connection at the first address)
527 */
528
529     tu = afs_GetUser(areq->uid, acell, SHARED_LOCK);
530
531     for (sa = aserver->addr; sa; sa = sa->next_sa) {
532         tc = afs_ConnBySA(sa, aport, acell, tu, aforce,
533                           0 /*don't create one */ ,
534                           locktype, rxconn);
535         if (tc)
536             break;
537     }
538
539     if (!tc) {
540         for (sa = aserver->addr; sa; sa = sa->next_sa) {
541             tc = afs_ConnBySA(sa, aport, acell, tu, aforce,
542                               1 /*create one */ ,
543                               locktype, rxconn);
544             if (tc)
545                 break;
546         }
547     }
548
549     afs_PutUser(tu, SHARED_LOCK);
550     return tc;
551
552 }                               /*afs_ConnByHost */
553
554
555 /**
556  * Connect by multiple hosts.
557  * Try to connect to one of the hosts from the ahosts array.
558  *
559  * @param ahosts Multiple hosts to connect to.
560  * @param aport Connection port.
561  * @param acell The cell where all of this happens.
562  * @param areq The request.
563  * @param locktype Type of lock to be used.
564  *
565  * @return The established connection or NULL.
566  */
567 struct afs_conn *
568 afs_ConnByMHosts(struct server *ahosts[], unsigned short aport,
569                  afs_int32 acell, struct vrequest *areq,
570                  afs_int32 locktype, struct rx_connection **rxconn)
571 {
572     afs_int32 i;
573     struct afs_conn *tconn;
574     struct server *ts;
575
576     *rxconn = NULL;
577
578     /* try to find any connection from the set */
579     AFS_STATCNT(afs_ConnByMHosts);
580     for (i = 0; i < AFS_MAXCELLHOSTS; i++) {
581         if ((ts = ahosts[i]) == NULL)
582             break;
583         tconn = afs_ConnByHost(ts, aport, acell, areq, 0, locktype, rxconn);
584         if (tconn) {
585             return tconn;
586         }
587     }
588     return NULL;
589
590 }                               /*afs_ConnByMHosts */
591
592
593 /**
594  * Decrement reference count to this connection.
595  * @param ac
596  * @param locktype
597  */
598 void
599 afs_PutConn(struct afs_conn *ac, struct rx_connection *rxconn,
600             afs_int32 locktype)
601 {
602     AFS_STATCNT(afs_PutConn);
603     ac->refCount--;
604     if (ac->refCount < 0) {
605         static int warned = 0;
606         /* So, someone is 'put'ing more refs than they got. From now on, we
607          * have no idea if the structure is actually still in use, so just
608          * set the refcount to a really negative number to make it unlikely
609          * that the count will ever reach 0 and the conn gets freed. This
610          * leaks memory, but the alternative is panicing, or risking memory
611          * corruption. */
612         ac->refCount = -10000;
613         if (!warned) {
614             warned = 1;
615             afs_warn("afs_PutConn: negative refCount with 0x%lx; this should "
616                      "not ever happen! Trying to carry on anyway, but please "
617                      "report this issue\n",
618                      (unsigned long)(uintptrsz)ac);
619         }
620         return;
621     }
622     ac->parent->refCount--;
623     rx_PutConnection(rxconn);
624 }                               /*afs_PutConn */
625
626
627 /**
628  * Free up a connection vector, allowing, eg, code in afs_user.c
629  * to ignore how connections are stored/pooled
630  * @param tcv
631  */
632 void
633 afs_ReleaseConns(struct sa_conn_vector *tcv) {
634     release_conns_vector(tcv);
635 }
636
637
638 /**
639  * Free connection vector(s) for a user
640  * @param au
641  */
642 void
643 afs_ReleaseConnsUser(struct unixuser *au) {
644
645     int i;
646     struct server *ts;
647
648     for (i = 0; i < NSERVERS; i++) {
649         for (ts = afs_servers[i]; ts; ts = ts->next) {
650             release_conns_user_server(au, ts);
651         }       /*For each server on chain */
652     } /*For each chain */
653 }
654
655
656 /**
657  * For multi homed clients, a RPC may timeout because of a
658  * client network interface going down. We need to reopen new
659  * connections in this case.
660  *
661  * @param sap Server address.
662  */
663 void
664 ForceNewConnections(struct srvAddr *sap)
665 {
666     int cix;
667     struct afs_conn *tc = NULL;
668     struct sa_conn_vector *tcv = NULL;
669
670     if (!sap)
671         return; /* defensive check */
672
673     ObtainWriteLock(&afs_xconn, 413);
674     for (tcv = sap->conns; tcv; tcv = tcv->next) {
675         for(cix = 0; cix < CVEC_LEN; ++cix) {
676             tc = &(tcv->cvec[cix]);
677             if (tc->activated)
678                 tc->forceConnectFS = 1;
679         }
680     }
681     ReleaseWriteLock(&afs_xconn);
682 }
683
684