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