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