Whamcloud - gitweb
808fbd8d0d4013a42f0235720d664118134c5d7c
[fs/lustre-release.git] / lustre / ptlrpc / sec.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/ptlrpc/sec.c
33  *
34  * Author: Eric Mei <ericm@clusterfs.com>
35  */
36
37 #define DEBUG_SUBSYSTEM S_SEC
38
39 #include <linux/user_namespace.h>
40 #ifdef HAVE_UIDGID_HEADER
41 # include <linux/uidgid.h>
42 #endif
43 #include <linux/crypto.h>
44 #include <linux/key.h>
45
46 #include <libcfs/libcfs.h>
47 #include <obd.h>
48 #include <obd_class.h>
49 #include <obd_support.h>
50 #include <lustre_net.h>
51 #include <lustre_import.h>
52 #include <lustre_dlm.h>
53 #include <lustre_sec.h>
54
55 #include "ptlrpc_internal.h"
56
57 static int send_sepol;
58 module_param(send_sepol, int, 0644);
59 MODULE_PARM_DESC(send_sepol, "Client sends SELinux policy status");
60
61 /*
62  * policy registers
63  */
64
65 static rwlock_t policy_lock;
66 static struct ptlrpc_sec_policy *policies[SPTLRPC_POLICY_MAX] = {
67         NULL,
68 };
69
70 int sptlrpc_register_policy(struct ptlrpc_sec_policy *policy)
71 {
72         __u16 number = policy->sp_policy;
73
74         LASSERT(policy->sp_name);
75         LASSERT(policy->sp_cops);
76         LASSERT(policy->sp_sops);
77
78         if (number >= SPTLRPC_POLICY_MAX)
79                 return -EINVAL;
80
81         write_lock(&policy_lock);
82         if (unlikely(policies[number])) {
83                 write_unlock(&policy_lock);
84                 return -EALREADY;
85         }
86         policies[number] = policy;
87         write_unlock(&policy_lock);
88
89         CDEBUG(D_SEC, "%s: registered\n", policy->sp_name);
90         return 0;
91 }
92 EXPORT_SYMBOL(sptlrpc_register_policy);
93
94 int sptlrpc_unregister_policy(struct ptlrpc_sec_policy *policy)
95 {
96         __u16 number = policy->sp_policy;
97
98         LASSERT(number < SPTLRPC_POLICY_MAX);
99
100         write_lock(&policy_lock);
101         if (unlikely(policies[number] == NULL)) {
102                 write_unlock(&policy_lock);
103                 CERROR("%s: already unregistered\n", policy->sp_name);
104                 return -EINVAL;
105         }
106
107         LASSERT(policies[number] == policy);
108         policies[number] = NULL;
109         write_unlock(&policy_lock);
110
111         CDEBUG(D_SEC, "%s: unregistered\n", policy->sp_name);
112         return 0;
113 }
114 EXPORT_SYMBOL(sptlrpc_unregister_policy);
115
116 static
117 struct ptlrpc_sec_policy *sptlrpc_wireflavor2policy(__u32 flavor)
118 {
119         static DEFINE_MUTEX(load_mutex);
120         static atomic_t           loaded = ATOMIC_INIT(0);
121         struct ptlrpc_sec_policy *policy;
122         __u16                     number = SPTLRPC_FLVR_POLICY(flavor);
123         __u16                     flag = 0;
124
125         if (number >= SPTLRPC_POLICY_MAX)
126                 return NULL;
127
128         while (1) {
129                 read_lock(&policy_lock);
130                 policy = policies[number];
131                 if (policy && !try_module_get(policy->sp_owner))
132                         policy = NULL;
133                 if (policy == NULL)
134                         flag = atomic_read(&loaded);
135                 read_unlock(&policy_lock);
136
137                 if (policy != NULL || flag != 0 ||
138                     number != SPTLRPC_POLICY_GSS)
139                         break;
140
141                 /* try to load gss module, once */
142                 mutex_lock(&load_mutex);
143                 if (atomic_read(&loaded) == 0) {
144                         if (request_module("ptlrpc_gss") == 0)
145                                 CDEBUG(D_SEC,
146                                        "module ptlrpc_gss loaded on demand\n");
147                         else
148                                 CERROR("Unable to load module ptlrpc_gss\n");
149
150                         atomic_set(&loaded, 1);
151                 }
152                 mutex_unlock(&load_mutex);
153         }
154
155         return policy;
156 }
157
158 __u32 sptlrpc_name2flavor_base(const char *name)
159 {
160         if (!strcmp(name, "null"))
161                 return SPTLRPC_FLVR_NULL;
162         if (!strcmp(name, "plain"))
163                 return SPTLRPC_FLVR_PLAIN;
164         if (!strcmp(name, "gssnull"))
165                 return SPTLRPC_FLVR_GSSNULL;
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         if (!strcmp(name, "skn"))
175                 return SPTLRPC_FLVR_SKN;
176         if (!strcmp(name, "ska"))
177                 return SPTLRPC_FLVR_SKA;
178         if (!strcmp(name, "ski"))
179                 return SPTLRPC_FLVR_SKI;
180         if (!strcmp(name, "skpi"))
181                 return SPTLRPC_FLVR_SKPI;
182
183         return SPTLRPC_FLVR_INVALID;
184 }
185 EXPORT_SYMBOL(sptlrpc_name2flavor_base);
186
187 const char *sptlrpc_flavor2name_base(__u32 flvr)
188 {
189         __u32   base = SPTLRPC_FLVR_BASE(flvr);
190
191         if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_NULL))
192                 return "null";
193         else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_PLAIN))
194                 return "plain";
195         else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_GSSNULL))
196                 return "gssnull";
197         else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_KRB5N))
198                 return "krb5n";
199         else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_KRB5A))
200                 return "krb5a";
201         else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_KRB5I))
202                 return "krb5i";
203         else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_KRB5P))
204                 return "krb5p";
205         else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_SKN))
206                 return "skn";
207         else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_SKA))
208                 return "ska";
209         else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_SKI))
210                 return "ski";
211         else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_SKPI))
212                 return "skpi";
213
214         CERROR("invalid wire flavor 0x%x\n", flvr);
215         return "invalid";
216 }
217 EXPORT_SYMBOL(sptlrpc_flavor2name_base);
218
219 char *sptlrpc_flavor2name_bulk(struct sptlrpc_flavor *sf,
220                                char *buf, int bufsize)
221 {
222         if (SPTLRPC_FLVR_POLICY(sf->sf_rpc) == SPTLRPC_POLICY_PLAIN)
223                 snprintf(buf, bufsize, "hash:%s",
224                         sptlrpc_get_hash_name(sf->u_bulk.hash.hash_alg));
225         else
226                 snprintf(buf, bufsize, "%s",
227                         sptlrpc_flavor2name_base(sf->sf_rpc));
228
229         buf[bufsize - 1] = '\0';
230         return buf;
231 }
232 EXPORT_SYMBOL(sptlrpc_flavor2name_bulk);
233
234 char *sptlrpc_flavor2name(struct sptlrpc_flavor *sf, char *buf, int bufsize)
235 {
236         snprintf(buf, bufsize, "%s", sptlrpc_flavor2name_base(sf->sf_rpc));
237
238         /*
239          * currently we don't support customized bulk specification for
240          * flavors other than plain
241          */
242         if (SPTLRPC_FLVR_POLICY(sf->sf_rpc) == SPTLRPC_POLICY_PLAIN) {
243                 char bspec[16];
244
245                 bspec[0] = '-';
246                 sptlrpc_flavor2name_bulk(sf, &bspec[1], sizeof(bspec) - 1);
247                 strncat(buf, bspec, bufsize);
248         }
249
250         buf[bufsize - 1] = '\0';
251         return buf;
252 }
253 EXPORT_SYMBOL(sptlrpc_flavor2name);
254
255 char *sptlrpc_secflags2str(__u32 flags, char *buf, int bufsize)
256 {
257         buf[0] = '\0';
258
259         if (flags & PTLRPC_SEC_FL_REVERSE)
260                 strlcat(buf, "reverse,", bufsize);
261         if (flags & PTLRPC_SEC_FL_ROOTONLY)
262                 strlcat(buf, "rootonly,", bufsize);
263         if (flags & PTLRPC_SEC_FL_UDESC)
264                 strlcat(buf, "udesc,", bufsize);
265         if (flags & PTLRPC_SEC_FL_BULK)
266                 strlcat(buf, "bulk,", bufsize);
267         if (buf[0] == '\0')
268                 strlcat(buf, "-,", bufsize);
269
270         return buf;
271 }
272 EXPORT_SYMBOL(sptlrpc_secflags2str);
273
274 /*
275  * client context APIs
276  */
277
278 static
279 struct ptlrpc_cli_ctx *get_my_ctx(struct ptlrpc_sec *sec)
280 {
281         struct vfs_cred vcred;
282         int create = 1, remove_dead = 1;
283
284         LASSERT(sec);
285         LASSERT(sec->ps_policy->sp_cops->lookup_ctx);
286
287         if (sec->ps_flvr.sf_flags & (PTLRPC_SEC_FL_REVERSE |
288                                      PTLRPC_SEC_FL_ROOTONLY)) {
289                 vcred.vc_uid = 0;
290                 vcred.vc_gid = 0;
291                 if (sec->ps_flvr.sf_flags & PTLRPC_SEC_FL_REVERSE) {
292                         create = 0;
293                         remove_dead = 0;
294                 }
295         } else {
296                 vcred.vc_uid = from_kuid(&init_user_ns, current_uid());
297                 vcred.vc_gid = from_kgid(&init_user_ns, current_gid());
298         }
299
300         return sec->ps_policy->sp_cops->lookup_ctx(sec, &vcred, create,
301                                                    remove_dead);
302 }
303
304 struct ptlrpc_cli_ctx *sptlrpc_cli_ctx_get(struct ptlrpc_cli_ctx *ctx)
305 {
306         atomic_inc(&ctx->cc_refcount);
307         return ctx;
308 }
309 EXPORT_SYMBOL(sptlrpc_cli_ctx_get);
310
311 void sptlrpc_cli_ctx_put(struct ptlrpc_cli_ctx *ctx, int sync)
312 {
313         struct ptlrpc_sec *sec = ctx->cc_sec;
314
315         LASSERT(sec);
316         LASSERT_ATOMIC_POS(&ctx->cc_refcount);
317
318         if (!atomic_dec_and_test(&ctx->cc_refcount))
319                 return;
320
321         sec->ps_policy->sp_cops->release_ctx(sec, ctx, sync);
322 }
323 EXPORT_SYMBOL(sptlrpc_cli_ctx_put);
324
325 /**
326  * Expire the client context immediately.
327  *
328  * \pre Caller must hold at least 1 reference on the \a ctx.
329  */
330 void sptlrpc_cli_ctx_expire(struct ptlrpc_cli_ctx *ctx)
331 {
332         LASSERT(ctx->cc_ops->die);
333         ctx->cc_ops->die(ctx, 0);
334 }
335 EXPORT_SYMBOL(sptlrpc_cli_ctx_expire);
336
337 /**
338  * To wake up the threads who are waiting for this client context. Called
339  * after some status change happened on \a ctx.
340  */
341 void sptlrpc_cli_ctx_wakeup(struct ptlrpc_cli_ctx *ctx)
342 {
343         struct ptlrpc_request *req, *next;
344
345         spin_lock(&ctx->cc_lock);
346         list_for_each_entry_safe(req, next, &ctx->cc_req_list,
347                                      rq_ctx_chain) {
348                 list_del_init(&req->rq_ctx_chain);
349                 ptlrpc_client_wake_req(req);
350         }
351         spin_unlock(&ctx->cc_lock);
352 }
353 EXPORT_SYMBOL(sptlrpc_cli_ctx_wakeup);
354
355 int sptlrpc_cli_ctx_display(struct ptlrpc_cli_ctx *ctx, char *buf, int bufsize)
356 {
357         LASSERT(ctx->cc_ops);
358
359         if (ctx->cc_ops->display == NULL)
360                 return 0;
361
362         return ctx->cc_ops->display(ctx, buf, bufsize);
363 }
364
365 static int import_sec_check_expire(struct obd_import *imp)
366 {
367         int adapt = 0;
368
369         write_lock(&imp->imp_sec_lock);
370         if (imp->imp_sec_expire &&
371             imp->imp_sec_expire < ktime_get_real_seconds()) {
372                 adapt = 1;
373                 imp->imp_sec_expire = 0;
374         }
375         write_unlock(&imp->imp_sec_lock);
376
377         if (!adapt)
378                 return 0;
379
380         CDEBUG(D_SEC, "found delayed sec adapt expired, do it now\n");
381         return sptlrpc_import_sec_adapt(imp, NULL, NULL);
382 }
383
384 /**
385  * Get and validate the client side ptlrpc security facilities from
386  * \a imp. There is a race condition on client reconnect when the import is
387  * being destroyed while there are outstanding client bound requests. In
388  * this case do not output any error messages if import secuity is not
389  * found.
390  *
391  * \param[in] imp obd import associated with client
392  * \param[out] sec client side ptlrpc security
393  *
394  * \retval 0 if security retrieved successfully
395  * \retval -ve errno if there was a problem
396  */
397 static int import_sec_validate_get(struct obd_import *imp,
398                                    struct ptlrpc_sec **sec)
399 {
400         int rc;
401
402         if (unlikely(imp->imp_sec_expire)) {
403                 rc = import_sec_check_expire(imp);
404                 if (rc)
405                         return rc;
406         }
407
408         *sec = sptlrpc_import_sec_ref(imp);
409         if (*sec == NULL) {
410                 CERROR("import %p (%s) with no sec\n",
411                         imp, ptlrpc_import_state_name(imp->imp_state));
412                 return -EACCES;
413         }
414
415         if (unlikely((*sec)->ps_dying)) {
416                 CERROR("attempt to use dying sec %p\n", sec);
417                 sptlrpc_sec_put(*sec);
418                 return -EACCES;
419         }
420
421         return 0;
422 }
423
424 /**
425  * Given a \a req, find or allocate an appropriate context for it.
426  * \pre req->rq_cli_ctx == NULL.
427  *
428  * \retval 0 succeed, and req->rq_cli_ctx is set.
429  * \retval -ev error number, and req->rq_cli_ctx == NULL.
430  */
431 int sptlrpc_req_get_ctx(struct ptlrpc_request *req)
432 {
433         struct obd_import *imp = req->rq_import;
434         struct ptlrpc_sec *sec;
435         int rc;
436
437         ENTRY;
438
439         LASSERT(!req->rq_cli_ctx);
440         LASSERT(imp);
441
442         rc = import_sec_validate_get(imp, &sec);
443         if (rc)
444                 RETURN(rc);
445
446         req->rq_cli_ctx = get_my_ctx(sec);
447
448         sptlrpc_sec_put(sec);
449
450         if (!req->rq_cli_ctx) {
451                 CERROR("req %p: fail to get context\n", req);
452                 RETURN(-ECONNREFUSED);
453         }
454
455         RETURN(0);
456 }
457
458 /**
459  * Drop the context for \a req.
460  * \pre req->rq_cli_ctx != NULL.
461  * \post req->rq_cli_ctx == NULL.
462  *
463  * If \a sync == 0, this function should return quickly without sleep;
464  * otherwise it might trigger and wait for the whole process of sending
465  * an context-destroying rpc to server.
466  */
467 void sptlrpc_req_put_ctx(struct ptlrpc_request *req, int sync)
468 {
469         ENTRY;
470
471         LASSERT(req);
472         LASSERT(req->rq_cli_ctx);
473
474         /*
475          * request might be asked to release earlier while still
476          * in the context waiting list.
477          */
478         if (!list_empty(&req->rq_ctx_chain)) {
479                 spin_lock(&req->rq_cli_ctx->cc_lock);
480                 list_del_init(&req->rq_ctx_chain);
481                 spin_unlock(&req->rq_cli_ctx->cc_lock);
482         }
483
484         sptlrpc_cli_ctx_put(req->rq_cli_ctx, sync);
485         req->rq_cli_ctx = NULL;
486         EXIT;
487 }
488
489 static
490 int sptlrpc_req_ctx_switch(struct ptlrpc_request *req,
491                            struct ptlrpc_cli_ctx *oldctx,
492                            struct ptlrpc_cli_ctx *newctx)
493 {
494         struct sptlrpc_flavor   old_flvr;
495         char *reqmsg = NULL; /* to workaround old gcc */
496         int reqmsg_size;
497         int rc = 0;
498
499         LASSERT(req->rq_reqmsg);
500         LASSERT(req->rq_reqlen);
501         LASSERT(req->rq_replen);
502
503         CDEBUG(D_SEC,
504                "req %p: switch ctx %p(%u->%s) -> %p(%u->%s), switch sec %p(%s) -> %p(%s)\n",
505                req, oldctx, oldctx->cc_vcred.vc_uid,
506                sec2target_str(oldctx->cc_sec), newctx, newctx->cc_vcred.vc_uid,
507                sec2target_str(newctx->cc_sec), oldctx->cc_sec,
508                oldctx->cc_sec->ps_policy->sp_name, newctx->cc_sec,
509                newctx->cc_sec->ps_policy->sp_name);
510
511         /* save flavor */
512         old_flvr = req->rq_flvr;
513
514         /* save request message */
515         reqmsg_size = req->rq_reqlen;
516         if (reqmsg_size != 0) {
517                 OBD_ALLOC_LARGE(reqmsg, reqmsg_size);
518                 if (reqmsg == NULL)
519                         return -ENOMEM;
520                 memcpy(reqmsg, req->rq_reqmsg, reqmsg_size);
521         }
522
523         /* release old req/rep buf */
524         req->rq_cli_ctx = oldctx;
525         sptlrpc_cli_free_reqbuf(req);
526         sptlrpc_cli_free_repbuf(req);
527         req->rq_cli_ctx = newctx;
528
529         /* recalculate the flavor */
530         sptlrpc_req_set_flavor(req, 0);
531
532         /*
533          * alloc new request buffer
534          * we don't need to alloc reply buffer here, leave it to the
535          * rest procedure of ptlrpc
536          */
537         if (reqmsg_size != 0) {
538                 rc = sptlrpc_cli_alloc_reqbuf(req, reqmsg_size);
539                 if (!rc) {
540                         LASSERT(req->rq_reqmsg);
541                         memcpy(req->rq_reqmsg, reqmsg, reqmsg_size);
542                 } else {
543                         CWARN("failed to alloc reqbuf: %d\n", rc);
544                         req->rq_flvr = old_flvr;
545                 }
546
547                 OBD_FREE_LARGE(reqmsg, reqmsg_size);
548         }
549         return rc;
550 }
551
552 /**
553  * If current context of \a req is dead somehow, e.g. we just switched flavor
554  * thus marked original contexts dead, we'll find a new context for it. if
555  * no switch is needed, \a req will end up with the same context.
556  *
557  * \note a request must have a context, to keep other parts of code happy.
558  * In any case of failure during the switching, we must restore the old one.
559  */
560 int sptlrpc_req_replace_dead_ctx(struct ptlrpc_request *req)
561 {
562         struct ptlrpc_cli_ctx *oldctx = req->rq_cli_ctx;
563         struct ptlrpc_cli_ctx *newctx;
564         int rc;
565
566         ENTRY;
567
568         LASSERT(oldctx);
569
570         sptlrpc_cli_ctx_get(oldctx);
571         sptlrpc_req_put_ctx(req, 0);
572
573         rc = sptlrpc_req_get_ctx(req);
574         if (unlikely(rc)) {
575                 LASSERT(!req->rq_cli_ctx);
576
577                 /* restore old ctx */
578                 req->rq_cli_ctx = oldctx;
579                 RETURN(rc);
580         }
581
582         newctx = req->rq_cli_ctx;
583         LASSERT(newctx);
584
585         if (unlikely(newctx == oldctx &&
586                      test_bit(PTLRPC_CTX_DEAD_BIT, &oldctx->cc_flags))) {
587                 /*
588                  * still get the old dead ctx, usually means system too busy
589                  */
590                 CDEBUG(D_SEC,
591                        "ctx (%p, fl %lx) doesn't switch, relax a little bit\n",
592                        newctx, newctx->cc_flags);
593
594                 set_current_state(TASK_INTERRUPTIBLE);
595                 schedule_timeout(cfs_time_seconds(1));
596         } else if (unlikely(test_bit(PTLRPC_CTX_UPTODATE_BIT, &newctx->cc_flags)
597                             == 0)) {
598                 /*
599                  * new ctx not up to date yet
600                  */
601                 CDEBUG(D_SEC,
602                        "ctx (%p, fl %lx) doesn't switch, not up to date yet\n",
603                        newctx, newctx->cc_flags);
604         } else {
605                 /*
606                  * it's possible newctx == oldctx if we're switching
607                  * subflavor with the same sec.
608                  */
609                 rc = sptlrpc_req_ctx_switch(req, oldctx, newctx);
610                 if (rc) {
611                         /* restore old ctx */
612                         sptlrpc_req_put_ctx(req, 0);
613                         req->rq_cli_ctx = oldctx;
614                         RETURN(rc);
615                 }
616
617                 LASSERT(req->rq_cli_ctx == newctx);
618         }
619
620         sptlrpc_cli_ctx_put(oldctx, 1);
621         RETURN(0);
622 }
623 EXPORT_SYMBOL(sptlrpc_req_replace_dead_ctx);
624
625 static
626 int ctx_check_refresh(struct ptlrpc_cli_ctx *ctx)
627 {
628         if (cli_ctx_is_refreshed(ctx))
629                 return 1;
630         return 0;
631 }
632
633 static
634 int ctx_refresh_timeout(struct ptlrpc_request *req)
635 {
636         int rc;
637
638         /* conn_cnt is needed in expire_one_request */
639         lustre_msg_set_conn_cnt(req->rq_reqmsg, req->rq_import->imp_conn_cnt);
640
641         rc = ptlrpc_expire_one_request(req, 1);
642         /*
643          * if we started recovery, we should mark this ctx dead; otherwise
644          * in case of lgssd died nobody would retire this ctx, following
645          * connecting will still find the same ctx thus cause deadlock.
646          * there's an assumption that expire time of the request should be
647          * later than the context refresh expire time.
648          */
649         if (rc == 0)
650                 req->rq_cli_ctx->cc_ops->die(req->rq_cli_ctx, 0);
651         return rc;
652 }
653
654 static
655 void ctx_refresh_interrupt(struct ptlrpc_request *req)
656 {
657
658         spin_lock(&req->rq_lock);
659         req->rq_intr = 1;
660         spin_unlock(&req->rq_lock);
661 }
662
663 static
664 void req_off_ctx_list(struct ptlrpc_request *req, struct ptlrpc_cli_ctx *ctx)
665 {
666         spin_lock(&ctx->cc_lock);
667         if (!list_empty(&req->rq_ctx_chain))
668                 list_del_init(&req->rq_ctx_chain);
669         spin_unlock(&ctx->cc_lock);
670 }
671
672 /**
673  * To refresh the context of \req, if it's not up-to-date.
674  * \param timeout
675  * - < 0: don't wait
676  * - = 0: wait until success or fatal error occur
677  * - > 0: timeout value (in seconds)
678  *
679  * The status of the context could be subject to be changed by other threads
680  * at any time. We allow this race, but once we return with 0, the caller will
681  * suppose it's uptodated and keep using it until the owning rpc is done.
682  *
683  * \retval 0 only if the context is uptodated.
684  * \retval -ev error number.
685  */
686 int sptlrpc_req_refresh_ctx(struct ptlrpc_request *req, long timeout)
687 {
688         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
689         struct ptlrpc_sec *sec;
690         int rc;
691
692         ENTRY;
693
694         LASSERT(ctx);
695
696         if (req->rq_ctx_init || req->rq_ctx_fini)
697                 RETURN(0);
698
699         /*
700          * during the process a request's context might change type even
701          * (e.g. from gss ctx to null ctx), so each loop we need to re-check
702          * everything
703          */
704 again:
705         rc = import_sec_validate_get(req->rq_import, &sec);
706         if (rc)
707                 RETURN(rc);
708
709         if (sec->ps_flvr.sf_rpc != req->rq_flvr.sf_rpc) {
710                 CDEBUG(D_SEC, "req %p: flavor has changed %x -> %x\n",
711                        req, req->rq_flvr.sf_rpc, sec->ps_flvr.sf_rpc);
712                 req_off_ctx_list(req, ctx);
713                 sptlrpc_req_replace_dead_ctx(req);
714                 ctx = req->rq_cli_ctx;
715         }
716         sptlrpc_sec_put(sec);
717
718         if (cli_ctx_is_eternal(ctx))
719                 RETURN(0);
720
721         if (unlikely(test_bit(PTLRPC_CTX_NEW_BIT, &ctx->cc_flags))) {
722                 LASSERT(ctx->cc_ops->refresh);
723                 ctx->cc_ops->refresh(ctx);
724         }
725         LASSERT(test_bit(PTLRPC_CTX_NEW_BIT, &ctx->cc_flags) == 0);
726
727         LASSERT(ctx->cc_ops->validate);
728         if (ctx->cc_ops->validate(ctx) == 0) {
729                 req_off_ctx_list(req, ctx);
730                 RETURN(0);
731         }
732
733         if (unlikely(test_bit(PTLRPC_CTX_ERROR_BIT, &ctx->cc_flags))) {
734                 spin_lock(&req->rq_lock);
735                 req->rq_err = 1;
736                 spin_unlock(&req->rq_lock);
737                 req_off_ctx_list(req, ctx);
738                 RETURN(-EPERM);
739         }
740
741         /*
742          * There's a subtle issue for resending RPCs, suppose following
743          * situation:
744          *  1. the request was sent to server.
745          *  2. recovery was kicked start, after finished the request was
746          *     marked as resent.
747          *  3. resend the request.
748          *  4. old reply from server received, we accept and verify the reply.
749          *     this has to be success, otherwise the error will be aware
750          *     by application.
751          *  5. new reply from server received, dropped by LNet.
752          *
753          * Note the xid of old & new request is the same. We can't simply
754          * change xid for the resent request because the server replies on
755          * it for reply reconstruction.
756          *
757          * Commonly the original context should be uptodate because we
758          * have an expiry nice time; server will keep its context because
759          * we at least hold a ref of old context which prevent context
760          * from destroying RPC being sent. So server still can accept the
761          * request and finish the RPC. But if that's not the case:
762          *  1. If server side context has been trimmed, a NO_CONTEXT will
763          *     be returned, gss_cli_ctx_verify/unseal will switch to new
764          *     context by force.
765          *  2. Current context never be refreshed, then we are fine: we
766          *     never really send request with old context before.
767          */
768         if (test_bit(PTLRPC_CTX_UPTODATE_BIT, &ctx->cc_flags) &&
769             unlikely(req->rq_reqmsg) &&
770             lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT) {
771                 req_off_ctx_list(req, ctx);
772                 RETURN(0);
773         }
774
775         if (unlikely(test_bit(PTLRPC_CTX_DEAD_BIT, &ctx->cc_flags))) {
776                 req_off_ctx_list(req, ctx);
777                 /*
778                  * don't switch ctx if import was deactivated
779                  */
780                 if (req->rq_import->imp_deactive) {
781                         spin_lock(&req->rq_lock);
782                         req->rq_err = 1;
783                         spin_unlock(&req->rq_lock);
784                         RETURN(-EINTR);
785                 }
786
787                 rc = sptlrpc_req_replace_dead_ctx(req);
788                 if (rc) {
789                         LASSERT(ctx == req->rq_cli_ctx);
790                         CERROR("req %p: failed to replace dead ctx %p: %d\n",
791                                req, ctx, rc);
792                         spin_lock(&req->rq_lock);
793                         req->rq_err = 1;
794                         spin_unlock(&req->rq_lock);
795                         RETURN(rc);
796                 }
797
798                 ctx = req->rq_cli_ctx;
799                 goto again;
800         }
801
802         /*
803          * Now we're sure this context is during upcall, add myself into
804          * waiting list
805          */
806         spin_lock(&ctx->cc_lock);
807         if (list_empty(&req->rq_ctx_chain))
808                 list_add(&req->rq_ctx_chain, &ctx->cc_req_list);
809         spin_unlock(&ctx->cc_lock);
810
811         if (timeout < 0)
812                 RETURN(-EWOULDBLOCK);
813
814         /* Clear any flags that may be present from previous sends */
815         LASSERT(req->rq_receiving_reply == 0);
816         spin_lock(&req->rq_lock);
817         req->rq_err = 0;
818         req->rq_timedout = 0;
819         req->rq_resend = 0;
820         req->rq_restart = 0;
821         spin_unlock(&req->rq_lock);
822
823         if (wait_event_idle_timeout(req->rq_reply_waitq,
824                                     ctx_check_refresh(ctx),
825                                     cfs_time_seconds(timeout)) == 0) {
826                 rc = -ETIMEDOUT;
827                 if (!ctx_refresh_timeout(req) &&
828                     l_wait_event_abortable(req->rq_reply_waitq,
829                                            ctx_check_refresh(ctx))
830                     == -ERESTARTSYS) {
831                         rc = -EINTR;
832                         ctx_refresh_interrupt(req);
833                 }
834         }
835
836         /*
837          * following cases could lead us here:
838          * - successfully refreshed;
839          * - interrupted;
840          * - timedout, and we don't want recover from the failure;
841          * - timedout, and waked up upon recovery finished;
842          * - someone else mark this ctx dead by force;
843          * - someone invalidate the req and call ptlrpc_client_wake_req(),
844          *   e.g. ptlrpc_abort_inflight();
845          */
846         if (!cli_ctx_is_refreshed(ctx)) {
847                 /* timed out or interruptted */
848                 req_off_ctx_list(req, ctx);
849
850                 LASSERT(rc != 0);
851                 RETURN(rc);
852         }
853
854         goto again;
855 }
856
857 /**
858  * Initialize flavor settings for \a req, according to \a opcode.
859  *
860  * \note this could be called in two situations:
861  * - new request from ptlrpc_pre_req(), with proper @opcode
862  * - old request which changed ctx in the middle, with @opcode == 0
863  */
864 void sptlrpc_req_set_flavor(struct ptlrpc_request *req, int opcode)
865 {
866         struct ptlrpc_sec *sec;
867
868         LASSERT(req->rq_import);
869         LASSERT(req->rq_cli_ctx);
870         LASSERT(req->rq_cli_ctx->cc_sec);
871         LASSERT(req->rq_bulk_read == 0 || req->rq_bulk_write == 0);
872
873         /* special security flags according to opcode */
874         switch (opcode) {
875         case OST_READ:
876         case MDS_READPAGE:
877         case MGS_CONFIG_READ:
878         case OBD_IDX_READ:
879                 req->rq_bulk_read = 1;
880                 break;
881         case OST_WRITE:
882         case MDS_WRITEPAGE:
883                 req->rq_bulk_write = 1;
884                 break;
885         case SEC_CTX_INIT:
886                 req->rq_ctx_init = 1;
887                 break;
888         case SEC_CTX_FINI:
889                 req->rq_ctx_fini = 1;
890                 break;
891         case 0:
892                 /* init/fini rpc won't be resend, so can't be here */
893                 LASSERT(req->rq_ctx_init == 0);
894                 LASSERT(req->rq_ctx_fini == 0);
895
896                 /* cleanup flags, which should be recalculated */
897                 req->rq_pack_udesc = 0;
898                 req->rq_pack_bulk = 0;
899                 break;
900         }
901
902         sec = req->rq_cli_ctx->cc_sec;
903
904         spin_lock(&sec->ps_lock);
905         req->rq_flvr = sec->ps_flvr;
906         spin_unlock(&sec->ps_lock);
907
908         /*
909          * force SVC_NULL for context initiation rpc, SVC_INTG for context
910          * destruction rpc
911          */
912         if (unlikely(req->rq_ctx_init))
913                 flvr_set_svc(&req->rq_flvr.sf_rpc, SPTLRPC_SVC_NULL);
914         else if (unlikely(req->rq_ctx_fini))
915                 flvr_set_svc(&req->rq_flvr.sf_rpc, SPTLRPC_SVC_INTG);
916
917         /* user descriptor flag, null security can't do it anyway */
918         if ((sec->ps_flvr.sf_flags & PTLRPC_SEC_FL_UDESC) &&
919             (req->rq_flvr.sf_rpc != SPTLRPC_FLVR_NULL))
920                 req->rq_pack_udesc = 1;
921
922         /* bulk security flag */
923         if ((req->rq_bulk_read || req->rq_bulk_write) &&
924             sptlrpc_flavor_has_bulk(&req->rq_flvr))
925                 req->rq_pack_bulk = 1;
926 }
927
928 void sptlrpc_request_out_callback(struct ptlrpc_request *req)
929 {
930         if (SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc) != SPTLRPC_SVC_PRIV)
931                 return;
932
933         LASSERT(req->rq_clrbuf);
934         if (req->rq_pool || !req->rq_reqbuf)
935                 return;
936
937         OBD_FREE(req->rq_reqbuf, req->rq_reqbuf_len);
938         req->rq_reqbuf = NULL;
939         req->rq_reqbuf_len = 0;
940 }
941
942 /**
943  * Given an import \a imp, check whether current user has a valid context
944  * or not. We may create a new context and try to refresh it, and try
945  * repeatedly try in case of non-fatal errors. Return 0 means success.
946  */
947 int sptlrpc_import_check_ctx(struct obd_import *imp)
948 {
949         struct ptlrpc_sec     *sec;
950         struct ptlrpc_cli_ctx *ctx;
951         struct ptlrpc_request *req = NULL;
952         int rc;
953
954         ENTRY;
955
956         might_sleep();
957
958         sec = sptlrpc_import_sec_ref(imp);
959         ctx = get_my_ctx(sec);
960         sptlrpc_sec_put(sec);
961
962         if (!ctx)
963                 RETURN(-ENOMEM);
964
965         if (cli_ctx_is_eternal(ctx) ||
966             ctx->cc_ops->validate(ctx) == 0) {
967                 sptlrpc_cli_ctx_put(ctx, 1);
968                 RETURN(0);
969         }
970
971         if (cli_ctx_is_error(ctx)) {
972                 sptlrpc_cli_ctx_put(ctx, 1);
973                 RETURN(-EACCES);
974         }
975
976         req = ptlrpc_request_cache_alloc(GFP_NOFS);
977         if (!req)
978                 RETURN(-ENOMEM);
979
980         ptlrpc_cli_req_init(req);
981         atomic_set(&req->rq_refcount, 10000);
982
983         req->rq_import = imp;
984         req->rq_flvr = sec->ps_flvr;
985         req->rq_cli_ctx = ctx;
986
987         rc = sptlrpc_req_refresh_ctx(req, 0);
988         LASSERT(list_empty(&req->rq_ctx_chain));
989         sptlrpc_cli_ctx_put(req->rq_cli_ctx, 1);
990         ptlrpc_request_cache_free(req);
991
992         RETURN(rc);
993 }
994
995 /**
996  * Used by ptlrpc client, to perform the pre-defined security transformation
997  * upon the request message of \a req. After this function called,
998  * req->rq_reqmsg is still accessible as clear text.
999  */
1000 int sptlrpc_cli_wrap_request(struct ptlrpc_request *req)
1001 {
1002         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
1003         int rc = 0;
1004
1005         ENTRY;
1006
1007         LASSERT(ctx);
1008         LASSERT(ctx->cc_sec);
1009         LASSERT(req->rq_reqbuf || req->rq_clrbuf);
1010
1011         /*
1012          * we wrap bulk request here because now we can be sure
1013          * the context is uptodate.
1014          */
1015         if (req->rq_bulk) {
1016                 rc = sptlrpc_cli_wrap_bulk(req, req->rq_bulk);
1017                 if (rc)
1018                         RETURN(rc);
1019         }
1020
1021         switch (SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc)) {
1022         case SPTLRPC_SVC_NULL:
1023         case SPTLRPC_SVC_AUTH:
1024         case SPTLRPC_SVC_INTG:
1025                 LASSERT(ctx->cc_ops->sign);
1026                 rc = ctx->cc_ops->sign(ctx, req);
1027                 break;
1028         case SPTLRPC_SVC_PRIV:
1029                 LASSERT(ctx->cc_ops->seal);
1030                 rc = ctx->cc_ops->seal(ctx, req);
1031                 break;
1032         default:
1033                 LBUG();
1034         }
1035
1036         if (rc == 0) {
1037                 LASSERT(req->rq_reqdata_len);
1038                 LASSERT(req->rq_reqdata_len % 8 == 0);
1039                 LASSERT(req->rq_reqdata_len <= req->rq_reqbuf_len);
1040         }
1041
1042         RETURN(rc);
1043 }
1044
1045 static int do_cli_unwrap_reply(struct ptlrpc_request *req)
1046 {
1047         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
1048         int rc;
1049
1050         ENTRY;
1051
1052         LASSERT(ctx);
1053         LASSERT(ctx->cc_sec);
1054         LASSERT(req->rq_repbuf);
1055         LASSERT(req->rq_repdata);
1056         LASSERT(req->rq_repmsg == NULL);
1057
1058         req->rq_rep_swab_mask = 0;
1059
1060         rc = __lustre_unpack_msg(req->rq_repdata, req->rq_repdata_len);
1061         switch (rc) {
1062         case 1:
1063                 lustre_set_rep_swabbed(req, MSG_PTLRPC_HEADER_OFF);
1064         case 0:
1065                 break;
1066         default:
1067                 CERROR("failed unpack reply: x%llu\n", req->rq_xid);
1068                 RETURN(-EPROTO);
1069         }
1070
1071         if (req->rq_repdata_len < sizeof(struct lustre_msg)) {
1072                 CERROR("replied data length %d too small\n",
1073                        req->rq_repdata_len);
1074                 RETURN(-EPROTO);
1075         }
1076
1077         if (SPTLRPC_FLVR_POLICY(req->rq_repdata->lm_secflvr) !=
1078             SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc)) {
1079                 CERROR("reply policy %u doesn't match request policy %u\n",
1080                        SPTLRPC_FLVR_POLICY(req->rq_repdata->lm_secflvr),
1081                        SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc));
1082                 RETURN(-EPROTO);
1083         }
1084
1085         switch (SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc)) {
1086         case SPTLRPC_SVC_NULL:
1087         case SPTLRPC_SVC_AUTH:
1088         case SPTLRPC_SVC_INTG:
1089                 LASSERT(ctx->cc_ops->verify);
1090                 rc = ctx->cc_ops->verify(ctx, req);
1091                 break;
1092         case SPTLRPC_SVC_PRIV:
1093                 LASSERT(ctx->cc_ops->unseal);
1094                 rc = ctx->cc_ops->unseal(ctx, req);
1095                 break;
1096         default:
1097                 LBUG();
1098         }
1099         LASSERT(rc || req->rq_repmsg || req->rq_resend);
1100
1101         if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL &&
1102             !req->rq_ctx_init)
1103                 req->rq_rep_swab_mask = 0;
1104         RETURN(rc);
1105 }
1106
1107 /**
1108  * Used by ptlrpc client, to perform security transformation upon the reply
1109  * message of \a req. After return successfully, req->rq_repmsg points to
1110  * the reply message in clear text.
1111  *
1112  * \pre the reply buffer should have been un-posted from LNet, so nothing is
1113  * going to change.
1114  */
1115 int sptlrpc_cli_unwrap_reply(struct ptlrpc_request *req)
1116 {
1117         LASSERT(req->rq_repbuf);
1118         LASSERT(req->rq_repdata == NULL);
1119         LASSERT(req->rq_repmsg == NULL);
1120         LASSERT(req->rq_reply_off + req->rq_nob_received <= req->rq_repbuf_len);
1121
1122         if (req->rq_reply_off == 0 &&
1123             (lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT)) {
1124                 CERROR("real reply with offset 0\n");
1125                 return -EPROTO;
1126         }
1127
1128         if (req->rq_reply_off % 8 != 0) {
1129                 CERROR("reply at odd offset %u\n", req->rq_reply_off);
1130                 return -EPROTO;
1131         }
1132
1133         req->rq_repdata = (struct lustre_msg *)
1134                                 (req->rq_repbuf + req->rq_reply_off);
1135         req->rq_repdata_len = req->rq_nob_received;
1136
1137         return do_cli_unwrap_reply(req);
1138 }
1139
1140 /**
1141  * Used by ptlrpc client, to perform security transformation upon the early
1142  * reply message of \a req. We expect the rq_reply_off is 0, and
1143  * rq_nob_received is the early reply size.
1144  *
1145  * Because the receive buffer might be still posted, the reply data might be
1146  * changed at any time, no matter we're holding rq_lock or not. For this reason
1147  * we allocate a separate ptlrpc_request and reply buffer for early reply
1148  * processing.
1149  *
1150  * \retval 0 success, \a req_ret is filled with a duplicated ptlrpc_request.
1151  * Later the caller must call sptlrpc_cli_finish_early_reply() on the returned
1152  * \a *req_ret to release it.
1153  * \retval -ev error number, and \a req_ret will not be set.
1154  */
1155 int sptlrpc_cli_unwrap_early_reply(struct ptlrpc_request *req,
1156                                    struct ptlrpc_request **req_ret)
1157 {
1158         struct ptlrpc_request *early_req;
1159         char *early_buf;
1160         int early_bufsz, early_size;
1161         int rc;
1162
1163         ENTRY;
1164
1165         early_req = ptlrpc_request_cache_alloc(GFP_NOFS);
1166         if (early_req == NULL)
1167                 RETURN(-ENOMEM);
1168
1169         ptlrpc_cli_req_init(early_req);
1170
1171         early_size = req->rq_nob_received;
1172         early_bufsz = size_roundup_power2(early_size);
1173         OBD_ALLOC_LARGE(early_buf, early_bufsz);
1174         if (early_buf == NULL)
1175                 GOTO(err_req, rc = -ENOMEM);
1176
1177         /* sanity checkings and copy data out, do it inside spinlock */
1178         spin_lock(&req->rq_lock);
1179
1180         if (req->rq_replied) {
1181                 spin_unlock(&req->rq_lock);
1182                 GOTO(err_buf, rc = -EALREADY);
1183         }
1184
1185         LASSERT(req->rq_repbuf);
1186         LASSERT(req->rq_repdata == NULL);
1187         LASSERT(req->rq_repmsg == NULL);
1188
1189         if (req->rq_reply_off != 0) {
1190                 CERROR("early reply with offset %u\n", req->rq_reply_off);
1191                 spin_unlock(&req->rq_lock);
1192                 GOTO(err_buf, rc = -EPROTO);
1193         }
1194
1195         if (req->rq_nob_received != early_size) {
1196                 /* even another early arrived the size should be the same */
1197                 CERROR("data size has changed from %u to %u\n",
1198                        early_size, req->rq_nob_received);
1199                 spin_unlock(&req->rq_lock);
1200                 GOTO(err_buf, rc = -EINVAL);
1201         }
1202
1203         if (req->rq_nob_received < sizeof(struct lustre_msg)) {
1204                 CERROR("early reply length %d too small\n",
1205                        req->rq_nob_received);
1206                 spin_unlock(&req->rq_lock);
1207                 GOTO(err_buf, rc = -EALREADY);
1208         }
1209
1210         memcpy(early_buf, req->rq_repbuf, early_size);
1211         spin_unlock(&req->rq_lock);
1212
1213         early_req->rq_cli_ctx = sptlrpc_cli_ctx_get(req->rq_cli_ctx);
1214         early_req->rq_flvr = req->rq_flvr;
1215         early_req->rq_repbuf = early_buf;
1216         early_req->rq_repbuf_len = early_bufsz;
1217         early_req->rq_repdata = (struct lustre_msg *) early_buf;
1218         early_req->rq_repdata_len = early_size;
1219         early_req->rq_early = 1;
1220         early_req->rq_reqmsg = req->rq_reqmsg;
1221
1222         rc = do_cli_unwrap_reply(early_req);
1223         if (rc) {
1224                 DEBUG_REQ(D_ADAPTTO, early_req,
1225                           "unwrap early reply: rc = %d", rc);
1226                 GOTO(err_ctx, rc);
1227         }
1228
1229         LASSERT(early_req->rq_repmsg);
1230         *req_ret = early_req;
1231         RETURN(0);
1232
1233 err_ctx:
1234         sptlrpc_cli_ctx_put(early_req->rq_cli_ctx, 1);
1235 err_buf:
1236         OBD_FREE_LARGE(early_buf, early_bufsz);
1237 err_req:
1238         ptlrpc_request_cache_free(early_req);
1239         RETURN(rc);
1240 }
1241
1242 /**
1243  * Used by ptlrpc client, to release a processed early reply \a early_req.
1244  *
1245  * \pre \a early_req was obtained from calling sptlrpc_cli_unwrap_early_reply().
1246  */
1247 void sptlrpc_cli_finish_early_reply(struct ptlrpc_request *early_req)
1248 {
1249         LASSERT(early_req->rq_repbuf);
1250         LASSERT(early_req->rq_repdata);
1251         LASSERT(early_req->rq_repmsg);
1252
1253         sptlrpc_cli_ctx_put(early_req->rq_cli_ctx, 1);
1254         OBD_FREE_LARGE(early_req->rq_repbuf, early_req->rq_repbuf_len);
1255         ptlrpc_request_cache_free(early_req);
1256 }
1257
1258 /**************************************************
1259  * sec ID                                         *
1260  **************************************************/
1261
1262 /*
1263  * "fixed" sec (e.g. null) use sec_id < 0
1264  */
1265 static atomic_t sptlrpc_sec_id = ATOMIC_INIT(1);
1266
1267 int sptlrpc_get_next_secid(void)
1268 {
1269         return atomic_inc_return(&sptlrpc_sec_id);
1270 }
1271 EXPORT_SYMBOL(sptlrpc_get_next_secid);
1272
1273 /*
1274  * client side high-level security APIs
1275  */
1276
1277 static int sec_cop_flush_ctx_cache(struct ptlrpc_sec *sec, uid_t uid,
1278                                    int grace, int force)
1279 {
1280         struct ptlrpc_sec_policy *policy = sec->ps_policy;
1281
1282         LASSERT(policy->sp_cops);
1283         LASSERT(policy->sp_cops->flush_ctx_cache);
1284
1285         return policy->sp_cops->flush_ctx_cache(sec, uid, grace, force);
1286 }
1287
1288 static void sec_cop_destroy_sec(struct ptlrpc_sec *sec)
1289 {
1290         struct ptlrpc_sec_policy *policy = sec->ps_policy;
1291
1292         LASSERT_ATOMIC_ZERO(&sec->ps_refcount);
1293         LASSERT_ATOMIC_ZERO(&sec->ps_nctx);
1294         LASSERT(policy->sp_cops->destroy_sec);
1295
1296         CDEBUG(D_SEC, "%s@%p: being destroied\n", sec->ps_policy->sp_name, sec);
1297
1298         policy->sp_cops->destroy_sec(sec);
1299         sptlrpc_policy_put(policy);
1300 }
1301
1302 void sptlrpc_sec_destroy(struct ptlrpc_sec *sec)
1303 {
1304         sec_cop_destroy_sec(sec);
1305 }
1306 EXPORT_SYMBOL(sptlrpc_sec_destroy);
1307
1308 static void sptlrpc_sec_kill(struct ptlrpc_sec *sec)
1309 {
1310         LASSERT_ATOMIC_POS(&sec->ps_refcount);
1311
1312         if (sec->ps_policy->sp_cops->kill_sec) {
1313                 sec->ps_policy->sp_cops->kill_sec(sec);
1314
1315                 sec_cop_flush_ctx_cache(sec, -1, 1, 1);
1316         }
1317 }
1318
1319 struct ptlrpc_sec *sptlrpc_sec_get(struct ptlrpc_sec *sec)
1320 {
1321         if (sec)
1322                 atomic_inc(&sec->ps_refcount);
1323
1324         return sec;
1325 }
1326 EXPORT_SYMBOL(sptlrpc_sec_get);
1327
1328 void sptlrpc_sec_put(struct ptlrpc_sec *sec)
1329 {
1330         if (sec) {
1331                 LASSERT_ATOMIC_POS(&sec->ps_refcount);
1332
1333                 if (atomic_dec_and_test(&sec->ps_refcount)) {
1334                         sptlrpc_gc_del_sec(sec);
1335                         sec_cop_destroy_sec(sec);
1336                 }
1337         }
1338 }
1339 EXPORT_SYMBOL(sptlrpc_sec_put);
1340
1341 /*
1342  * policy module is responsible for taking refrence of import
1343  */
1344 static
1345 struct ptlrpc_sec * sptlrpc_sec_create(struct obd_import *imp,
1346                                        struct ptlrpc_svc_ctx *svc_ctx,
1347                                        struct sptlrpc_flavor *sf,
1348                                        enum lustre_sec_part sp)
1349 {
1350         struct ptlrpc_sec_policy *policy;
1351         struct ptlrpc_sec *sec;
1352         char str[32];
1353
1354         ENTRY;
1355
1356         if (svc_ctx) {
1357                 LASSERT(imp->imp_dlm_fake == 1);
1358
1359                 CDEBUG(D_SEC, "%s %s: reverse sec using flavor %s\n",
1360                        imp->imp_obd->obd_type->typ_name,
1361                        imp->imp_obd->obd_name,
1362                        sptlrpc_flavor2name(sf, str, sizeof(str)));
1363
1364                 policy = sptlrpc_policy_get(svc_ctx->sc_policy);
1365                 sf->sf_flags |= PTLRPC_SEC_FL_REVERSE | PTLRPC_SEC_FL_ROOTONLY;
1366         } else {
1367                 LASSERT(imp->imp_dlm_fake == 0);
1368
1369                 CDEBUG(D_SEC, "%s %s: select security flavor %s\n",
1370                        imp->imp_obd->obd_type->typ_name,
1371                        imp->imp_obd->obd_name,
1372                        sptlrpc_flavor2name(sf, str, sizeof(str)));
1373
1374                 policy = sptlrpc_wireflavor2policy(sf->sf_rpc);
1375                 if (!policy) {
1376                         CERROR("invalid flavor 0x%x\n", sf->sf_rpc);
1377                         RETURN(NULL);
1378                 }
1379         }
1380
1381         sec = policy->sp_cops->create_sec(imp, svc_ctx, sf);
1382         if (sec) {
1383                 atomic_inc(&sec->ps_refcount);
1384
1385                 sec->ps_part = sp;
1386
1387                 if (sec->ps_gc_interval && policy->sp_cops->gc_ctx)
1388                         sptlrpc_gc_add_sec(sec);
1389         } else {
1390                 sptlrpc_policy_put(policy);
1391         }
1392
1393         RETURN(sec);
1394 }
1395
1396 struct ptlrpc_sec *sptlrpc_import_sec_ref(struct obd_import *imp)
1397 {
1398         struct ptlrpc_sec *sec;
1399
1400         read_lock(&imp->imp_sec_lock);
1401         sec = sptlrpc_sec_get(imp->imp_sec);
1402         read_unlock(&imp->imp_sec_lock);
1403
1404         return sec;
1405 }
1406 EXPORT_SYMBOL(sptlrpc_import_sec_ref);
1407
1408 static void sptlrpc_import_sec_install(struct obd_import *imp,
1409                                        struct ptlrpc_sec *sec)
1410 {
1411         struct ptlrpc_sec *old_sec;
1412
1413         LASSERT_ATOMIC_POS(&sec->ps_refcount);
1414
1415         write_lock(&imp->imp_sec_lock);
1416         old_sec = imp->imp_sec;
1417         imp->imp_sec = sec;
1418         write_unlock(&imp->imp_sec_lock);
1419
1420         if (old_sec) {
1421                 sptlrpc_sec_kill(old_sec);
1422
1423                 /* balance the ref taken by this import */
1424                 sptlrpc_sec_put(old_sec);
1425         }
1426 }
1427
1428 static inline
1429 int flavor_equal(struct sptlrpc_flavor *sf1, struct sptlrpc_flavor *sf2)
1430 {
1431         return (memcmp(sf1, sf2, sizeof(*sf1)) == 0);
1432 }
1433
1434 static inline
1435 void flavor_copy(struct sptlrpc_flavor *dst, struct sptlrpc_flavor *src)
1436 {
1437         *dst = *src;
1438 }
1439
1440 /**
1441  * To get an appropriate ptlrpc_sec for the \a imp, according to the current
1442  * configuration. Upon called, imp->imp_sec may or may not be NULL.
1443  *
1444  *  - regular import: \a svc_ctx should be NULL and \a flvr is ignored;
1445  *  - reverse import: \a svc_ctx and \a flvr are obtained from incoming request.
1446  */
1447 int sptlrpc_import_sec_adapt(struct obd_import *imp,
1448                              struct ptlrpc_svc_ctx *svc_ctx,
1449                              struct sptlrpc_flavor *flvr)
1450 {
1451         struct ptlrpc_connection *conn;
1452         struct sptlrpc_flavor sf;
1453         struct ptlrpc_sec *sec, *newsec;
1454         enum lustre_sec_part sp;
1455         char str[24];
1456         int rc = 0;
1457
1458         ENTRY;
1459
1460         might_sleep();
1461
1462         if (imp == NULL)
1463                 RETURN(0);
1464
1465         conn = imp->imp_connection;
1466
1467         if (svc_ctx == NULL) {
1468                 struct client_obd *cliobd = &imp->imp_obd->u.cli;
1469                 /*
1470                  * normal import, determine flavor from rule set, except
1471                  * for mgc the flavor is predetermined.
1472                  */
1473                 if (cliobd->cl_sp_me == LUSTRE_SP_MGC)
1474                         sf = cliobd->cl_flvr_mgc;
1475                 else
1476                         sptlrpc_conf_choose_flavor(cliobd->cl_sp_me,
1477                                                    cliobd->cl_sp_to,
1478                                                    &cliobd->cl_target_uuid,
1479                                                    conn->c_self, &sf);
1480
1481                 sp = imp->imp_obd->u.cli.cl_sp_me;
1482         } else {
1483                 /* reverse import, determine flavor from incoming reqeust */
1484                 sf = *flvr;
1485
1486                 if (sf.sf_rpc != SPTLRPC_FLVR_NULL)
1487                         sf.sf_flags = PTLRPC_SEC_FL_REVERSE |
1488                                       PTLRPC_SEC_FL_ROOTONLY;
1489
1490                 sp = sptlrpc_target_sec_part(imp->imp_obd);
1491         }
1492
1493         sec = sptlrpc_import_sec_ref(imp);
1494         if (sec) {
1495                 char str2[24];
1496
1497                 if (flavor_equal(&sf, &sec->ps_flvr))
1498                         GOTO(out, rc);
1499
1500                 CDEBUG(D_SEC, "import %s->%s: changing flavor %s -> %s\n",
1501                        imp->imp_obd->obd_name,
1502                        obd_uuid2str(&conn->c_remote_uuid),
1503                        sptlrpc_flavor2name(&sec->ps_flvr, str, sizeof(str)),
1504                        sptlrpc_flavor2name(&sf, str2, sizeof(str2)));
1505         } else if (SPTLRPC_FLVR_BASE(sf.sf_rpc) !=
1506                    SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_NULL)) {
1507                 CDEBUG(D_SEC, "import %s->%s netid %x: select flavor %s\n",
1508                        imp->imp_obd->obd_name,
1509                        obd_uuid2str(&conn->c_remote_uuid),
1510                        LNET_NIDNET(conn->c_self),
1511                        sptlrpc_flavor2name(&sf, str, sizeof(str)));
1512         }
1513
1514         newsec = sptlrpc_sec_create(imp, svc_ctx, &sf, sp);
1515         if (newsec) {
1516                 sptlrpc_import_sec_install(imp, newsec);
1517         } else {
1518                 CERROR("import %s->%s: failed to create new sec\n",
1519                        imp->imp_obd->obd_name,
1520                        obd_uuid2str(&conn->c_remote_uuid));
1521                 rc = -EPERM;
1522         }
1523
1524 out:
1525         sptlrpc_sec_put(sec);
1526         RETURN(rc);
1527 }
1528
1529 void sptlrpc_import_sec_put(struct obd_import *imp)
1530 {
1531         if (imp->imp_sec) {
1532                 sptlrpc_sec_kill(imp->imp_sec);
1533
1534                 sptlrpc_sec_put(imp->imp_sec);
1535                 imp->imp_sec = NULL;
1536         }
1537 }
1538
1539 static void import_flush_ctx_common(struct obd_import *imp,
1540                                     uid_t uid, int grace, int force)
1541 {
1542         struct ptlrpc_sec *sec;
1543
1544         if (imp == NULL)
1545                 return;
1546
1547         sec = sptlrpc_import_sec_ref(imp);
1548         if (sec == NULL)
1549                 return;
1550
1551         sec_cop_flush_ctx_cache(sec, uid, grace, force);
1552         sptlrpc_sec_put(sec);
1553 }
1554
1555 void sptlrpc_import_flush_root_ctx(struct obd_import *imp)
1556 {
1557         /*
1558          * it's important to use grace mode, see explain in
1559          * sptlrpc_req_refresh_ctx()
1560          */
1561         import_flush_ctx_common(imp, 0, 1, 1);
1562 }
1563
1564 void sptlrpc_import_flush_my_ctx(struct obd_import *imp)
1565 {
1566         import_flush_ctx_common(imp, from_kuid(&init_user_ns, current_uid()),
1567                                 1, 1);
1568 }
1569 EXPORT_SYMBOL(sptlrpc_import_flush_my_ctx);
1570
1571 void sptlrpc_import_flush_all_ctx(struct obd_import *imp)
1572 {
1573         import_flush_ctx_common(imp, -1, 1, 1);
1574 }
1575 EXPORT_SYMBOL(sptlrpc_import_flush_all_ctx);
1576
1577 /**
1578  * Used by ptlrpc client to allocate request buffer of \a req. Upon return
1579  * successfully, req->rq_reqmsg points to a buffer with size \a msgsize.
1580  */
1581 int sptlrpc_cli_alloc_reqbuf(struct ptlrpc_request *req, int msgsize)
1582 {
1583         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
1584         struct ptlrpc_sec_policy *policy;
1585         int rc;
1586
1587         LASSERT(ctx);
1588         LASSERT(ctx->cc_sec);
1589         LASSERT(ctx->cc_sec->ps_policy);
1590         LASSERT(req->rq_reqmsg == NULL);
1591         LASSERT_ATOMIC_POS(&ctx->cc_refcount);
1592
1593         policy = ctx->cc_sec->ps_policy;
1594         rc = policy->sp_cops->alloc_reqbuf(ctx->cc_sec, req, msgsize);
1595         if (!rc) {
1596                 LASSERT(req->rq_reqmsg);
1597                 LASSERT(req->rq_reqbuf || req->rq_clrbuf);
1598
1599                 /* zeroing preallocated buffer */
1600                 if (req->rq_pool)
1601                         memset(req->rq_reqmsg, 0, msgsize);
1602         }
1603
1604         return rc;
1605 }
1606
1607 /**
1608  * Used by ptlrpc client to free request buffer of \a req. After this
1609  * req->rq_reqmsg is set to NULL and should not be accessed anymore.
1610  */
1611 void sptlrpc_cli_free_reqbuf(struct ptlrpc_request *req)
1612 {
1613         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
1614         struct ptlrpc_sec_policy *policy;
1615
1616         LASSERT(ctx);
1617         LASSERT(ctx->cc_sec);
1618         LASSERT(ctx->cc_sec->ps_policy);
1619         LASSERT_ATOMIC_POS(&ctx->cc_refcount);
1620
1621         if (req->rq_reqbuf == NULL && req->rq_clrbuf == NULL)
1622                 return;
1623
1624         policy = ctx->cc_sec->ps_policy;
1625         policy->sp_cops->free_reqbuf(ctx->cc_sec, req);
1626         req->rq_reqmsg = NULL;
1627 }
1628
1629 /*
1630  * NOTE caller must guarantee the buffer size is enough for the enlargement
1631  */
1632 void _sptlrpc_enlarge_msg_inplace(struct lustre_msg *msg,
1633                                   int segment, int newsize)
1634 {
1635         void *src, *dst;
1636         int oldsize, oldmsg_size, movesize;
1637
1638         LASSERT(segment < msg->lm_bufcount);
1639         LASSERT(msg->lm_buflens[segment] <= newsize);
1640
1641         if (msg->lm_buflens[segment] == newsize)
1642                 return;
1643
1644         /* nothing to do if we are enlarging the last segment */
1645         if (segment == msg->lm_bufcount - 1) {
1646                 msg->lm_buflens[segment] = newsize;
1647                 return;
1648         }
1649
1650         oldsize = msg->lm_buflens[segment];
1651
1652         src = lustre_msg_buf(msg, segment + 1, 0);
1653         msg->lm_buflens[segment] = newsize;
1654         dst = lustre_msg_buf(msg, segment + 1, 0);
1655         msg->lm_buflens[segment] = oldsize;
1656
1657         /* move from segment + 1 to end segment */
1658         LASSERT(msg->lm_magic == LUSTRE_MSG_MAGIC_V2);
1659         oldmsg_size = lustre_msg_size_v2(msg->lm_bufcount, msg->lm_buflens);
1660         movesize = oldmsg_size - ((unsigned long) src - (unsigned long) msg);
1661         LASSERT(movesize >= 0);
1662
1663         if (movesize)
1664                 memmove(dst, src, movesize);
1665
1666         /* note we don't clear the ares where old data live, not secret */
1667
1668         /* finally set new segment size */
1669         msg->lm_buflens[segment] = newsize;
1670 }
1671 EXPORT_SYMBOL(_sptlrpc_enlarge_msg_inplace);
1672
1673 /**
1674  * Used by ptlrpc client to enlarge the \a segment of request message pointed
1675  * by req->rq_reqmsg to size \a newsize, all previously filled-in data will be
1676  * preserved after the enlargement. this must be called after original request
1677  * buffer being allocated.
1678  *
1679  * \note after this be called, rq_reqmsg and rq_reqlen might have been changed,
1680  * so caller should refresh its local pointers if needed.
1681  */
1682 int sptlrpc_cli_enlarge_reqbuf(struct ptlrpc_request *req,
1683                                const struct req_msg_field *field,
1684                                int newsize)
1685 {
1686         struct req_capsule *pill = &req->rq_pill;
1687         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
1688         struct ptlrpc_sec_cops *cops;
1689         struct lustre_msg *msg = req->rq_reqmsg;
1690         int segment = __req_capsule_offset(pill, field, RCL_CLIENT);
1691
1692         LASSERT(ctx);
1693         LASSERT(msg);
1694         LASSERT(msg->lm_bufcount > segment);
1695         LASSERT(msg->lm_buflens[segment] <= newsize);
1696
1697         if (msg->lm_buflens[segment] == newsize)
1698                 return 0;
1699
1700         cops = ctx->cc_sec->ps_policy->sp_cops;
1701         LASSERT(cops->enlarge_reqbuf);
1702         return cops->enlarge_reqbuf(ctx->cc_sec, req, segment, newsize);
1703 }
1704 EXPORT_SYMBOL(sptlrpc_cli_enlarge_reqbuf);
1705
1706 /**
1707  * Used by ptlrpc client to allocate reply buffer of \a req.
1708  *
1709  * \note After this, req->rq_repmsg is still not accessible.
1710  */
1711 int sptlrpc_cli_alloc_repbuf(struct ptlrpc_request *req, int msgsize)
1712 {
1713         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
1714         struct ptlrpc_sec_policy *policy;
1715
1716         ENTRY;
1717
1718         LASSERT(ctx);
1719         LASSERT(ctx->cc_sec);
1720         LASSERT(ctx->cc_sec->ps_policy);
1721
1722         if (req->rq_repbuf)
1723                 RETURN(0);
1724
1725         policy = ctx->cc_sec->ps_policy;
1726         RETURN(policy->sp_cops->alloc_repbuf(ctx->cc_sec, req, msgsize));
1727 }
1728
1729 /**
1730  * Used by ptlrpc client to free reply buffer of \a req. After this
1731  * req->rq_repmsg is set to NULL and should not be accessed anymore.
1732  */
1733 void sptlrpc_cli_free_repbuf(struct ptlrpc_request *req)
1734 {
1735         struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
1736         struct ptlrpc_sec_policy *policy;
1737
1738         ENTRY;
1739
1740         LASSERT(ctx);
1741         LASSERT(ctx->cc_sec);
1742         LASSERT(ctx->cc_sec->ps_policy);
1743         LASSERT_ATOMIC_POS(&ctx->cc_refcount);
1744
1745         if (req->rq_repbuf == NULL)
1746                 return;
1747         LASSERT(req->rq_repbuf_len);
1748
1749         policy = ctx->cc_sec->ps_policy;
1750         policy->sp_cops->free_repbuf(ctx->cc_sec, req);
1751         req->rq_repmsg = NULL;
1752         EXIT;
1753 }
1754 EXPORT_SYMBOL(sptlrpc_cli_free_repbuf);
1755
1756 int sptlrpc_cli_install_rvs_ctx(struct obd_import *imp,
1757                                 struct ptlrpc_cli_ctx *ctx)
1758 {
1759         struct ptlrpc_sec_policy *policy = ctx->cc_sec->ps_policy;
1760
1761         if (!policy->sp_cops->install_rctx)
1762                 return 0;
1763         return policy->sp_cops->install_rctx(imp, ctx->cc_sec, ctx);
1764 }
1765
1766 int sptlrpc_svc_install_rvs_ctx(struct obd_import *imp,
1767                                 struct ptlrpc_svc_ctx *ctx)
1768 {
1769         struct ptlrpc_sec_policy *policy = ctx->sc_policy;
1770
1771         if (!policy->sp_sops->install_rctx)
1772                 return 0;
1773         return policy->sp_sops->install_rctx(imp, ctx);
1774 }
1775
1776 /* Get SELinux policy info from userspace */
1777 static int sepol_helper(struct obd_import *imp)
1778 {
1779         char mtime_str[21] = { 0 }, mode_str[2] = { 0 };
1780         char *argv[] = {
1781                 [0] = "/usr/sbin/l_getsepol",
1782                 [1] = "-o",
1783                 [2] = NULL,         /* obd type */
1784                 [3] = "-n",
1785                 [4] = NULL,         /* obd name */
1786                 [5] = "-t",
1787                 [6] = mtime_str,    /* policy mtime */
1788                 [7] = "-m",
1789                 [8] = mode_str,     /* enforcing mode */
1790                 [9] = NULL
1791         };
1792         char *envp[] = {
1793                 [0] = "HOME=/",
1794                 [1] = "PATH=/sbin:/usr/sbin",
1795                 [2] = NULL
1796         };
1797         signed short ret;
1798         int rc = 0;
1799
1800         if (imp == NULL || imp->imp_obd == NULL ||
1801             imp->imp_obd->obd_type == NULL) {
1802                 rc = -EINVAL;
1803         } else {
1804                 argv[2] = (char *)imp->imp_obd->obd_type->typ_name;
1805                 argv[4] = imp->imp_obd->obd_name;
1806                 spin_lock(&imp->imp_sec->ps_lock);
1807                 if (imp->imp_sec->ps_sepol_mtime == 0 &&
1808                     imp->imp_sec->ps_sepol[0] == '\0') {
1809                         /* ps_sepol has not been initialized */
1810                         argv[5] = NULL;
1811                         argv[7] = NULL;
1812                 } else {
1813                         snprintf(mtime_str, sizeof(mtime_str), "%lu",
1814                                  imp->imp_sec->ps_sepol_mtime);
1815                         mode_str[0] = imp->imp_sec->ps_sepol[0];
1816                 }
1817                 spin_unlock(&imp->imp_sec->ps_lock);
1818                 ret = call_usermodehelper(argv[0], argv, envp, UMH_WAIT_PROC);
1819                 rc = ret>>8;
1820         }
1821
1822         return rc;
1823 }
1824
1825 static inline int sptlrpc_sepol_needs_check(struct ptlrpc_sec *imp_sec)
1826 {
1827         ktime_t checknext;
1828
1829         if (send_sepol == 0 || !selinux_is_enabled())
1830                 return 0;
1831
1832         if (send_sepol == -1)
1833                 /* send_sepol == -1 means fetch sepol status every time */
1834                 return 1;
1835
1836         spin_lock(&imp_sec->ps_lock);
1837         checknext = imp_sec->ps_sepol_checknext;
1838         spin_unlock(&imp_sec->ps_lock);
1839
1840         /* next check is too far in time, please update */
1841         if (ktime_after(checknext,
1842                         ktime_add(ktime_get(), ktime_set(send_sepol, 0))))
1843                 goto setnext;
1844
1845         if (ktime_before(ktime_get(), checknext))
1846                 /* too early to fetch sepol status */
1847                 return 0;
1848
1849 setnext:
1850         /* define new sepol_checknext time */
1851         spin_lock(&imp_sec->ps_lock);
1852         imp_sec->ps_sepol_checknext = ktime_add(ktime_get(),
1853                                                 ktime_set(send_sepol, 0));
1854         spin_unlock(&imp_sec->ps_lock);
1855
1856         return 1;
1857 }
1858
1859 int sptlrpc_get_sepol(struct ptlrpc_request *req)
1860 {
1861         struct ptlrpc_sec *imp_sec = req->rq_import->imp_sec;
1862         int rc = 0;
1863
1864         ENTRY;
1865
1866         (req->rq_sepol)[0] = '\0';
1867
1868 #ifndef HAVE_SELINUX
1869         if (unlikely(send_sepol != 0))
1870                 CDEBUG(D_SEC,
1871                        "Client cannot report SELinux status, it was not built against libselinux.\n");
1872         RETURN(0);
1873 #endif
1874
1875         if (send_sepol == 0 || !selinux_is_enabled())
1876                 RETURN(0);
1877
1878         if (imp_sec == NULL)
1879                 RETURN(-EINVAL);
1880
1881         /* Retrieve SELinux status info */
1882         if (sptlrpc_sepol_needs_check(imp_sec))
1883                 rc = sepol_helper(req->rq_import);
1884         if (likely(rc == 0)) {
1885                 spin_lock(&imp_sec->ps_lock);
1886                 memcpy(req->rq_sepol, imp_sec->ps_sepol,
1887                        sizeof(req->rq_sepol));
1888                 spin_unlock(&imp_sec->ps_lock);
1889         }
1890
1891         RETURN(rc);
1892 }
1893 EXPORT_SYMBOL(sptlrpc_get_sepol);
1894
1895 /*
1896  * server side security
1897  */
1898
1899 static int flavor_allowed(struct sptlrpc_flavor *exp,
1900                           struct ptlrpc_request *req)
1901 {
1902         struct sptlrpc_flavor *flvr = &req->rq_flvr;
1903
1904         if (exp->sf_rpc == SPTLRPC_FLVR_ANY || exp->sf_rpc == flvr->sf_rpc)
1905                 return 1;
1906
1907         if ((req->rq_ctx_init || req->rq_ctx_fini) &&
1908             SPTLRPC_FLVR_POLICY(exp->sf_rpc) ==
1909             SPTLRPC_FLVR_POLICY(flvr->sf_rpc) &&
1910             SPTLRPC_FLVR_MECH(exp->sf_rpc) == SPTLRPC_FLVR_MECH(flvr->sf_rpc))
1911                 return 1;
1912
1913         return 0;
1914 }
1915
1916 #define EXP_FLVR_UPDATE_EXPIRE      (OBD_TIMEOUT_DEFAULT + 10)
1917
1918 /**
1919  * Given an export \a exp, check whether the flavor of incoming \a req
1920  * is allowed by the export \a exp. Main logic is about taking care of
1921  * changing configurations. Return 0 means success.
1922  */
1923 int sptlrpc_target_export_check(struct obd_export *exp,
1924                                 struct ptlrpc_request *req)
1925 {
1926         struct sptlrpc_flavor   flavor;
1927
1928         if (exp == NULL)
1929                 return 0;
1930
1931         /*
1932          * client side export has no imp_reverse, skip
1933          * FIXME maybe we should check flavor this as well???
1934          */
1935         if (exp->exp_imp_reverse == NULL)
1936                 return 0;
1937
1938         /* don't care about ctx fini rpc */
1939         if (req->rq_ctx_fini)
1940                 return 0;
1941
1942         spin_lock(&exp->exp_lock);
1943
1944         /*
1945          * if flavor just changed (exp->exp_flvr_changed != 0), we wait for
1946          * the first req with the new flavor, then treat it as current flavor,
1947          * adapt reverse sec according to it.
1948          * note the first rpc with new flavor might not be with root ctx, in
1949          * which case delay the sec_adapt by leaving exp_flvr_adapt == 1.
1950          */
1951         if (unlikely(exp->exp_flvr_changed) &&
1952             flavor_allowed(&exp->exp_flvr_old[1], req)) {
1953                 /*
1954                  * make the new flavor as "current", and old ones as
1955                  * about-to-expire
1956                  */
1957                 CDEBUG(D_SEC, "exp %p: just changed: %x->%x\n", exp,
1958                        exp->exp_flvr.sf_rpc, exp->exp_flvr_old[1].sf_rpc);
1959                 flavor = exp->exp_flvr_old[1];
1960                 exp->exp_flvr_old[1] = exp->exp_flvr_old[0];
1961                 exp->exp_flvr_expire[1] = exp->exp_flvr_expire[0];
1962                 exp->exp_flvr_old[0] = exp->exp_flvr;
1963                 exp->exp_flvr_expire[0] = ktime_get_real_seconds() +
1964                                           EXP_FLVR_UPDATE_EXPIRE;
1965                 exp->exp_flvr = flavor;
1966
1967                 /* flavor change finished */
1968                 exp->exp_flvr_changed = 0;
1969                 LASSERT(exp->exp_flvr_adapt == 1);
1970
1971                 /* if it's gss, we only interested in root ctx init */
1972                 if (req->rq_auth_gss &&
1973                     !(req->rq_ctx_init &&
1974                     (req->rq_auth_usr_root || req->rq_auth_usr_mdt ||
1975                     req->rq_auth_usr_ost))) {
1976                         spin_unlock(&exp->exp_lock);
1977                         CDEBUG(D_SEC, "is good but not root(%d:%d:%d:%d:%d)\n",
1978                                req->rq_auth_gss, req->rq_ctx_init,
1979                                req->rq_auth_usr_root, req->rq_auth_usr_mdt,
1980                                req->rq_auth_usr_ost);
1981                         return 0;
1982                 }
1983
1984                 exp->exp_flvr_adapt = 0;
1985                 spin_unlock(&exp->exp_lock);
1986
1987                 return sptlrpc_import_sec_adapt(exp->exp_imp_reverse,
1988                                                 req->rq_svc_ctx, &flavor);
1989         }
1990
1991         /*
1992          * if it equals to the current flavor, we accept it, but need to
1993          * dealing with reverse sec/ctx
1994          */
1995         if (likely(flavor_allowed(&exp->exp_flvr, req))) {
1996                 /*
1997                  * most cases should return here, we only interested in
1998                  * gss root ctx init
1999                  */
2000                 if (!req->rq_auth_gss || !req->rq_ctx_init ||
2001                     (!req->rq_auth_usr_root && !req->rq_auth_usr_mdt &&
2002                      !req->rq_auth_usr_ost)) {
2003                         spin_unlock(&exp->exp_lock);
2004                         return 0;
2005                 }
2006
2007                 /*
2008                  * if flavor just changed, we should not proceed, just leave
2009                  * it and current flavor will be discovered and replaced
2010                  * shortly, and let _this_ rpc pass through
2011                  */
2012                 if (exp->exp_flvr_changed) {
2013                         LASSERT(exp->exp_flvr_adapt);
2014                         spin_unlock(&exp->exp_lock);
2015                         return 0;
2016                 }
2017
2018                 if (exp->exp_flvr_adapt) {
2019                         exp->exp_flvr_adapt = 0;
2020                         CDEBUG(D_SEC, "exp %p (%x|%x|%x): do delayed adapt\n",
2021                                exp, exp->exp_flvr.sf_rpc,
2022                                exp->exp_flvr_old[0].sf_rpc,
2023                                exp->exp_flvr_old[1].sf_rpc);
2024                         flavor = exp->exp_flvr;
2025                         spin_unlock(&exp->exp_lock);
2026
2027                         return sptlrpc_import_sec_adapt(exp->exp_imp_reverse,
2028                                                         req->rq_svc_ctx,
2029                                                         &flavor);
2030                 } else {
2031                         CDEBUG(D_SEC,
2032                                "exp %p (%x|%x|%x): is current flavor, install rvs ctx\n",
2033                                exp, exp->exp_flvr.sf_rpc,
2034                                exp->exp_flvr_old[0].sf_rpc,
2035                                exp->exp_flvr_old[1].sf_rpc);
2036                         spin_unlock(&exp->exp_lock);
2037
2038                         return sptlrpc_svc_install_rvs_ctx(exp->exp_imp_reverse,
2039                                                            req->rq_svc_ctx);
2040                 }
2041         }
2042
2043         if (exp->exp_flvr_expire[0]) {
2044                 if (exp->exp_flvr_expire[0] >= ktime_get_real_seconds()) {
2045                         if (flavor_allowed(&exp->exp_flvr_old[0], req)) {
2046                                 CDEBUG(D_SEC,
2047                                        "exp %p (%x|%x|%x): match the middle one (%lld)\n",
2048                                        exp, exp->exp_flvr.sf_rpc,
2049                                        exp->exp_flvr_old[0].sf_rpc,
2050                                        exp->exp_flvr_old[1].sf_rpc,
2051                                        (s64)(exp->exp_flvr_expire[0] -
2052                                              ktime_get_real_seconds()));
2053                                 spin_unlock(&exp->exp_lock);
2054                                 return 0;
2055                         }
2056                 } else {
2057                         CDEBUG(D_SEC, "mark middle expired\n");
2058                         exp->exp_flvr_expire[0] = 0;
2059                 }
2060                 CDEBUG(D_SEC, "exp %p (%x|%x|%x): %x not match middle\n", exp,
2061                        exp->exp_flvr.sf_rpc,
2062                        exp->exp_flvr_old[0].sf_rpc, exp->exp_flvr_old[1].sf_rpc,
2063                        req->rq_flvr.sf_rpc);
2064         }
2065
2066         /*
2067          * now it doesn't match the current flavor, the only chance we can
2068          * accept it is match the old flavors which is not expired.
2069          */
2070         if (exp->exp_flvr_changed == 0 && exp->exp_flvr_expire[1]) {
2071                 if (exp->exp_flvr_expire[1] >= ktime_get_real_seconds()) {
2072                         if (flavor_allowed(&exp->exp_flvr_old[1], req)) {
2073                                 CDEBUG(D_SEC, "exp %p (%x|%x|%x): match the oldest one (%lld)\n",
2074                                        exp,
2075                                        exp->exp_flvr.sf_rpc,
2076                                        exp->exp_flvr_old[0].sf_rpc,
2077                                        exp->exp_flvr_old[1].sf_rpc,
2078                                        (s64)(exp->exp_flvr_expire[1] -
2079                                        ktime_get_real_seconds()));
2080                                 spin_unlock(&exp->exp_lock);
2081                                 return 0;
2082                         }
2083                 } else {
2084                         CDEBUG(D_SEC, "mark oldest expired\n");
2085                         exp->exp_flvr_expire[1] = 0;
2086                 }
2087                 CDEBUG(D_SEC, "exp %p (%x|%x|%x): %x not match found\n",
2088                        exp, exp->exp_flvr.sf_rpc,
2089                        exp->exp_flvr_old[0].sf_rpc, exp->exp_flvr_old[1].sf_rpc,
2090                        req->rq_flvr.sf_rpc);
2091         } else {
2092                 CDEBUG(D_SEC, "exp %p (%x|%x|%x): skip the last one\n",
2093                        exp, exp->exp_flvr.sf_rpc, exp->exp_flvr_old[0].sf_rpc,
2094                        exp->exp_flvr_old[1].sf_rpc);
2095         }
2096
2097         spin_unlock(&exp->exp_lock);
2098
2099         CWARN("exp %p(%s): req %p (%u|%u|%u|%u|%u|%u) with unauthorized flavor %x, expect %x|%x(%+lld)|%x(%+lld)\n",
2100               exp, exp->exp_obd->obd_name,
2101               req, req->rq_auth_gss, req->rq_ctx_init, req->rq_ctx_fini,
2102               req->rq_auth_usr_root, req->rq_auth_usr_mdt, req->rq_auth_usr_ost,
2103               req->rq_flvr.sf_rpc,
2104               exp->exp_flvr.sf_rpc,
2105               exp->exp_flvr_old[0].sf_rpc,
2106               exp->exp_flvr_expire[0] ?
2107               (s64)(exp->exp_flvr_expire[0] - ktime_get_real_seconds()) : 0,
2108               exp->exp_flvr_old[1].sf_rpc,
2109               exp->exp_flvr_expire[1] ?
2110               (s64)(exp->exp_flvr_expire[1] - ktime_get_real_seconds()) : 0);
2111         return -EACCES;
2112 }
2113 EXPORT_SYMBOL(sptlrpc_target_export_check);
2114
2115 void sptlrpc_target_update_exp_flavor(struct obd_device *obd,
2116                                       struct sptlrpc_rule_set *rset)
2117 {
2118         struct obd_export *exp;
2119         struct sptlrpc_flavor new_flvr;
2120
2121         LASSERT(obd);
2122
2123         spin_lock(&obd->obd_dev_lock);
2124
2125         list_for_each_entry(exp, &obd->obd_exports, exp_obd_chain) {
2126                 if (exp->exp_connection == NULL)
2127                         continue;
2128
2129                 /*
2130                  * note if this export had just been updated flavor
2131                  * (exp_flvr_changed == 1), this will override the
2132                  * previous one.
2133                  */
2134                 spin_lock(&exp->exp_lock);
2135                 sptlrpc_target_choose_flavor(rset, exp->exp_sp_peer,
2136                                              exp->exp_connection->c_peer.nid,
2137                                              &new_flvr);
2138                 if (exp->exp_flvr_changed ||
2139                     !flavor_equal(&new_flvr, &exp->exp_flvr)) {
2140                         exp->exp_flvr_old[1] = new_flvr;
2141                         exp->exp_flvr_expire[1] = 0;
2142                         exp->exp_flvr_changed = 1;
2143                         exp->exp_flvr_adapt = 1;
2144
2145                         CDEBUG(D_SEC, "exp %p (%s): updated flavor %x->%x\n",
2146                                exp, sptlrpc_part2name(exp->exp_sp_peer),
2147                                exp->exp_flvr.sf_rpc,
2148                                exp->exp_flvr_old[1].sf_rpc);
2149                 }
2150                 spin_unlock(&exp->exp_lock);
2151         }
2152
2153         spin_unlock(&obd->obd_dev_lock);
2154 }
2155 EXPORT_SYMBOL(sptlrpc_target_update_exp_flavor);
2156
2157 static int sptlrpc_svc_check_from(struct ptlrpc_request *req, int svc_rc)
2158 {
2159         /* peer's claim is unreliable unless gss is being used */
2160         if (!req->rq_auth_gss || svc_rc == SECSVC_DROP)
2161                 return svc_rc;
2162
2163         switch (req->rq_sp_from) {
2164         case LUSTRE_SP_CLI:
2165                 if (req->rq_auth_usr_mdt || req->rq_auth_usr_ost) {
2166                         /* The below message is checked in sanity-sec test_33 */
2167                         DEBUG_REQ(D_ERROR, req, "faked source CLI");
2168                         svc_rc = SECSVC_DROP;
2169                 }
2170                 break;
2171         case LUSTRE_SP_MDT:
2172                 if (!req->rq_auth_usr_mdt) {
2173                         /* The below message is checked in sanity-sec test_33 */
2174                         DEBUG_REQ(D_ERROR, req, "faked source MDT");
2175                         svc_rc = SECSVC_DROP;
2176                 }
2177                 break;
2178         case LUSTRE_SP_OST:
2179                 if (!req->rq_auth_usr_ost) {
2180                         /* The below message is checked in sanity-sec test_33 */
2181                         DEBUG_REQ(D_ERROR, req, "faked source OST");
2182                         svc_rc = SECSVC_DROP;
2183                 }
2184                 break;
2185         case LUSTRE_SP_MGS:
2186         case LUSTRE_SP_MGC:
2187                 if (!req->rq_auth_usr_root && !req->rq_auth_usr_mdt &&
2188                     !req->rq_auth_usr_ost) {
2189                         /* The below message is checked in sanity-sec test_33 */
2190                         DEBUG_REQ(D_ERROR, req, "faked source MGC/MGS");
2191                         svc_rc = SECSVC_DROP;
2192                 }
2193                 break;
2194         case LUSTRE_SP_ANY:
2195         default:
2196                 DEBUG_REQ(D_ERROR, req, "invalid source %u", req->rq_sp_from);
2197                 svc_rc = SECSVC_DROP;
2198         }
2199
2200         return svc_rc;
2201 }
2202
2203 /**
2204  * Used by ptlrpc server, to perform transformation upon request message of
2205  * incoming \a req. This must be the first thing to do with an incoming
2206  * request in ptlrpc layer.
2207  *
2208  * \retval SECSVC_OK success, and req->rq_reqmsg point to request message in
2209  * clear text, size is req->rq_reqlen; also req->rq_svc_ctx is set.
2210  * \retval SECSVC_COMPLETE success, the request has been fully processed, and
2211  * reply message has been prepared.
2212  * \retval SECSVC_DROP failed, this request should be dropped.
2213  */
2214 int sptlrpc_svc_unwrap_request(struct ptlrpc_request *req)
2215 {
2216         struct ptlrpc_sec_policy *policy;
2217         struct lustre_msg *msg = req->rq_reqbuf;
2218         int rc;
2219
2220         ENTRY;
2221
2222         LASSERT(msg);
2223         LASSERT(req->rq_reqmsg == NULL);
2224         LASSERT(req->rq_repmsg == NULL);
2225         LASSERT(req->rq_svc_ctx == NULL);
2226
2227         req->rq_req_swab_mask = 0;
2228
2229         rc = __lustre_unpack_msg(msg, req->rq_reqdata_len);
2230         switch (rc) {
2231         case 1:
2232                 lustre_set_req_swabbed(req, MSG_PTLRPC_HEADER_OFF);
2233         case 0:
2234                 break;
2235         default:
2236                 CERROR("error unpacking request from %s x%llu\n",
2237                        libcfs_id2str(req->rq_peer), req->rq_xid);
2238                 RETURN(SECSVC_DROP);
2239         }
2240
2241         req->rq_flvr.sf_rpc = WIRE_FLVR(msg->lm_secflvr);
2242         req->rq_sp_from = LUSTRE_SP_ANY;
2243         req->rq_auth_uid = -1; /* set to INVALID_UID */
2244         req->rq_auth_mapped_uid = -1;
2245
2246         policy = sptlrpc_wireflavor2policy(req->rq_flvr.sf_rpc);
2247         if (!policy) {
2248                 CERROR("unsupported rpc flavor %x\n", req->rq_flvr.sf_rpc);
2249                 RETURN(SECSVC_DROP);
2250         }
2251
2252         LASSERT(policy->sp_sops->accept);
2253         rc = policy->sp_sops->accept(req);
2254         sptlrpc_policy_put(policy);
2255         LASSERT(req->rq_reqmsg || rc != SECSVC_OK);
2256         LASSERT(req->rq_svc_ctx || rc == SECSVC_DROP);
2257
2258         /*
2259          * if it's not null flavor (which means embedded packing msg),
2260          * reset the swab mask for the comming inner msg unpacking.
2261          */
2262         if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL)
2263                 req->rq_req_swab_mask = 0;
2264
2265         /* sanity check for the request source */
2266         rc = sptlrpc_svc_check_from(req, rc);
2267         RETURN(rc);
2268 }
2269
2270 /**
2271  * Used by ptlrpc server, to allocate reply buffer for \a req. If succeed,
2272  * req->rq_reply_state is set, and req->rq_reply_state->rs_msg point to
2273  * a buffer of \a msglen size.
2274  */
2275 int sptlrpc_svc_alloc_rs(struct ptlrpc_request *req, int msglen)
2276 {
2277         struct ptlrpc_sec_policy *policy;
2278         struct ptlrpc_reply_state *rs;
2279         int rc;
2280
2281         ENTRY;
2282
2283         LASSERT(req->rq_svc_ctx);
2284         LASSERT(req->rq_svc_ctx->sc_policy);
2285
2286         policy = req->rq_svc_ctx->sc_policy;
2287         LASSERT(policy->sp_sops->alloc_rs);
2288
2289         rc = policy->sp_sops->alloc_rs(req, msglen);
2290         if (unlikely(rc == -ENOMEM)) {
2291                 struct ptlrpc_service_part *svcpt = req->rq_rqbd->rqbd_svcpt;
2292
2293                 if (svcpt->scp_service->srv_max_reply_size <
2294                    msglen + sizeof(struct ptlrpc_reply_state)) {
2295                         /* Just return failure if the size is too big */
2296                         CERROR("size of message is too big (%zd), %d allowed\n",
2297                                 msglen + sizeof(struct ptlrpc_reply_state),
2298                                 svcpt->scp_service->srv_max_reply_size);
2299                         RETURN(-ENOMEM);
2300                 }
2301
2302                 /* failed alloc, try emergency pool */
2303                 rs = lustre_get_emerg_rs(svcpt);
2304                 if (rs == NULL)
2305                         RETURN(-ENOMEM);
2306
2307                 req->rq_reply_state = rs;
2308                 rc = policy->sp_sops->alloc_rs(req, msglen);
2309                 if (rc) {
2310                         lustre_put_emerg_rs(rs);
2311                         req->rq_reply_state = NULL;
2312                 }
2313         }
2314
2315         LASSERT(rc != 0 ||
2316                 (req->rq_reply_state && req->rq_reply_state->rs_msg));
2317
2318         RETURN(rc);
2319 }
2320
2321 /**
2322  * Used by ptlrpc server, to perform transformation upon reply message.
2323  *
2324  * \post req->rq_reply_off is set to approriate server-controlled reply offset.
2325  * \post req->rq_repmsg and req->rq_reply_state->rs_msg becomes inaccessible.
2326  */
2327 int sptlrpc_svc_wrap_reply(struct ptlrpc_request *req)
2328 {
2329         struct ptlrpc_sec_policy *policy;
2330         int rc;
2331
2332         ENTRY;
2333
2334         LASSERT(req->rq_svc_ctx);
2335         LASSERT(req->rq_svc_ctx->sc_policy);
2336
2337         policy = req->rq_svc_ctx->sc_policy;
2338         LASSERT(policy->sp_sops->authorize);
2339
2340         rc = policy->sp_sops->authorize(req);
2341         LASSERT(rc || req->rq_reply_state->rs_repdata_len);
2342
2343         RETURN(rc);
2344 }
2345
2346 /**
2347  * Used by ptlrpc server, to free reply_state.
2348  */
2349 void sptlrpc_svc_free_rs(struct ptlrpc_reply_state *rs)
2350 {
2351         struct ptlrpc_sec_policy *policy;
2352         unsigned int prealloc;
2353
2354         ENTRY;
2355
2356         LASSERT(rs->rs_svc_ctx);
2357         LASSERT(rs->rs_svc_ctx->sc_policy);
2358
2359         policy = rs->rs_svc_ctx->sc_policy;
2360         LASSERT(policy->sp_sops->free_rs);
2361
2362         prealloc = rs->rs_prealloc;
2363         policy->sp_sops->free_rs(rs);
2364
2365         if (prealloc)
2366                 lustre_put_emerg_rs(rs);
2367         EXIT;
2368 }
2369
2370 void sptlrpc_svc_ctx_addref(struct ptlrpc_request *req)
2371 {
2372         struct ptlrpc_svc_ctx *ctx = req->rq_svc_ctx;
2373
2374         if (ctx != NULL)
2375                 atomic_inc(&ctx->sc_refcount);
2376 }
2377
2378 void sptlrpc_svc_ctx_decref(struct ptlrpc_request *req)
2379 {
2380         struct ptlrpc_svc_ctx *ctx = req->rq_svc_ctx;
2381
2382         if (ctx == NULL)
2383                 return;
2384
2385         LASSERT_ATOMIC_POS(&ctx->sc_refcount);
2386         if (atomic_dec_and_test(&ctx->sc_refcount)) {
2387                 if (ctx->sc_policy->sp_sops->free_ctx)
2388                         ctx->sc_policy->sp_sops->free_ctx(ctx);
2389         }
2390         req->rq_svc_ctx = NULL;
2391 }
2392
2393 void sptlrpc_svc_ctx_invalidate(struct ptlrpc_request *req)
2394 {
2395         struct ptlrpc_svc_ctx *ctx = req->rq_svc_ctx;
2396
2397         if (ctx == NULL)
2398                 return;
2399
2400         LASSERT_ATOMIC_POS(&ctx->sc_refcount);
2401         if (ctx->sc_policy->sp_sops->invalidate_ctx)
2402                 ctx->sc_policy->sp_sops->invalidate_ctx(ctx);
2403 }
2404 EXPORT_SYMBOL(sptlrpc_svc_ctx_invalidate);
2405
2406 /*
2407  * bulk security
2408  */
2409
2410 /**
2411  * Perform transformation upon bulk data pointed by \a desc. This is called
2412  * before transforming the request message.
2413  */
2414 int sptlrpc_cli_wrap_bulk(struct ptlrpc_request *req,
2415                           struct ptlrpc_bulk_desc *desc)
2416 {
2417         struct ptlrpc_cli_ctx *ctx;
2418
2419         LASSERT(req->rq_bulk_read || req->rq_bulk_write);
2420
2421         if (!req->rq_pack_bulk)
2422                 return 0;
2423
2424         ctx = req->rq_cli_ctx;
2425         if (ctx->cc_ops->wrap_bulk)
2426                 return ctx->cc_ops->wrap_bulk(ctx, req, desc);
2427         return 0;
2428 }
2429 EXPORT_SYMBOL(sptlrpc_cli_wrap_bulk);
2430
2431 /**
2432  * This is called after unwrap the reply message.
2433  * return nob of actual plain text size received, or error code.
2434  */
2435 int sptlrpc_cli_unwrap_bulk_read(struct ptlrpc_request *req,
2436                                  struct ptlrpc_bulk_desc *desc,
2437                                  int nob)
2438 {
2439         struct ptlrpc_cli_ctx *ctx;
2440         int rc;
2441
2442         LASSERT(req->rq_bulk_read && !req->rq_bulk_write);
2443
2444         if (!req->rq_pack_bulk)
2445                 return desc->bd_nob_transferred;
2446
2447         ctx = req->rq_cli_ctx;
2448         if (ctx->cc_ops->unwrap_bulk) {
2449                 rc = ctx->cc_ops->unwrap_bulk(ctx, req, desc);
2450                 if (rc < 0)
2451                         return rc;
2452         }
2453         return desc->bd_nob_transferred;
2454 }
2455 EXPORT_SYMBOL(sptlrpc_cli_unwrap_bulk_read);
2456
2457 /**
2458  * This is called after unwrap the reply message.
2459  * return 0 for success or error code.
2460  */
2461 int sptlrpc_cli_unwrap_bulk_write(struct ptlrpc_request *req,
2462                                   struct ptlrpc_bulk_desc *desc)
2463 {
2464         struct ptlrpc_cli_ctx *ctx;
2465         int rc;
2466
2467         LASSERT(!req->rq_bulk_read && req->rq_bulk_write);
2468
2469         if (!req->rq_pack_bulk)
2470                 return 0;
2471
2472         ctx = req->rq_cli_ctx;
2473         if (ctx->cc_ops->unwrap_bulk) {
2474                 rc = ctx->cc_ops->unwrap_bulk(ctx, req, desc);
2475                 if (rc < 0)
2476                         return rc;
2477         }
2478
2479         /*
2480          * if everything is going right, nob should equals to nob_transferred.
2481          * in case of privacy mode, nob_transferred needs to be adjusted.
2482          */
2483         if (desc->bd_nob != desc->bd_nob_transferred) {
2484                 CERROR("nob %d doesn't match transferred nob %d\n",
2485                        desc->bd_nob, desc->bd_nob_transferred);
2486                 return -EPROTO;
2487         }
2488
2489         return 0;
2490 }
2491 EXPORT_SYMBOL(sptlrpc_cli_unwrap_bulk_write);
2492
2493 #ifdef HAVE_SERVER_SUPPORT
2494 /**
2495  * Performe transformation upon outgoing bulk read.
2496  */
2497 int sptlrpc_svc_wrap_bulk(struct ptlrpc_request *req,
2498                           struct ptlrpc_bulk_desc *desc)
2499 {
2500         struct ptlrpc_svc_ctx *ctx;
2501
2502         LASSERT(req->rq_bulk_read);
2503
2504         if (!req->rq_pack_bulk)
2505                 return 0;
2506
2507         ctx = req->rq_svc_ctx;
2508         if (ctx->sc_policy->sp_sops->wrap_bulk)
2509                 return ctx->sc_policy->sp_sops->wrap_bulk(req, desc);
2510
2511         return 0;
2512 }
2513 EXPORT_SYMBOL(sptlrpc_svc_wrap_bulk);
2514
2515 /**
2516  * Performe transformation upon incoming bulk write.
2517  */
2518 int sptlrpc_svc_unwrap_bulk(struct ptlrpc_request *req,
2519                             struct ptlrpc_bulk_desc *desc)
2520 {
2521         struct ptlrpc_svc_ctx *ctx;
2522         int rc;
2523
2524         LASSERT(req->rq_bulk_write);
2525
2526         /*
2527          * if it's in privacy mode, transferred should >= expected; otherwise
2528          * transferred should == expected.
2529          */
2530         if (desc->bd_nob_transferred < desc->bd_nob ||
2531             (desc->bd_nob_transferred > desc->bd_nob &&
2532              SPTLRPC_FLVR_BULK_SVC(req->rq_flvr.sf_rpc) !=
2533              SPTLRPC_BULK_SVC_PRIV)) {
2534                 DEBUG_REQ(D_ERROR, req, "truncated bulk GET %d(%d)",
2535                           desc->bd_nob_transferred, desc->bd_nob);
2536                 return -ETIMEDOUT;
2537         }
2538
2539         if (!req->rq_pack_bulk)
2540                 return 0;
2541
2542         ctx = req->rq_svc_ctx;
2543         if (ctx->sc_policy->sp_sops->unwrap_bulk) {
2544                 rc = ctx->sc_policy->sp_sops->unwrap_bulk(req, desc);
2545                 if (rc)
2546                         CERROR("error unwrap bulk: %d\n", rc);
2547         }
2548
2549         /* return 0 to allow reply be sent */
2550         return 0;
2551 }
2552 EXPORT_SYMBOL(sptlrpc_svc_unwrap_bulk);
2553
2554 /**
2555  * Prepare buffers for incoming bulk write.
2556  */
2557 int sptlrpc_svc_prep_bulk(struct ptlrpc_request *req,
2558                           struct ptlrpc_bulk_desc *desc)
2559 {
2560         struct ptlrpc_svc_ctx *ctx;
2561
2562         LASSERT(req->rq_bulk_write);
2563
2564         if (!req->rq_pack_bulk)
2565                 return 0;
2566
2567         ctx = req->rq_svc_ctx;
2568         if (ctx->sc_policy->sp_sops->prep_bulk)
2569                 return ctx->sc_policy->sp_sops->prep_bulk(req, desc);
2570
2571         return 0;
2572 }
2573 EXPORT_SYMBOL(sptlrpc_svc_prep_bulk);
2574
2575 #endif /* HAVE_SERVER_SUPPORT */
2576
2577 /*
2578  * user descriptor helpers
2579  */
2580
2581 int sptlrpc_current_user_desc_size(void)
2582 {
2583         int ngroups;
2584
2585         ngroups = current_ngroups;
2586
2587         if (ngroups > LUSTRE_MAX_GROUPS)
2588                 ngroups = LUSTRE_MAX_GROUPS;
2589         return sptlrpc_user_desc_size(ngroups);
2590 }
2591 EXPORT_SYMBOL(sptlrpc_current_user_desc_size);
2592
2593 int sptlrpc_pack_user_desc(struct lustre_msg *msg, int offset)
2594 {
2595         struct ptlrpc_user_desc *pud;
2596
2597         pud = lustre_msg_buf(msg, offset, 0);
2598
2599         pud->pud_uid = from_kuid(&init_user_ns, current_uid());
2600         pud->pud_gid = from_kgid(&init_user_ns, current_gid());
2601         pud->pud_fsuid = from_kuid(&init_user_ns, current_fsuid());
2602         pud->pud_fsgid = from_kgid(&init_user_ns, current_fsgid());
2603         pud->pud_cap = cfs_curproc_cap_pack();
2604         pud->pud_ngroups = (msg->lm_buflens[offset] - sizeof(*pud)) / 4;
2605
2606         task_lock(current);
2607         if (pud->pud_ngroups > current_ngroups)
2608                 pud->pud_ngroups = current_ngroups;
2609 #ifdef HAVE_GROUP_INFO_GID
2610         memcpy(pud->pud_groups, current_cred()->group_info->gid,
2611                pud->pud_ngroups * sizeof(__u32));
2612 #else /* !HAVE_GROUP_INFO_GID */
2613         memcpy(pud->pud_groups, current_cred()->group_info->blocks[0],
2614                pud->pud_ngroups * sizeof(__u32));
2615 #endif /* HAVE_GROUP_INFO_GID */
2616         task_unlock(current);
2617
2618         return 0;
2619 }
2620 EXPORT_SYMBOL(sptlrpc_pack_user_desc);
2621
2622 int sptlrpc_unpack_user_desc(struct lustre_msg *msg, int offset, int swabbed)
2623 {
2624         struct ptlrpc_user_desc *pud;
2625         int i;
2626
2627         pud = lustre_msg_buf(msg, offset, sizeof(*pud));
2628         if (!pud)
2629                 return -EINVAL;
2630
2631         if (swabbed) {
2632                 __swab32s(&pud->pud_uid);
2633                 __swab32s(&pud->pud_gid);
2634                 __swab32s(&pud->pud_fsuid);
2635                 __swab32s(&pud->pud_fsgid);
2636                 __swab32s(&pud->pud_cap);
2637                 __swab32s(&pud->pud_ngroups);
2638         }
2639
2640         if (pud->pud_ngroups > LUSTRE_MAX_GROUPS) {
2641                 CERROR("%u groups is too large\n", pud->pud_ngroups);
2642                 return -EINVAL;
2643         }
2644
2645         if (sizeof(*pud) + pud->pud_ngroups * sizeof(__u32) >
2646             msg->lm_buflens[offset]) {
2647                 CERROR("%u groups are claimed but bufsize only %u\n",
2648                        pud->pud_ngroups, msg->lm_buflens[offset]);
2649                 return -EINVAL;
2650         }
2651
2652         if (swabbed) {
2653                 for (i = 0; i < pud->pud_ngroups; i++)
2654                         __swab32s(&pud->pud_groups[i]);
2655         }
2656
2657         return 0;
2658 }
2659 EXPORT_SYMBOL(sptlrpc_unpack_user_desc);
2660
2661 /*
2662  * misc helpers
2663  */
2664
2665 const char *sec2target_str(struct ptlrpc_sec *sec)
2666 {
2667         if (!sec || !sec->ps_import || !sec->ps_import->imp_obd)
2668                 return "*";
2669         if (sec_is_reverse(sec))
2670                 return "c";
2671         return obd_uuid2str(&sec->ps_import->imp_obd->u.cli.cl_target_uuid);
2672 }
2673 EXPORT_SYMBOL(sec2target_str);
2674
2675 /*
2676  * return true if the bulk data is protected
2677  */
2678 int sptlrpc_flavor_has_bulk(struct sptlrpc_flavor *flvr)
2679 {
2680         switch (SPTLRPC_FLVR_BULK_SVC(flvr->sf_rpc)) {
2681         case SPTLRPC_BULK_SVC_INTG:
2682         case SPTLRPC_BULK_SVC_PRIV:
2683                 return 1;
2684         default:
2685                 return 0;
2686         }
2687 }
2688 EXPORT_SYMBOL(sptlrpc_flavor_has_bulk);
2689
2690 /*
2691  * crypto API helper/alloc blkciper
2692  */
2693
2694 /*
2695  * initialize/finalize
2696  */
2697
2698 int sptlrpc_init(void)
2699 {
2700         int rc;
2701
2702         rwlock_init(&policy_lock);
2703
2704         rc = sptlrpc_gc_init();
2705         if (rc)
2706                 goto out;
2707
2708         rc = sptlrpc_conf_init();
2709         if (rc)
2710                 goto out_gc;
2711
2712         rc = sptlrpc_enc_pool_init();
2713         if (rc)
2714                 goto out_conf;
2715
2716         rc = sptlrpc_null_init();
2717         if (rc)
2718                 goto out_pool;
2719
2720         rc = sptlrpc_plain_init();
2721         if (rc)
2722                 goto out_null;
2723
2724         rc = sptlrpc_lproc_init();
2725         if (rc)
2726                 goto out_plain;
2727
2728         return 0;
2729
2730 out_plain:
2731         sptlrpc_plain_fini();
2732 out_null:
2733         sptlrpc_null_fini();
2734 out_pool:
2735         sptlrpc_enc_pool_fini();
2736 out_conf:
2737         sptlrpc_conf_fini();
2738 out_gc:
2739         sptlrpc_gc_fini();
2740 out:
2741         return rc;
2742 }
2743
2744 void sptlrpc_fini(void)
2745 {
2746         sptlrpc_lproc_fini();
2747         sptlrpc_plain_fini();
2748         sptlrpc_null_fini();
2749         sptlrpc_enc_pool_fini();
2750         sptlrpc_conf_fini();
2751         sptlrpc_gc_fini();
2752 }