We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
TypeError: initializer for ctype 'HMAC_CTX *
I sometimes get the below exception when using Fernet within an Apache mod_wsgi runtime.  It does not occur when using a non-Apache environment (Eventlet).

Is this cryptography module thread safe?  Or maybe is there an issue in how I used the module?

TypeError: initializer for ctype 'HMAC_CTX *' must be a pointer to same type, not cdata 'HMAC_CTX *'
Cryptography version: 0.7.2

Sample code:

```
def __init__(self):
    key = self._load_key()
    self.fernet = Fernet(key)

def encode(self, input, errors='strict'):
    return (self.fernet.encrypt(input), len(input))

def decode(self, input, errors='strict'):
    return (self.fernet.decrypt(input), len(input))

def _load_key(self):
    # Load the key from a file
    username = pwd.getpwuid(os.getuid()).pw_name
    filename = '/etc/fernet/%s.key' % username
    try:
        with open(filename) as f:
            key = f.read()
            return key
    except IOError:
        raise UnicodeEncodeError()
```

```
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi   File "/usr/lib/python2.7/encodings/fernet.py", line 19, in decode
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi     return (self.fernet.decrypt(input), len(input))
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi   File "/usr/local/lib/python2.7/dist-packages/cryptography/fernet.py", line 96, in decrypt
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi     h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi   File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/primitives/hmac.py", line 32, in __init__
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi     self._ctx = self._backend.create_hmac_ctx(key, self.algorithm)
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi   File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/multibackend.py", line 99, in create_hmac_ctx
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi     return b.create_hmac_ctx(key, algorithm)
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi   File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/openssl/backend.py", line 140, in create_hmac_ctx
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi     return _HMACContext(self, key, algorithm)
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi   File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/openssl/hmac.py", line 24, in __init__
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi     self._backend._lib.HMAC_CTX_init(ctx)
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi TypeError: initializer for ctype 'HMAC_CTX *' must be a pointer to same type, not cdata 'HMAC_CTX *'
2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi 
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/cryptography/hazmat/bindings/commoncrypto/binding.py`
Content:
```
1 # This file is dual licensed under the terms of the Apache License, Version
2 # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3 # for complete details.
4 
5 from __future__ import absolute_import, division, print_function
6 
7 from cryptography.hazmat.bindings.utils import (
8     build_ffi_for_binding, load_library_for_binding,
9 )
10 
11 
12 class Binding(object):
13     """
14     CommonCrypto API wrapper.
15     """
16     _module_prefix = "cryptography.hazmat.bindings.commoncrypto."
17     _modules = [
18         "cf",
19         "common_digest",
20         "common_hmac",
21         "common_key_derivation",
22         "common_cryptor",
23         "common_symmetric_key_wrap",
24         "secimport",
25         "secitem",
26         "seckey",
27         "seckeychain",
28         "sectransform",
29     ]
30 
31     ffi = build_ffi_for_binding(
32         module_prefix=_module_prefix,
33         modules=_modules,
34         extra_link_args=[
35             "-framework", "Security", "-framework", "CoreFoundation"
36         ],
37     )
38     lib = None
39 
40     def __init__(self):
41         self._ensure_ffi_initialized()
42 
43     @classmethod
44     def _ensure_ffi_initialized(cls):
45         if cls.lib is not None:
46             return
47 
48         cls.lib = load_library_for_binding(
49             cls.ffi,
50             module_prefix=cls._module_prefix,
51             modules=cls._modules,
52         )
53
```

Path: `src/cryptography/hazmat/bindings/openssl/binding.py`
Content:
```
1 # This file is dual licensed under the terms of the Apache License, Version
2 # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3 # for complete details.
4 
5 from __future__ import absolute_import, division, print_function
6 
7 import os
8 import sys
9 import threading
10 
11 from cryptography.hazmat.bindings.utils import (
12     build_ffi_for_binding, load_library_for_binding,
13 )
14 
15 
16 _OSX_PRE_INCLUDE = """
17 #ifdef __APPLE__
18 #include <AvailabilityMacros.h>
19 #define __ORIG_DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER \
20     DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER
21 #undef DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER
22 #define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER
23 #endif
24 """
25 
26 _OSX_POST_INCLUDE = """
27 #ifdef __APPLE__
28 #undef DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER
29 #define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER \
30     __ORIG_DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER
31 #endif
32 """
33 
34 
35 def _get_libraries(platform):
36     # OpenSSL goes by a different library name on different operating systems.
37     if platform != "win32":
38         # In some circumstances, the order in which these libs are
39         # specified on the linker command-line is significant;
40         # libssl must come before libcrypto
41         # (http://marc.info/?l=openssl-users&m=135361825921871)
42         return ["ssl", "crypto"]
43     else:
44         link_type = os.environ.get("PYCA_WINDOWS_LINK_TYPE", "static")
45         return _get_windows_libraries(link_type)
46 
47 
48 def _get_windows_libraries(link_type):
49     if link_type == "dynamic":
50         return ["libeay32", "ssleay32", "advapi32"]
51     elif link_type == "static" or link_type == "":
52         return ["libeay32mt", "ssleay32mt", "advapi32",
53                 "crypt32", "gdi32", "user32", "ws2_32"]
54     else:
55         raise ValueError(
56             "PYCA_WINDOWS_LINK_TYPE must be 'static' or 'dynamic'"
57         )
58 
59 
60 class Binding(object):
61     """
62     OpenSSL API wrapper.
63     """
64     _module_prefix = "cryptography.hazmat.bindings.openssl."
65     _modules = [
66         "aes",
67         "asn1",
68         "bignum",
69         "bio",
70         "cmac",
71         "cms",
72         "conf",
73         "crypto",
74         "dh",
75         "dsa",
76         "ec",
77         "ecdh",
78         "ecdsa",
79         "engine",
80         "err",
81         "evp",
82         "hmac",
83         "nid",
84         "objects",
85         "opensslv",
86         "osrandom_engine",
87         "pem",
88         "pkcs7",
89         "pkcs12",
90         "rand",
91         "rsa",
92         "ssl",
93         "x509",
94         "x509name",
95         "x509v3",
96         "x509_vfy"
97     ]
98 
99     _locks = None
100     _lock_cb_handle = None
101     _lock_init_lock = threading.Lock()
102 
103     ffi = build_ffi_for_binding(
104         module_prefix=_module_prefix,
105         modules=_modules,
106         pre_include=_OSX_PRE_INCLUDE,
107         post_include=_OSX_POST_INCLUDE,
108         libraries=_get_libraries(sys.platform)
109     )
110     lib = None
111 
112     def __init__(self):
113         self._ensure_ffi_initialized()
114 
115     @classmethod
116     def _ensure_ffi_initialized(cls):
117         if cls.lib is not None:
118             return
119 
120         cls.lib = load_library_for_binding(
121             cls.ffi,
122             cls._module_prefix,
123             cls._modules,
124         )
125 
126         res = cls.lib.Cryptography_add_osrandom_engine()
127         assert res != 0
128 
129     @classmethod
130     def init_static_locks(cls):
131         with cls._lock_init_lock:
132             cls._ensure_ffi_initialized()
133 
134             if not cls._lock_cb_handle:
135                 cls._lock_cb_handle = cls.ffi.callback(
136                     "void(int, int, const char *, int)",
137                     cls._lock_cb
138                 )
139 
140             # Use Python's implementation if available, importing _ssl triggers
141             # the setup for this.
142             __import__("_ssl")
143 
144             if cls.lib.CRYPTO_get_locking_callback() != cls.ffi.NULL:
145                 return
146 
147             # If nothing else has setup a locking callback already, we set up
148             # our own
149             num_locks = cls.lib.CRYPTO_num_locks()
150             cls._locks = [threading.Lock() for n in range(num_locks)]
151 
152             cls.lib.CRYPTO_set_locking_callback(cls._lock_cb_handle)
153 
154     @classmethod
155     def _lock_cb(cls, mode, n, file, line):
156         lock = cls._locks[n]
157 
158         if mode & cls.lib.CRYPTO_LOCK:
159             lock.acquire()
160         elif mode & cls.lib.CRYPTO_UNLOCK:
161             lock.release()
162         else:
163             raise RuntimeError(
164                 "Unknown lock mode {0}: lock={1}, file={2}, line={3}.".format(
165                     mode, n, file, line
166                 )
167             )
168
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/cryptography/hazmat/bindings/commoncrypto/binding.py b/src/cryptography/hazmat/bindings/commoncrypto/binding.py
--- a/src/cryptography/hazmat/bindings/commoncrypto/binding.py
+++ b/src/cryptography/hazmat/bindings/commoncrypto/binding.py
@@ -4,6 +4,8 @@
 
 from __future__ import absolute_import, division, print_function
 
+import threading
+
 from cryptography.hazmat.bindings.utils import (
     build_ffi_for_binding, load_library_for_binding,
 )
@@ -36,6 +38,7 @@
         ],
     )
     lib = None
+    _init_lock = threading.Lock()
 
     def __init__(self):
         self._ensure_ffi_initialized()
@@ -45,8 +48,10 @@
         if cls.lib is not None:
             return
 
-        cls.lib = load_library_for_binding(
-            cls.ffi,
-            module_prefix=cls._module_prefix,
-            modules=cls._modules,
-        )
+        with cls._init_lock:
+            if cls.lib is None:
+                cls.lib = load_library_for_binding(
+                    cls.ffi,
+                    module_prefix=cls._module_prefix,
+                    modules=cls._modules,
+                )
diff --git a/src/cryptography/hazmat/bindings/openssl/binding.py b/src/cryptography/hazmat/bindings/openssl/binding.py
--- a/src/cryptography/hazmat/bindings/openssl/binding.py
+++ b/src/cryptography/hazmat/bindings/openssl/binding.py
@@ -98,6 +98,7 @@
 
     _locks = None
     _lock_cb_handle = None
+    _init_lock = threading.Lock()
     _lock_init_lock = threading.Lock()
 
     ffi = build_ffi_for_binding(
@@ -117,14 +118,16 @@
         if cls.lib is not None:
             return
 
-        cls.lib = load_library_for_binding(
-            cls.ffi,
-            cls._module_prefix,
-            cls._modules,
-        )
+        with cls._init_lock:
+            if cls.lib is None:
+                cls.lib = load_library_for_binding(
+                    cls.ffi,
+                    cls._module_prefix,
+                    cls._modules,
+                )
 
-        res = cls.lib.Cryptography_add_osrandom_engine()
-        assert res != 0
+                res = cls.lib.Cryptography_add_osrandom_engine()
+                assert res != 0
 
     @classmethod
     def init_static_locks(cls):

{"golden_diff": "diff --git a/src/cryptography/hazmat/bindings/commoncrypto/binding.py b/src/cryptography/hazmat/bindings/commoncrypto/binding.py\n--- a/src/cryptography/hazmat/bindings/commoncrypto/binding.py\n+++ b/src/cryptography/hazmat/bindings/commoncrypto/binding.py\n@@ -4,6 +4,8 @@\n \n from __future__ import absolute_import, division, print_function\n \n+import threading\n+\n from cryptography.hazmat.bindings.utils import (\n     build_ffi_for_binding, load_library_for_binding,\n )\n@@ -36,6 +38,7 @@\n         ],\n     )\n     lib = None\n+    _init_lock = threading.Lock()\n \n     def __init__(self):\n         self._ensure_ffi_initialized()\n@@ -45,8 +48,10 @@\n         if cls.lib is not None:\n             return\n \n-        cls.lib = load_library_for_binding(\n-            cls.ffi,\n-            module_prefix=cls._module_prefix,\n-            modules=cls._modules,\n-        )\n+        with cls._init_lock:\n+            if cls.lib is None:\n+                cls.lib = load_library_for_binding(\n+                    cls.ffi,\n+                    module_prefix=cls._module_prefix,\n+                    modules=cls._modules,\n+                )\ndiff --git a/src/cryptography/hazmat/bindings/openssl/binding.py b/src/cryptography/hazmat/bindings/openssl/binding.py\n--- a/src/cryptography/hazmat/bindings/openssl/binding.py\n+++ b/src/cryptography/hazmat/bindings/openssl/binding.py\n@@ -98,6 +98,7 @@\n \n     _locks = None\n     _lock_cb_handle = None\n+    _init_lock = threading.Lock()\n     _lock_init_lock = threading.Lock()\n \n     ffi = build_ffi_for_binding(\n@@ -117,14 +118,16 @@\n         if cls.lib is not None:\n             return\n \n-        cls.lib = load_library_for_binding(\n-            cls.ffi,\n-            cls._module_prefix,\n-            cls._modules,\n-        )\n+        with cls._init_lock:\n+            if cls.lib is None:\n+                cls.lib = load_library_for_binding(\n+                    cls.ffi,\n+                    cls._module_prefix,\n+                    cls._modules,\n+                )\n \n-        res = cls.lib.Cryptography_add_osrandom_engine()\n-        assert res != 0\n+                res = cls.lib.Cryptography_add_osrandom_engine()\n+                assert res != 0\n \n     @classmethod\n     def init_static_locks(cls):\n", "issue": "TypeError: initializer for ctype 'HMAC_CTX *\nI sometimes get the below exception when using Fernet within an Apache mod_wsgi runtime.  It does not occur when using a non-Apache environment (Eventlet).\n\nIs this cryptography module thread safe?  Or maybe is there an issue in how I used the module?\n\nTypeError: initializer for ctype 'HMAC_CTX *' must be a pointer to same type, not cdata 'HMAC_CTX *'\nCryptography version: 0.7.2\n\nSample code:\n\n```\ndef __init__(self):\n    key = self._load_key()\n    self.fernet = Fernet(key)\n\ndef encode(self, input, errors='strict'):\n    return (self.fernet.encrypt(input), len(input))\n\ndef decode(self, input, errors='strict'):\n    return (self.fernet.decrypt(input), len(input))\n\ndef _load_key(self):\n    # Load the key from a file\n    username = pwd.getpwuid(os.getuid()).pw_name\n    filename = '/etc/fernet/%s.key' % username\n    try:\n        with open(filename) as f:\n            key = f.read()\n            return key\n    except IOError:\n        raise UnicodeEncodeError()\n```\n\n```\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi   File \"/usr/lib/python2.7/encodings/fernet.py\", line 19, in decode\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi     return (self.fernet.decrypt(input), len(input))\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi   File \"/usr/local/lib/python2.7/dist-packages/cryptography/fernet.py\", line 96, in decrypt\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi     h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi   File \"/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/primitives/hmac.py\", line 32, in __init__\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi     self._ctx = self._backend.create_hmac_ctx(key, self.algorithm)\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi   File \"/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/multibackend.py\", line 99, in create_hmac_ctx\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi     return b.create_hmac_ctx(key, algorithm)\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi   File \"/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/openssl/backend.py\", line 140, in create_hmac_ctx\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi     return _HMACContext(self, key, algorithm)\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi   File \"/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/openssl/hmac.py\", line 24, in __init__\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi     self._backend._lib.HMAC_CTX_init(ctx)\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi TypeError: initializer for ctype 'HMAC_CTX *' must be a pointer to same type, not cdata 'HMAC_CTX *'\n2015-03-18 22:55:08.512 6509 TRACE keystone.common.wsgi \n```\n\n", "before_files": [{"content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom cryptography.hazmat.bindings.utils import (\n    build_ffi_for_binding, load_library_for_binding,\n)\n\n\nclass Binding(object):\n    \"\"\"\n    CommonCrypto API wrapper.\n    \"\"\"\n    _module_prefix = \"cryptography.hazmat.bindings.commoncrypto.\"\n    _modules = [\n        \"cf\",\n        \"common_digest\",\n        \"common_hmac\",\n        \"common_key_derivation\",\n        \"common_cryptor\",\n        \"common_symmetric_key_wrap\",\n        \"secimport\",\n        \"secitem\",\n        \"seckey\",\n        \"seckeychain\",\n        \"sectransform\",\n    ]\n\n    ffi = build_ffi_for_binding(\n        module_prefix=_module_prefix,\n        modules=_modules,\n        extra_link_args=[\n            \"-framework\", \"Security\", \"-framework\", \"CoreFoundation\"\n        ],\n    )\n    lib = None\n\n    def __init__(self):\n        self._ensure_ffi_initialized()\n\n    @classmethod\n    def _ensure_ffi_initialized(cls):\n        if cls.lib is not None:\n            return\n\n        cls.lib = load_library_for_binding(\n            cls.ffi,\n            module_prefix=cls._module_prefix,\n            modules=cls._modules,\n        )\n", "path": "src/cryptography/hazmat/bindings/commoncrypto/binding.py"}, {"content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nfrom __future__ import absolute_import, division, print_function\n\nimport os\nimport sys\nimport threading\n\nfrom cryptography.hazmat.bindings.utils import (\n    build_ffi_for_binding, load_library_for_binding,\n)\n\n\n_OSX_PRE_INCLUDE = \"\"\"\n#ifdef __APPLE__\n#include <AvailabilityMacros.h>\n#define __ORIG_DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER \\\n    DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER\n#undef DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER\n#define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER\n#endif\n\"\"\"\n\n_OSX_POST_INCLUDE = \"\"\"\n#ifdef __APPLE__\n#undef DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER\n#define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER \\\n    __ORIG_DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER\n#endif\n\"\"\"\n\n\ndef _get_libraries(platform):\n    # OpenSSL goes by a different library name on different operating systems.\n    if platform != \"win32\":\n        # In some circumstances, the order in which these libs are\n        # specified on the linker command-line is significant;\n        # libssl must come before libcrypto\n        # (http://marc.info/?l=openssl-users&m=135361825921871)\n        return [\"ssl\", \"crypto\"]\n    else:\n        link_type = os.environ.get(\"PYCA_WINDOWS_LINK_TYPE\", \"static\")\n        return _get_windows_libraries(link_type)\n\n\ndef _get_windows_libraries(link_type):\n    if link_type == \"dynamic\":\n        return [\"libeay32\", \"ssleay32\", \"advapi32\"]\n    elif link_type == \"static\" or link_type == \"\":\n        return [\"libeay32mt\", \"ssleay32mt\", \"advapi32\",\n                \"crypt32\", \"gdi32\", \"user32\", \"ws2_32\"]\n    else:\n        raise ValueError(\n            \"PYCA_WINDOWS_LINK_TYPE must be 'static' or 'dynamic'\"\n        )\n\n\nclass Binding(object):\n    \"\"\"\n    OpenSSL API wrapper.\n    \"\"\"\n    _module_prefix = \"cryptography.hazmat.bindings.openssl.\"\n    _modules = [\n        \"aes\",\n        \"asn1\",\n        \"bignum\",\n        \"bio\",\n        \"cmac\",\n        \"cms\",\n        \"conf\",\n        \"crypto\",\n        \"dh\",\n        \"dsa\",\n        \"ec\",\n        \"ecdh\",\n        \"ecdsa\",\n        \"engine\",\n        \"err\",\n        \"evp\",\n        \"hmac\",\n        \"nid\",\n        \"objects\",\n        \"opensslv\",\n        \"osrandom_engine\",\n        \"pem\",\n        \"pkcs7\",\n        \"pkcs12\",\n        \"rand\",\n        \"rsa\",\n        \"ssl\",\n        \"x509\",\n        \"x509name\",\n        \"x509v3\",\n        \"x509_vfy\"\n    ]\n\n    _locks = None\n    _lock_cb_handle = None\n    _lock_init_lock = threading.Lock()\n\n    ffi = build_ffi_for_binding(\n        module_prefix=_module_prefix,\n        modules=_modules,\n        pre_include=_OSX_PRE_INCLUDE,\n        post_include=_OSX_POST_INCLUDE,\n        libraries=_get_libraries(sys.platform)\n    )\n    lib = None\n\n    def __init__(self):\n        self._ensure_ffi_initialized()\n\n    @classmethod\n    def _ensure_ffi_initialized(cls):\n        if cls.lib is not None:\n            return\n\n        cls.lib = load_library_for_binding(\n            cls.ffi,\n            cls._module_prefix,\n            cls._modules,\n        )\n\n        res = cls.lib.Cryptography_add_osrandom_engine()\n        assert res != 0\n\n    @classmethod\n    def init_static_locks(cls):\n        with cls._lock_init_lock:\n            cls._ensure_ffi_initialized()\n\n            if not cls._lock_cb_handle:\n                cls._lock_cb_handle = cls.ffi.callback(\n                    \"void(int, int, const char *, int)\",\n                    cls._lock_cb\n                )\n\n            # Use Python's implementation if available, importing _ssl triggers\n            # the setup for this.\n            __import__(\"_ssl\")\n\n            if cls.lib.CRYPTO_get_locking_callback() != cls.ffi.NULL:\n                return\n\n            # If nothing else has setup a locking callback already, we set up\n            # our own\n            num_locks = cls.lib.CRYPTO_num_locks()\n            cls._locks = [threading.Lock() for n in range(num_locks)]\n\n            cls.lib.CRYPTO_set_locking_callback(cls._lock_cb_handle)\n\n    @classmethod\n    def _lock_cb(cls, mode, n, file, line):\n        lock = cls._locks[n]\n\n        if mode & cls.lib.CRYPTO_LOCK:\n            lock.acquire()\n        elif mode & cls.lib.CRYPTO_UNLOCK:\n            lock.release()\n        else:\n            raise RuntimeError(\n                \"Unknown lock mode {0}: lock={1}, file={2}, line={3}.\".format(\n                    mode, n, file, line\n                )\n            )\n", "path": "src/cryptography/hazmat/bindings/openssl/binding.py"}], "after_files": [{"content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nfrom __future__ import absolute_import, division, print_function\n\nimport threading\n\nfrom cryptography.hazmat.bindings.utils import (\n    build_ffi_for_binding, load_library_for_binding,\n)\n\n\nclass Binding(object):\n    \"\"\"\n    CommonCrypto API wrapper.\n    \"\"\"\n    _module_prefix = \"cryptography.hazmat.bindings.commoncrypto.\"\n    _modules = [\n        \"cf\",\n        \"common_digest\",\n        \"common_hmac\",\n        \"common_key_derivation\",\n        \"common_cryptor\",\n        \"common_symmetric_key_wrap\",\n        \"secimport\",\n        \"secitem\",\n        \"seckey\",\n        \"seckeychain\",\n        \"sectransform\",\n    ]\n\n    ffi = build_ffi_for_binding(\n        module_prefix=_module_prefix,\n        modules=_modules,\n        extra_link_args=[\n            \"-framework\", \"Security\", \"-framework\", \"CoreFoundation\"\n        ],\n    )\n    lib = None\n    _init_lock = threading.Lock()\n\n    def __init__(self):\n        self._ensure_ffi_initialized()\n\n    @classmethod\n    def _ensure_ffi_initialized(cls):\n        if cls.lib is not None:\n            return\n\n        with cls._init_lock:\n            if cls.lib is None:\n                cls.lib = load_library_for_binding(\n                    cls.ffi,\n                    module_prefix=cls._module_prefix,\n                    modules=cls._modules,\n                )\n", "path": "src/cryptography/hazmat/bindings/commoncrypto/binding.py"}, {"content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nfrom __future__ import absolute_import, division, print_function\n\nimport os\nimport sys\nimport threading\n\nfrom cryptography.hazmat.bindings.utils import (\n    build_ffi_for_binding, load_library_for_binding,\n)\n\n\n_OSX_PRE_INCLUDE = \"\"\"\n#ifdef __APPLE__\n#include <AvailabilityMacros.h>\n#define __ORIG_DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER \\\n    DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER\n#undef DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER\n#define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER\n#endif\n\"\"\"\n\n_OSX_POST_INCLUDE = \"\"\"\n#ifdef __APPLE__\n#undef DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER\n#define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER \\\n    __ORIG_DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER\n#endif\n\"\"\"\n\n\ndef _get_libraries(platform):\n    # OpenSSL goes by a different library name on different operating systems.\n    if platform != \"win32\":\n        # In some circumstances, the order in which these libs are\n        # specified on the linker command-line is significant;\n        # libssl must come before libcrypto\n        # (http://marc.info/?l=openssl-users&m=135361825921871)\n        return [\"ssl\", \"crypto\"]\n    else:\n        link_type = os.environ.get(\"PYCA_WINDOWS_LINK_TYPE\", \"static\")\n        return _get_windows_libraries(link_type)\n\n\ndef _get_windows_libraries(link_type):\n    if link_type == \"dynamic\":\n        return [\"libeay32\", \"ssleay32\", \"advapi32\"]\n    elif link_type == \"static\" or link_type == \"\":\n        return [\"libeay32mt\", \"ssleay32mt\", \"advapi32\",\n                \"crypt32\", \"gdi32\", \"user32\", \"ws2_32\"]\n    else:\n        raise ValueError(\n            \"PYCA_WINDOWS_LINK_TYPE must be 'static' or 'dynamic'\"\n        )\n\n\nclass Binding(object):\n    \"\"\"\n    OpenSSL API wrapper.\n    \"\"\"\n    _module_prefix = \"cryptography.hazmat.bindings.openssl.\"\n    _modules = [\n        \"aes\",\n        \"asn1\",\n        \"bignum\",\n        \"bio\",\n        \"cmac\",\n        \"cms\",\n        \"conf\",\n        \"crypto\",\n        \"dh\",\n        \"dsa\",\n        \"ec\",\n        \"ecdh\",\n        \"ecdsa\",\n        \"engine\",\n        \"err\",\n        \"evp\",\n        \"hmac\",\n        \"nid\",\n        \"objects\",\n        \"opensslv\",\n        \"osrandom_engine\",\n        \"pem\",\n        \"pkcs7\",\n        \"pkcs12\",\n        \"rand\",\n        \"rsa\",\n        \"ssl\",\n        \"x509\",\n        \"x509name\",\n        \"x509v3\",\n        \"x509_vfy\"\n    ]\n\n    _locks = None\n    _lock_cb_handle = None\n    _init_lock = threading.Lock()\n    _lock_init_lock = threading.Lock()\n\n    ffi = build_ffi_for_binding(\n        module_prefix=_module_prefix,\n        modules=_modules,\n        pre_include=_OSX_PRE_INCLUDE,\n        post_include=_OSX_POST_INCLUDE,\n        libraries=_get_libraries(sys.platform)\n    )\n    lib = None\n\n    def __init__(self):\n        self._ensure_ffi_initialized()\n\n    @classmethod\n    def _ensure_ffi_initialized(cls):\n        if cls.lib is not None:\n            return\n\n        with cls._init_lock:\n            if cls.lib is None:\n                cls.lib = load_library_for_binding(\n                    cls.ffi,\n                    cls._module_prefix,\n                    cls._modules,\n                )\n\n                res = cls.lib.Cryptography_add_osrandom_engine()\n                assert res != 0\n\n    @classmethod\n    def init_static_locks(cls):\n        with cls._lock_init_lock:\n            cls._ensure_ffi_initialized()\n\n            if not cls._lock_cb_handle:\n                cls._lock_cb_handle = cls.ffi.callback(\n                    \"void(int, int, const char *, int)\",\n                    cls._lock_cb\n                )\n\n            # Use Python's implementation if available, importing _ssl triggers\n            # the setup for this.\n            __import__(\"_ssl\")\n\n            if cls.lib.CRYPTO_get_locking_callback() != cls.ffi.NULL:\n                return\n\n            # If nothing else has setup a locking callback already, we set up\n            # our own\n            num_locks = cls.lib.CRYPTO_num_locks()\n            cls._locks = [threading.Lock() for n in range(num_locks)]\n\n            cls.lib.CRYPTO_set_locking_callback(cls._lock_cb_handle)\n\n    @classmethod\n    def _lock_cb(cls, mode, n, file, line):\n        lock = cls._locks[n]\n\n        if mode & cls.lib.CRYPTO_LOCK:\n            lock.acquire()\n        elif mode & cls.lib.CRYPTO_UNLOCK:\n            lock.release()\n        else:\n            raise RuntimeError(\n                \"Unknown lock mode {0}: lock={1}, file={2}, line={3}.\".format(\n                    mode, n, file, line\n                )\n            )\n", "path": "src/cryptography/hazmat/bindings/openssl/binding.py"}]}