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