1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5  * You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #ifndef nss_policy_h_
8 #define nss_policy_h_
9 
10 #include "prtypes.h"
11 #include "secoid.h"
12 
13 namespace nss_test {
14 
15 // container class to hold all a temp policy
16 class NssPolicy {
17  public:
NssPolicy()18   NssPolicy() : oid_(SEC_OID_UNKNOWN), set_(0), clear_(0) {}
NssPolicy(SECOidTag _oid,PRUint32 _set,PRUint32 _clear)19   NssPolicy(SECOidTag _oid, PRUint32 _set, PRUint32 _clear)
20       : oid_(_oid), set_(_set), clear_(_clear) {}
NssPolicy(const NssPolicy & p)21   NssPolicy(const NssPolicy &p)
22       : oid_(p.oid_), set_(p.set_), clear_(p.clear_) {}
23   // clone the current policy for this oid
NssPolicy(SECOidTag _oid)24   NssPolicy(SECOidTag _oid) : oid_(_oid), set_(0), clear_(0) {
25     NSS_GetAlgorithmPolicy(_oid, &set_);
26     clear_ = ~set_;
27   }
oid(void)28   SECOidTag oid(void) const { return oid_; }
set(void)29   PRUint32 set(void) const { return set_; }
clear(void)30   PRUint32 clear(void) const { return clear_; }
31   operator bool() const { return oid_ != SEC_OID_UNKNOWN; }
32 
33  private:
34   SECOidTag oid_;
35   PRUint32 set_;
36   PRUint32 clear_;
37 };
38 
39 // set the policy indicated in NssPolicy and restor the old policy
40 // when we go out of scope
41 class NssManagePolicy {
42  public:
NssManagePolicy(const NssPolicy & p)43   NssManagePolicy(const NssPolicy &p) : policy_(p), current_(~(PRUint32)0) {
44     if (p) {
45       (void)NSS_GetAlgorithmPolicy(p.oid(), &current_);
46       (void)NSS_SetAlgorithmPolicy(p.oid(), p.set(), p.clear());
47     }
48   }
~NssManagePolicy()49   ~NssManagePolicy() {
50     if (policy_) {
51       (void)NSS_SetAlgorithmPolicy(policy_.oid(), current_, ~current_);
52     }
53   }
54 
55  private:
56   NssPolicy policy_;
57   PRUint32 current_;
58 };
59 
60 // wrapping PRFileDesc this way ensures that tests that attempt to access
61 // PRFileDesc always correctly apply
62 // the policy that was bound to that socket with TlsAgent::SetPolicy().
63 class NssManagedFileDesc {
64  public:
NssManagedFileDesc(PRFileDesc * fd,const NssPolicy & policy)65   NssManagedFileDesc(PRFileDesc *fd, const NssPolicy &policy)
66       : fd_(fd), managed_policy_(policy) {}
get(void)67   PRFileDesc *get(void) const { return fd_; }
68   operator PRFileDesc *() const { return fd_; }
69   bool operator==(PRFileDesc *fd) const { return fd_ == fd; }
70 
71  private:
72   PRFileDesc *fd_;
73   NssManagePolicy managed_policy_;
74 };
75 
76 }  // namespace nss_test
77 
78 #endif
79