Whamcloud - gitweb
branch: HEAD
[fs/lustre-release.git] / lustre / ptlrpc / sec.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/ptlrpc/sec.c
37  *
38  * Author: Eric Mei <ericm@clusterfs.com>
39  */
40
41 #ifndef EXPORT_SYMTAB
42 #define EXPORT_SYMTAB
43 #endif
44 #define DEBUG_SUBSYSTEM S_SEC
45
46 #include <libcfs/libcfs.h>
47 #ifndef __KERNEL__
48 #include <liblustre.h>
49 #include <libcfs/list.h>
50 #else
51 #include <linux/crypto.h>
52 #include <linux/key.h>
53 #endif
54
55 #include <obd.h>
56 #include <obd_class.h>
57 #include <obd_support.h>
58 #include <lustre_net.h>
59 #include <lustre_import.h>
60 #include <lustre_dlm.h>
61 #include <lustre_sec.h>
62
63 #include "ptlrpc_internal.h"
64
65 /***********************************************
66  * policy registers                            *
67  ***********************************************/
68
69 static rwlock_t policy_lock = RW_LOCK_UNLOCKED;
70 static struct ptlrpc_sec_policy *policies[SPTLRPC_POLICY_MAX] = {
71         NULL,
72 };
73
74 int sptlrpc_register_policy(struct ptlrpc_sec_policy *policy)
75 {
76         __u16 number = policy->sp_policy;
77
78         LASSERT(policy->sp_name);
79         LASSERT(policy->sp_cops);
80         LASSERT(policy->sp_sops);
81
82         if (number >= SPTLRPC_POLICY_MAX)
83                 return -EINVAL;
84
85         write_lock(&policy_lock);
86         if (unlikely(policies[number])) {
87                 write_unlock(&policy_lock);
88                 return -EALREADY;
89         }
90         policies[number] = policy;
91         write_unlock(&policy_lock);
92
93         CDEBUG(D_SEC, "%s: registered\n", policy->sp_name);
94         return 0;
95 }
96 EXPORT_SYMBOL(sptlrpc_register_policy);
97
98 int sptlrpc_unregister_policy(struct ptlrpc_sec_policy *policy)
99 {
100         __u16 number = policy->sp_policy;
101
102         LASSERT(number < SPTLRPC_POLICY_MAX);
103
104         write_lock(&policy_lock);
105         if (unlikely(policies[number] == NULL)) {
106                 write_unlock(&policy_lock);
107                 CERROR("%s: already unregistered\n", policy->sp_name);
108                 return -EINVAL;
109         }
110
111         LASSERT(policies[number] == policy);
112         policies[number] = NULL;
113         write_unlock(&policy_lock);
114
115         CDEBUG(D_SEC, "%s: unregistered\n", policy->sp_name);
116         return 0;
117 }
118 EXPORT_SYMBOL(sptlrpc_unregister_policy);
119
120 static
121 struct ptlrpc_sec_policy * sptlrpc_rpcflavor2policy(__u16 flavor)
122 {
123         static DECLARE_MUTEX(load_mutex);
124         static atomic_t           loaded = ATOMIC_INIT(0);
125         struct ptlrpc_sec_policy *policy;
126         __u16                     number = RPC_FLVR_POLICY(flavor), flag = 0;
127
128         if (number >= SPTLRPC_POLICY_MAX)
129                 return NULL;
130
131         while (1) {
132                 read_lock(&policy_lock);
133                 policy = policies[number];
134                 if (policy && !try_module_get(policy->sp_owner))
135                         policy = NULL;
136                 if (policy == NULL)
137                         flag = atomic_read(&loaded);
138                 read_unlock(&policy_lock);
139
140                 if (policy != NULL || flag != 0 ||
141                     number != SPTLRPC_POLICY_GSS)
142                         break;
143
144                 /* try to load gss module, once */
145                 mutex_down(&load_mutex);
146                 if (atomic_read(&loaded) == 0) {
147                         if (request_module("ptlrpc_gss") == 0)
148                                 CWARN("module ptlrpc_gss loaded on demand\n");
149                         else
150                                 CERROR("Unable to load module ptlrpc_gss\n");
151
152                         atomic_set(&loaded, 1);
153                 }
154                 mutex_up(&load_mutex);
155         }
156
157         return policy;
158 }
159
160 __u16 sptlrpc_name2rpcflavor(const char *name)
161 {
162         if (!strcmp(name, "null"))
163                 return SPTLRPC_FLVR_NULL;
164         if (!strcmp(name, "plain"))
165                 return SPTLRPC_FLVR_PLAIN;
166         if (!strcmp(name, "krb5n"))
167                 return SPTLRPC_FLVR_KRB5N;
168         if (!strcmp(name, "krb5a"))
169                 return SPTLRPC_FLVR_KRB5A;
170         if (!strcmp(name, "krb5i"))
171                 return SPTLRPC_FLVR_KRB5I;
172         if (!strcmp(name, "krb5p"))
173                 return SPTLRPC_FLVR_KRB5P;
174
175         return SPTLRPC_FLVR_INVALID;
176 }
177 EXPORT_SYMBOL(sptlrpc_name2rpcflavor);
178
179 const char *sptlrpc_rpcflavor2name(__u16 flavor)
180 {
181         switch (flavor) {
182         case SPTLRPC_FLVR_NULL:
183                 return "null";
184         case SPTLRPC_FLVR_PLAIN:
185                 return "plain";
186         case SPTLRPC_FLVR_KRB5N:
187                 return "krb5n";
188         case SPTLRPC_FLVR_KRB5A:
189                 return "krb5a";
190         case SPTLRPC_FLVR_KRB5I:
191                 return "krb5i";
192         case SPTLRPC_FLVR_KRB5P:
193                 return "krb5p";
194         default:
195                 CERROR("invalid rpc flavor 0x%x(p%u,s%u,v%u)\n", flavor,
196                        RPC_FLVR_POLICY(flavor), RPC_FLVR_MECH(flavor),
197                        RPC_FLVR_SVC(flavor));
198         }
199         return "unknown";
200 }
201 EXPORT_SYMBOL(sptlrpc_rpcflavor2name);
202
203 int sptlrpc_flavor2name(struct sptlrpc_flavor *sf, char *buf, int bufsize)
204 {
205         char           *bulk;
206
207         if (sf->sf_bulk_ciph != BULK_CIPH_ALG_NULL)
208                 bulk = "bulkp";
209         else if (sf->sf_bulk_hash != BULK_HASH_ALG_NULL)
210                 bulk = "bulki";
211         else
212                 bulk = "bulkn";
213
214         snprintf(buf, bufsize, "%s-%s:%s/%s",
215                  sptlrpc_rpcflavor2name(sf->sf_rpc), bulk,
216                  sptlrpc_get_hash_name(sf->sf_bulk_hash),
217                  sptlrpc_get_ciph_name(sf->sf_bulk_ciph));
218         return 0;
219 }
220 EXPORT_SYMBOL(sptlrpc_flavor2name);
221
222 /**************************************************
223  * client context APIs                            *
224  **************************************************/
225
226 static
227 struct ptlrpc_cli_ctx *get_my_ctx(struct ptlrpc_sec *sec)
228 {
229         struct vfs_cred vcred;
230         int create = 1, remove_dead = 1;
231
232         LASSERT(sec);
233         LASSERT(sec->ps_policy->sp_cops->lookup_ctx);
234
235         if (sec->ps_flvr.sf_flags & (PTLRPC_SEC_FL_REVERSE |
236                                      PTLRPC_SEC_FL_ROOTONLY)) {
237                 vcred.vc_uid = 0;
238                 vcred.vc_gid = 0;
239                 if (sec->ps_flvr.sf_flags & PTLRPC_SEC_FL_REVERSE) {
240                         create = 0;
241                         remove_dead = 0;
242                 }
243         } else {
244                 vcred.vc_uid = cfs_current()->uid;
245                 vcred.vc_gid = cfs_current()->gid;
246         }
247
248         return sec->ps_policy->sp_cops->lookup_ctx(sec, &vcred,
249                                                    create, remove_dead);
250 }
251
252 struct ptlrpc_cli_ctx *sptlrpc_cli_ctx_get(struct ptlrpc_cli_ctx *ctx)
253 {
254         LASSERT(atomic_read(&ctx->cc_refcount) > 0);
255         atomic_inc(&ctx->cc_refcount);
256         return ctx;
257 }
258 EXPORT_SYMBOL(sptlrpc_cli_ctx_get);
259
260 void sptlrpc_cli_ctx_put(struct ptlrpc_cli_ctx *ctx, int sync)
261 {
262         struct ptlrpc_sec *sec = ctx->cc_sec;
263
264         LASSERT(sec);
265         LASSERT(atomic_read(&ctx->cc_refcount));
266
267         if (!atomic_dec_and_test(&ctx->cc_refcount))
268                 return;
269
270         sec->ps_policy->sp_cops->release_ctx(sec, ctx, sync);
271 }
272 EXPORT_SYMBOL(sptlrpc_cli_ctx_put);
273
274 /*
275  * expire the context immediately.
276  * the caller must hold at least 1 ref on the ctx.
277  */
278 void sptlrpc_cli_ctx_expire(struct ptlrpc_cli_ctx *ctx)
279 {
280         LASSERT(ctx->cc_ops->die);
281         ctx->cc_ops->die(ctx, 0);
282 }
283 EXPORT_SYMBOL(sptlrpc_cli_ctx_expire);
284
285 void sptlrpc_cli_ctx_wakeup(struct ptlrpc_cli_ctx *ctx)
286 {
287         struct ptlrpc_request *req, *next;
288
289         spin_lock(&ctx->cc_lock);
290         list_for_each_entry_safe(req, next, &ctx->cc_req_list, rq_ctx_chain) {
291                 list_del_init(&req->rq_ctx_chain);
292                 ptlrpc_wake_client_req(req);
293         }
294         spin_unlock(&ctx->cc_lock);
295 }
296 EXPORT_SYMBOL(sptlrpc_cli_ctx_wakeup);
297
298 int sptlrpc_cli_ctx_display(struct ptlrpc_cli_ctx *ctx, char *buf, int bufsize)
299 {
300         LASSERT(ctx->cc_ops);
301
302         if (ctx->cc_ops->display == NULL)
303                 return 0;
304
305         return ctx->cc_ops->display(ctx, buf, bufsize);
306 }
307
308 static int sptlrpc_import_sec_check_expire(struct obd_import *imp)
309 {
310         int     adapt = 0;
311
312         spin_lock(&imp->imp_lock);
313         if (imp->imp_sec_expire &&
314             imp->imp_sec_expire < cfs_time_current_sec()) {
315                 adapt = 1;
316                 imp->imp_sec_expire = 0;
317         }
318         spin_unlock(&imp->imp_lock);
319
320         if (!adapt)
321                 return 0;
322
323         CDEBUG(D_SEC, "found delayed sec adapt expired, do it now\n");
324         return sptlrpc_import_sec_adapt(imp, NULL, 0);
325 }
326
327 int sptlrpc_req_get_ctx(struct ptlrpc_request *req)
328 {
329         struct obd_import *imp = req->rq_import;
330         struct ptlrpc_sec *sec;
331         int                rc;
332         ENTRY;
333
334         LASSERT(!req->rq_cli_ctx);
335         LASSERT(imp);
336
337         if (unlikely(imp->imp_sec_expire)) {
338                 rc = sptlrpc_import_sec_check_expire(imp);
339                 if (rc)
340                         RETURN(rc);
341         }
342
343         sec = sptlrpc_import_sec_ref(imp);
344         if (sec == NULL) {
345                 CERROR("import %p (%s) with no ptlrpc_sec\n",
346                        imp, ptlrpc_import_state_name(imp->imp_state));
347                 RETURN(-EACCES);
348         }
349
350         if (unlikely(sec->ps_dying)) {
351                 CERROR("attempt to use dying sec %p\n", sec);
352                 return -EACCES;
353         }
354
355         req->rq_cli_ctx = get_my_ctx(sec);
356
357         sptlrpc_sec_put(sec);
358
359         if (!req->rq_cli_ctx) {
360                 CERROR("req %p: fail to get context\n", req);
361                 RETURN(-ENOMEM);
362         }
363
364         RETURN(0);
365 }
366
367 /*
368  * if @sync == 0, this function should return quickly without sleep;
369  * otherwise might trigger ctx destroying rpc to server.
370  */
371 void sptlrpc_req_put_ctx(struct ptlrpc_request *req, int sync)
372 {
373         ENTRY;
374
375         LASSERT(req);
376         LASSERT(req->rq_cli_ctx);
377
378         /* request might be asked to release earlier while still
379          * in the context waiting list.
380          */
381         if (!list_empty(&req->rq_ctx_chain)) {
382                 spin_lock(&req->rq_cli_ctx->cc_lock);
383                 list_del_init(&req->rq_ctx_chain);
384                 spin_unlock(&req->rq_cli_ctx->cc_lock);
385         }
386
387         sptlrpc_cli_ctx_put(req->rq_cli_ctx, sync);
388         req->rq_cli_ctx = NULL;
389         EXIT;
390 }
391
392 static
393 int sptlrpc_req_ctx_switch(struct ptlrpc_request *req,
394                            struct ptlrpc_cli_ctx *oldctx,
395                            struct ptlrpc_cli_ctx *newctx)
396 {
397         struct sptlrpc_flavor   old_flvr;
398         char                   *reqmsg;
399         int                     reqmsg_size;
400         int                     rc;
401
402         if (likely(oldctx->cc_sec == newctx->cc_sec))
403                 return 0;
404
405         LASSERT(req->rq_reqmsg);
406         LASSERT(req->rq_reqlen);
407         LASSERT(req->rq_replen);
408
409         CWARN("req %p: switch ctx %p -> %p, switch sec %p(%s) -> %p(%s)\n",
410               req, oldctx, newctx,
411               oldctx->cc_sec, oldctx->cc_sec->ps_policy->sp_name,
412               newctx->cc_sec, newctx->cc_sec->ps_policy->sp_name);
413
414         /* save flavor */
415         old_flvr = req->rq_flvr;
416
417         /* save request message */
418         reqmsg_size = req->rq_reqlen;
419         OBD_ALLOC(reqmsg, reqmsg_size);
420         if (reqmsg == NULL)
421                 return -ENOMEM;
422         memcpy(reqmsg, req->rq_reqmsg, reqmsg_size);
423
424         /* release old req/rep buf */
425         req->rq_cli_ctx = oldctx;
426         sptlrpc_cli_free_reqbuf(req);
427         sptlrpc_cli_free_repbuf(req);
428         req->rq_cli_ctx = newctx;
429
430         /* recalculate the flavor */
431         sptlrpc_req_set_flavor(req, 0);
432
433         /* alloc new request buffer
434          * we don't need to alloc reply buffer here, leave it to the
435          * rest procedure of ptlrpc
436          */
437         rc = sptlrpc_cli_alloc_reqbuf(req, reqmsg_size);
438         if (!rc) {
439                 LASSERT(req->rq_reqmsg);
440                 memcpy(req->rq_reqmsg, reqmsg, reqmsg_size);
441         } else {
442                 CWARN("failed to alloc reqbuf: %d\n", rc);
443                 req->rq_flvr = old_flvr;
444         }
445
446         OBD_FREE(reqmsg, reqmsg_size);
447         return rc;
448 }
449
450 /*
451  * request must have a context. in any case of failure, restore the
452  * restore the old one. a request must have a ctx.
453  */
454 int sptlrpc_req_replace_dead_ctx(struct ptlrpc_request *req)
455 {
456         struct ptlrpc_cli_ctx *oldctx = req->rq_cli_ctx;
457         struct ptlrpc_cli_ctx *newctx;
458         int                    rc;
459         ENTRY;
460
461         LASSERT(oldctx);
462         LASSERT(test_bit(PTLRPC_CTX_DEAD_BIT, &oldctx->cc_flags));
463
464         sptlrpc_cli_ctx_get(oldctx);
465         sptlrpc_req_put_ctx(req, 0);
466
467         rc = sptlrpc_req_get_ctx(req);
468         if (unlikely(rc)) {
469                 LASSERT(!req->rq_cli_ctx);
470
471                 /* restore old ctx */
472                 req->rq_cli_ctx = oldctx;
473                 RETURN(rc);
474         }
475
476         newctx = req->rq_cli_ctx;
477         LASSERT(newctx);
478
479         if (unlikely(newctx == oldctx)) {
480                 /*
481                  * still get the old ctx, usually means system busy
482                  */
483                 CWARN("ctx (%p, fl %lx) doesn't switch, relax a little bit\n",
484                       newctx, newctx->cc_flags);
485
486                 cfs_schedule_timeout(CFS_TASK_INTERRUPTIBLE, HZ);
487         } else {
488                 rc = sptlrpc_req_ctx_switch(req, oldctx, newctx);
489                 if (rc) {
490                         /* restore old ctx */
491                         sptlrpc_req_put_ctx(req, 0);
492                         req->rq_cli_ctx = oldctx;
493                         RETURN(rc);
494                 }
495
496                 LASSERT(req->rq_cli_ctx == newctx);
497         }
498
499         sptlrpc_cli_ctx_put(oldctx, 1);
500         RETURN(0);
501 }
502 EXPORT_SYMBOL(sptlrpc_req_replace_dead_ctx);
503
504 static
505 int ctx_check_refresh(struct ptlrpc_cli_ctx *ctx)
506 {
507         if (cli_ctx_is_refreshed(ctx))
508                 return 1;
509         return 0;
510 }
511
512 static
513 int ctx_refresh_timeout(void *data)
514 {
515         struct ptlrpc_request *req = data;
516         int rc;
517
518         /* conn_cnt is needed in expire_one_request */
519         lustre_msg_set_conn_cnt(req->rq_reqmsg, req->rq_import->imp_conn_cnt);
520
521         rc = ptlrpc_expire_one_request(req);
522         /* if we started recovery, we should mark this ctx dead; otherwise
523          * in case of lgssd died nobody would retire this ctx, following
524          * connecting will still find the same ctx thus cause deadlock.
525          * there's an assumption that expire time of the request should be
526          * later than the context refresh expire time.
527          */
528         if (rc == 0)
529                 req->rq_cli_ctx->cc_ops->die(req->rq_cli_ctx, 0);
530         return rc;
531 }
532
533 static
534 void ctx_refresh_interrupt(void *data)
535 {
536         struct ptlrpc_request *req = data;
537
538         spin_lock(&req->rq_lock);
539         req->rq_intr = 1;
540         spin_unlock(&req->rq_lock);
541 }
542
543 static
544 void req_off_ctx_list(struct ptlrpc_request *req, struct ptlrpc_cli_ctx *ctx)
545 {
546         spin_lock(&ctx->cc_lock);
547         if (!list_empty(&req->rq_ctx_chain))
548                 list_del_init(&req->rq_ctx_chain);
549         spin_unlock(&ctx->cc_lock);
550 }
551
552 /*
553  * the status of context could be subject to be changed by other threads at any
554  * time. we allow this race. but once we return with 0, the caller will
555  * suppose it's uptodated and keep using it until the owning rpc is done.
556  *
557  * @timeout:
558  *    < 0  - don't wait
559  *    = 0  - wait until success or fatal error occur
560  *    > 0  - timeout value
561  *
562  * return 0 only if the context is uptodated.
563  */
564 int sptlrpc_req_refresh_ctx(struct ptlrpc_request *req, long timeout)
565 {
566         struct ptlrpc_cli_ctx  *ctx = req->rq_cli_ctx;
567         struct l_wait_info      lwi;
568         int                     rc;
569         ENTRY;
570
571         LASSERT(ctx);
572
573         /*
574          * during the process a request's context might change type even
575          * (e.g. from gss ctx to plain ctx), so each loop we need to re-check
576          * everything
577          */
578 again:
579         /* skip special ctxs */
580         if (cli_ctx_is_eternal(ctx) || req->rq_ctx_init || req->rq_ctx_fini)
581                 RETURN(0);
582
583         if (test_bit(PTLRPC_CTX_NEW_BIT, &ctx->cc_flags)) {
584                 LASSERT(ctx->cc_ops->refresh);
585                 ctx->cc_ops->refresh(ctx);
586         }
587         LASSERT(test_bit(PTLRPC_CTX_NEW_BIT, &ctx->cc_flags) == 0);
588
589         LASSERT(ctx->cc_ops->validate);
590         if (ctx->cc_ops->validate(ctx) == 0) {
591                 req_off_ctx_list(req, ctx);
592                 RETURN(0);
593         }
594
595         if (unlikely(test_bit(PTLRPC_CTX_ERROR_BIT, &ctx->cc_flags))) {
596                 req->rq_err = 1;
597                 req_off_ctx_list(req, ctx);
598                 RETURN(-EPERM);
599         }
600
601         /* This is subtle. For resent message we have to keep original
602          * context to survive following situation:
603          *  1. the request sent to server
604          *  2. recovery was kick start
605          *  3. recovery finished, the request marked as resent
606          *  4. resend the request
607          *  5. old reply from server received (because xid is the same)
608          *  6. verify reply (has to be success)
609          *  7. new reply from server received, lnet drop it
610          *
611          * Note we can't simply change xid for resent request because
612          * server reply on it for reply reconstruction.
613          *
614          * Commonly the original context should be uptodate because we
615          * have a expiry nice time; And server will keep their half part
616          * context because we at least hold a ref of old context which
617          * prevent the context detroy RPC be sent. So server still can
618          * accept the request and finish RPC. Two cases:
619          *  1. If server side context has been trimed, a NO_CONTEXT will
620          *     be returned, gss_cli_ctx_verify/unseal will switch to new
621          *     context by force.
622          *  2. Current context never be refreshed, then we are fine: we
623          *     never really send request with old context before.
624          */
625         if (test_bit(PTLRPC_CTX_UPTODATE_BIT, &ctx->cc_flags) &&
626             unlikely(req->rq_reqmsg) &&
627             lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT) {
628                 req_off_ctx_list(req, ctx);
629                 RETURN(0);
630         }
631
632         if (unlikely(test_bit(PTLRPC_CTX_DEAD_BIT, &ctx->cc_flags))) {
633                 rc = sptlrpc_req_replace_dead_ctx(req);
634                 if (rc) {
635                         LASSERT(ctx == req->rq_cli_ctx);
636                         CERROR("req %p: failed to replace dead ctx %p: %d\n",
637                                 req, ctx, rc);
638                         req->rq_err = 1;
639                         LASSERT(list_empty(&req->rq_ctx_chain));
640                         RETURN(rc);
641                 }
642
643                 CWARN("req %p: replace dead ctx %p => ctx %p (%u->%s)\n",
644                       req, ctx, req->rq_cli_ctx,
645                       req->rq_cli_ctx->cc_vcred.vc_uid,
646                       sec2target_str(req->rq_cli_ctx->cc_sec));
647
648                 ctx = req->rq_cli_ctx;
649                 LASSERT(list_empty(&req->rq_ctx_chain));
650
651                 goto again;
652         }
653
654         /* Now we're sure this context is during upcall, add myself into
655          * waiting list
656          */
657         spin_lock(&ctx->cc_lock);
658         if (list_empty(&req->rq_ctx_chain))
659                 list_add(&req->rq_ctx_chain, &ctx->cc_req_list);
660         spin_unlock(&ctx->cc_lock);
661
662         if (timeout < 0) {
663                 RETURN(-EWOULDBLOCK);
664         }
665
666         /* Clear any flags that may be present from previous sends */
667         LASSERT(req->rq_receiving_reply == 0);
668         spin_lock(&req->rq_lock);
669         req->rq_err = 0;
670         req->rq_timedout = 0;
671         req->rq_resend = 0;
672         req->rq_restart = 0;
673         spin_unlock(&req->rq_lock);
674
675         lwi = LWI_TIMEOUT_INTR(timeout * HZ, ctx_refresh_timeout,
676                                ctx_refresh_interrupt, req);
677         rc = l_wait_event(req->rq_reply_waitq, ctx_check_refresh(ctx), &lwi);
678
679         /* following cases we could be here:
680          * - successfully refreshed;
681          * - interruptted;
682          * - timedout, and we don't want recover from the failure;
683          * - timedout, and waked up upon recovery finished;
684          * - someone else mark this ctx dead by force;
685          * - someone invalidate the req and call wake_client_req(),
686          *   e.g. ptlrpc_abort_inflight();
687          */
688         if (!cli_ctx_is_refreshed(ctx)) {
689                 /* timed out or interruptted */
690                 req_off_ctx_list(req, ctx);
691
692                 LASSERT(rc != 0);
693                 RETURN(rc);
694         }
695
696         goto again;
697 }
698
699 /*
700  * Note this could be called in two situations:
701  * - new request from ptlrpc_pre_req(), with proper @opcode
702  * - old request which changed ctx in the middle, with @opcode == 0
703  */
704 void sptlrpc_req_set_flavor(struct ptlrpc_request *req, int opcode)
705 {
706         struct ptlrpc_sec *sec;
707
708         LASSERT(req->rq_import);
709         LASSERT(req->rq_cli_ctx);
710         LASSERT(req->rq_cli_ctx->cc_sec);
711         LASSERT(req->rq_bulk_read == 0 || req->rq_bulk_write == 0);
712
713         /* special security flags accoding to opcode */
714         switch (opcode) {
715         case OST_READ:
716                 req->rq_bulk_read = 1;
717                 break;
718         case OST_WRITE:
719                 req->rq_bulk_write = 1;
720                 break;
721         case SEC_CTX_INIT:
722                 req->rq_ctx_init = 1;
723                 break;
724         case SEC_CTX_FINI:
725                 req->rq_ctx_fini = 1;
726                 break;
727         case 0:
728                 /* init/fini rpc won't be resend, so can't be here */
729                 LASSERT(req->rq_ctx_init == 0);
730                 LASSERT(req->rq_ctx_fini == 0);
731
732                 /* cleanup flags, which should be recalculated */
733                 req->rq_pack_udesc = 0;
734                 req->rq_pack_bulk = 0;
735                 break;
736         }
737
738         sec = req->rq_cli_ctx->cc_sec;
739
740         spin_lock(&sec->ps_lock);
741         req->rq_flvr = sec->ps_flvr;
742         spin_unlock(&sec->ps_lock);
743
744         /* force SVC_NULL for context initiation rpc, SVC_INTG for context
745          * destruction rpc */
746         if (unlikely(req->rq_ctx_init))
747                 rpc_flvr_set_svc(&req->rq_flvr.sf_rpc, SPTLRPC_SVC_NULL);
748         else if (unlikely(req->rq_ctx_fini))
749                 rpc_flvr_set_svc(&req->rq_flvr.sf_rpc, SPTLRPC_SVC_INTG);
750
751         /* user descriptor flag, null security can't do it anyway */
752         if ((sec->ps_flvr.sf_flags & PTLRPC_SEC_FL_UDESC) &&
753             (req->rq_flvr.sf_rpc != SPTLRPC_FLVR_NULL))
754                 req->rq_pack_udesc = 1;
755
756         /* bulk security flag */
757         if ((req->rq_bulk_read || req->rq_bulk_write) &&
758             (req->rq_flvr.sf_bulk_ciph != BULK_CIPH_ALG_NULL ||
759              req->rq_flvr.sf_bulk_hash != BULK_HASH_ALG_NULL))
760                 req->rq_pack_bulk = 1;
761 }
762
763 void sptlrpc_request_out_callback(struct ptlrpc_request *req)
764 {
765         if (RPC_FLVR_SVC(req->rq_flvr.sf_rpc) != SPTLRPC_SVC_PRIV)
766                 return;
767
768         LASSERT(req->rq_clrbuf);
769         if (req->rq_pool || !req->rq_reqbuf)
770                 return;
771
772         OBD_FREE(req->rq_reqbuf, req->rq_reqbuf_len);
773         req->rq_reqbuf = NULL;
774         req->rq_reqbuf_len = 0;
775 }
776
777 /*
778  * check whether current user have valid context for an import or not.
779  * might repeatedly try in case of non-fatal errors.
780  * return 0 on success, < 0 on failure
781  */
782 int sptlrpc_import_check_ctx(struct obd_import *imp)
783 {
784         struct ptlrpc_sec     *sec;
785         struct ptlrpc_cli_ctx *ctx;
786         struct ptlrpc_request *req = NULL;
787         int rc;
788         ENTRY;
789
790         might_sleep();
791
792         sec = sptlrpc_import_sec_ref(imp);
793         ctx = get_my_ctx(sec);
794         sptlrpc_sec_put(sec);
795
796         if (!ctx)
797                 RETURN(1);
798
799         if (cli_ctx_is_eternal(ctx) ||
800             ctx->cc_ops->validate(ctx) == 0) {
801                 sptlrpc_cli_ctx_put(ctx, 1);
802                 RETURN(0);
803         }
804
805         OBD_ALLOC_PTR(req);
806         if (!req)
807                 RETURN(-ENOMEM);
808
809         spin_lock_init(&req->rq_lock);
810         atomic_set(&req->rq_refcount, 10000);
811         CFS_INIT_LIST_HEAD(&req->rq_ctx_chain);
812         cfs_waitq_init(&req->rq_reply_waitq);
813         req->rq_import = imp;
814         req->rq_cli_ctx = ctx;
815
816         rc = sptlrpc_req_refresh_ctx(req, 0);
817         LASSERT(list_empty(&req->rq_ctx_chain));
818         sptlrpc_cli_ctx_put(req->rq_cli_ctx, 1);
819         OBD_FREE_PTR(req);
820
821         RETURN(rc);
822 }
823
824 int sptlrpc_cli_wrap_request(struct ptlrpc_request *req)
825 {
826         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
827         int rc = 0;
828         ENTRY;
829
830         LASSERT(ctx);
831         LASSERT(ctx->cc_sec);
832         LASSERT(req->rq_reqbuf || req->rq_clrbuf);
833
834         /* we wrap bulk request here because now we can be sure
835          * the context is uptodate.
836          */
837         if (req->rq_bulk) {
838                 rc = sptlrpc_cli_wrap_bulk(req, req->rq_bulk);
839                 if (rc)
840                         RETURN(rc);
841         }
842
843         switch (RPC_FLVR_SVC(req->rq_flvr.sf_rpc)) {
844         case SPTLRPC_SVC_NULL:
845         case SPTLRPC_SVC_AUTH:
846         case SPTLRPC_SVC_INTG:
847                 LASSERT(ctx->cc_ops->sign);
848                 rc = ctx->cc_ops->sign(ctx, req);
849                 break;
850         case SPTLRPC_SVC_PRIV:
851                 LASSERT(ctx->cc_ops->seal);
852                 rc = ctx->cc_ops->seal(ctx, req);
853                 break;
854         default:
855                 LBUG();
856         }
857
858         if (rc == 0) {
859                 LASSERT(req->rq_reqdata_len);
860                 LASSERT(req->rq_reqdata_len % 8 == 0);
861                 LASSERT(req->rq_reqdata_len <= req->rq_reqbuf_len);
862         }
863
864         RETURN(rc);
865 }
866
867 static int do_cli_unwrap_reply(struct ptlrpc_request *req)
868 {
869         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
870         int                    rc;
871         __u16                  rpc_flvr;
872         ENTRY;
873
874         LASSERT(ctx);
875         LASSERT(ctx->cc_sec);
876         LASSERT(req->rq_repbuf);
877         LASSERT(req->rq_repdata);
878         LASSERT(req->rq_repmsg == NULL);
879
880         if (req->rq_repdata_len < sizeof(struct lustre_msg)) {
881                 CERROR("replied data length %d too small\n",
882                        req->rq_repdata_len);
883                 RETURN(-EPROTO);
884         }
885
886         /* v2 message, check request/reply policy match */
887         rpc_flvr = WIRE_FLVR_RPC(req->rq_repdata->lm_secflvr);
888
889         if (req->rq_repdata->lm_magic == LUSTRE_MSG_MAGIC_V2_SWABBED)
890                 __swab16s(&rpc_flvr);
891
892         if (RPC_FLVR_POLICY(rpc_flvr) !=
893             RPC_FLVR_POLICY(req->rq_flvr.sf_rpc)) {
894                 CERROR("request policy was %u while reply with %u\n",
895                        RPC_FLVR_POLICY(req->rq_flvr.sf_rpc),
896                        RPC_FLVR_POLICY(rpc_flvr));
897                 RETURN(-EPROTO);
898         }
899
900         /* do nothing if it's null policy; otherwise unpack the
901          * wrapper message */
902         if (RPC_FLVR_POLICY(rpc_flvr) != SPTLRPC_POLICY_NULL &&
903             lustre_unpack_msg(req->rq_repdata, req->rq_repdata_len))
904                 RETURN(-EPROTO);
905
906         switch (RPC_FLVR_SVC(req->rq_flvr.sf_rpc)) {
907         case SPTLRPC_SVC_NULL:
908         case SPTLRPC_SVC_AUTH:
909         case SPTLRPC_SVC_INTG:
910                 LASSERT(ctx->cc_ops->verify);
911                 rc = ctx->cc_ops->verify(ctx, req);
912                 break;
913         case SPTLRPC_SVC_PRIV:
914                 LASSERT(ctx->cc_ops->unseal);
915                 rc = ctx->cc_ops->unseal(ctx, req);
916                 break;
917         default:
918                 LBUG();
919         }
920
921         LASSERT(rc || req->rq_repmsg || req->rq_resend);
922         RETURN(rc);
923 }
924
925 /*
926  * upon this be called, the reply buffer should have been un-posted,
927  * so nothing is going to change.
928  */
929 int sptlrpc_cli_unwrap_reply(struct ptlrpc_request *req)
930 {
931         LASSERT(req->rq_repbuf);
932         LASSERT(req->rq_repdata == NULL);
933         LASSERT(req->rq_repmsg == NULL);
934         LASSERT(req->rq_reply_off + req->rq_nob_received <= req->rq_repbuf_len);
935
936         if (req->rq_reply_off == 0) {
937                 CERROR("real reply with offset 0\n");
938                 return -EPROTO;
939         }
940
941         if (req->rq_reply_off % 8 != 0) {
942                 CERROR("reply at odd offset %u\n", req->rq_reply_off);
943                 return -EPROTO;
944         }
945
946         req->rq_repdata = (struct lustre_msg *)
947                                 (req->rq_repbuf + req->rq_reply_off);
948         req->rq_repdata_len = req->rq_nob_received;
949
950         return do_cli_unwrap_reply(req);
951 }
952
953 /**
954  * Upon called, the receive buffer might be still posted, so the reply data
955  * might be changed at any time, no matter we're holding rq_lock or not. we
956  * expect the rq_reply_off be 0, rq_nob_received is the early reply size.
957  *
958  * we allocate separate ptlrpc_request and reply buffer for early reply
959  * processing, return 0 and @req_ret is a duplicated ptlrpc_request. caller
960  * must call sptlrpc_cli_finish_early_reply() on the returned request to
961  * release it. if anything goes wrong @req_ret will not be set.
962  */
963 int sptlrpc_cli_unwrap_early_reply(struct ptlrpc_request *req,
964                                    struct ptlrpc_request **req_ret)
965 {
966         struct ptlrpc_request  *early_req;
967         char                   *early_buf;
968         int                     early_bufsz, early_size;
969         int                     rc;
970         ENTRY;
971
972         OBD_ALLOC_PTR(early_req);
973         if (early_req == NULL)
974                 RETURN(-ENOMEM);
975
976         early_size = req->rq_nob_received;
977         early_bufsz = size_roundup_power2(early_size);
978         OBD_ALLOC(early_buf, early_bufsz);
979         if (early_buf == NULL)
980                 GOTO(err_req, rc = -ENOMEM);
981
982         /* sanity checkings and copy data out, do it inside spinlock */
983         spin_lock(&req->rq_lock);
984
985         if (req->rq_replied) {
986                 spin_unlock(&req->rq_lock);
987                 GOTO(err_buf, rc = -EALREADY);
988         }
989
990         LASSERT(req->rq_repbuf);
991         LASSERT(req->rq_repdata == NULL);
992         LASSERT(req->rq_repmsg == NULL);
993
994         if (req->rq_reply_off != 0) {
995                 CERROR("early reply with offset %u\n", req->rq_reply_off);
996                 spin_unlock(&req->rq_lock);
997                 GOTO(err_buf, rc = -EPROTO);
998         }
999
1000         if (req->rq_nob_received != early_size) {
1001                 /* even another early arrived the size should be the same */
1002                 CERROR("data size has changed from %u to %u\n",
1003                        early_size, req->rq_nob_received);
1004                 spin_unlock(&req->rq_lock);
1005                 GOTO(err_buf, rc = -EINVAL);
1006         }
1007
1008         if (req->rq_nob_received < sizeof(struct lustre_msg)) {
1009                 CERROR("early reply length %d too small\n",
1010                        req->rq_nob_received);
1011                 spin_unlock(&req->rq_lock);
1012                 GOTO(err_buf, rc = -EALREADY);
1013         }
1014
1015         memcpy(early_buf, req->rq_repbuf, early_size);
1016         spin_unlock(&req->rq_lock);
1017
1018         early_req->rq_cli_ctx = sptlrpc_cli_ctx_get(req->rq_cli_ctx);
1019         early_req->rq_flvr = req->rq_flvr;
1020         early_req->rq_repbuf = early_buf;
1021         early_req->rq_repbuf_len = early_bufsz;
1022         early_req->rq_repdata = (struct lustre_msg *) early_buf;
1023         early_req->rq_repdata_len = early_size;
1024         early_req->rq_early = 1;
1025
1026         rc = do_cli_unwrap_reply(early_req);
1027         if (rc) {
1028                 DEBUG_REQ(D_ADAPTTO, early_req,
1029                           "error %d unwrap early reply", rc);
1030                 GOTO(err_ctx, rc);
1031         }
1032
1033         LASSERT(early_req->rq_repmsg);
1034         *req_ret = early_req;
1035         RETURN(0);
1036
1037 err_ctx:
1038         sptlrpc_cli_ctx_put(early_req->rq_cli_ctx, 1);
1039 err_buf:
1040         OBD_FREE(early_buf, early_bufsz);
1041 err_req:
1042         OBD_FREE_PTR(early_req);
1043         RETURN(rc);
1044 }
1045
1046 void sptlrpc_cli_finish_early_reply(struct ptlrpc_request *early_req)
1047 {
1048         LASSERT(early_req->rq_repbuf);
1049         LASSERT(early_req->rq_repdata);
1050         LASSERT(early_req->rq_repmsg);
1051
1052         sptlrpc_cli_ctx_put(early_req->rq_cli_ctx, 1);
1053         OBD_FREE(early_req->rq_repbuf, early_req->rq_repbuf_len);
1054         OBD_FREE_PTR(early_req);
1055 }
1056
1057 /**************************************************
1058  * sec ID                                         *
1059  **************************************************/
1060
1061 /*
1062  * "fixed" sec (e.g. null) use sec_id < 0
1063  */
1064 static atomic_t sptlrpc_sec_id = ATOMIC_INIT(1);
1065
1066 int sptlrpc_get_next_secid(void)
1067 {
1068         return atomic_inc_return(&sptlrpc_sec_id);
1069 }
1070 EXPORT_SYMBOL(sptlrpc_get_next_secid);
1071
1072 /**************************************************
1073  * client side high-level security APIs           *
1074  **************************************************/
1075
1076 static int sec_cop_flush_ctx_cache(struct ptlrpc_sec *sec, uid_t uid,
1077                                    int grace, int force)
1078 {
1079         struct ptlrpc_sec_policy *policy = sec->ps_policy;
1080
1081         LASSERT(policy->sp_cops);
1082         LASSERT(policy->sp_cops->flush_ctx_cache);
1083
1084         return policy->sp_cops->flush_ctx_cache(sec, uid, grace, force);
1085 }
1086
1087 static void sec_cop_destroy_sec(struct ptlrpc_sec *sec)
1088 {
1089         struct ptlrpc_sec_policy *policy = sec->ps_policy;
1090
1091         LASSERT(atomic_read(&sec->ps_refcount) == 0);
1092         LASSERT(atomic_read(&sec->ps_nctx) == 0);
1093         LASSERT(policy->sp_cops->destroy_sec);
1094
1095         CDEBUG(D_SEC, "%s@%p: being destroied\n", sec->ps_policy->sp_name, sec);
1096
1097         policy->sp_cops->destroy_sec(sec);
1098         sptlrpc_policy_put(policy);
1099 }
1100
1101 void sptlrpc_sec_destroy(struct ptlrpc_sec *sec)
1102 {
1103         sec_cop_destroy_sec(sec);
1104 }
1105 EXPORT_SYMBOL(sptlrpc_sec_destroy);
1106
1107 static void sptlrpc_sec_kill(struct ptlrpc_sec *sec)
1108 {
1109         LASSERT(atomic_read(&sec->ps_refcount) > 0);
1110
1111         if (sec->ps_policy->sp_cops->kill_sec) {
1112                 sec->ps_policy->sp_cops->kill_sec(sec);
1113
1114                 sec_cop_flush_ctx_cache(sec, -1, 1, 1);
1115         }
1116 }
1117
1118 struct ptlrpc_sec *sptlrpc_sec_get(struct ptlrpc_sec *sec)
1119 {
1120         if (sec) {
1121                 LASSERT(atomic_read(&sec->ps_refcount) > 0);
1122                 atomic_inc(&sec->ps_refcount);
1123         }
1124
1125         return sec;
1126 }
1127 EXPORT_SYMBOL(sptlrpc_sec_get);
1128
1129 void sptlrpc_sec_put(struct ptlrpc_sec *sec)
1130 {
1131         if (sec) {
1132                 LASSERT(atomic_read(&sec->ps_refcount) > 0);
1133
1134                 if (atomic_dec_and_test(&sec->ps_refcount)) {
1135                         LASSERT(atomic_read(&sec->ps_nctx) == 0);
1136
1137                         sptlrpc_gc_del_sec(sec);
1138                         sec_cop_destroy_sec(sec);
1139                 }
1140         }
1141 }
1142 EXPORT_SYMBOL(sptlrpc_sec_put);
1143
1144 /*
1145  * it's policy module responsible for taking refrence of import
1146  */
1147 static
1148 struct ptlrpc_sec * sptlrpc_sec_create(struct obd_import *imp,
1149                                        struct ptlrpc_svc_ctx *svc_ctx,
1150                                        struct sptlrpc_flavor *sf,
1151                                        enum lustre_sec_part sp)
1152 {
1153         struct ptlrpc_sec_policy *policy;
1154         struct ptlrpc_sec        *sec;
1155         ENTRY;
1156
1157         if (svc_ctx) {
1158                 LASSERT(imp->imp_dlm_fake == 1);
1159
1160                 CDEBUG(D_SEC, "%s %s: reverse sec using flavor %s\n",
1161                        imp->imp_obd->obd_type->typ_name,
1162                        imp->imp_obd->obd_name,
1163                        sptlrpc_rpcflavor2name(sf->sf_rpc));
1164
1165                 policy = sptlrpc_policy_get(svc_ctx->sc_policy);
1166                 sf->sf_flags |= PTLRPC_SEC_FL_REVERSE | PTLRPC_SEC_FL_ROOTONLY;
1167         } else {
1168                 LASSERT(imp->imp_dlm_fake == 0);
1169
1170                 CDEBUG(D_SEC, "%s %s: select security flavor %s\n",
1171                        imp->imp_obd->obd_type->typ_name,
1172                        imp->imp_obd->obd_name,
1173                        sptlrpc_rpcflavor2name(sf->sf_rpc));
1174
1175                 policy = sptlrpc_rpcflavor2policy(sf->sf_rpc);
1176                 if (!policy) {
1177                         CERROR("invalid flavor 0x%x\n", sf->sf_rpc);
1178                         RETURN(NULL);
1179                 }
1180         }
1181
1182         sec = policy->sp_cops->create_sec(imp, svc_ctx, sf);
1183         if (sec) {
1184                 atomic_inc(&sec->ps_refcount);
1185
1186                 sec->ps_part = sp;
1187
1188                 if (sec->ps_gc_interval && policy->sp_cops->gc_ctx)
1189                         sptlrpc_gc_add_sec(sec);
1190         } else {
1191                 sptlrpc_policy_put(policy);
1192         }
1193
1194         RETURN(sec);
1195 }
1196
1197 struct ptlrpc_sec *sptlrpc_import_sec_ref(struct obd_import *imp)
1198 {
1199         struct ptlrpc_sec *sec;
1200
1201         spin_lock(&imp->imp_lock);
1202         sec = sptlrpc_sec_get(imp->imp_sec);
1203         spin_unlock(&imp->imp_lock);
1204
1205         return sec;
1206 }
1207 EXPORT_SYMBOL(sptlrpc_import_sec_ref);
1208
1209 static void sptlrpc_import_sec_install(struct obd_import *imp,
1210                                        struct ptlrpc_sec *sec)
1211 {
1212         struct ptlrpc_sec *old_sec;
1213
1214         LASSERT(atomic_read(&sec->ps_refcount) > 0);
1215
1216         spin_lock(&imp->imp_lock);
1217         old_sec = imp->imp_sec;
1218         imp->imp_sec = sec;
1219         spin_unlock(&imp->imp_lock);
1220
1221         if (old_sec) {
1222                 sptlrpc_sec_kill(old_sec);
1223
1224                 /* balance the ref taken by this import */
1225                 sptlrpc_sec_put(old_sec);
1226         }
1227 }
1228
1229 static void sptlrpc_import_sec_adapt_inplace(struct obd_import *imp,
1230                                              struct ptlrpc_sec *sec,
1231                                              struct sptlrpc_flavor *sf)
1232 {
1233         if (sf->sf_bulk_ciph != sec->ps_flvr.sf_bulk_ciph ||
1234             sf->sf_bulk_hash != sec->ps_flvr.sf_bulk_hash) {
1235                 CWARN("imp %p (%s->%s): changing bulk flavor %s/%s -> %s/%s\n",
1236                       imp, imp->imp_obd->obd_name,
1237                       obd_uuid2str(&imp->imp_connection->c_remote_uuid),
1238                       sptlrpc_get_ciph_name(sec->ps_flvr.sf_bulk_ciph),
1239                       sptlrpc_get_hash_name(sec->ps_flvr.sf_bulk_hash),
1240                       sptlrpc_get_ciph_name(sf->sf_bulk_ciph),
1241                       sptlrpc_get_hash_name(sf->sf_bulk_hash));
1242
1243                 spin_lock(&sec->ps_lock);
1244                 sec->ps_flvr.sf_bulk_ciph = sf->sf_bulk_ciph;
1245                 sec->ps_flvr.sf_bulk_hash = sf->sf_bulk_hash;
1246                 spin_unlock(&sec->ps_lock);
1247         }
1248
1249         if (!equi(sf->sf_flags & PTLRPC_SEC_FL_UDESC,
1250                   sec->ps_flvr.sf_flags & PTLRPC_SEC_FL_UDESC)) {
1251                 CWARN("imp %p (%s->%s): %s shipping user descriptor\n",
1252                       imp, imp->imp_obd->obd_name,
1253                       obd_uuid2str(&imp->imp_connection->c_remote_uuid),
1254                       (sf->sf_flags & PTLRPC_SEC_FL_UDESC) ? "start" : "stop");
1255
1256                 spin_lock(&sec->ps_lock);
1257                 sec->ps_flvr.sf_flags &= ~PTLRPC_SEC_FL_UDESC;
1258                 sec->ps_flvr.sf_flags |= sf->sf_flags & PTLRPC_SEC_FL_UDESC;
1259                 spin_unlock(&sec->ps_lock);
1260         }
1261 }
1262
1263 /*
1264  * for normal import, @svc_ctx should be NULL and @rpc_flavor is ignored;
1265  * for reverse import, @svc_ctx and @rpc_flavor is from incoming request.
1266  */
1267 int sptlrpc_import_sec_adapt(struct obd_import *imp,
1268                              struct ptlrpc_svc_ctx *svc_ctx,
1269                              __u16 rpc_flavor)
1270 {
1271         struct ptlrpc_connection   *conn;
1272         struct sptlrpc_flavor       sf;
1273         struct ptlrpc_sec          *sec, *newsec;
1274         enum lustre_sec_part        sp;
1275         int                         rc;
1276
1277         if (imp == NULL)
1278                 return 0;
1279
1280         conn = imp->imp_connection;
1281
1282         if (svc_ctx == NULL) {
1283                 /* normal import, determine flavor from rule set */
1284                 sptlrpc_rule_set_choose(&imp->imp_obd->u.cli.cl_sptlrpc_rset,
1285                                         LUSTRE_SP_ANY, conn->c_self, &sf);
1286
1287                 sp = imp->imp_obd->u.cli.cl_sec_part;
1288         } else {
1289                 /* reverse import, determine flavor from incoming reqeust */
1290                 sf.sf_rpc = rpc_flavor;
1291                 sf.sf_bulk_ciph = BULK_CIPH_ALG_NULL;
1292                 sf.sf_bulk_hash = BULK_HASH_ALG_NULL;
1293                 sf.sf_flags = PTLRPC_SEC_FL_REVERSE | PTLRPC_SEC_FL_ROOTONLY;
1294
1295                 sp = sptlrpc_target_sec_part(imp->imp_obd);
1296         }
1297
1298         sec = sptlrpc_import_sec_ref(imp);
1299         if (sec) {
1300                 if (svc_ctx == NULL) {
1301                         /* normal import, only check rpc flavor, if just bulk
1302                          * flavor or flags changed, we can handle it on the fly
1303                          * without switching sec. */
1304                         if (sf.sf_rpc == sec->ps_flvr.sf_rpc) {
1305                                 sptlrpc_import_sec_adapt_inplace(imp, sec, &sf);
1306
1307                                 rc = 0;
1308                                 goto out;
1309                         }
1310                 } else {
1311                         /* reverse import, do not compare bulk flavor */
1312                         if (sf.sf_rpc == sec->ps_flvr.sf_rpc) {
1313                                 rc = 0;
1314                                 goto out;
1315                         }
1316                 }
1317
1318                 CWARN("%simport %p (%s%s%s): changing flavor "
1319                       "(%s, %s/%s) -> (%s, %s/%s)\n",
1320                       svc_ctx ? "reverse " : "",
1321                       imp, imp->imp_obd->obd_name,
1322                       svc_ctx == NULL ? "->" : "<-",
1323                       obd_uuid2str(&conn->c_remote_uuid),
1324                       sptlrpc_rpcflavor2name(sec->ps_flvr.sf_rpc),
1325                       sptlrpc_get_hash_name(sec->ps_flvr.sf_bulk_hash),
1326                       sptlrpc_get_ciph_name(sec->ps_flvr.sf_bulk_ciph),
1327                       sptlrpc_rpcflavor2name(sf.sf_rpc),
1328                       sptlrpc_get_hash_name(sf.sf_bulk_hash),
1329                       sptlrpc_get_ciph_name(sf.sf_bulk_ciph));
1330         } else {
1331                 CWARN("%simport %p (%s%s%s) netid %x: "
1332                       "select initial flavor (%s, %s/%s)\n",
1333                       svc_ctx == NULL ? "" : "reverse ",
1334                       imp, imp->imp_obd->obd_name,
1335                       svc_ctx == NULL ? "->" : "<-",
1336                       obd_uuid2str(&conn->c_remote_uuid),
1337                       LNET_NIDNET(conn->c_self),
1338                       sptlrpc_rpcflavor2name(sf.sf_rpc),
1339                       sptlrpc_get_hash_name(sf.sf_bulk_hash),
1340                       sptlrpc_get_ciph_name(sf.sf_bulk_ciph));
1341         }
1342
1343         mutex_down(&imp->imp_sec_mutex);
1344
1345         newsec = sptlrpc_sec_create(imp, svc_ctx, &sf, sp);
1346         if (newsec) {
1347                 sptlrpc_import_sec_install(imp, newsec);
1348                 rc = 0;
1349         } else {
1350                 CERROR("%simport %p (%s): failed to create new sec\n",
1351                        svc_ctx == NULL ? "" : "reverse ",
1352                        imp, obd_uuid2str(&conn->c_remote_uuid));
1353                 rc = -EPERM;
1354         }
1355
1356         mutex_up(&imp->imp_sec_mutex);
1357
1358 out:
1359         sptlrpc_sec_put(sec);
1360         return 0;
1361 }
1362
1363 void sptlrpc_import_sec_put(struct obd_import *imp)
1364 {
1365         if (imp->imp_sec) {
1366                 sptlrpc_sec_kill(imp->imp_sec);
1367
1368                 sptlrpc_sec_put(imp->imp_sec);
1369                 imp->imp_sec = NULL;
1370         }
1371 }
1372
1373 static void import_flush_ctx_common(struct obd_import *imp,
1374                                     uid_t uid, int grace, int force)
1375 {
1376         struct ptlrpc_sec *sec;
1377
1378         if (imp == NULL)
1379                 return;
1380
1381         sec = sptlrpc_import_sec_ref(imp);
1382         if (sec == NULL)
1383                 return;
1384
1385         sec_cop_flush_ctx_cache(sec, uid, grace, force);
1386         sptlrpc_sec_put(sec);
1387 }
1388
1389 void sptlrpc_import_inval_all_ctx(struct obd_import *imp)
1390 {
1391         /* use grace == 0 */
1392         import_flush_ctx_common(imp, -1, 0, 1);
1393 }
1394
1395 void sptlrpc_import_flush_root_ctx(struct obd_import *imp)
1396 {
1397         /* it's important to use grace mode, see explain in
1398          * sptlrpc_req_refresh_ctx() */
1399         import_flush_ctx_common(imp, 0, 1, 1);
1400 }
1401
1402 void sptlrpc_import_flush_my_ctx(struct obd_import *imp)
1403 {
1404         import_flush_ctx_common(imp, cfs_current()->uid, 1, 1);
1405 }
1406 EXPORT_SYMBOL(sptlrpc_import_flush_my_ctx);
1407
1408 void sptlrpc_import_flush_all_ctx(struct obd_import *imp)
1409 {
1410         import_flush_ctx_common(imp, -1, 1, 1);
1411 }
1412 EXPORT_SYMBOL(sptlrpc_import_flush_all_ctx);
1413
1414 /*
1415  * when complete successfully, req->rq_reqmsg should point to the
1416  * right place.
1417  */
1418 int sptlrpc_cli_alloc_reqbuf(struct ptlrpc_request *req, int msgsize)
1419 {
1420         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
1421         struct ptlrpc_sec_policy *policy;
1422         int rc;
1423
1424         LASSERT(ctx);
1425         LASSERT(atomic_read(&ctx->cc_refcount));
1426         LASSERT(ctx->cc_sec);
1427         LASSERT(ctx->cc_sec->ps_policy);
1428         LASSERT(req->rq_reqmsg == NULL);
1429
1430         policy = ctx->cc_sec->ps_policy;
1431         rc = policy->sp_cops->alloc_reqbuf(ctx->cc_sec, req, msgsize);
1432         if (!rc) {
1433                 LASSERT(req->rq_reqmsg);
1434                 LASSERT(req->rq_reqbuf || req->rq_clrbuf);
1435
1436                 /* zeroing preallocated buffer */
1437                 if (req->rq_pool)
1438                         memset(req->rq_reqmsg, 0, msgsize);
1439         }
1440
1441         return rc;
1442 }
1443
1444 void sptlrpc_cli_free_reqbuf(struct ptlrpc_request *req)
1445 {
1446         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
1447         struct ptlrpc_sec_policy *policy;
1448
1449         LASSERT(ctx);
1450         LASSERT(atomic_read(&ctx->cc_refcount));
1451         LASSERT(ctx->cc_sec);
1452         LASSERT(ctx->cc_sec->ps_policy);
1453
1454         if (req->rq_reqbuf == NULL && req->rq_clrbuf == NULL)
1455                 return;
1456
1457         policy = ctx->cc_sec->ps_policy;
1458         policy->sp_cops->free_reqbuf(ctx->cc_sec, req);
1459 }
1460
1461 /*
1462  * NOTE caller must guarantee the buffer size is enough for the enlargement
1463  */
1464 void _sptlrpc_enlarge_msg_inplace(struct lustre_msg *msg,
1465                                   int segment, int newsize)
1466 {
1467         void   *src, *dst;
1468         int     oldsize, oldmsg_size, movesize;
1469
1470         LASSERT(segment < msg->lm_bufcount);
1471         LASSERT(msg->lm_buflens[segment] <= newsize);
1472
1473         if (msg->lm_buflens[segment] == newsize)
1474                 return;
1475
1476         /* nothing to do if we are enlarging the last segment */
1477         if (segment == msg->lm_bufcount - 1) {
1478                 msg->lm_buflens[segment] = newsize;
1479                 return;
1480         }
1481
1482         oldsize = msg->lm_buflens[segment];
1483
1484         src = lustre_msg_buf(msg, segment + 1, 0);
1485         msg->lm_buflens[segment] = newsize;
1486         dst = lustre_msg_buf(msg, segment + 1, 0);
1487         msg->lm_buflens[segment] = oldsize;
1488
1489         /* move from segment + 1 to end segment */
1490         LASSERT(msg->lm_magic == LUSTRE_MSG_MAGIC_V2);
1491         oldmsg_size = lustre_msg_size_v2(msg->lm_bufcount, msg->lm_buflens);
1492         movesize = oldmsg_size - ((unsigned long) src - (unsigned long) msg);
1493         LASSERT(movesize >= 0);
1494
1495         if (movesize)
1496                 memmove(dst, src, movesize);
1497
1498         /* note we don't clear the ares where old data live, not secret */
1499
1500         /* finally set new segment size */
1501         msg->lm_buflens[segment] = newsize;
1502 }
1503 EXPORT_SYMBOL(_sptlrpc_enlarge_msg_inplace);
1504
1505 /*
1506  * enlarge @segment of upper message req->rq_reqmsg to @newsize, all data
1507  * will be preserved after enlargement. this must be called after rq_reqmsg has
1508  * been intialized at least.
1509  *
1510  * caller's attention: upon return, rq_reqmsg and rq_reqlen might have
1511  * been changed.
1512  */
1513 int sptlrpc_cli_enlarge_reqbuf(struct ptlrpc_request *req,
1514                                int segment, int newsize)
1515 {
1516         struct ptlrpc_cli_ctx    *ctx = req->rq_cli_ctx;
1517         struct ptlrpc_sec_cops   *cops;
1518         struct lustre_msg        *msg = req->rq_reqmsg;
1519
1520         LASSERT(ctx);
1521         LASSERT(msg);
1522         LASSERT(msg->lm_bufcount > segment);
1523         LASSERT(msg->lm_buflens[segment] <= newsize);
1524
1525         if (msg->lm_buflens[segment] == newsize)
1526                 return 0;
1527
1528         cops = ctx->cc_sec->ps_policy->sp_cops;
1529         LASSERT(cops->enlarge_reqbuf);
1530         return cops->enlarge_reqbuf(ctx->cc_sec, req, segment, newsize);
1531 }
1532 EXPORT_SYMBOL(sptlrpc_cli_enlarge_reqbuf);
1533
1534 int sptlrpc_cli_alloc_repbuf(struct ptlrpc_request *req, int msgsize)
1535 {
1536         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
1537         struct ptlrpc_sec_policy *policy;
1538         ENTRY;
1539
1540         LASSERT(ctx);
1541         LASSERT(atomic_read(&ctx->cc_refcount));
1542         LASSERT(ctx->cc_sec);
1543         LASSERT(ctx->cc_sec->ps_policy);
1544
1545         if (req->rq_repbuf)
1546                 RETURN(0);
1547
1548         policy = ctx->cc_sec->ps_policy;
1549         RETURN(policy->sp_cops->alloc_repbuf(ctx->cc_sec, req, msgsize));
1550 }
1551
1552 void sptlrpc_cli_free_repbuf(struct ptlrpc_request *req)
1553 {
1554         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
1555         struct ptlrpc_sec_policy *policy;
1556         ENTRY;
1557
1558         LASSERT(ctx);
1559         LASSERT(atomic_read(&ctx->cc_refcount));
1560         LASSERT(ctx->cc_sec);
1561         LASSERT(ctx->cc_sec->ps_policy);
1562
1563         if (req->rq_repbuf == NULL)
1564                 return;
1565         LASSERT(req->rq_repbuf_len);
1566
1567         policy = ctx->cc_sec->ps_policy;
1568         policy->sp_cops->free_repbuf(ctx->cc_sec, req);
1569         EXIT;
1570 }
1571
1572 int sptlrpc_cli_install_rvs_ctx(struct obd_import *imp,
1573                                 struct ptlrpc_cli_ctx *ctx)
1574 {
1575         struct ptlrpc_sec_policy *policy = ctx->cc_sec->ps_policy;
1576
1577         if (!policy->sp_cops->install_rctx)
1578                 return 0;
1579         return policy->sp_cops->install_rctx(imp, ctx->cc_sec, ctx);
1580 }
1581
1582 int sptlrpc_svc_install_rvs_ctx(struct obd_import *imp,
1583                                 struct ptlrpc_svc_ctx *ctx)
1584 {
1585         struct ptlrpc_sec_policy *policy = ctx->sc_policy;
1586
1587         if (!policy->sp_sops->install_rctx)
1588                 return 0;
1589         return policy->sp_sops->install_rctx(imp, ctx);
1590 }
1591
1592 /****************************************
1593  * server side security                 *
1594  ****************************************/
1595
1596 static int flavor_allowed(struct sptlrpc_flavor *exp,
1597                           struct ptlrpc_request *req)
1598 {
1599         struct sptlrpc_flavor *flvr = &req->rq_flvr;
1600
1601         if (exp->sf_rpc == flvr->sf_rpc)
1602                 return 1;
1603
1604         if ((req->rq_ctx_init || req->rq_ctx_fini) &&
1605             RPC_FLVR_POLICY(exp->sf_rpc) == RPC_FLVR_POLICY(flvr->sf_rpc) &&
1606             RPC_FLVR_MECH(exp->sf_rpc) == RPC_FLVR_MECH(flvr->sf_rpc))
1607                 return 1;
1608
1609         return 0;
1610 }
1611
1612 #define EXP_FLVR_UPDATE_EXPIRE      (OBD_TIMEOUT_DEFAULT + 10)
1613
1614 int sptlrpc_target_export_check(struct obd_export *exp,
1615                                 struct ptlrpc_request *req)
1616 {
1617         struct sptlrpc_flavor   flavor;
1618
1619         if (exp == NULL)
1620                 return 0;
1621
1622         /* client side export has no imp_reverse, skip
1623          * FIXME maybe we should check flavor this as well??? */
1624         if (exp->exp_imp_reverse == NULL)
1625                 return 0;
1626
1627         /* don't care about ctx fini rpc */
1628         if (req->rq_ctx_fini)
1629                 return 0;
1630
1631         spin_lock(&exp->exp_lock);
1632
1633         /* if flavor just changed (exp->exp_flvr_changed != 0), we wait for
1634          * the first req with the new flavor, then treat it as current flavor,
1635          * adapt reverse sec according to it.
1636          * note the first rpc with new flavor might not be with root ctx, in
1637          * which case delay the sec_adapt by leaving exp_flvr_adapt == 1. */
1638         if (unlikely(exp->exp_flvr_changed) &&
1639             flavor_allowed(&exp->exp_flvr_old[1], req)) {
1640                 /* make the new flavor as "current", and old ones as
1641                  * about-to-expire */
1642                 CDEBUG(D_SEC, "exp %p: just changed: %x->%x\n", exp,
1643                        exp->exp_flvr.sf_rpc, exp->exp_flvr_old[1].sf_rpc);
1644                 flavor = exp->exp_flvr_old[1];
1645                 exp->exp_flvr_old[1] = exp->exp_flvr_old[0];
1646                 exp->exp_flvr_expire[1] = exp->exp_flvr_expire[0];
1647                 exp->exp_flvr_old[0] = exp->exp_flvr;
1648                 exp->exp_flvr_expire[0] = cfs_time_current_sec() +
1649                                           EXP_FLVR_UPDATE_EXPIRE;
1650                 exp->exp_flvr = flavor;
1651
1652                 /* flavor change finished */
1653                 exp->exp_flvr_changed = 0;
1654                 LASSERT(exp->exp_flvr_adapt == 1);
1655
1656                 /* if it's gss, we only interested in root ctx init */
1657                 if (req->rq_auth_gss &&
1658                     !(req->rq_ctx_init && (req->rq_auth_usr_root ||
1659                                            req->rq_auth_usr_mdt))) {
1660                         spin_unlock(&exp->exp_lock);
1661                         CDEBUG(D_SEC, "is good but not root(%d:%d:%d:%d)\n",
1662                                req->rq_auth_gss, req->rq_ctx_init,
1663                                req->rq_auth_usr_root, req->rq_auth_usr_mdt);
1664                         return 0;
1665                 }
1666
1667                 exp->exp_flvr_adapt = 0;
1668                 spin_unlock(&exp->exp_lock);
1669
1670                 return sptlrpc_import_sec_adapt(exp->exp_imp_reverse,
1671                                                 req->rq_svc_ctx, flavor.sf_rpc);
1672         }
1673
1674         /* if it equals to the current flavor, we accept it, but need to
1675          * dealing with reverse sec/ctx */
1676         if (likely(flavor_allowed(&exp->exp_flvr, req))) {
1677                 /* most cases should return here, we only interested in
1678                  * gss root ctx init */
1679                 if (!req->rq_auth_gss || !req->rq_ctx_init ||
1680                     (!req->rq_auth_usr_root && !req->rq_auth_usr_mdt)) {
1681                         spin_unlock(&exp->exp_lock);
1682                         return 0;
1683                 }
1684
1685                 /* if flavor just changed, we should not proceed, just leave
1686                  * it and current flavor will be discovered and replaced
1687                  * shortly, and let _this_ rpc pass through */
1688                 if (exp->exp_flvr_changed) {
1689                         LASSERT(exp->exp_flvr_adapt);
1690                         spin_unlock(&exp->exp_lock);
1691                         return 0;
1692                 }
1693
1694                 if (exp->exp_flvr_adapt) {
1695                         exp->exp_flvr_adapt = 0;
1696                         CDEBUG(D_SEC, "exp %p (%x|%x|%x): do delayed adapt\n",
1697                                exp, exp->exp_flvr.sf_rpc,
1698                                exp->exp_flvr_old[0].sf_rpc,
1699                                exp->exp_flvr_old[1].sf_rpc);
1700                         flavor = exp->exp_flvr;
1701                         spin_unlock(&exp->exp_lock);
1702
1703                         return sptlrpc_import_sec_adapt(exp->exp_imp_reverse,
1704                                                         req->rq_svc_ctx,
1705                                                         flavor.sf_rpc);
1706                 } else {
1707                         CDEBUG(D_SEC, "exp %p (%x|%x|%x): is current flavor, "
1708                                "install rvs ctx\n", exp, exp->exp_flvr.sf_rpc,
1709                                exp->exp_flvr_old[0].sf_rpc,
1710                                exp->exp_flvr_old[1].sf_rpc);
1711                         spin_unlock(&exp->exp_lock);
1712
1713                         return sptlrpc_svc_install_rvs_ctx(exp->exp_imp_reverse,
1714                                                            req->rq_svc_ctx);
1715                 }
1716         }
1717
1718         if (exp->exp_flvr_expire[0]) {
1719                 if (exp->exp_flvr_expire[0] >= cfs_time_current_sec()) {
1720                         if (flavor_allowed(&exp->exp_flvr_old[0], req)) {
1721                                 CDEBUG(D_SEC, "exp %p (%x|%x|%x): match the "
1722                                        "middle one ("CFS_DURATION_T")\n", exp,
1723                                        exp->exp_flvr.sf_rpc,
1724                                        exp->exp_flvr_old[0].sf_rpc,
1725                                        exp->exp_flvr_old[1].sf_rpc,
1726                                        exp->exp_flvr_expire[0] -
1727                                                 cfs_time_current_sec());
1728                                 spin_unlock(&exp->exp_lock);
1729                                 return 0;
1730                         }
1731                 } else {
1732                         CDEBUG(D_SEC, "mark middle expired\n");
1733                         exp->exp_flvr_expire[0] = 0;
1734                 }
1735                 CDEBUG(D_SEC, "exp %p (%x|%x|%x): %x not match middle\n", exp,
1736                        exp->exp_flvr.sf_rpc,
1737                        exp->exp_flvr_old[0].sf_rpc, exp->exp_flvr_old[1].sf_rpc,
1738                        req->rq_flvr.sf_rpc);
1739         }
1740
1741         /* now it doesn't match the current flavor, the only chance we can
1742          * accept it is match the old flavors which is not expired. */
1743         if (exp->exp_flvr_changed == 0 && exp->exp_flvr_expire[1]) {
1744                 if (exp->exp_flvr_expire[1] >= cfs_time_current_sec()) {
1745                         if (flavor_allowed(&exp->exp_flvr_old[1], req)) {
1746                                 CDEBUG(D_SEC, "exp %p (%x|%x|%x): match the "
1747                                        "oldest one ("CFS_DURATION_T")\n", exp,
1748                                        exp->exp_flvr.sf_rpc,
1749                                        exp->exp_flvr_old[0].sf_rpc,
1750                                        exp->exp_flvr_old[1].sf_rpc,
1751                                        exp->exp_flvr_expire[1] -
1752                                                 cfs_time_current_sec());
1753                                 spin_unlock(&exp->exp_lock);
1754                                 return 0;
1755                         }
1756                 } else {
1757                         CDEBUG(D_SEC, "mark oldest expired\n");
1758                         exp->exp_flvr_expire[1] = 0;
1759                 }
1760                 CDEBUG(D_SEC, "exp %p (%x|%x|%x): %x not match found\n",
1761                        exp, exp->exp_flvr.sf_rpc,
1762                        exp->exp_flvr_old[0].sf_rpc, exp->exp_flvr_old[1].sf_rpc,
1763                        req->rq_flvr.sf_rpc);
1764         } else {
1765                 CDEBUG(D_SEC, "exp %p (%x|%x|%x): skip the last one\n",
1766                        exp, exp->exp_flvr.sf_rpc, exp->exp_flvr_old[0].sf_rpc,
1767                        exp->exp_flvr_old[1].sf_rpc);
1768         }
1769
1770         spin_unlock(&exp->exp_lock);
1771
1772         CWARN("req %p: (%u|%u|%u|%u|%u) with unauthorized flavor %x\n",
1773               req, req->rq_auth_gss, req->rq_ctx_init, req->rq_ctx_fini,
1774               req->rq_auth_usr_root, req->rq_auth_usr_mdt, req->rq_flvr.sf_rpc);
1775         return -EACCES;
1776 }
1777
1778 void sptlrpc_target_update_exp_flavor(struct obd_device *obd,
1779                                       struct sptlrpc_rule_set *rset)
1780 {
1781         struct obd_export       *exp;
1782         struct sptlrpc_flavor    new_flvr;
1783
1784         LASSERT(obd);
1785
1786         spin_lock(&obd->obd_dev_lock);
1787
1788         list_for_each_entry(exp, &obd->obd_exports, exp_obd_chain) {
1789                 if (exp->exp_connection == NULL)
1790                         continue;
1791
1792                 /* note if this export had just been updated flavor
1793                  * (exp_flvr_changed == 1), this will override the
1794                  * previous one. */
1795                 spin_lock(&exp->exp_lock);
1796                 sptlrpc_rule_set_choose(rset, exp->exp_sp_peer,
1797                                         exp->exp_connection->c_peer.nid,
1798                                         &new_flvr);
1799                 if (exp->exp_flvr_changed ||
1800                     memcmp(&new_flvr, &exp->exp_flvr, sizeof(new_flvr))) {
1801                         exp->exp_flvr_old[1] = new_flvr;
1802                         exp->exp_flvr_expire[1] = 0;
1803                         exp->exp_flvr_changed = 1;
1804                         exp->exp_flvr_adapt = 1;
1805                         CDEBUG(D_SEC, "exp %p (%s): updated flavor %x->%x\n",
1806                                exp, sptlrpc_part2name(exp->exp_sp_peer),
1807                                exp->exp_flvr.sf_rpc,
1808                                exp->exp_flvr_old[1].sf_rpc);
1809                 }
1810                 spin_unlock(&exp->exp_lock);
1811         }
1812
1813         spin_unlock(&obd->obd_dev_lock);
1814 }
1815 EXPORT_SYMBOL(sptlrpc_target_update_exp_flavor);
1816
1817 static int sptlrpc_svc_check_from(struct ptlrpc_request *req, int svc_rc)
1818 {
1819         if (svc_rc == SECSVC_DROP)
1820                 return SECSVC_DROP;
1821
1822         switch (req->rq_sp_from) {
1823         case LUSTRE_SP_CLI:
1824         case LUSTRE_SP_MDT:
1825         case LUSTRE_SP_OST:
1826         case LUSTRE_SP_MGS:
1827         case LUSTRE_SP_ANY:
1828                 break;
1829         default:
1830                 DEBUG_REQ(D_ERROR, req, "invalid source %u", req->rq_sp_from);
1831                 return SECSVC_DROP;
1832         }
1833
1834         if (!req->rq_auth_gss)
1835                 return svc_rc;
1836
1837         if (unlikely(req->rq_sp_from == LUSTRE_SP_ANY)) {
1838                 CERROR("not specific part\n");
1839                 return SECSVC_DROP;
1840         }
1841
1842         /* from MDT, must be authenticated as MDT */
1843         if (unlikely(req->rq_sp_from == LUSTRE_SP_MDT &&
1844                      !req->rq_auth_usr_mdt)) {
1845                 DEBUG_REQ(D_ERROR, req, "fake source MDT");
1846                 return SECSVC_DROP;
1847         }
1848
1849         /* from OST, must be callback to MDT and CLI, the reverse sec
1850          * was from mdt/root keytab, so it should be MDT or root FIXME */
1851         if (unlikely(req->rq_sp_from == LUSTRE_SP_OST &&
1852                      !req->rq_auth_usr_mdt && !req->rq_auth_usr_root)) {
1853                 DEBUG_REQ(D_ERROR, req, "fake source OST");
1854                 return SECSVC_DROP;
1855         }
1856
1857         return svc_rc;
1858 }
1859
1860 int sptlrpc_svc_unwrap_request(struct ptlrpc_request *req)
1861 {
1862         struct ptlrpc_sec_policy *policy;
1863         struct lustre_msg *msg = req->rq_reqbuf;
1864         int rc;
1865         ENTRY;
1866
1867         LASSERT(msg);
1868         LASSERT(req->rq_reqmsg == NULL);
1869         LASSERT(req->rq_repmsg == NULL);
1870
1871         req->rq_sp_from = LUSTRE_SP_ANY;
1872         req->rq_auth_uid = INVALID_UID;
1873         req->rq_auth_mapped_uid = INVALID_UID;
1874
1875         if (req->rq_reqdata_len < sizeof(struct lustre_msg)) {
1876                 CERROR("request size %d too small\n", req->rq_reqdata_len);
1877                 RETURN(SECSVC_DROP);
1878         }
1879
1880         /*
1881          * v2 message.
1882          */
1883         if (msg->lm_magic == LUSTRE_MSG_MAGIC_V2)
1884                 req->rq_flvr.sf_rpc = WIRE_FLVR_RPC(msg->lm_secflvr);
1885         else
1886                 req->rq_flvr.sf_rpc = WIRE_FLVR_RPC(__swab32(msg->lm_secflvr));
1887
1888         /* unpack the wrapper message if the policy is not null */
1889         if ((RPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL) &&
1890              lustre_unpack_msg(msg, req->rq_reqdata_len))
1891                 RETURN(SECSVC_DROP);
1892
1893         policy = sptlrpc_rpcflavor2policy(req->rq_flvr.sf_rpc);
1894         if (!policy) {
1895                 CERROR("unsupported rpc flavor %x\n", req->rq_flvr.sf_rpc);
1896                 RETURN(SECSVC_DROP);
1897         }
1898
1899         LASSERT(policy->sp_sops->accept);
1900         rc = policy->sp_sops->accept(req);
1901
1902         LASSERT(req->rq_reqmsg || rc != SECSVC_OK);
1903         sptlrpc_policy_put(policy);
1904
1905         /* sanity check for the request source */
1906         rc = sptlrpc_svc_check_from(req, rc);
1907
1908         /* FIXME move to proper place */
1909         if (rc == SECSVC_OK) {
1910                 __u32 opc = lustre_msg_get_opc(req->rq_reqmsg);
1911
1912                 if (opc == OST_WRITE)
1913                         req->rq_bulk_write = 1;
1914                 else if (opc == OST_READ)
1915                         req->rq_bulk_read = 1;
1916         }
1917
1918         LASSERT(req->rq_svc_ctx || rc == SECSVC_DROP);
1919         RETURN(rc);
1920 }
1921
1922 int sptlrpc_svc_alloc_rs(struct ptlrpc_request *req,
1923                          int msglen)
1924 {
1925         struct ptlrpc_sec_policy *policy;
1926         struct ptlrpc_reply_state *rs;
1927         int rc;
1928         ENTRY;
1929
1930         LASSERT(req->rq_svc_ctx);
1931         LASSERT(req->rq_svc_ctx->sc_policy);
1932
1933         policy = req->rq_svc_ctx->sc_policy;
1934         LASSERT(policy->sp_sops->alloc_rs);
1935
1936         rc = policy->sp_sops->alloc_rs(req, msglen);
1937         if (unlikely(rc == -ENOMEM)) {
1938                 /* failed alloc, try emergency pool */
1939                 rs = lustre_get_emerg_rs(req->rq_rqbd->rqbd_service);
1940                 if (rs == NULL)
1941                         RETURN(-ENOMEM);
1942
1943                 req->rq_reply_state = rs;
1944                 rc = policy->sp_sops->alloc_rs(req, msglen);
1945                 if (rc) {
1946                         lustre_put_emerg_rs(rs);
1947                         req->rq_reply_state = NULL;
1948                 }
1949         }
1950
1951         LASSERT(rc != 0 ||
1952                 (req->rq_reply_state && req->rq_reply_state->rs_msg));
1953
1954         RETURN(rc);
1955 }
1956
1957 int sptlrpc_svc_wrap_reply(struct ptlrpc_request *req)
1958 {
1959         struct ptlrpc_sec_policy *policy;
1960         int rc;
1961         ENTRY;
1962
1963         LASSERT(req->rq_svc_ctx);
1964         LASSERT(req->rq_svc_ctx->sc_policy);
1965
1966         policy = req->rq_svc_ctx->sc_policy;
1967         LASSERT(policy->sp_sops->authorize);
1968
1969         rc = policy->sp_sops->authorize(req);
1970         LASSERT(rc || req->rq_reply_state->rs_repdata_len);
1971
1972         RETURN(rc);
1973 }
1974
1975 void sptlrpc_svc_free_rs(struct ptlrpc_reply_state *rs)
1976 {
1977         struct ptlrpc_sec_policy *policy;
1978         unsigned int prealloc;
1979         ENTRY;
1980
1981         LASSERT(rs->rs_svc_ctx);
1982         LASSERT(rs->rs_svc_ctx->sc_policy);
1983
1984         policy = rs->rs_svc_ctx->sc_policy;
1985         LASSERT(policy->sp_sops->free_rs);
1986
1987         prealloc = rs->rs_prealloc;
1988         policy->sp_sops->free_rs(rs);
1989
1990         if (prealloc)
1991                 lustre_put_emerg_rs(rs);
1992         EXIT;
1993 }
1994
1995 void sptlrpc_svc_ctx_addref(struct ptlrpc_request *req)
1996 {
1997         struct ptlrpc_svc_ctx *ctx = req->rq_svc_ctx;
1998
1999         if (ctx == NULL)
2000                 return;
2001
2002         LASSERT(atomic_read(&ctx->sc_refcount) > 0);
2003         atomic_inc(&ctx->sc_refcount);
2004 }
2005
2006 void sptlrpc_svc_ctx_decref(struct ptlrpc_request *req)
2007 {
2008         struct ptlrpc_svc_ctx *ctx = req->rq_svc_ctx;
2009
2010         if (ctx == NULL)
2011                 return;
2012
2013         LASSERT(atomic_read(&ctx->sc_refcount) > 0);
2014         if (atomic_dec_and_test(&ctx->sc_refcount)) {
2015                 if (ctx->sc_policy->sp_sops->free_ctx)
2016                         ctx->sc_policy->sp_sops->free_ctx(ctx);
2017         }
2018         req->rq_svc_ctx = NULL;
2019 }
2020
2021 void sptlrpc_svc_ctx_invalidate(struct ptlrpc_request *req)
2022 {
2023         struct ptlrpc_svc_ctx *ctx = req->rq_svc_ctx;
2024
2025         if (ctx == NULL)
2026                 return;
2027
2028         LASSERT(atomic_read(&ctx->sc_refcount) > 0);
2029         if (ctx->sc_policy->sp_sops->invalidate_ctx)
2030                 ctx->sc_policy->sp_sops->invalidate_ctx(ctx);
2031 }
2032 EXPORT_SYMBOL(sptlrpc_svc_ctx_invalidate);
2033
2034 /****************************************
2035  * bulk security                        *
2036  ****************************************/
2037
2038 int sptlrpc_cli_wrap_bulk(struct ptlrpc_request *req,
2039                           struct ptlrpc_bulk_desc *desc)
2040 {
2041         struct ptlrpc_cli_ctx *ctx;
2042
2043         if (!req->rq_pack_bulk)
2044                 return 0;
2045
2046         LASSERT(req->rq_bulk_read || req->rq_bulk_write);
2047
2048         ctx = req->rq_cli_ctx;
2049         if (ctx->cc_ops->wrap_bulk)
2050                 return ctx->cc_ops->wrap_bulk(ctx, req, desc);
2051         return 0;
2052 }
2053 EXPORT_SYMBOL(sptlrpc_cli_wrap_bulk);
2054
2055 static
2056 void pga_to_bulk_desc(int nob, obd_count pg_count, struct brw_page **pga,
2057                       struct ptlrpc_bulk_desc *desc)
2058 {
2059         int i;
2060
2061         LASSERT(pga);
2062         LASSERT(*pga);
2063
2064         for (i = 0; i < pg_count && nob > 0; i++) {
2065 #ifdef __KERNEL__
2066                 desc->bd_iov[i].kiov_page = pga[i]->pg;
2067                 desc->bd_iov[i].kiov_len = pga[i]->count > nob ?
2068                                            nob : pga[i]->count;
2069                 desc->bd_iov[i].kiov_offset = pga[i]->off & ~CFS_PAGE_MASK;
2070 #else
2071                 /* FIXME currently liblustre doesn't support bulk encryption.
2072                  * if we do, check again following may not be right. */
2073                 LASSERTF(0, "Bulk encryption not implemented for liblustre\n");
2074                 desc->bd_iov[i].iov_base = pga[i]->pg->addr;
2075                 desc->bd_iov[i].iov_len = pga[i]->count > nob ?
2076                                            nob : pga[i]->count;
2077 #endif
2078
2079                 desc->bd_iov_count++;
2080                 nob -= pga[i]->count;
2081         }
2082 }
2083
2084 int sptlrpc_cli_unwrap_bulk_read(struct ptlrpc_request *req,
2085                                  int nob, obd_count pg_count,
2086                                  struct brw_page **pga)
2087 {
2088         struct ptlrpc_bulk_desc *desc;
2089         struct ptlrpc_cli_ctx *ctx;
2090         int rc = 0;
2091
2092         if (!req->rq_pack_bulk)
2093                 return 0;
2094
2095         LASSERT(req->rq_bulk_read && !req->rq_bulk_write);
2096
2097         OBD_ALLOC(desc, offsetof(struct ptlrpc_bulk_desc, bd_iov[pg_count]));
2098         if (desc == NULL) {
2099                 CERROR("out of memory, can't verify bulk read data\n");
2100                 return -ENOMEM;
2101         }
2102
2103         pga_to_bulk_desc(nob, pg_count, pga, desc);
2104
2105         ctx = req->rq_cli_ctx;
2106         if (ctx->cc_ops->unwrap_bulk)
2107                 rc = ctx->cc_ops->unwrap_bulk(ctx, req, desc);
2108
2109         OBD_FREE(desc, offsetof(struct ptlrpc_bulk_desc, bd_iov[pg_count]));
2110
2111         return rc;
2112 }
2113 EXPORT_SYMBOL(sptlrpc_cli_unwrap_bulk_read);
2114
2115 int sptlrpc_cli_unwrap_bulk_write(struct ptlrpc_request *req,
2116                                   struct ptlrpc_bulk_desc *desc)
2117 {
2118         struct ptlrpc_cli_ctx *ctx;
2119
2120         if (!req->rq_pack_bulk)
2121                 return 0;
2122
2123         LASSERT(!req->rq_bulk_read && req->rq_bulk_write);
2124
2125         ctx = req->rq_cli_ctx;
2126         if (ctx->cc_ops->unwrap_bulk)
2127                 return ctx->cc_ops->unwrap_bulk(ctx, req, desc);
2128
2129         return 0;
2130 }
2131 EXPORT_SYMBOL(sptlrpc_cli_unwrap_bulk_write);
2132
2133 int sptlrpc_svc_wrap_bulk(struct ptlrpc_request *req,
2134                           struct ptlrpc_bulk_desc *desc)
2135 {
2136         struct ptlrpc_svc_ctx *ctx;
2137
2138         if (!req->rq_pack_bulk)
2139                 return 0;
2140
2141         LASSERT(req->rq_bulk_read || req->rq_bulk_write);
2142
2143         ctx = req->rq_svc_ctx;
2144         if (ctx->sc_policy->sp_sops->wrap_bulk)
2145                 return ctx->sc_policy->sp_sops->wrap_bulk(req, desc);
2146
2147         return 0;
2148 }
2149 EXPORT_SYMBOL(sptlrpc_svc_wrap_bulk);
2150
2151 int sptlrpc_svc_unwrap_bulk(struct ptlrpc_request *req,
2152                             struct ptlrpc_bulk_desc *desc)
2153 {
2154         struct ptlrpc_svc_ctx *ctx;
2155
2156         if (!req->rq_pack_bulk)
2157                 return 0;
2158
2159         LASSERT(req->rq_bulk_read || req->rq_bulk_write);
2160
2161         ctx = req->rq_svc_ctx;
2162         if (ctx->sc_policy->sp_sops->unwrap_bulk);
2163                 return ctx->sc_policy->sp_sops->unwrap_bulk(req, desc);
2164
2165         return 0;
2166 }
2167 EXPORT_SYMBOL(sptlrpc_svc_unwrap_bulk);
2168
2169
2170 /****************************************
2171  * user descriptor helpers              *
2172  ****************************************/
2173
2174 int sptlrpc_current_user_desc_size(void)
2175 {
2176         int ngroups;
2177
2178 #ifdef __KERNEL__
2179         ngroups = current_ngroups;
2180
2181         if (ngroups > LUSTRE_MAX_GROUPS)
2182                 ngroups = LUSTRE_MAX_GROUPS;
2183 #else
2184         ngroups = 0;
2185 #endif
2186         return sptlrpc_user_desc_size(ngroups);
2187 }
2188 EXPORT_SYMBOL(sptlrpc_current_user_desc_size);
2189
2190 int sptlrpc_pack_user_desc(struct lustre_msg *msg, int offset)
2191 {
2192         struct ptlrpc_user_desc *pud;
2193
2194         pud = lustre_msg_buf(msg, offset, 0);
2195
2196         pud->pud_uid = cfs_current()->uid;
2197         pud->pud_gid = cfs_current()->gid;
2198         pud->pud_fsuid = cfs_current()->fsuid;
2199         pud->pud_fsgid = cfs_current()->fsgid;
2200         pud->pud_cap = cfs_curproc_cap_pack();
2201         pud->pud_ngroups = (msg->lm_buflens[offset] - sizeof(*pud)) / 4;
2202
2203 #ifdef __KERNEL__
2204         task_lock(current);
2205         if (pud->pud_ngroups > current_ngroups)
2206                 pud->pud_ngroups = current_ngroups;
2207         memcpy(pud->pud_groups, cfs_current()->group_info->blocks[0],
2208                pud->pud_ngroups * sizeof(__u32));
2209         task_unlock(current);
2210 #endif
2211
2212         return 0;
2213 }
2214 EXPORT_SYMBOL(sptlrpc_pack_user_desc);
2215
2216 int sptlrpc_unpack_user_desc(struct lustre_msg *msg, int offset)
2217 {
2218         struct ptlrpc_user_desc *pud;
2219         int                      i;
2220
2221         pud = lustre_msg_buf(msg, offset, sizeof(*pud));
2222         if (!pud)
2223                 return -EINVAL;
2224
2225         if (lustre_msg_swabbed(msg)) {
2226                 __swab32s(&pud->pud_uid);
2227                 __swab32s(&pud->pud_gid);
2228                 __swab32s(&pud->pud_fsuid);
2229                 __swab32s(&pud->pud_fsgid);
2230                 __swab32s(&pud->pud_cap);
2231                 __swab32s(&pud->pud_ngroups);
2232         }
2233
2234         if (pud->pud_ngroups > LUSTRE_MAX_GROUPS) {
2235                 CERROR("%u groups is too large\n", pud->pud_ngroups);
2236                 return -EINVAL;
2237         }
2238
2239         if (sizeof(*pud) + pud->pud_ngroups * sizeof(__u32) >
2240             msg->lm_buflens[offset]) {
2241                 CERROR("%u groups are claimed but bufsize only %u\n",
2242                        pud->pud_ngroups, msg->lm_buflens[offset]);
2243                 return -EINVAL;
2244         }
2245
2246         if (lustre_msg_swabbed(msg)) {
2247                 for (i = 0; i < pud->pud_ngroups; i++)
2248                         __swab32s(&pud->pud_groups[i]);
2249         }
2250
2251         return 0;
2252 }
2253 EXPORT_SYMBOL(sptlrpc_unpack_user_desc);
2254
2255 /****************************************
2256  * misc helpers                         *
2257  ****************************************/
2258
2259 const char * sec2target_str(struct ptlrpc_sec *sec)
2260 {
2261         if (!sec || !sec->ps_import || !sec->ps_import->imp_obd)
2262                 return "*";
2263         if (sec_is_reverse(sec))
2264                 return "c";
2265         return obd_uuid2str(&sec->ps_import->imp_obd->u.cli.cl_target_uuid);
2266 }
2267 EXPORT_SYMBOL(sec2target_str);
2268
2269 /****************************************
2270  * crypto API helper/alloc blkciper     *
2271  ****************************************/
2272
2273 #ifdef __KERNEL__
2274 #ifndef HAVE_ASYNC_BLOCK_CIPHER
2275 struct ll_crypto_cipher *ll_crypto_alloc_blkcipher(const char * algname,
2276                                                    u32 type, u32 mask)
2277 {
2278         char        buf[CRYPTO_MAX_ALG_NAME + 1];
2279         const char *pan = algname;
2280         u32         flag = 0; 
2281
2282         if (strncmp("cbc(", algname, 4) == 0)
2283                 flag |= CRYPTO_TFM_MODE_CBC;
2284         else if (strncmp("ecb(", algname, 4) == 0)
2285                 flag |= CRYPTO_TFM_MODE_ECB;
2286         if (flag) {
2287                 char *vp = strnchr(algname, CRYPTO_MAX_ALG_NAME, ')');
2288                 if (vp) {
2289                         memcpy(buf, algname + 4, vp - algname - 4);
2290                         buf[vp - algname - 4] = '\0';
2291                         pan = buf;
2292                 } else {
2293                         flag = 0;
2294                 }
2295         }
2296         return crypto_alloc_tfm(pan, flag);
2297 }
2298 EXPORT_SYMBOL(ll_crypto_alloc_blkcipher);
2299 #endif
2300 #endif
2301
2302 /****************************************
2303  * initialize/finalize                  *
2304  ****************************************/
2305
2306 int __init sptlrpc_init(void)
2307 {
2308         int rc;
2309
2310         rc = sptlrpc_gc_start_thread();
2311         if (rc)
2312                 goto out;
2313
2314         rc = sptlrpc_enc_pool_init();
2315         if (rc)
2316                 goto out_gc;
2317
2318         rc = sptlrpc_null_init();
2319         if (rc)
2320                 goto out_pool;
2321
2322         rc = sptlrpc_plain_init();
2323         if (rc)
2324                 goto out_null;
2325
2326         rc = sptlrpc_lproc_init();
2327         if (rc)
2328                 goto out_plain;
2329
2330         return 0;
2331
2332 out_plain:
2333         sptlrpc_plain_fini();
2334 out_null:
2335         sptlrpc_null_fini();
2336 out_pool:
2337         sptlrpc_enc_pool_fini();
2338 out_gc:
2339         sptlrpc_gc_stop_thread();
2340 out:
2341         return rc;
2342 }
2343
2344 void __exit sptlrpc_fini(void)
2345 {
2346         sptlrpc_lproc_fini();
2347         sptlrpc_plain_fini();
2348         sptlrpc_null_fini();
2349         sptlrpc_enc_pool_fini();
2350         sptlrpc_gc_stop_thread();
2351 }