An interpreted, interactive, object-oriented programming language
CentOS Sources
2017-08-01 71084d584ff953f5463757ec6536406320560b4d
commit | author | age
f63228 1 # HG changeset patch
CS 2 # User Benjamin Peterson <benjamin@python.org>
3 # Date 1408562090 18000
4 # Node ID 221a1f9155e2a8b4d12015261b83a2ce3a0c62a2
5 # Parent  c1edc4e43eb103254c5d96f1708542623fe08f17
6 backport many ssl features from Python 3 (closes #21308)
7
8 A contribution of Alex Gaynor and David Reid with the generous support of
9 Rackspace. May God have mercy on their souls.
10
11 diff -up Python-2.7.5/Lib/ssl.py.rev Python-2.7.5/Lib/ssl.py
12 --- Python-2.7.5/Lib/ssl.py.rev    2015-03-03 11:11:56.743921122 +0100
13 +++ Python-2.7.5/Lib/ssl.py    2015-03-03 11:18:11.829704572 +0100
14 @@ -89,6 +89,7 @@ else:
15  
16  from socket import socket, _fileobject, _delegate_methods, error as socket_error
17  from socket import getnameinfo as _getnameinfo
18 +from socket import SOL_SOCKET, SO_TYPE, SOCK_STREAM
19  import base64        # for DER-to-PEM translation
20  import errno
21  
22 @@ -108,6 +109,10 @@ class SSLSocket(socket):
23                   ssl_version=PROTOCOL_SSLv23, ca_certs=None,
24                   do_handshake_on_connect=True,
25                   suppress_ragged_eofs=True, ciphers=None):
26 +        # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
27 +        # mixed in.
28 +        if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
29 +            raise NotImplementedError("only stream sockets are supported")
30          socket.__init__(self, _sock=sock._sock)
31          # The initializer for socket overrides the methods send(), recv(), etc.
32          # in the instancce, which we don't need -- but we want to provide the
33 diff -up Python-2.7.5/Lib/test/test_ssl.py.rev Python-2.7.5/Lib/test/test_ssl.py
34 diff -up Python-2.7.5/Modules/_ssl.c.rev Python-2.7.5/Modules/_ssl.c
35 --- Python-2.7.5/Modules/_ssl.c.rev    2015-03-03 10:37:10.331849242 +0100
36 +++ Python-2.7.5/Modules/_ssl.c    2015-03-03 11:11:09.324442807 +0100
37 @@ -281,6 +281,7 @@ newPySSLObject(PySocketSockObject *Sock,
38      self->ssl = NULL;
39      self->ctx = NULL;
40      self->Socket = NULL;
41 +    self->shutdown_seen_zero = 0;
42  
43      /* Make sure the SSL error state is initialized */
44      (void) ERR_get_state();
45 @@ -686,7 +687,7 @@ _get_peer_alt_names (X509 *certificate)
46  
47      int i, j;
48      PyObject *peer_alt_names = Py_None;
49 -    PyObject *v, *t;
50 +    PyObject *v = NULL, *t;
51      X509_EXTENSION *ext = NULL;
52      GENERAL_NAMES *names = NULL;
53      GENERAL_NAME *name;
54 @@ -745,7 +746,7 @@ _get_peer_alt_names (X509 *certificate)
55              ASN1_STRING *as = NULL;
56  
57              name = sk_GENERAL_NAME_value(names, j);
58 -            gntype = name-> type;
59 +            gntype = name->type;
60              switch (gntype) {
61              case GEN_DIRNAME:
62  
63 @@ -781,15 +782,15 @@ _get_peer_alt_names (X509 *certificate)
64                      goto fail;
65                  switch (gntype) {
66                  case GEN_EMAIL:
67 -                    v = PyUnicode_FromString("email");
68 +                    v = PyString_FromString("email");
69                      as = name->d.rfc822Name;
70                      break;
71                  case GEN_DNS:
72 -                    v = PyUnicode_FromString("DNS");
73 +                    v = PyString_FromString("DNS");
74                      as = name->d.dNSName;
75                      break;
76                  case GEN_URI:
77 -                    v = PyUnicode_FromString("URI");
78 +                    v = PyString_FromString("URI");
79                      as = name->d.uniformResourceIdentifier;
80                      break;
81                  }
82 @@ -819,7 +820,7 @@ _get_peer_alt_names (X509 *certificate)
83                          break;
84                      default:
85                          if (PyErr_Warn(PyExc_RuntimeWarning,
86 -                       "Unknown general name type") == -1) {
87 +                                       "Unknown general name type") == -1) {
88                              goto fail;
89                          }
90                          break;
91 @@ -849,7 +850,7 @@ _get_peer_alt_names (X509 *certificate)
92                      goto fail;
93                  }
94                  PyTuple_SET_ITEM(t, 1, v);
95 -        break;
96 +                break;
97              }
98  
99              /* and add that rendering to the list */
100 @@ -1248,6 +1249,12 @@ static PyObject *PySSL_SSLwrite(PySSLObj
101      if (!PyArg_ParseTuple(args, "s*:write", &buf))
102          return NULL;
103  
104 +    if (buf.len > INT_MAX) {
105 +        PyErr_Format(PyExc_OverflowError,
106 +                     "string longer than %d bytes", INT_MAX);
107 +        goto error;
108 +    }
109 +
110      /* just in case the blocking state of the socket has been changed */
111      nonblocking = (self->Socket->sock_timeout >= 0.0);
112      BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
113 @@ -1269,7 +1276,7 @@ static PyObject *PySSL_SSLwrite(PySSLObj
114      }
115      do {
116          PySSL_BEGIN_ALLOW_THREADS
117 -        len = SSL_write(self->ssl, buf.buf, buf.len);
118 +        len = SSL_write(self->ssl, buf.buf, (int)buf.len);
119          err = SSL_get_error(self->ssl, len);
120          PySSL_END_ALLOW_THREADS
121          if (PyErr_CheckSignals()) {
122 @@ -1451,7 +1458,7 @@ static PyObject *PySSL_SSLshutdown(PySSL
123           * Otherwise OpenSSL might read in too much data,
124           * eating clear text data that happens to be
125           * transmitted after the SSL shutdown.
126 -         * Should be safe to call repeatedly everytime this
127 +         * Should be safe to call repeatedly every time this
128           * function is used and the shutdown_seen_zero != 0
129           * condition is met.
130           */
131 @@ -1615,9 +1622,9 @@ PyDoc_STRVAR(PySSL_RAND_egd_doc,
132  \n\
133  Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
134  Returns number of bytes read.  Raises SSLError if connection to EGD\n\
135 -fails or if it does provide enough data to seed PRNG.");
136 +fails or if it does not provide enough data to seed PRNG.");
137  
138 -#endif
139 +#endif /* HAVE_OPENSSL_RAND */
140  
141  /* List of functions exported by this module. */
142  
143 diff -up Python-2.7.5/Modules/_ssl.c.ssl2 Python-2.7.5/Modules/_ssl.c
144 --- Python-2.7.5/Modules/_ssl.c.ssl2    2015-03-03 15:48:56.112889298 +0100
145 +++ Python-2.7.5/Modules/_ssl.c    2015-03-03 15:47:21.598870012 +0100
146 @@ -14,20 +14,26 @@
147         http://bugs.python.org/issue8108#msg102867 ?
148  */
149  
150 +#define PY_SSIZE_T_CLEAN
151  #include "Python.h"
152  
153  #ifdef WITH_THREAD
154  #include "pythread.h"
155 +#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
156 +    do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
157 +#define PySSL_END_ALLOW_THREADS_S(save) \
158 +    do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
159  #define PySSL_BEGIN_ALLOW_THREADS { \
160              PyThreadState *_save = NULL;  \
161 -            if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
162 -#define PySSL_BLOCK_THREADS     if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
163 -#define PySSL_UNBLOCK_THREADS   if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
164 -#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
165 -         }
166 +            PySSL_BEGIN_ALLOW_THREADS_S(_save);
167 +#define PySSL_BLOCK_THREADS     PySSL_END_ALLOW_THREADS_S(_save);
168 +#define PySSL_UNBLOCK_THREADS   PySSL_BEGIN_ALLOW_THREADS_S(_save);
169 +#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
170  
171  #else   /* no WITH_THREAD */
172  
173 +#define PySSL_BEGIN_ALLOW_THREADS_S(save)
174 +#define PySSL_END_ALLOW_THREADS_S(save)
175  #define PySSL_BEGIN_ALLOW_THREADS
176  #define PySSL_BLOCK_THREADS
177  #define PySSL_UNBLOCK_THREADS
178 @@ -35,6 +41,68 @@
179  
180  #endif
181  
182 +/* Include symbols from _socket module */
183 +#include "socketmodule.h"
184 +
185 +#if defined(HAVE_POLL_H)
186 +#include <poll.h>
187 +#elif defined(HAVE_SYS_POLL_H)
188 +#include <sys/poll.h>
189 +#endif
190 +
191 +/* Include OpenSSL header files */
192 +#include "openssl/rsa.h"
193 +#include "openssl/crypto.h"
194 +#include "openssl/x509.h"
195 +#include "openssl/x509v3.h"
196 +#include "openssl/pem.h"
197 +#include "openssl/ssl.h"
198 +#include "openssl/err.h"
199 +#include "openssl/rand.h"
200 +
201 +/* SSL error object */
202 +static PyObject *PySSLErrorObject;
203 +static PyObject *PySSLZeroReturnErrorObject;
204 +static PyObject *PySSLWantReadErrorObject;
205 +static PyObject *PySSLWantWriteErrorObject;
206 +static PyObject *PySSLSyscallErrorObject;
207 +static PyObject *PySSLEOFErrorObject;
208 +
209 +/* Error mappings */
210 +static PyObject *err_codes_to_names;
211 +static PyObject *err_names_to_codes;
212 +static PyObject *lib_codes_to_names;
213 +
214 +struct py_ssl_error_code {
215 +    const char *mnemonic;
216 +    int library, reason;
217 +};
218 +struct py_ssl_library_code {
219 +    const char *library;
220 +    int code;
221 +};
222 +
223 +/* Include generated data (error codes) */
224 +#include "_ssl_data.h"
225 +
226 +/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
227 +    http://www.openssl.org/news/changelog.html
228 + */
229 +#if OPENSSL_VERSION_NUMBER >= 0x10001000L
230 +# define HAVE_TLSv1_2 1
231 +#else
232 +# define HAVE_TLSv1_2 0
233 +#endif
234 +
235 +/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
236 + * This includes the SSL_set_SSL_CTX() function.
237 + */
238 +#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
239 +# define HAVE_SNI 1
240 +#else
241 +# define HAVE_SNI 0
242 +#endif
243 +
244  enum py_ssl_error {
245      /* these mirror ssl.h */
246      PY_SSL_ERROR_NONE,
247 @@ -47,6 +115,7 @@ enum py_ssl_error {
248      PY_SSL_ERROR_WANT_CONNECT,
249      /* start of non ssl.h errorcodes */
250      PY_SSL_ERROR_EOF,         /* special case of SSL_ERROR_SYSCALL */
251 +    PY_SSL_ERROR_NO_SOCKET,   /* socket has been GC'd */
252      PY_SSL_ERROR_INVALID_ERROR_CODE
253  };
254  
255 @@ -62,35 +131,17 @@ enum py_ssl_cert_requirements {
256  };
257  
258  enum py_ssl_version {
259 -#ifndef OPENSSL_NO_SSL2
260      PY_SSL_VERSION_SSL2,
261 -#endif
262      PY_SSL_VERSION_SSL3=1,
263      PY_SSL_VERSION_SSL23,
264 +#if HAVE_TLSv1_2
265 +    PY_SSL_VERSION_TLS1,
266 +    PY_SSL_VERSION_TLS1_1,
267 +    PY_SSL_VERSION_TLS1_2
268 +#else
269      PY_SSL_VERSION_TLS1
270 -};
271 -
272 -/* Include symbols from _socket module */
273 -#include "socketmodule.h"
274 -
275 -#if defined(HAVE_POLL_H)
276 -#include <poll.h>
277 -#elif defined(HAVE_SYS_POLL_H)
278 -#include <sys/poll.h>
279  #endif
280 -
281 -/* Include OpenSSL header files */
282 -#include "openssl/rsa.h"
283 -#include "openssl/crypto.h"
284 -#include "openssl/x509.h"
285 -#include "openssl/x509v3.h"
286 -#include "openssl/pem.h"
287 -#include "openssl/ssl.h"
288 -#include "openssl/err.h"
289 -#include "openssl/rand.h"
290 -
291 -/* SSL error object */
292 -static PyObject *PySSLErrorObject;
293 +};
294  
295  #ifdef WITH_THREAD
296  
297 @@ -112,27 +163,79 @@ static unsigned int _ssl_locks_count = 0
298  # undef HAVE_OPENSSL_RAND
299  #endif
300  
301 +/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
302 + * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
303 + * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
304 +#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
305 +# define HAVE_SSL_CTX_CLEAR_OPTIONS
306 +#else
307 +# undef HAVE_SSL_CTX_CLEAR_OPTIONS
308 +#endif
309 +
310 +/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
311 + * older SSL, but let's be safe */
312 +#define PySSL_CB_MAXLEN 128
313 +
314 +/* SSL_get_finished got added to OpenSSL in 0.9.5 */
315 +#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
316 +# define HAVE_OPENSSL_FINISHED 1
317 +#else
318 +# define HAVE_OPENSSL_FINISHED 0
319 +#endif
320 +
321 +/* ECDH support got added to OpenSSL in 0.9.8 */
322 +#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
323 +# define OPENSSL_NO_ECDH
324 +#endif
325 +
326 +/* compression support got added to OpenSSL in 0.9.8 */
327 +#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
328 +# define OPENSSL_NO_COMP
329 +#endif
330 +
331 +/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
332 +#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
333 +# define HAVE_OPENSSL_VERIFY_PARAM
334 +#endif
335 +
336 +
337 +typedef struct {
338 +    PyObject_HEAD
339 +    SSL_CTX *ctx;
340 +#ifdef OPENSSL_NPN_NEGOTIATED
341 +    char *npn_protocols;
342 +    int npn_protocols_len;
343 +#endif
344 +#ifndef OPENSSL_NO_TLSEXT
345 +    PyObject *set_hostname;
346 +#endif
347 +    int check_hostname;
348 +} PySSLContext;
349 +
350  typedef struct {
351      PyObject_HEAD
352 -    PySocketSockObject *Socket;         /* Socket on which we're layered */
353 -    SSL_CTX*            ctx;
354 -    SSL*                ssl;
355 -    X509*               peer_cert;
356 -    char                server[X509_NAME_MAXLEN];
357 -    char                issuer[X509_NAME_MAXLEN];
358 -    int                 shutdown_seen_zero;
359 -
360 -} PySSLObject;
361 -
362 -static PyTypeObject PySSL_Type;
363 -static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
364 -static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
365 +    PySocketSockObject *Socket;
366 +    PyObject *ssl_sock;
367 +    SSL *ssl;
368 +    PySSLContext *ctx; /* weakref to SSL context */
369 +    X509 *peer_cert;
370 +    char shutdown_seen_zero;
371 +    char handshake_done;
372 +    enum py_ssl_server_or_client socket_type;
373 +} PySSLSocket;
374 +
375 +static PyTypeObject PySSLContext_Type;
376 +static PyTypeObject PySSLSocket_Type;
377 +
378 +static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
379 +static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
380  static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
381                                               int writing);
382 -static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
383 -static PyObject *PySSL_cipher(PySSLObject *self);
384 +static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
385 +static PyObject *PySSL_cipher(PySSLSocket *self);
386  
387 -#define PySSLObject_Check(v)    (Py_TYPE(v) == &PySSL_Type)
388 +#define PySSLContext_Check(v)   (Py_TYPE(v) == &PySSLContext_Type)
389 +#define PySSLSocket_Check(v)    (Py_TYPE(v) == &PySSLSocket_Type)
390  
391  typedef enum {
392      SOCKET_IS_NONBLOCKING,
393 @@ -149,36 +252,140 @@ typedef enum {
394  #define ERRSTR1(x,y,z) (x ":" y ": " z)
395  #define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
396  
397 -/* XXX It might be helpful to augment the error message generated
398 -   below with the name of the SSL function that generated the error.
399 -   I expect it's obvious most of the time.
400 -*/
401 +
402 +/*
403 + * SSL errors.
404 + */
405 +
406 +PyDoc_STRVAR(SSLError_doc,
407 +"An error occurred in the SSL implementation.");
408 +
409 +PyDoc_STRVAR(SSLZeroReturnError_doc,
410 +"SSL/TLS session closed cleanly.");
411 +
412 +PyDoc_STRVAR(SSLWantReadError_doc,
413 +"Non-blocking SSL socket needs to read more data\n"
414 +"before the requested operation can be completed.");
415 +
416 +PyDoc_STRVAR(SSLWantWriteError_doc,
417 +"Non-blocking SSL socket needs to write more data\n"
418 +"before the requested operation can be completed.");
419 +
420 +PyDoc_STRVAR(SSLSyscallError_doc,
421 +"System error when attempting SSL operation.");
422 +
423 +PyDoc_STRVAR(SSLEOFError_doc,
424 +"SSL/TLS connection terminated abruptly.");
425 +
426  
427  static PyObject *
428 -PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
429 +SSLError_str(PyEnvironmentErrorObject *self)
430  {
431 -    PyObject *v;
432 -    char buf[2048];
433 -    char *errstr;
434 +    if (self->strerror != NULL) {
435 +        Py_INCREF(self->strerror);
436 +        return self->strerror;
437 +    }
438 +    else
439 +        return PyObject_Str(self->args);
440 +}
441 +
442 +static void
443 +fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
444 +                      int lineno, unsigned long errcode)
445 +{
446 +    PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
447 +    PyObject *init_value, *msg, *key;
448 +
449 +    if (errcode != 0) {
450 +        int lib, reason;
451 +
452 +        lib = ERR_GET_LIB(errcode);
453 +        reason = ERR_GET_REASON(errcode);
454 +        key = Py_BuildValue("ii", lib, reason);
455 +        if (key == NULL)
456 +            goto fail;
457 +        reason_obj = PyDict_GetItem(err_codes_to_names, key);
458 +        Py_DECREF(key);
459 +        if (reason_obj == NULL) {
460 +            /* XXX if reason < 100, it might reflect a library number (!!) */
461 +            PyErr_Clear();
462 +        }
463 +        key = PyLong_FromLong(lib);
464 +        if (key == NULL)
465 +            goto fail;
466 +        lib_obj = PyDict_GetItem(lib_codes_to_names, key);
467 +        Py_DECREF(key);
468 +        if (lib_obj == NULL) {
469 +            PyErr_Clear();
470 +        }
471 +        if (errstr == NULL)
472 +            errstr = ERR_reason_error_string(errcode);
473 +    }
474 +    if (errstr == NULL)
475 +        errstr = "unknown error";
476 +
477 +    if (reason_obj && lib_obj)
478 +        msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
479 +                                   lib_obj, reason_obj, errstr, lineno);
480 +    else if (lib_obj)
481 +        msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
482 +                                   lib_obj, errstr, lineno);
483 +    else
484 +        msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
485 +    if (msg == NULL)
486 +        goto fail;
487 +
488 +    init_value = Py_BuildValue("iN", ssl_errno, msg);
489 +    if (init_value == NULL)
490 +        goto fail;
491 +
492 +    err_value = PyObject_CallObject(type, init_value);
493 +    Py_DECREF(init_value);
494 +    if (err_value == NULL)
495 +        goto fail;
496 +
497 +    if (reason_obj == NULL)
498 +        reason_obj = Py_None;
499 +    if (PyObject_SetAttrString(err_value, "reason", reason_obj))
500 +        goto fail;
501 +    if (lib_obj == NULL)
502 +        lib_obj = Py_None;
503 +    if (PyObject_SetAttrString(err_value, "library", lib_obj))
504 +        goto fail;
505 +    PyErr_SetObject(type, err_value);
506 +fail:
507 +    Py_XDECREF(err_value);
508 +}
509 +
510 +static PyObject *
511 +PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
512 +{
513 +    PyObject *type = PySSLErrorObject;
514 +    char *errstr = NULL;
515      int err;
516      enum py_ssl_error p = PY_SSL_ERROR_NONE;
517 +    unsigned long e = 0;
518  
519      assert(ret <= 0);
520 +    e = ERR_peek_last_error();
521  
522      if (obj->ssl != NULL) {
523          err = SSL_get_error(obj->ssl, ret);
524  
525          switch (err) {
526          case SSL_ERROR_ZERO_RETURN:
527 -            errstr = "TLS/SSL connection has been closed";
528 +            errstr = "TLS/SSL connection has been closed (EOF)";
529 +            type = PySSLZeroReturnErrorObject;
530              p = PY_SSL_ERROR_ZERO_RETURN;
531              break;
532          case SSL_ERROR_WANT_READ:
533              errstr = "The operation did not complete (read)";
534 +            type = PySSLWantReadErrorObject;
535              p = PY_SSL_ERROR_WANT_READ;
536              break;
537          case SSL_ERROR_WANT_WRITE:
538              p = PY_SSL_ERROR_WANT_WRITE;
539 +            type = PySSLWantWriteErrorObject;
540              errstr = "The operation did not complete (write)";
541              break;
542          case SSL_ERROR_WANT_X509_LOOKUP:
543 @@ -191,210 +398,109 @@ PySSL_SetError(PySSLObject *obj, int ret
544              break;
545          case SSL_ERROR_SYSCALL:
546          {
547 -            unsigned long e = ERR_get_error();
548              if (e == 0) {
549 -                if (ret == 0 || !obj->Socket) {
550 +                PySocketSockObject *s = obj->Socket;
551 +                if (ret == 0) {
552                      p = PY_SSL_ERROR_EOF;
553 +                    type = PySSLEOFErrorObject;
554                      errstr = "EOF occurred in violation of protocol";
555                  } else if (ret == -1) {
556                      /* underlying BIO reported an I/O error */
557 +                    Py_INCREF(s);
558                      ERR_clear_error();
559 -                    return obj->Socket->errorhandler();
560 +                    s->errorhandler();
561 +                    Py_DECREF(s);
562 +                    return NULL;
563                  } else { /* possible? */
564                      p = PY_SSL_ERROR_SYSCALL;
565 +                    type = PySSLSyscallErrorObject;
566                      errstr = "Some I/O error occurred";
567                  }
568              } else {
569                  p = PY_SSL_ERROR_SYSCALL;
570 -                /* XXX Protected by global interpreter lock */
571 -                errstr = ERR_error_string(e, NULL);
572              }
573              break;
574          }
575          case SSL_ERROR_SSL:
576          {
577 -            unsigned long e = ERR_get_error();
578              p = PY_SSL_ERROR_SSL;
579 -            if (e != 0)
580 -                /* XXX Protected by global interpreter lock */
581 -                errstr = ERR_error_string(e, NULL);
582 -            else {              /* possible? */
583 +            if (e == 0)
584 +                /* possible? */
585                  errstr = "A failure in the SSL library occurred";
586 -            }
587              break;
588          }
589          default:
590              p = PY_SSL_ERROR_INVALID_ERROR_CODE;
591              errstr = "Invalid error code";
592          }
593 -    } else {
594 -        errstr = ERR_error_string(ERR_peek_last_error(), NULL);
595      }
596 -    PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
597 +    fill_and_set_sslerror(type, p, errstr, lineno, e);
598      ERR_clear_error();
599 -    v = Py_BuildValue("(is)", p, buf);
600 -    if (v != NULL) {
601 -        PyErr_SetObject(PySSLErrorObject, v);
602 -        Py_DECREF(v);
603 -    }
604      return NULL;
605  }
606  
607  static PyObject *
608  _setSSLError (char *errstr, int errcode, char *filename, int lineno) {
609  
610 -    char buf[2048];
611 -    PyObject *v;
612 -
613 -    if (errstr == NULL) {
614 +    if (errstr == NULL)
615          errcode = ERR_peek_last_error();
616 -        errstr = ERR_error_string(errcode, NULL);
617 -    }
618 -    PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
619 +    else
620 +        errcode = 0;
621 +    fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
622      ERR_clear_error();
623 -    v = Py_BuildValue("(is)", errcode, buf);
624 -    if (v != NULL) {
625 -        PyErr_SetObject(PySSLErrorObject, v);
626 -        Py_DECREF(v);
627 -    }
628      return NULL;
629  }
630  
631 -static PySSLObject *
632 -newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
633 +/*
634 + * SSL objects
635 + */
636 +
637 +static PySSLSocket *
638 +newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
639                 enum py_ssl_server_or_client socket_type,
640 -               enum py_ssl_cert_requirements certreq,
641 -               enum py_ssl_version proto_version,
642 -               char *cacerts_file, char *ciphers)
643 +               char *server_hostname, PyObject *ssl_sock)
644  {
645 -    PySSLObject *self;
646 -    char *errstr = NULL;
647 -    int ret;
648 -    int verification_mode;
649 +    PySSLSocket *self;
650 +    SSL_CTX *ctx = sslctx->ctx;
651 +    long mode;
652  
653 -    self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
654 +    self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
655      if (self == NULL)
656          return NULL;
657 -    memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN);
658 -    memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);
659 +
660      self->peer_cert = NULL;
661      self->ssl = NULL;
662 -    self->ctx = NULL;
663      self->Socket = NULL;
664 +    self->ssl_sock = NULL;
665 +    self->ctx = sslctx;
666      self->shutdown_seen_zero = 0;
667 +    self->handshake_done = 0;
668 +    Py_INCREF(sslctx);
669  
670      /* Make sure the SSL error state is initialized */
671      (void) ERR_get_state();
672      ERR_clear_error();
673  
674 -    if ((key_file && !cert_file) || (!key_file && cert_file)) {
675 -        errstr = ERRSTR("Both the key & certificate files "
676 -                        "must be specified");
677 -        goto fail;
678 -    }
679 -
680 -    if ((socket_type == PY_SSL_SERVER) &&
681 -        ((key_file == NULL) || (cert_file == NULL))) {
682 -        errstr = ERRSTR("Both the key & certificate files "
683 -                        "must be specified for server-side operation");
684 -        goto fail;
685 -    }
686 -
687 -    PySSL_BEGIN_ALLOW_THREADS
688 -    if (proto_version == PY_SSL_VERSION_TLS1)
689 -        self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
690 -    else if (proto_version == PY_SSL_VERSION_SSL3)
691 -        self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
692 -#ifndef OPENSSL_NO_SSL2
693 -    else if (proto_version == PY_SSL_VERSION_SSL2)
694 -        self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
695 -#endif
696 -    else if (proto_version == PY_SSL_VERSION_SSL23)
697 -        self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
698 -    PySSL_END_ALLOW_THREADS
699 -
700 -    if (self->ctx == NULL) {
701 -        errstr = ERRSTR("Invalid SSL protocol variant specified.");
702 -        goto fail;
703 -    }
704 -
705 -    if (ciphers != NULL) {
706 -        ret = SSL_CTX_set_cipher_list(self->ctx, ciphers);
707 -        if (ret == 0) {
708 -            errstr = ERRSTR("No cipher can be selected.");
709 -            goto fail;
710 -        }
711 -    }
712 -
713 -    if (certreq != PY_SSL_CERT_NONE) {
714 -        if (cacerts_file == NULL) {
715 -            errstr = ERRSTR("No root certificates specified for "
716 -                            "verification of other-side certificates.");
717 -            goto fail;
718 -        } else {
719 -            PySSL_BEGIN_ALLOW_THREADS
720 -            ret = SSL_CTX_load_verify_locations(self->ctx,
721 -                                                cacerts_file,
722 -                                                NULL);
723 -            PySSL_END_ALLOW_THREADS
724 -            if (ret != 1) {
725 -                _setSSLError(NULL, 0, __FILE__, __LINE__);
726 -                goto fail;
727 -            }
728 -        }
729 -    }
730 -    if (key_file) {
731 -        PySSL_BEGIN_ALLOW_THREADS
732 -        ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
733 -                                          SSL_FILETYPE_PEM);
734 -        PySSL_END_ALLOW_THREADS
735 -        if (ret != 1) {
736 -            _setSSLError(NULL, ret, __FILE__, __LINE__);
737 -            goto fail;
738 -        }
739 -
740 -        PySSL_BEGIN_ALLOW_THREADS
741 -        ret = SSL_CTX_use_certificate_chain_file(self->ctx,
742 -                                                 cert_file);
743 -        PySSL_END_ALLOW_THREADS
744 -        if (ret != 1) {
745 -            /*
746 -            fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
747 -                ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
748 -                */
749 -            if (ERR_peek_last_error() != 0) {
750 -                _setSSLError(NULL, ret, __FILE__, __LINE__);
751 -                goto fail;
752 -            }
753 -        }
754 -    }
755 -
756 -    /* ssl compatibility */
757 -    SSL_CTX_set_options(self->ctx,
758 -                        SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
759 -
760 -    verification_mode = SSL_VERIFY_NONE;
761 -    if (certreq == PY_SSL_CERT_OPTIONAL)
762 -        verification_mode = SSL_VERIFY_PEER;
763 -    else if (certreq == PY_SSL_CERT_REQUIRED)
764 -        verification_mode = (SSL_VERIFY_PEER |
765 -                             SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
766 -    SSL_CTX_set_verify(self->ctx, verification_mode,
767 -                       NULL); /* set verify lvl */
768 -
769      PySSL_BEGIN_ALLOW_THREADS
770 -    self->ssl = SSL_new(self->ctx); /* New ssl struct */
771 +    self->ssl = SSL_new(ctx);
772      PySSL_END_ALLOW_THREADS
773 -    SSL_set_fd(self->ssl, Sock->sock_fd);       /* Set the socket for SSL */
774 +    SSL_set_app_data(self->ssl,self);
775 +    SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
776 +    mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
777  #ifdef SSL_MODE_AUTO_RETRY
778 -    SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
779 +    mode |= SSL_MODE_AUTO_RETRY;
780 +#endif
781 +    SSL_set_mode(self->ssl, mode);
782 +
783 +#if HAVE_SNI
784 +    if (server_hostname != NULL)
785 +        SSL_set_tlsext_host_name(self->ssl, server_hostname);
786  #endif
787  
788      /* If the socket is in non-blocking mode or timeout mode, set the BIO
789       * to non-blocking mode (blocking is the default)
790       */
791 -    if (Sock->sock_timeout >= 0.0) {
792 -        /* Set both the read and write BIO's to non-blocking mode */
793 +    if (sock->sock_timeout >= 0.0) {
794          BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
795          BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
796      }
797 @@ -406,65 +512,31 @@ newPySSLObject(PySocketSockObject *Sock,
798          SSL_set_accept_state(self->ssl);
799      PySSL_END_ALLOW_THREADS
800  
801 -    self->Socket = Sock;
802 +    self->socket_type = socket_type;
803 +    self->Socket = sock;
804      Py_INCREF(self->Socket);
805 +    self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
806 +    if (self->ssl_sock == NULL) {
807 +        Py_DECREF(self);
808 +        return NULL;
809 +    }
810      return self;
811 - fail:
812 -    if (errstr)
813 -        PyErr_SetString(PySSLErrorObject, errstr);
814 -    Py_DECREF(self);
815 -    return NULL;
816  }
817  
818 -static PyObject *
819 -PySSL_sslwrap(PyObject *self, PyObject *args)
820 -{
821 -    PySocketSockObject *Sock;
822 -    int server_side = 0;
823 -    int verification_mode = PY_SSL_CERT_NONE;
824 -    int protocol = PY_SSL_VERSION_SSL23;
825 -    char *key_file = NULL;
826 -    char *cert_file = NULL;
827 -    char *cacerts_file = NULL;
828 -    char *ciphers = NULL;
829 -
830 -    if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap",
831 -                          PySocketModule.Sock_Type,
832 -                          &Sock,
833 -                          &server_side,
834 -                          &key_file, &cert_file,
835 -                          &verification_mode, &protocol,
836 -                          &cacerts_file, &ciphers))
837 -        return NULL;
838 -
839 -    /*
840 -    fprintf(stderr,
841 -        "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
842 -        "protocol %d, certs %p\n",
843 -        server_side, key_file, cert_file, verification_mode,
844 -        protocol, cacerts_file);
845 -     */
846 -
847 -    return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
848 -                                       server_side, verification_mode,
849 -                                       protocol, cacerts_file,
850 -                                       ciphers);
851 -}
852 -
853 -PyDoc_STRVAR(ssl_doc,
854 -"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
855 -"                              cacertsfile, ciphers]) -> sslobject");
856  
857  /* SSL object methods */
858  
859 -static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
860 +static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
861  {
862      int ret;
863      int err;
864      int sockstate, nonblocking;
865 +    PySocketSockObject *sock = self->Socket;
866 +
867 +    Py_INCREF(sock);
868  
869      /* just in case the blocking state of the socket has been changed */
870 -    nonblocking = (self->Socket->sock_timeout >= 0.0);
871 +    nonblocking = (sock->sock_timeout >= 0.0);
872      BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
873      BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
874  
875 @@ -475,60 +547,48 @@ static PyObject *PySSL_SSLdo_handshake(P
876          ret = SSL_do_handshake(self->ssl);
877          err = SSL_get_error(self->ssl, ret);
878          PySSL_END_ALLOW_THREADS
879 -        if(PyErr_CheckSignals()) {
880 -            return NULL;
881 -        }
882 +        if (PyErr_CheckSignals())
883 +            goto error;
884          if (err == SSL_ERROR_WANT_READ) {
885 -            sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
886 +            sockstate = check_socket_and_wait_for_timeout(sock, 0);
887          } else if (err == SSL_ERROR_WANT_WRITE) {
888 -            sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
889 +            sockstate = check_socket_and_wait_for_timeout(sock, 1);
890          } else {
891              sockstate = SOCKET_OPERATION_OK;
892          }
893          if (sockstate == SOCKET_HAS_TIMED_OUT) {
894              PyErr_SetString(PySSLErrorObject,
895                              ERRSTR("The handshake operation timed out"));
896 -            return NULL;
897 +            goto error;
898          } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
899              PyErr_SetString(PySSLErrorObject,
900                              ERRSTR("Underlying socket has been closed."));
901 -            return NULL;
902 +            goto error;
903          } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
904              PyErr_SetString(PySSLErrorObject,
905                              ERRSTR("Underlying socket too large for select()."));
906 -            return NULL;
907 +            goto error;
908          } else if (sockstate == SOCKET_IS_NONBLOCKING) {
909              break;
910          }
911      } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
912 +    Py_DECREF(sock);
913      if (ret < 1)
914          return PySSL_SetError(self, ret, __FILE__, __LINE__);
915  
916      if (self->peer_cert)
917          X509_free (self->peer_cert);
918      PySSL_BEGIN_ALLOW_THREADS
919 -    if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) {
920 -        X509_NAME_oneline(X509_get_subject_name(self->peer_cert),
921 -                          self->server, X509_NAME_MAXLEN);
922 -        X509_NAME_oneline(X509_get_issuer_name(self->peer_cert),
923 -                          self->issuer, X509_NAME_MAXLEN);
924 -    }
925 +    self->peer_cert = SSL_get_peer_certificate(self->ssl);
926      PySSL_END_ALLOW_THREADS
927 +    self->handshake_done = 1;
928  
929      Py_INCREF(Py_None);
930      return Py_None;
931 -}
932 -
933 -static PyObject *
934 -PySSL_server(PySSLObject *self)
935 -{
936 -    return PyString_FromString(self->server);
937 -}
938  
939 -static PyObject *
940 -PySSL_issuer(PySSLObject *self)
941 -{
942 -    return PyString_FromString(self->issuer);
943 +error:
944 +    Py_DECREF(sock);
945 +    return NULL;
946  }
947  
948  static PyObject *
949 @@ -634,8 +694,8 @@ _create_tuple_for_X509_NAME (X509_NAME *
950          /*
951          fprintf(stderr, "RDN level %d, attribute %s: %s\n",
952              entry->set,
953 -            PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
954 -            PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
955 +            PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
956 +            PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
957          */
958          if (attr == NULL)
959              goto fail1;
960 @@ -722,21 +782,24 @@ _get_peer_alt_names (X509 *certificate)
961          /* now decode the altName */
962          ext = X509_get_ext(certificate, i);
963          if(!(method = X509V3_EXT_get(ext))) {
964 -            PyErr_SetString(PySSLErrorObject,
965 -                            ERRSTR("No method for internalizing subjectAltName!"));
966 +            PyErr_SetString
967 +              (PySSLErrorObject,
968 +               ERRSTR("No method for internalizing subjectAltName!"));
969              goto fail;
970          }
971  
972          p = ext->value->data;
973          if (method->it)
974 -            names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL,
975 -                                                    &p,
976 -                                                    ext->value->length,
977 -                                                    ASN1_ITEM_ptr(method->it)));
978 +            names = (GENERAL_NAMES*)
979 +              (ASN1_item_d2i(NULL,
980 +                             &p,
981 +                             ext->value->length,
982 +                             ASN1_ITEM_ptr(method->it)));
983          else
984 -            names = (GENERAL_NAMES*) (method->d2i(NULL,
985 -                                                  &p,
986 -                                                  ext->value->length));
987 +            names = (GENERAL_NAMES*)
988 +              (method->d2i(NULL,
989 +                           &p,
990 +                           ext->value->length));
991  
992          for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
993  
994 @@ -885,7 +948,127 @@ _get_peer_alt_names (X509 *certificate)
995  }
996  
997  static PyObject *
998 -_decode_certificate (X509 *certificate, int verbose) {
999 +_get_aia_uri(X509 *certificate, int nid) {
1000 +    PyObject *lst = NULL, *ostr = NULL;
1001 +    int i, result;
1002 +    AUTHORITY_INFO_ACCESS *info;
1003 +
1004 +    info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
1005 +    if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
1006 +        return Py_None;
1007 +    }
1008 +
1009 +    if ((lst = PyList_New(0)) == NULL) {
1010 +        goto fail;
1011 +    }
1012 +
1013 +    for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1014 +        ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1015 +        ASN1_IA5STRING *uri;
1016 +
1017 +        if ((OBJ_obj2nid(ad->method) != nid) ||
1018 +                (ad->location->type != GEN_URI)) {
1019 +            continue;
1020 +        }
1021 +        uri = ad->location->d.uniformResourceIdentifier;
1022 +        ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1023 +                                           uri->length);
1024 +        if (ostr == NULL) {
1025 +            goto fail;
1026 +        }
1027 +        result = PyList_Append(lst, ostr);
1028 +        Py_DECREF(ostr);
1029 +        if (result < 0) {
1030 +            goto fail;
1031 +        }
1032 +    }
1033 +    AUTHORITY_INFO_ACCESS_free(info);
1034 +
1035 +    /* convert to tuple or None */
1036 +    if (PyList_Size(lst) == 0) {
1037 +        Py_DECREF(lst);
1038 +        return Py_None;
1039 +    } else {
1040 +        PyObject *tup;
1041 +        tup = PyList_AsTuple(lst);
1042 +        Py_DECREF(lst);
1043 +        return tup;
1044 +    }
1045 +
1046 +  fail:
1047 +    AUTHORITY_INFO_ACCESS_free(info);
1048 +    Py_XDECREF(lst);
1049 +    return NULL;
1050 +}
1051 +
1052 +static PyObject *
1053 +_get_crl_dp(X509 *certificate) {
1054 +    STACK_OF(DIST_POINT) *dps;
1055 +    int i, j, result;
1056 +    PyObject *lst;
1057 +
1058 +#if OPENSSL_VERSION_NUMBER < 0x10001000L
1059 +    dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1060 +                           NULL, NULL);
1061 +#else
1062 +    /* Calls x509v3_cache_extensions and sets up crldp */
1063 +    X509_check_ca(certificate);
1064 +    dps = certificate->crldp;
1065 +#endif
1066 +
1067 +    if (dps == NULL) {
1068 +        return Py_None;
1069 +    }
1070 +
1071 +    if ((lst = PyList_New(0)) == NULL) {
1072 +        return NULL;
1073 +    }
1074 +
1075 +    for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1076 +        DIST_POINT *dp;
1077 +        STACK_OF(GENERAL_NAME) *gns;
1078 +
1079 +        dp = sk_DIST_POINT_value(dps, i);
1080 +        gns = dp->distpoint->name.fullname;
1081 +
1082 +        for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1083 +            GENERAL_NAME *gn;
1084 +            ASN1_IA5STRING *uri;
1085 +            PyObject *ouri;
1086 +
1087 +            gn = sk_GENERAL_NAME_value(gns, j);
1088 +            if (gn->type != GEN_URI) {
1089 +                continue;
1090 +            }
1091 +            uri = gn->d.uniformResourceIdentifier;
1092 +            ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1093 +                                               uri->length);
1094 +            if (ouri == NULL) {
1095 +                Py_DECREF(lst);
1096 +                return NULL;
1097 +            }
1098 +            result = PyList_Append(lst, ouri);
1099 +            Py_DECREF(ouri);
1100 +            if (result < 0) {
1101 +                Py_DECREF(lst);
1102 +                return NULL;
1103 +            }
1104 +        }
1105 +    }
1106 +    /* convert to tuple or None */
1107 +    if (PyList_Size(lst) == 0) {
1108 +        Py_DECREF(lst);
1109 +        return Py_None;
1110 +    } else {
1111 +        PyObject *tup;
1112 +        tup = PyList_AsTuple(lst);
1113 +        Py_DECREF(lst);
1114 +        return tup;
1115 +    }
1116 +}
1117 +
1118 +static PyObject *
1119 +_decode_certificate(X509 *certificate) {
1120  
1121      PyObject *retval = NULL;
1122      BIO *biobuf = NULL;
1123 @@ -894,9 +1077,10 @@ _decode_certificate (X509 *certificate,
1124      PyObject *issuer;
1125      PyObject *version;
1126      PyObject *sn_obj;
1127 +    PyObject *obj;
1128      ASN1_INTEGER *serialNumber;
1129      char buf[2048];
1130 -    int len;
1131 +    int len, result;
1132      ASN1_TIME *notBefore, *notAfter;
1133      PyObject *pnotBefore, *pnotAfter;
1134  
1135 @@ -914,65 +1098,62 @@ _decode_certificate (X509 *certificate,
1136      }
1137      Py_DECREF(peer);
1138  
1139 -    if (verbose) {
1140 -        issuer = _create_tuple_for_X509_NAME(
1141 -            X509_get_issuer_name(certificate));
1142 -        if (issuer == NULL)
1143 -            goto fail0;
1144 -        if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
1145 -            Py_DECREF(issuer);
1146 -            goto fail0;
1147 -        }
1148 +    issuer = _create_tuple_for_X509_NAME(
1149 +        X509_get_issuer_name(certificate));
1150 +    if (issuer == NULL)
1151 +        goto fail0;
1152 +    if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
1153          Py_DECREF(issuer);
1154 +        goto fail0;
1155 +    }
1156 +    Py_DECREF(issuer);
1157  
1158 -        version = PyInt_FromLong(X509_get_version(certificate) + 1);
1159 -        if (PyDict_SetItemString(retval, "version", version) < 0) {
1160 -            Py_DECREF(version);
1161 -            goto fail0;
1162 -        }
1163 +    version = PyLong_FromLong(X509_get_version(certificate) + 1);
1164 +    if (version == NULL)
1165 +        goto fail0;
1166 +    if (PyDict_SetItemString(retval, "version", version) < 0) {
1167          Py_DECREF(version);
1168 +        goto fail0;
1169      }
1170 +    Py_DECREF(version);
1171  
1172      /* get a memory buffer */
1173      biobuf = BIO_new(BIO_s_mem());
1174  
1175 -    if (verbose) {
1176 -
1177 -        (void) BIO_reset(biobuf);
1178 -        serialNumber = X509_get_serialNumber(certificate);
1179 -        /* should not exceed 20 octets, 160 bits, so buf is big enough */
1180 -        i2a_ASN1_INTEGER(biobuf, serialNumber);
1181 -        len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1182 -        if (len < 0) {
1183 -            _setSSLError(NULL, 0, __FILE__, __LINE__);
1184 -            goto fail1;
1185 -        }
1186 -        sn_obj = PyString_FromStringAndSize(buf, len);
1187 -        if (sn_obj == NULL)
1188 -            goto fail1;
1189 -        if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1190 -            Py_DECREF(sn_obj);
1191 -            goto fail1;
1192 -        }
1193 +    (void) BIO_reset(biobuf);
1194 +    serialNumber = X509_get_serialNumber(certificate);
1195 +    /* should not exceed 20 octets, 160 bits, so buf is big enough */
1196 +    i2a_ASN1_INTEGER(biobuf, serialNumber);
1197 +    len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1198 +    if (len < 0) {
1199 +        _setSSLError(NULL, 0, __FILE__, __LINE__);
1200 +        goto fail1;
1201 +    }
1202 +    sn_obj = PyUnicode_FromStringAndSize(buf, len);
1203 +    if (sn_obj == NULL)
1204 +        goto fail1;
1205 +    if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1206          Py_DECREF(sn_obj);
1207 +        goto fail1;
1208 +    }
1209 +    Py_DECREF(sn_obj);
1210  
1211 -        (void) BIO_reset(biobuf);
1212 -        notBefore = X509_get_notBefore(certificate);
1213 -        ASN1_TIME_print(biobuf, notBefore);
1214 -        len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1215 -        if (len < 0) {
1216 -            _setSSLError(NULL, 0, __FILE__, __LINE__);
1217 -            goto fail1;
1218 -        }
1219 -        pnotBefore = PyString_FromStringAndSize(buf, len);
1220 -        if (pnotBefore == NULL)
1221 -            goto fail1;
1222 -        if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1223 -            Py_DECREF(pnotBefore);
1224 -            goto fail1;
1225 -        }
1226 +    (void) BIO_reset(biobuf);
1227 +    notBefore = X509_get_notBefore(certificate);
1228 +    ASN1_TIME_print(biobuf, notBefore);
1229 +    len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1230 +    if (len < 0) {
1231 +        _setSSLError(NULL, 0, __FILE__, __LINE__);
1232 +        goto fail1;
1233 +    }
1234 +    pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1235 +    if (pnotBefore == NULL)
1236 +        goto fail1;
1237 +    if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1238          Py_DECREF(pnotBefore);
1239 +        goto fail1;
1240      }
1241 +    Py_DECREF(pnotBefore);
1242  
1243      (void) BIO_reset(biobuf);
1244      notAfter = X509_get_notAfter(certificate);
1245 @@ -1005,6 +1186,41 @@ _decode_certificate (X509 *certificate,
1246          Py_DECREF(peer_alt_names);
1247      }
1248  
1249 +    /* Authority Information Access: OCSP URIs */
1250 +    obj = _get_aia_uri(certificate, NID_ad_OCSP);
1251 +    if (obj == NULL) {
1252 +        goto fail1;
1253 +    } else if (obj != Py_None) {
1254 +        result = PyDict_SetItemString(retval, "OCSP", obj);
1255 +        Py_DECREF(obj);
1256 +        if (result < 0) {
1257 +            goto fail1;
1258 +        }
1259 +    }
1260 +
1261 +    obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1262 +    if (obj == NULL) {
1263 +        goto fail1;
1264 +    } else if (obj != Py_None) {
1265 +        result = PyDict_SetItemString(retval, "caIssuers", obj);
1266 +        Py_DECREF(obj);
1267 +        if (result < 0) {
1268 +            goto fail1;
1269 +        }
1270 +    }
1271 +
1272 +    /* CDP (CRL distribution points) */
1273 +    obj = _get_crl_dp(certificate);
1274 +    if (obj == NULL) {
1275 +        goto fail1;
1276 +    } else if (obj != Py_None) {
1277 +        result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1278 +        Py_DECREF(obj);
1279 +        if (result < 0) {
1280 +            goto fail1;
1281 +        }
1282 +    }
1283 +
1284      BIO_free(biobuf);
1285      return retval;
1286  
1287 @@ -1016,6 +1232,24 @@ _decode_certificate (X509 *certificate,
1288      return NULL;
1289  }
1290  
1291 +static PyObject *
1292 +_certificate_to_der(X509 *certificate)
1293 +{
1294 +    unsigned char *bytes_buf = NULL;
1295 +    int len;
1296 +    PyObject *retval;
1297 +
1298 +    bytes_buf = NULL;
1299 +    len = i2d_X509(certificate, &bytes_buf);
1300 +    if (len < 0) {
1301 +        _setSSLError(NULL, 0, __FILE__, __LINE__);
1302 +        return NULL;
1303 +    }
1304 +    /* this is actually an immutable bytes sequence */
1305 +    retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1306 +    OPENSSL_free(bytes_buf);
1307 +    return retval;
1308 +}
1309  
1310  static PyObject *
1311  PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1312 @@ -1024,28 +1258,30 @@ PySSL_test_decode_certificate (PyObject
1313      char *filename = NULL;
1314      X509 *x=NULL;
1315      BIO *cert;
1316 -    int verbose = 1;
1317  
1318 -    if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose))
1319 +    if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
1320          return NULL;
1321  
1322      if ((cert=BIO_new(BIO_s_file())) == NULL) {
1323 -        PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file");
1324 +        PyErr_SetString(PySSLErrorObject,
1325 +                        "Can't malloc memory to read file");
1326          goto fail0;
1327      }
1328  
1329      if (BIO_read_filename(cert,filename) <= 0) {
1330 -        PyErr_SetString(PySSLErrorObject, "Can't open file");
1331 +        PyErr_SetString(PySSLErrorObject,
1332 +                        "Can't open file");
1333          goto fail0;
1334      }
1335  
1336      x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1337      if (x == NULL) {
1338 -        PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file");
1339 +        PyErr_SetString(PySSLErrorObject,
1340 +                        "Error decoding PEM-encoded file");
1341          goto fail0;
1342      }
1343  
1344 -    retval = _decode_certificate(x, verbose);
1345 +    retval = _decode_certificate(x);
1346      X509_free(x);
1347  
1348    fail0:
1349 @@ -1056,10 +1292,8 @@ PySSL_test_decode_certificate (PyObject
1350  
1351  
1352  static PyObject *
1353 -PySSL_peercert(PySSLObject *self, PyObject *args)
1354 +PySSL_peercert(PySSLSocket *self, PyObject *args)
1355  {
1356 -    PyObject *retval = NULL;
1357 -    int len;
1358      int verification;
1359      PyObject *binary_mode = Py_None;
1360      int b;
1361 @@ -1067,6 +1301,11 @@ PySSL_peercert(PySSLObject *self, PyObje
1362      if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1363          return NULL;
1364  
1365 +    if (!self->handshake_done) {
1366 +        PyErr_SetString(PyExc_ValueError,
1367 +                        "handshake not done yet");
1368 +        return NULL;
1369 +    }
1370      if (!self->peer_cert)
1371          Py_RETURN_NONE;
1372  
1373 @@ -1075,26 +1314,13 @@ PySSL_peercert(PySSLObject *self, PyObje
1374          return NULL;
1375      if (b) {
1376          /* return cert in DER-encoded format */
1377 -
1378 -        unsigned char *bytes_buf = NULL;
1379 -
1380 -        bytes_buf = NULL;
1381 -        len = i2d_X509(self->peer_cert, &bytes_buf);
1382 -        if (len < 0) {
1383 -            PySSL_SetError(self, len, __FILE__, __LINE__);
1384 -            return NULL;
1385 -        }
1386 -        retval = PyString_FromStringAndSize((const char *) bytes_buf, len);
1387 -        OPENSSL_free(bytes_buf);
1388 -        return retval;
1389 -
1390 +        return _certificate_to_der(self->peer_cert);
1391      } else {
1392 -
1393 -        verification = SSL_CTX_get_verify_mode(self->ctx);
1394 +        verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
1395          if ((verification & SSL_VERIFY_PEER) == 0)
1396              return PyDict_New();
1397          else
1398 -            return _decode_certificate (self->peer_cert, 0);
1399 +            return _decode_certificate(self->peer_cert);
1400      }
1401  }
1402  
1403 @@ -1110,7 +1336,7 @@ If the optional argument is True, return
1404  peer certificate, or None if no certificate was provided.  This will\n\
1405  return the certificate even if it wasn't validated.");
1406  
1407 -static PyObject *PySSL_cipher (PySSLObject *self) {
1408 +static PyObject *PySSL_cipher (PySSLSocket *self) {
1409  
1410      PyObject *retval, *v;
1411      const SSL_CIPHER *current;
1412 @@ -1137,7 +1363,7 @@ static PyObject *PySSL_cipher (PySSLObje
1413              goto fail0;
1414          PyTuple_SET_ITEM(retval, 0, v);
1415      }
1416 -    cipher_protocol = SSL_CIPHER_get_version(current);
1417 +    cipher_protocol = (char *) SSL_CIPHER_get_version(current);
1418      if (cipher_protocol == NULL) {
1419          Py_INCREF(Py_None);
1420          PyTuple_SET_ITEM(retval, 1, Py_None);
1421 @@ -1158,15 +1384,85 @@ static PyObject *PySSL_cipher (PySSLObje
1422      return NULL;
1423  }
1424  
1425 -static void PySSL_dealloc(PySSLObject *self)
1426 +#ifdef OPENSSL_NPN_NEGOTIATED
1427 +static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1428 +    const unsigned char *out;
1429 +    unsigned int outlen;
1430 +
1431 +    SSL_get0_next_proto_negotiated(self->ssl,
1432 +                                   &out, &outlen);
1433 +
1434 +    if (out == NULL)
1435 +        Py_RETURN_NONE;
1436 +    return PyUnicode_FromStringAndSize((char *) out, outlen);
1437 +}
1438 +#endif
1439 +
1440 +static PyObject *PySSL_compression(PySSLSocket *self) {
1441 +#ifdef OPENSSL_NO_COMP
1442 +    Py_RETURN_NONE;
1443 +#else
1444 +    const COMP_METHOD *comp_method;
1445 +    const char *short_name;
1446 +
1447 +    if (self->ssl == NULL)
1448 +        Py_RETURN_NONE;
1449 +    comp_method = SSL_get_current_compression(self->ssl);
1450 +    if (comp_method == NULL || comp_method->type == NID_undef)
1451 +        Py_RETURN_NONE;
1452 +    short_name = OBJ_nid2sn(comp_method->type);
1453 +    if (short_name == NULL)
1454 +        Py_RETURN_NONE;
1455 +    return PyBytes_FromString(short_name);
1456 +#endif
1457 +}
1458 +
1459 +static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1460 +    Py_INCREF(self->ctx);
1461 +    return self->ctx;
1462 +}
1463 +
1464 +static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1465 +                                   void *closure) {
1466 +
1467 +    if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1468 +#if !HAVE_SNI
1469 +        PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1470 +                        "context is not supported by your OpenSSL library");
1471 +        return -1;
1472 +#else
1473 +        Py_INCREF(value);
1474 +        Py_DECREF(self->ctx);
1475 +        self->ctx = (PySSLContext *) value;
1476 +        SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1477 +#endif
1478 +    } else {
1479 +        PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1480 +        return -1;
1481 +    }
1482 +
1483 +    return 0;
1484 +}
1485 +
1486 +PyDoc_STRVAR(PySSL_set_context_doc,
1487 +"_setter_context(ctx)\n\
1488 +\
1489 +This changes the context associated with the SSLSocket. This is typically\n\
1490 +used from within a callback function set by the set_servername_callback\n\
1491 +on the SSLContext to change the certificate information associated with the\n\
1492 +SSLSocket before the cryptographic exchange handshake messages\n");
1493 +
1494 +
1495 +
1496 +static void PySSL_dealloc(PySSLSocket *self)
1497  {
1498      if (self->peer_cert)        /* Possible not to have one? */
1499          X509_free (self->peer_cert);
1500      if (self->ssl)
1501          SSL_free(self->ssl);
1502 -    if (self->ctx)
1503 -        SSL_CTX_free(self->ctx);
1504      Py_XDECREF(self->Socket);
1505 +    Py_XDECREF(self->ssl_sock);
1506 +    Py_XDECREF(self->ctx);
1507      PyObject_Del(self);
1508  }
1509  
1510 @@ -1238,16 +1534,21 @@ normal_return:
1511      return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
1512  }
1513  
1514 -static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1515 +static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
1516  {
1517      Py_buffer buf;
1518      int len;
1519      int sockstate;
1520      int err;
1521      int nonblocking;
1522 +    PySocketSockObject *sock = self->Socket;
1523 +
1524 +    Py_INCREF(sock);
1525  
1526 -    if (!PyArg_ParseTuple(args, "s*:write", &buf))
1527 +    if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1528 +        Py_DECREF(sock);
1529          return NULL;
1530 +    }
1531  
1532      if (buf.len > INT_MAX) {
1533          PyErr_Format(PyExc_OverflowError,
1534 @@ -1256,11 +1557,11 @@ static PyObject *PySSL_SSLwrite(PySSLObj
1535      }
1536  
1537      /* just in case the blocking state of the socket has been changed */
1538 -    nonblocking = (self->Socket->sock_timeout >= 0.0);
1539 +    nonblocking = (sock->sock_timeout >= 0.0);
1540      BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1541      BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1542  
1543 -    sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1544 +    sockstate = check_socket_and_wait_for_timeout(sock, 1);
1545      if (sockstate == SOCKET_HAS_TIMED_OUT) {
1546          PyErr_SetString(PySSLErrorObject,
1547                          "The write operation timed out");
1548 @@ -1283,9 +1584,9 @@ static PyObject *PySSL_SSLwrite(PySSLObj
1549              goto error;
1550          }
1551          if (err == SSL_ERROR_WANT_READ) {
1552 -            sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1553 +            sockstate = check_socket_and_wait_for_timeout(sock, 0);
1554          } else if (err == SSL_ERROR_WANT_WRITE) {
1555 -            sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1556 +            sockstate = check_socket_and_wait_for_timeout(sock, 1);
1557          } else {
1558              sockstate = SOCKET_OPERATION_OK;
1559          }
1560 @@ -1302,6 +1603,7 @@ static PyObject *PySSL_SSLwrite(PySSLObj
1561          }
1562      } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1563  
1564 +    Py_DECREF(sock);
1565      PyBuffer_Release(&buf);
1566      if (len > 0)
1567          return PyInt_FromLong(len);
1568 @@ -1309,6 +1611,7 @@ static PyObject *PySSL_SSLwrite(PySSLObj
1569          return PySSL_SetError(self, len, __FILE__, __LINE__);
1570  
1571  error:
1572 +    Py_DECREF(sock);
1573      PyBuffer_Release(&buf);
1574      return NULL;
1575  }
1576 @@ -1319,7 +1622,7 @@ PyDoc_STRVAR(PySSL_SSLwrite_doc,
1577  Writes the string s into the SSL object.  Returns the number\n\
1578  of bytes written.");
1579  
1580 -static PyObject *PySSL_SSLpending(PySSLObject *self)
1581 +static PyObject *PySSL_SSLpending(PySSLSocket *self)
1582  {
1583      int count = 0;
1584  
1585 @@ -1338,23 +1641,46 @@ PyDoc_STRVAR(PySSL_SSLpending_doc,
1586  Returns the number of already decrypted bytes available for read,\n\
1587  pending on the connection.\n");
1588  
1589 -static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1590 +static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
1591  {
1592 -    PyObject *buf;
1593 -    int count = 0;
1594 -    int len = 1024;
1595 +    PyObject *dest = NULL;
1596 +    Py_buffer buf;
1597 +    char *mem;
1598 +    int len, count;
1599 +    int buf_passed = 0;
1600      int sockstate;
1601      int err;
1602      int nonblocking;
1603 +    PySocketSockObject *sock = self->Socket;
1604  
1605 -    if (!PyArg_ParseTuple(args, "|i:read", &len))
1606 -        return NULL;
1607 +    Py_INCREF(sock);
1608  
1609 -    if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
1610 -        return NULL;
1611 +    buf.obj = NULL;
1612 +    buf.buf = NULL;
1613 +    if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1614 +        goto error;
1615 +
1616 +    if ((buf.buf == NULL) && (buf.obj == NULL)) {
1617 +        dest = PyBytes_FromStringAndSize(NULL, len);
1618 +        if (dest == NULL)
1619 +            goto error;
1620 +        mem = PyBytes_AS_STRING(dest);
1621 +    }
1622 +    else {
1623 +        buf_passed = 1;
1624 +        mem = buf.buf;
1625 +        if (len <= 0 || len > buf.len) {
1626 +            len = (int) buf.len;
1627 +            if (buf.len != len) {
1628 +                PyErr_SetString(PyExc_OverflowError,
1629 +                                "maximum length can't fit in a C 'int'");
1630 +                goto error;
1631 +            }
1632 +        }
1633 +    }
1634  
1635      /* just in case the blocking state of the socket has been changed */
1636 -    nonblocking = (self->Socket->sock_timeout >= 0.0);
1637 +    nonblocking = (sock->sock_timeout >= 0.0);
1638      BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1639      BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1640  
1641 @@ -1364,70 +1690,71 @@ static PyObject *PySSL_SSLread(PySSLObje
1642      PySSL_END_ALLOW_THREADS
1643  
1644      if (!count) {
1645 -        sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1646 +        sockstate = check_socket_and_wait_for_timeout(sock, 0);
1647          if (sockstate == SOCKET_HAS_TIMED_OUT) {
1648              PyErr_SetString(PySSLErrorObject,
1649                              "The read operation timed out");
1650 -            Py_DECREF(buf);
1651 -            return NULL;
1652 +            goto error;
1653          } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1654              PyErr_SetString(PySSLErrorObject,
1655                              "Underlying socket too large for select().");
1656 -            Py_DECREF(buf);
1657 -            return NULL;
1658 +            goto error;
1659          } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1660 -            if (SSL_get_shutdown(self->ssl) !=
1661 -                SSL_RECEIVED_SHUTDOWN)
1662 -            {
1663 -                Py_DECREF(buf);
1664 -                PyErr_SetString(PySSLErrorObject,
1665 -                                "Socket closed without SSL shutdown handshake");
1666 -                return NULL;
1667 -            } else {
1668 -                /* should contain a zero-length string */
1669 -                _PyString_Resize(&buf, 0);
1670 -                return buf;
1671 -            }
1672 +            count = 0;
1673 +            goto done;
1674          }
1675      }
1676      do {
1677          PySSL_BEGIN_ALLOW_THREADS
1678 -        count = SSL_read(self->ssl, PyString_AsString(buf), len);
1679 +        count = SSL_read(self->ssl, mem, len);
1680          err = SSL_get_error(self->ssl, count);
1681          PySSL_END_ALLOW_THREADS
1682 -        if(PyErr_CheckSignals()) {
1683 -            Py_DECREF(buf);
1684 -            return NULL;
1685 -        }
1686 +        if (PyErr_CheckSignals())
1687 +            goto error;
1688          if (err == SSL_ERROR_WANT_READ) {
1689 -            sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1690 +            sockstate = check_socket_and_wait_for_timeout(sock, 0);
1691          } else if (err == SSL_ERROR_WANT_WRITE) {
1692 -            sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1693 +            sockstate = check_socket_and_wait_for_timeout(sock, 1);
1694          } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1695                     (SSL_get_shutdown(self->ssl) ==
1696                      SSL_RECEIVED_SHUTDOWN))
1697          {
1698 -            _PyString_Resize(&buf, 0);
1699 -            return buf;
1700 +            count = 0;
1701 +            goto done;
1702          } else {
1703              sockstate = SOCKET_OPERATION_OK;
1704          }
1705          if (sockstate == SOCKET_HAS_TIMED_OUT) {
1706              PyErr_SetString(PySSLErrorObject,
1707                              "The read operation timed out");
1708 -            Py_DECREF(buf);
1709 -            return NULL;
1710 +            goto error;
1711          } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1712              break;
1713          }
1714      } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1715      if (count <= 0) {
1716 -        Py_DECREF(buf);
1717 -        return PySSL_SetError(self, count, __FILE__, __LINE__);
1718 +        PySSL_SetError(self, count, __FILE__, __LINE__);
1719 +        goto error;
1720 +    }
1721 +
1722 +done:
1723 +    Py_DECREF(sock);
1724 +    if (!buf_passed) {
1725 +        _PyBytes_Resize(&dest, count);
1726 +        return dest;
1727      }
1728 -    if (count != len)
1729 -        _PyString_Resize(&buf, count);
1730 -    return buf;
1731 +    else {
1732 +        PyBuffer_Release(&buf);
1733 +        return PyLong_FromLong(count);
1734 +    }
1735 +
1736 +error:
1737 +    Py_DECREF(sock);
1738 +    if (!buf_passed)
1739 +        Py_XDECREF(dest);
1740 +    else
1741 +        PyBuffer_Release(&buf);
1742 +    return NULL;
1743  }
1744  
1745  PyDoc_STRVAR(PySSL_SSLread_doc,
1746 @@ -1435,20 +1762,22 @@ PyDoc_STRVAR(PySSL_SSLread_doc,
1747  \n\
1748  Read up to len bytes from the SSL socket.");
1749  
1750 -static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1751 +static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
1752  {
1753      int err, ssl_err, sockstate, nonblocking;
1754      int zeros = 0;
1755 +    PySocketSockObject *sock = self->Socket;
1756  
1757      /* Guard against closed socket */
1758 -    if (self->Socket->sock_fd < 0) {
1759 -        PyErr_SetString(PySSLErrorObject,
1760 -                        "Underlying socket has been closed.");
1761 +    if (sock->sock_fd < 0) {
1762 +        _setSSLError("Underlying socket connection gone",
1763 +                     PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1764          return NULL;
1765      }
1766 +    Py_INCREF(sock);
1767  
1768      /* Just in case the blocking state of the socket has been changed */
1769 -    nonblocking = (self->Socket->sock_timeout >= 0.0);
1770 +    nonblocking = (sock->sock_timeout >= 0.0);
1771      BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1772      BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1773  
1774 @@ -1483,9 +1812,9 @@ static PyObject *PySSL_SSLshutdown(PySSL
1775          /* Possibly retry shutdown until timeout or failure */
1776          ssl_err = SSL_get_error(self->ssl, err);
1777          if (ssl_err == SSL_ERROR_WANT_READ)
1778 -            sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1779 +            sockstate = check_socket_and_wait_for_timeout(sock, 0);
1780          else if (ssl_err == SSL_ERROR_WANT_WRITE)
1781 -            sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1782 +            sockstate = check_socket_and_wait_for_timeout(sock, 1);
1783          else
1784              break;
1785          if (sockstate == SOCKET_HAS_TIMED_OUT) {
1786 @@ -1495,24 +1824,29 @@ static PyObject *PySSL_SSLshutdown(PySSL
1787              else
1788                  PyErr_SetString(PySSLErrorObject,
1789                                  "The write operation timed out");
1790 -            return NULL;
1791 +            goto error;
1792          }
1793          else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1794              PyErr_SetString(PySSLErrorObject,
1795                              "Underlying socket too large for select().");
1796 -            return NULL;
1797 +            goto error;
1798          }
1799          else if (sockstate != SOCKET_OPERATION_OK)
1800              /* Retain the SSL error code */
1801              break;
1802      }
1803  
1804 -    if (err < 0)
1805 +    if (err < 0) {
1806 +        Py_DECREF(sock);
1807          return PySSL_SetError(self, err, __FILE__, __LINE__);
1808 -    else {
1809 -        Py_INCREF(self->Socket);
1810 -        return (PyObject *) (self->Socket);
1811      }
1812 +    else
1813 +        /* It's already INCREF'ed */
1814 +        return (PyObject *) sock;
1815 +
1816 +error:
1817 +    Py_DECREF(sock);
1818 +    return NULL;
1819  }
1820  
1821  PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1822 @@ -1521,6 +1855,47 @@ PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1823  Does the SSL shutdown handshake with the remote end, and returns\n\
1824  the underlying socket object.");
1825  
1826 +#if HAVE_OPENSSL_FINISHED
1827 +static PyObject *
1828 +PySSL_tls_unique_cb(PySSLSocket *self)
1829 +{
1830 +    PyObject *retval = NULL;
1831 +    char buf[PySSL_CB_MAXLEN];
1832 +    size_t len;
1833 +
1834 +    if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1835 +        /* if session is resumed XOR we are the client */
1836 +        len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1837 +    }
1838 +    else {
1839 +        /* if a new session XOR we are the server */
1840 +        len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1841 +    }
1842 +
1843 +    /* It cannot be negative in current OpenSSL version as of July 2011 */
1844 +    if (len == 0)
1845 +        Py_RETURN_NONE;
1846 +
1847 +    retval = PyBytes_FromStringAndSize(buf, len);
1848 +
1849 +    return retval;
1850 +}
1851 +
1852 +PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1853 +"tls_unique_cb() -> bytes\n\
1854 +\n\
1855 +Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1856 +\n\
1857 +If the TLS handshake is not yet complete, None is returned");
1858 +
1859 +#endif /* HAVE_OPENSSL_FINISHED */
1860 +
1861 +static PyGetSetDef ssl_getsetlist[] = {
1862 +    {"context", (getter) PySSL_get_context,
1863 +                (setter) PySSL_set_context, PySSL_set_context_doc},
1864 +    {NULL},            /* sentinel */
1865 +};
1866 +
1867  static PyMethodDef PySSLMethods[] = {
1868      {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1869      {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1870 @@ -1529,118 +1904,1786 @@ static PyMethodDef PySSLMethods[] = {
1871       PySSL_SSLread_doc},
1872      {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1873       PySSL_SSLpending_doc},
1874 -    {"server", (PyCFunction)PySSL_server, METH_NOARGS},
1875 -    {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
1876      {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1877       PySSL_peercert_doc},
1878      {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1879 +#ifdef OPENSSL_NPN_NEGOTIATED
1880 +    {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1881 +#endif
1882 +    {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
1883      {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1884       PySSL_SSLshutdown_doc},
1885 +#if HAVE_OPENSSL_FINISHED
1886 +    {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1887 +     PySSL_tls_unique_cb_doc},
1888 +#endif
1889      {NULL, NULL}
1890  };
1891  
1892 -static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1893 -{
1894 -    return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
1895 -}
1896 -
1897 -static PyTypeObject PySSL_Type = {
1898 +static PyTypeObject PySSLSocket_Type = {
1899      PyVarObject_HEAD_INIT(NULL, 0)
1900 -    "ssl.SSLContext",                   /*tp_name*/
1901 -    sizeof(PySSLObject),                /*tp_basicsize*/
1902 +    "_ssl._SSLSocket",                  /*tp_name*/
1903 +    sizeof(PySSLSocket),                /*tp_basicsize*/
1904      0,                                  /*tp_itemsize*/
1905      /* methods */
1906      (destructor)PySSL_dealloc,          /*tp_dealloc*/
1907      0,                                  /*tp_print*/
1908 -    (getattrfunc)PySSL_getattr,         /*tp_getattr*/
1909 +    0,                                  /*tp_getattr*/
1910      0,                                  /*tp_setattr*/
1911 -    0,                                  /*tp_compare*/
1912 +    0,                                  /*tp_reserved*/
1913      0,                                  /*tp_repr*/
1914      0,                                  /*tp_as_number*/
1915      0,                                  /*tp_as_sequence*/
1916      0,                                  /*tp_as_mapping*/
1917      0,                                  /*tp_hash*/
1918 +    0,                                  /*tp_call*/
1919 +    0,                                  /*tp_str*/
1920 +    0,                                  /*tp_getattro*/
1921 +    0,                                  /*tp_setattro*/
1922 +    0,                                  /*tp_as_buffer*/
1923 +    Py_TPFLAGS_DEFAULT,                 /*tp_flags*/
1924 +    0,                                  /*tp_doc*/
1925 +    0,                                  /*tp_traverse*/
1926 +    0,                                  /*tp_clear*/
1927 +    0,                                  /*tp_richcompare*/
1928 +    0,                                  /*tp_weaklistoffset*/
1929 +    0,                                  /*tp_iter*/
1930 +    0,                                  /*tp_iternext*/
1931 +    PySSLMethods,                       /*tp_methods*/
1932 +    0,                                  /*tp_members*/
1933 +    ssl_getsetlist,                     /*tp_getset*/
1934  };
1935  
1936 -#ifdef HAVE_OPENSSL_RAND
1937  
1938 -/* helper routines for seeding the SSL PRNG */
1939 +/*
1940 + * _SSLContext objects
1941 + */
1942 +
1943  static PyObject *
1944 -PySSL_RAND_add(PyObject *self, PyObject *args)
1945 +context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1946  {
1947 -    char *buf;
1948 -    int len;
1949 -    double entropy;
1950 +    char *kwlist[] = {"protocol", NULL};
1951 +    PySSLContext *self;
1952 +    int proto_version = PY_SSL_VERSION_SSL23;
1953 +    long options;
1954 +    SSL_CTX *ctx = NULL;
1955 +
1956 +    if (!PyArg_ParseTupleAndKeywords(
1957 +        args, kwds, "i:_SSLContext", kwlist,
1958 +        &proto_version))
1959 +        return NULL;
1960  
1961 -    if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1962 +    PySSL_BEGIN_ALLOW_THREADS
1963 +    if (proto_version == PY_SSL_VERSION_TLS1)
1964 +        ctx = SSL_CTX_new(TLSv1_method());
1965 +#if HAVE_TLSv1_2
1966 +    else if (proto_version == PY_SSL_VERSION_TLS1_1)
1967 +        ctx = SSL_CTX_new(TLSv1_1_method());
1968 +    else if (proto_version == PY_SSL_VERSION_TLS1_2)
1969 +        ctx = SSL_CTX_new(TLSv1_2_method());
1970 +#endif
1971 +    else if (proto_version == PY_SSL_VERSION_SSL3)
1972 +        ctx = SSL_CTX_new(SSLv3_method());
1973 +#ifndef OPENSSL_NO_SSL2
1974 +    else if (proto_version == PY_SSL_VERSION_SSL2)
1975 +        ctx = SSL_CTX_new(SSLv2_method());
1976 +#endif
1977 +    else if (proto_version == PY_SSL_VERSION_SSL23)
1978 +        ctx = SSL_CTX_new(SSLv23_method());
1979 +    else
1980 +        proto_version = -1;
1981 +    PySSL_END_ALLOW_THREADS
1982 +
1983 +    if (proto_version == -1) {
1984 +        PyErr_SetString(PyExc_ValueError,
1985 +                        "invalid protocol version");
1986          return NULL;
1987 -    RAND_add(buf, len, entropy);
1988 -    Py_INCREF(Py_None);
1989 -    return Py_None;
1990 +    }
1991 +    if (ctx == NULL) {
1992 +        PyErr_SetString(PySSLErrorObject,
1993 +                        "failed to allocate SSL context");
1994 +        return NULL;
1995 +    }
1996 +
1997 +    assert(type != NULL && type->tp_alloc != NULL);
1998 +    self = (PySSLContext *) type->tp_alloc(type, 0);
1999 +    if (self == NULL) {
2000 +        SSL_CTX_free(ctx);
2001 +        return NULL;
2002 +    }
2003 +    self->ctx = ctx;
2004 +#ifdef OPENSSL_NPN_NEGOTIATED
2005 +    self->npn_protocols = NULL;
2006 +#endif
2007 +#ifndef OPENSSL_NO_TLSEXT
2008 +    self->set_hostname = NULL;
2009 +#endif
2010 +    /* Don't check host name by default */
2011 +    self->check_hostname = 0;
2012 +    /* Defaults */
2013 +    SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2014 +    options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2015 +    SSL_CTX_set_options(self->ctx, options);
2016 +
2017 +#ifndef OPENSSL_NO_ECDH
2018 +    /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2019 +       prime256v1 by default.  This is Apache mod_ssl's initialization
2020 +       policy, so we should be safe. */
2021 +#if defined(SSL_CTX_set_ecdh_auto)
2022 +    SSL_CTX_set_ecdh_auto(self->ctx, 1);
2023 +#else
2024 +    {
2025 +        EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2026 +        SSL_CTX_set_tmp_ecdh(self->ctx, key);
2027 +        EC_KEY_free(key);
2028 +    }
2029 +#endif
2030 +#endif
2031 +
2032 +#define SID_CTX "Python"
2033 +    SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2034 +                                   sizeof(SID_CTX));
2035 +#undef SID_CTX
2036 +
2037 +    return (PyObject *)self;
2038  }
2039  
2040 -PyDoc_STRVAR(PySSL_RAND_add_doc,
2041 -"RAND_add(string, entropy)\n\
2042 -\n\
2043 -Mix string into the OpenSSL PRNG state.  entropy (a float) is a lower\n\
2044 -bound on the entropy contained in string.  See RFC 1750.");
2045 +static int
2046 +context_traverse(PySSLContext *self, visitproc visit, void *arg)
2047 +{
2048 +#ifndef OPENSSL_NO_TLSEXT
2049 +    Py_VISIT(self->set_hostname);
2050 +#endif
2051 +    return 0;
2052 +}
2053  
2054 -static PyObject *
2055 -PySSL_RAND_status(PyObject *self)
2056 +static int
2057 +context_clear(PySSLContext *self)
2058  {
2059 -    return PyInt_FromLong(RAND_status());
2060 +#ifndef OPENSSL_NO_TLSEXT
2061 +    Py_CLEAR(self->set_hostname);
2062 +#endif
2063 +    return 0;
2064  }
2065  
2066 -PyDoc_STRVAR(PySSL_RAND_status_doc,
2067 -"RAND_status() -> 0 or 1\n\
2068 -\n\
2069 -Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2070 -It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2071 -using the ssl() function.");
2072 +static void
2073 +context_dealloc(PySSLContext *self)
2074 +{
2075 +    context_clear(self);
2076 +    SSL_CTX_free(self->ctx);
2077 +#ifdef OPENSSL_NPN_NEGOTIATED
2078 +    PyMem_Free(self->npn_protocols);
2079 +#endif
2080 +    Py_TYPE(self)->tp_free(self);
2081 +}
2082  
2083  static PyObject *
2084 -PySSL_RAND_egd(PyObject *self, PyObject *arg)
2085 +set_ciphers(PySSLContext *self, PyObject *args)
2086  {
2087 -    int bytes;
2088 +    int ret;
2089 +    const char *cipherlist;
2090  
2091 -    if (!PyString_Check(arg))
2092 -        return PyErr_Format(PyExc_TypeError,
2093 -                            "RAND_egd() expected string, found %s",
2094 -                            Py_TYPE(arg)->tp_name);
2095 -    bytes = RAND_egd(PyString_AS_STRING(arg));
2096 -    if (bytes == -1) {
2097 +    if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2098 +        return NULL;
2099 +    ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2100 +    if (ret == 0) {
2101 +        /* Clearing the error queue is necessary on some OpenSSL versions,
2102 +           otherwise the error will be reported again when another SSL call
2103 +           is done. */
2104 +        ERR_clear_error();
2105          PyErr_SetString(PySSLErrorObject,
2106 -                        "EGD connection failed or EGD did not return "
2107 -                        "enough data to seed the PRNG");
2108 +                        "No cipher can be selected.");
2109          return NULL;
2110      }
2111 -    return PyInt_FromLong(bytes);
2112 +    Py_RETURN_NONE;
2113  }
2114  
2115 -PyDoc_STRVAR(PySSL_RAND_egd_doc,
2116 -"RAND_egd(path) -> bytes\n\
2117 -\n\
2118 -Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2119 -Returns number of bytes read.  Raises SSLError if connection to EGD\n\
2120 -fails or if it does not provide enough data to seed PRNG.");
2121 +#ifdef OPENSSL_NPN_NEGOTIATED
2122 +/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2123 +static int
2124 +_advertiseNPN_cb(SSL *s,
2125 +                 const unsigned char **data, unsigned int *len,
2126 +                 void *args)
2127 +{
2128 +    PySSLContext *ssl_ctx = (PySSLContext *) args;
2129  
2130 -#endif /* HAVE_OPENSSL_RAND */
2131 +    if (ssl_ctx->npn_protocols == NULL) {
2132 +        *data = (unsigned char *) "";
2133 +        *len = 0;
2134 +    } else {
2135 +        *data = (unsigned char *) ssl_ctx->npn_protocols;
2136 +        *len = ssl_ctx->npn_protocols_len;
2137 +    }
2138  
2139 -/* List of functions exported by this module. */
2140 +    return SSL_TLSEXT_ERR_OK;
2141 +}
2142 +/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2143 +static int
2144 +_selectNPN_cb(SSL *s,
2145 +              unsigned char **out, unsigned char *outlen,
2146 +              const unsigned char *server, unsigned int server_len,
2147 +              void *args)
2148 +{
2149 +    PySSLContext *ssl_ctx = (PySSLContext *) args;
2150 +
2151 +    unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2152 +    int client_len;
2153 +
2154 +    if (client == NULL) {
2155 +        client = (unsigned char *) "";
2156 +        client_len = 0;
2157 +    } else {
2158 +        client_len = ssl_ctx->npn_protocols_len;
2159 +    }
2160 +
2161 +    SSL_select_next_proto(out, outlen,
2162 +                          server, server_len,
2163 +                          client, client_len);
2164 +
2165 +    return SSL_TLSEXT_ERR_OK;
2166 +}
2167 +#endif
2168 +
2169 +static PyObject *
2170 +_set_npn_protocols(PySSLContext *self, PyObject *args)
2171 +{
2172 +#ifdef OPENSSL_NPN_NEGOTIATED
2173 +    Py_buffer protos;
2174 +
2175 +    if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2176 +        return NULL;
2177 +
2178 +    if (self->npn_protocols != NULL) {
2179 +        PyMem_Free(self->npn_protocols);
2180 +    }
2181 +
2182 +    self->npn_protocols = PyMem_Malloc(protos.len);
2183 +    if (self->npn_protocols == NULL) {
2184 +        PyBuffer_Release(&protos);
2185 +        return PyErr_NoMemory();
2186 +    }
2187 +    memcpy(self->npn_protocols, protos.buf, protos.len);
2188 +    self->npn_protocols_len = (int) protos.len;
2189 +
2190 +    /* set both server and client callbacks, because the context can
2191 +     * be used to create both types of sockets */
2192 +    SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2193 +                                          _advertiseNPN_cb,
2194 +                                          self);
2195 +    SSL_CTX_set_next_proto_select_cb(self->ctx,
2196 +                                     _selectNPN_cb,
2197 +                                     self);
2198 +
2199 +    PyBuffer_Release(&protos);
2200 +    Py_RETURN_NONE;
2201 +#else
2202 +    PyErr_SetString(PyExc_NotImplementedError,
2203 +                    "The NPN extension requires OpenSSL 1.0.1 or later.");
2204 +    return NULL;
2205 +#endif
2206 +}
2207 +
2208 +static PyObject *
2209 +get_verify_mode(PySSLContext *self, void *c)
2210 +{
2211 +    switch (SSL_CTX_get_verify_mode(self->ctx)) {
2212 +    case SSL_VERIFY_NONE:
2213 +        return PyLong_FromLong(PY_SSL_CERT_NONE);
2214 +    case SSL_VERIFY_PEER:
2215 +        return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2216 +    case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2217 +        return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2218 +    }
2219 +    PyErr_SetString(PySSLErrorObject,
2220 +                    "invalid return value from SSL_CTX_get_verify_mode");
2221 +    return NULL;
2222 +}
2223 +
2224 +static int
2225 +set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2226 +{
2227 +    int n, mode;
2228 +    if (!PyArg_Parse(arg, "i", &n))
2229 +        return -1;
2230 +    if (n == PY_SSL_CERT_NONE)
2231 +        mode = SSL_VERIFY_NONE;
2232 +    else if (n == PY_SSL_CERT_OPTIONAL)
2233 +        mode = SSL_VERIFY_PEER;
2234 +    else if (n == PY_SSL_CERT_REQUIRED)
2235 +        mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2236 +    else {
2237 +        PyErr_SetString(PyExc_ValueError,
2238 +                        "invalid value for verify_mode");
2239 +        return -1;
2240 +    }
2241 +    if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2242 +        PyErr_SetString(PyExc_ValueError,
2243 +                        "Cannot set verify_mode to CERT_NONE when "
2244 +                        "check_hostname is enabled.");
2245 +        return -1;
2246 +    }
2247 +    SSL_CTX_set_verify(self->ctx, mode, NULL);
2248 +    return 0;
2249 +}
2250 +
2251 +#ifdef HAVE_OPENSSL_VERIFY_PARAM
2252 +static PyObject *
2253 +get_verify_flags(PySSLContext *self, void *c)
2254 +{
2255 +    X509_STORE *store;
2256 +    unsigned long flags;
2257 +
2258 +    store = SSL_CTX_get_cert_store(self->ctx);
2259 +    flags = X509_VERIFY_PARAM_get_flags(store->param);
2260 +    return PyLong_FromUnsignedLong(flags);
2261 +}
2262 +
2263 +static int
2264 +set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2265 +{
2266 +    X509_STORE *store;
2267 +    unsigned long new_flags, flags, set, clear;
2268 +
2269 +    if (!PyArg_Parse(arg, "k", &new_flags))
2270 +        return -1;
2271 +    store = SSL_CTX_get_cert_store(self->ctx);
2272 +    flags = X509_VERIFY_PARAM_get_flags(store->param);
2273 +    clear = flags & ~new_flags;
2274 +    set = ~flags & new_flags;
2275 +    if (clear) {
2276 +        if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2277 +            _setSSLError(NULL, 0, __FILE__, __LINE__);
2278 +            return -1;
2279 +        }
2280 +    }
2281 +    if (set) {
2282 +        if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2283 +            _setSSLError(NULL, 0, __FILE__, __LINE__);
2284 +            return -1;
2285 +        }
2286 +    }
2287 +    return 0;
2288 +}
2289 +#endif
2290 +
2291 +static PyObject *
2292 +get_options(PySSLContext *self, void *c)
2293 +{
2294 +    return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2295 +}
2296 +
2297 +static int
2298 +set_options(PySSLContext *self, PyObject *arg, void *c)
2299 +{
2300 +    long new_opts, opts, set, clear;
2301 +    if (!PyArg_Parse(arg, "l", &new_opts))
2302 +        return -1;
2303 +    opts = SSL_CTX_get_options(self->ctx);
2304 +    clear = opts & ~new_opts;
2305 +    set = ~opts & new_opts;
2306 +    if (clear) {
2307 +#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2308 +        SSL_CTX_clear_options(self->ctx, clear);
2309 +#else
2310 +        PyErr_SetString(PyExc_ValueError,
2311 +                        "can't clear options before OpenSSL 0.9.8m");
2312 +        return -1;
2313 +#endif
2314 +    }
2315 +    if (set)
2316 +        SSL_CTX_set_options(self->ctx, set);
2317 +    return 0;
2318 +}
2319 +
2320 +static PyObject *
2321 +get_check_hostname(PySSLContext *self, void *c)
2322 +{
2323 +    return PyBool_FromLong(self->check_hostname);
2324 +}
2325 +
2326 +static int
2327 +set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2328 +{
2329 +    PyObject *py_check_hostname;
2330 +    int check_hostname;
2331 +    if (!PyArg_Parse(arg, "O", &py_check_hostname))
2332 +        return -1;
2333 +
2334 +    check_hostname = PyObject_IsTrue(py_check_hostname);
2335 +    if (check_hostname < 0)
2336 +        return -1;
2337 +    if (check_hostname &&
2338 +            SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2339 +        PyErr_SetString(PyExc_ValueError,
2340 +                        "check_hostname needs a SSL context with either "
2341 +                        "CERT_OPTIONAL or CERT_REQUIRED");
2342 +        return -1;
2343 +    }
2344 +    self->check_hostname = check_hostname;
2345 +    return 0;
2346 +}
2347 +
2348 +
2349 +typedef struct {
2350 +    PyThreadState *thread_state;
2351 +    PyObject *callable;
2352 +    char *password;
2353 +    int size;
2354 +    int error;
2355 +} _PySSLPasswordInfo;
2356 +
2357 +static int
2358 +_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2359 +            const char *bad_type_error)
2360 +{
2361 +    /* Set the password and size fields of a _PySSLPasswordInfo struct
2362 +       from a unicode, bytes, or byte array object.
2363 +       The password field will be dynamically allocated and must be freed
2364 +       by the caller */
2365 +    PyObject *password_bytes = NULL;
2366 +    const char *data = NULL;
2367 +    Py_ssize_t size;
2368 +
2369 +    if (PyUnicode_Check(password)) {
2370 +        password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2371 +        if (!password_bytes) {
2372 +            goto error;
2373 +        }
2374 +        data = PyBytes_AS_STRING(password_bytes);
2375 +        size = PyBytes_GET_SIZE(password_bytes);
2376 +    } else if (PyBytes_Check(password)) {
2377 +        data = PyBytes_AS_STRING(password);
2378 +        size = PyBytes_GET_SIZE(password);
2379 +    } else if (PyByteArray_Check(password)) {
2380 +        data = PyByteArray_AS_STRING(password);
2381 +        size = PyByteArray_GET_SIZE(password);
2382 +    } else {
2383 +        PyErr_SetString(PyExc_TypeError, bad_type_error);
2384 +        goto error;
2385 +    }
2386 +
2387 +    if (size > (Py_ssize_t)INT_MAX) {
2388 +        PyErr_Format(PyExc_ValueError,
2389 +                     "password cannot be longer than %d bytes", INT_MAX);
2390 +        goto error;
2391 +    }
2392 +
2393 +    PyMem_Free(pw_info->password);
2394 +    pw_info->password = PyMem_Malloc(size);
2395 +    if (!pw_info->password) {
2396 +        PyErr_SetString(PyExc_MemoryError,
2397 +                        "unable to allocate password buffer");
2398 +        goto error;
2399 +    }
2400 +    memcpy(pw_info->password, data, size);
2401 +    pw_info->size = (int)size;
2402 +
2403 +    Py_XDECREF(password_bytes);
2404 +    return 1;
2405 +
2406 +error:
2407 +    Py_XDECREF(password_bytes);
2408 +    return 0;
2409 +}
2410 +
2411 +static int
2412 +_password_callback(char *buf, int size, int rwflag, void *userdata)
2413 +{
2414 +    _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2415 +    PyObject *fn_ret = NULL;
2416 +
2417 +    PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2418 +
2419 +    if (pw_info->callable) {
2420 +        fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2421 +        if (!fn_ret) {
2422 +            /* TODO: It would be nice to move _ctypes_add_traceback() into the
2423 +               core python API, so we could use it to add a frame here */
2424 +            goto error;
2425 +        }
2426 +
2427 +        if (!_pwinfo_set(pw_info, fn_ret,
2428 +                         "password callback must return a string")) {
2429 +            goto error;
2430 +        }
2431 +        Py_CLEAR(fn_ret);
2432 +    }
2433 +
2434 +    if (pw_info->size > size) {
2435 +        PyErr_Format(PyExc_ValueError,
2436 +                     "password cannot be longer than %d bytes", size);
2437 +        goto error;
2438 +    }
2439 +
2440 +    PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2441 +    memcpy(buf, pw_info->password, pw_info->size);
2442 +    return pw_info->size;
2443 +
2444 +error:
2445 +    Py_XDECREF(fn_ret);
2446 +    PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2447 +    pw_info->error = 1;
2448 +    return -1;
2449 +}
2450 +
2451 +static PyObject *
2452 +load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2453 +{
2454 +    char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2455 +    PyObject *password = NULL;
2456 +    char *certfile_bytes = NULL, *keyfile_bytes = NULL;
2457 +    pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2458 +    void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2459 +    _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2460 +    int r;
2461 +
2462 +    errno = 0;
2463 +    ERR_clear_error();
2464 +    if (!PyArg_ParseTupleAndKeywords(args, kwds,
2465 +            "et|etO:load_cert_chain", kwlist,
2466 +            Py_FileSystemDefaultEncoding, &certfile_bytes,
2467 +            Py_FileSystemDefaultEncoding, &keyfile_bytes,
2468 +            &password))
2469 +        return NULL;
2470 +    if (password && password != Py_None) {
2471 +        if (PyCallable_Check(password)) {
2472 +            pw_info.callable = password;
2473 +        } else if (!_pwinfo_set(&pw_info, password,
2474 +                                "password should be a string or callable")) {
2475 +            goto error;
2476 +        }
2477 +        SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2478 +        SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2479 +    }
2480 +    PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2481 +    r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2482 +    PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2483 +    if (r != 1) {
2484 +        if (pw_info.error) {
2485 +            ERR_clear_error();
2486 +            /* the password callback has already set the error information */
2487 +        }
2488 +        else if (errno != 0) {
2489 +            ERR_clear_error();
2490 +            PyErr_SetFromErrno(PyExc_IOError);
2491 +        }
2492 +        else {
2493 +            _setSSLError(NULL, 0, __FILE__, __LINE__);
2494 +        }
2495 +        goto error;
2496 +    }
2497 +    PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2498 +    r = SSL_CTX_use_PrivateKey_file(self->ctx,
2499 +        keyfile_bytes ? keyfile_bytes : certfile_bytes,
2500 +        SSL_FILETYPE_PEM);
2501 +    PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2502 +    if (r != 1) {
2503 +        if (pw_info.error) {
2504 +            ERR_clear_error();
2505 +            /* the password callback has already set the error information */
2506 +        }
2507 +        else if (errno != 0) {
2508 +            ERR_clear_error();
2509 +            PyErr_SetFromErrno(PyExc_IOError);
2510 +        }
2511 +        else {
2512 +            _setSSLError(NULL, 0, __FILE__, __LINE__);
2513 +        }
2514 +        goto error;
2515 +    }
2516 +    PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2517 +    r = SSL_CTX_check_private_key(self->ctx);
2518 +    PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2519 +    if (r != 1) {
2520 +        _setSSLError(NULL, 0, __FILE__, __LINE__);
2521 +        goto error;
2522 +    }
2523 +    SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2524 +    SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2525 +    PyMem_Free(pw_info.password);
2526 +    Py_RETURN_NONE;
2527 +
2528 +error:
2529 +    SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2530 +    SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2531 +    PyMem_Free(pw_info.password);
2532 +    PyMem_Free(keyfile_bytes);
2533 +    PyMem_Free(certfile_bytes);
2534 +    return NULL;
2535 +}
2536 +
2537 +/* internal helper function, returns -1 on error
2538 + */
2539 +static int
2540 +_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2541 +              int filetype)
2542 +{
2543 +    BIO *biobuf = NULL;
2544 +    X509_STORE *store;
2545 +    int retval = 0, err, loaded = 0;
2546 +
2547 +    assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2548 +
2549 +    if (len <= 0) {
2550 +        PyErr_SetString(PyExc_ValueError,
2551 +                        "Empty certificate data");
2552 +        return -1;
2553 +    } else if (len > INT_MAX) {
2554 +        PyErr_SetString(PyExc_OverflowError,
2555 +                        "Certificate data is too long.");
2556 +        return -1;
2557 +    }
2558 +
2559 +    biobuf = BIO_new_mem_buf(data, (int)len);
2560 +    if (biobuf == NULL) {
2561 +        _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2562 +        return -1;
2563 +    }
2564 +
2565 +    store = SSL_CTX_get_cert_store(self->ctx);
2566 +    assert(store != NULL);
2567 +
2568 +    while (1) {
2569 +        X509 *cert = NULL;
2570 +        int r;
2571 +
2572 +        if (filetype == SSL_FILETYPE_ASN1) {
2573 +            cert = d2i_X509_bio(biobuf, NULL);
2574 +        } else {
2575 +            cert = PEM_read_bio_X509(biobuf, NULL,
2576 +                                     self->ctx->default_passwd_callback,
2577 +                                     self->ctx->default_passwd_callback_userdata);
2578 +        }
2579 +        if (cert == NULL) {
2580 +            break;
2581 +        }
2582 +        r = X509_STORE_add_cert(store, cert);
2583 +        X509_free(cert);
2584 +        if (!r) {
2585 +            err = ERR_peek_last_error();
2586 +            if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2587 +                (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2588 +                /* cert already in hash table, not an error */
2589 +                ERR_clear_error();
2590 +            } else {
2591 +                break;
2592 +            }
2593 +        }
2594 +        loaded++;
2595 +    }
2596 +
2597 +    err = ERR_peek_last_error();
2598 +    if ((filetype == SSL_FILETYPE_ASN1) &&
2599 +            (loaded > 0) &&
2600 +            (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2601 +            (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2602 +        /* EOF ASN1 file, not an error */
2603 +        ERR_clear_error();
2604 +        retval = 0;
2605 +    } else if ((filetype == SSL_FILETYPE_PEM) &&
2606 +                   (loaded > 0) &&
2607 +                   (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2608 +                   (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2609 +        /* EOF PEM file, not an error */
2610 +        ERR_clear_error();
2611 +        retval = 0;
2612 +    } else {
2613 +        _setSSLError(NULL, 0, __FILE__, __LINE__);
2614 +        retval = -1;
2615 +    }
2616 +
2617 +    BIO_free(biobuf);
2618 +    return retval;
2619 +}
2620 +
2621 +
2622 +static PyObject *
2623 +load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2624 +{
2625 +    char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2626 +    PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2627 +    PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2628 +    const char *cafile_buf = NULL, *capath_buf = NULL;
2629 +    int r = 0, ok = 1;
2630 +
2631 +    errno = 0;
2632 +    if (!PyArg_ParseTupleAndKeywords(args, kwds,
2633 +            "|OOO:load_verify_locations", kwlist,
2634 +            &cafile, &capath, &cadata))
2635 +        return NULL;
2636 +
2637 +    if (cafile == Py_None)
2638 +        cafile = NULL;
2639 +    if (capath == Py_None)
2640 +        capath = NULL;
2641 +    if (cadata == Py_None)
2642 +        cadata = NULL;
2643 +
2644 +    if (cafile == NULL && capath == NULL && cadata == NULL) {
2645 +        PyErr_SetString(PyExc_TypeError,
2646 +                        "cafile, capath and cadata cannot be all omitted");
2647 +        goto error;
2648 +    }
2649 +
2650 +    if (cafile) {
2651 +        cafile_bytes = PyString_AsEncodedObject(
2652 +            cafile, Py_FileSystemDefaultEncoding, "strict");
2653 +        if (!cafile_bytes) {
2654 +            goto error;
2655 +        }
2656 +    }
2657 +    if (capath) {
2658 +        capath_bytes = PyString_AsEncodedObject(
2659 +            capath, Py_FileSystemDefaultEncoding, "strict");
2660 +        if (!capath_bytes) {
2661 +            goto error;
2662 +        }
2663 +    }
2664 +
2665 +    /* validata cadata type and load cadata */
2666 +    if (cadata) {
2667 +        Py_buffer buf;
2668 +        PyObject *cadata_ascii = NULL;
2669 +
2670 +        if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2671 +            if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2672 +                PyBuffer_Release(&buf);
2673 +                PyErr_SetString(PyExc_TypeError,
2674 +                                "cadata should be a contiguous buffer with "
2675 +                                "a single dimension");
2676 +                goto error;
2677 +            }
2678 +            r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2679 +            PyBuffer_Release(&buf);
2680 +            if (r == -1) {
2681 +                goto error;
2682 +            }
2683 +        } else {
2684 +            PyErr_Clear();
2685 +            cadata_ascii = PyUnicode_AsASCIIString(cadata);
2686 +            if (cadata_ascii == NULL) {
2687 +                PyErr_SetString(PyExc_TypeError,
2688 +                                "cadata should be a ASCII string or a "
2689 +                                "bytes-like object");
2690 +                goto error;
2691 +            }
2692 +            r = _add_ca_certs(self,
2693 +                              PyBytes_AS_STRING(cadata_ascii),
2694 +                              PyBytes_GET_SIZE(cadata_ascii),
2695 +                              SSL_FILETYPE_PEM);
2696 +            Py_DECREF(cadata_ascii);
2697 +            if (r == -1) {
2698 +                goto error;
2699 +            }
2700 +        }
2701 +    }
2702 +
2703 +    /* load cafile or capath */
2704 +    if (cafile_bytes || capath_bytes) {
2705 +        if (cafile)
2706 +            cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2707 +        if (capath)
2708 +            capath_buf = PyBytes_AS_STRING(capath_bytes);
2709 +        PySSL_BEGIN_ALLOW_THREADS
2710 +        r = SSL_CTX_load_verify_locations(
2711 +            self->ctx,
2712 +            cafile_buf,
2713 +            capath_buf);
2714 +        PySSL_END_ALLOW_THREADS
2715 +        if (r != 1) {
2716 +            ok = 0;
2717 +            if (errno != 0) {
2718 +                ERR_clear_error();
2719 +                PyErr_SetFromErrno(PyExc_IOError);
2720 +            }
2721 +            else {
2722 +                _setSSLError(NULL, 0, __FILE__, __LINE__);
2723 +            }
2724 +            goto error;
2725 +        }
2726 +    }
2727 +    goto end;
2728 +
2729 +  error:
2730 +    ok = 0;
2731 +  end:
2732 +    Py_XDECREF(cafile_bytes);
2733 +    Py_XDECREF(capath_bytes);
2734 +    if (ok) {
2735 +        Py_RETURN_NONE;
2736 +    } else {
2737 +        return NULL;
2738 +    }
2739 +}
2740 +
2741 +static PyObject *
2742 +load_dh_params(PySSLContext *self, PyObject *filepath)
2743 +{
2744 +    BIO *bio;
2745 +    DH *dh;
2746 +    char *path = PyBytes_AsString(filepath);
2747 +    if (!path) {
2748 +        return NULL;
2749 +    }
2750 +
2751 +    bio = BIO_new_file(path, "r");
2752 +    if (bio == NULL) {
2753 +        ERR_clear_error();
2754 +        PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
2755 +        return NULL;
2756 +    }
2757 +    errno = 0;
2758 +    PySSL_BEGIN_ALLOW_THREADS
2759 +    dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2760 +    BIO_free(bio);
2761 +    PySSL_END_ALLOW_THREADS
2762 +    if (dh == NULL) {
2763 +        if (errno != 0) {
2764 +            ERR_clear_error();
2765 +            PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2766 +        }
2767 +        else {
2768 +            _setSSLError(NULL, 0, __FILE__, __LINE__);
2769 +        }
2770 +        return NULL;
2771 +    }
2772 +    if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2773 +        _setSSLError(NULL, 0, __FILE__, __LINE__);
2774 +    DH_free(dh);
2775 +    Py_RETURN_NONE;
2776 +}
2777 +
2778 +static PyObject *
2779 +context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2780 +{
2781 +    char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
2782 +    PySocketSockObject *sock;
2783 +    int server_side = 0;
2784 +    char *hostname = NULL;
2785 +    PyObject *hostname_obj, *ssl_sock = Py_None, *res;
2786 +
2787 +    /* server_hostname is either None (or absent), or to be encoded
2788 +       using the idna encoding. */
2789 +    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
2790 +                                     PySocketModule.Sock_Type,
2791 +                                     &sock, &server_side,
2792 +                                     Py_TYPE(Py_None), &hostname_obj,
2793 +                                     &ssl_sock)) {
2794 +        PyErr_Clear();
2795 +        if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
2796 +            PySocketModule.Sock_Type,
2797 +            &sock, &server_side,
2798 +            "idna", &hostname, &ssl_sock))
2799 +            return NULL;
2800 +#if !HAVE_SNI
2801 +        PyMem_Free(hostname);
2802 +        PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2803 +                        "by your OpenSSL library");
2804 +        return NULL;
2805 +#endif
2806 +    }
2807 +
2808 +    res = (PyObject *) newPySSLSocket(self, sock, server_side,
2809 +                                      hostname, ssl_sock);
2810 +    if (hostname != NULL)
2811 +        PyMem_Free(hostname);
2812 +    return res;
2813 +}
2814 +
2815 +static PyObject *
2816 +session_stats(PySSLContext *self, PyObject *unused)
2817 +{
2818 +    int r;
2819 +    PyObject *value, *stats = PyDict_New();
2820 +    if (!stats)
2821 +        return NULL;
2822 +
2823 +#define ADD_STATS(SSL_NAME, KEY_NAME) \
2824 +    value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2825 +    if (value == NULL) \
2826 +        goto error; \
2827 +    r = PyDict_SetItemString(stats, KEY_NAME, value); \
2828 +    Py_DECREF(value); \
2829 +    if (r < 0) \
2830 +        goto error;
2831 +
2832 +    ADD_STATS(number, "number");
2833 +    ADD_STATS(connect, "connect");
2834 +    ADD_STATS(connect_good, "connect_good");
2835 +    ADD_STATS(connect_renegotiate, "connect_renegotiate");
2836 +    ADD_STATS(accept, "accept");
2837 +    ADD_STATS(accept_good, "accept_good");
2838 +    ADD_STATS(accept_renegotiate, "accept_renegotiate");
2839 +    ADD_STATS(accept, "accept");
2840 +    ADD_STATS(hits, "hits");
2841 +    ADD_STATS(misses, "misses");
2842 +    ADD_STATS(timeouts, "timeouts");
2843 +    ADD_STATS(cache_full, "cache_full");
2844 +
2845 +#undef ADD_STATS
2846 +
2847 +    return stats;
2848 +
2849 +error:
2850 +    Py_DECREF(stats);
2851 +    return NULL;
2852 +}
2853 +
2854 +static PyObject *
2855 +set_default_verify_paths(PySSLContext *self, PyObject *unused)
2856 +{
2857 +    if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2858 +        _setSSLError(NULL, 0, __FILE__, __LINE__);
2859 +        return NULL;
2860 +    }
2861 +    Py_RETURN_NONE;
2862 +}
2863 +
2864 +#ifndef OPENSSL_NO_ECDH
2865 +static PyObject *
2866 +set_ecdh_curve(PySSLContext *self, PyObject *name)
2867 +{
2868 +    char *name_bytes;
2869 +    int nid;
2870 +    EC_KEY *key;
2871 +
2872 +    name_bytes = PyBytes_AsString(name);
2873 +    if (!name_bytes) {
2874 +        return NULL;
2875 +    }
2876 +    nid = OBJ_sn2nid(name_bytes);
2877 +    if (nid == 0) {
2878 +        PyErr_Format(PyExc_ValueError,
2879 +                     "unknown elliptic curve name %R", name);
2880 +        return NULL;
2881 +    }
2882 +    key = EC_KEY_new_by_curve_name(nid);
2883 +    if (key == NULL) {
2884 +        _setSSLError(NULL, 0, __FILE__, __LINE__);
2885 +        return NULL;
2886 +    }
2887 +    SSL_CTX_set_tmp_ecdh(self->ctx, key);
2888 +    EC_KEY_free(key);
2889 +    Py_RETURN_NONE;
2890 +}
2891 +#endif
2892 +
2893 +#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
2894 +static int
2895 +_servername_callback(SSL *s, int *al, void *args)
2896 +{
2897 +    int ret;
2898 +    PySSLContext *ssl_ctx = (PySSLContext *) args;
2899 +    PySSLSocket *ssl;
2900 +    PyObject *servername_o;
2901 +    PyObject *servername_idna;
2902 +    PyObject *result;
2903 +    /* The high-level ssl.SSLSocket object */
2904 +    PyObject *ssl_socket;
2905 +    const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2906 +#ifdef WITH_THREAD
2907 +    PyGILState_STATE gstate = PyGILState_Ensure();
2908 +#endif
2909 +
2910 +    if (ssl_ctx->set_hostname == NULL) {
2911 +        /* remove race condition in this the call back while if removing the
2912 +         * callback is in progress */
2913 +#ifdef WITH_THREAD
2914 +        PyGILState_Release(gstate);
2915 +#endif
2916 +        return SSL_TLSEXT_ERR_OK;
2917 +    }
2918 +
2919 +    ssl = SSL_get_app_data(s);
2920 +    assert(PySSLSocket_Check(ssl));
2921 +    ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
2922 +    Py_INCREF(ssl_socket);
2923 +    if (ssl_socket == Py_None) {
2924 +        goto error;
2925 +    }
2926 +
2927 +    if (servername == NULL) {
2928 +        result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2929 +                                              Py_None, ssl_ctx, NULL);
2930 +    }
2931 +    else {
2932 +        servername_o = PyBytes_FromString(servername);
2933 +        if (servername_o == NULL) {
2934 +            PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2935 +            goto error;
2936 +        }
2937 +        servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2938 +        if (servername_idna == NULL) {
2939 +            PyErr_WriteUnraisable(servername_o);
2940 +            Py_DECREF(servername_o);
2941 +            goto error;
2942 +        }
2943 +        Py_DECREF(servername_o);
2944 +        result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2945 +                                              servername_idna, ssl_ctx, NULL);
2946 +        Py_DECREF(servername_idna);
2947 +    }
2948 +    Py_DECREF(ssl_socket);
2949 +
2950 +    if (result == NULL) {
2951 +        PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2952 +        *al = SSL_AD_HANDSHAKE_FAILURE;
2953 +        ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2954 +    }
2955 +    else {
2956 +        if (result != Py_None) {
2957 +            *al = (int) PyLong_AsLong(result);
2958 +            if (PyErr_Occurred()) {
2959 +                PyErr_WriteUnraisable(result);
2960 +                *al = SSL_AD_INTERNAL_ERROR;
2961 +            }
2962 +            ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2963 +        }
2964 +        else {
2965 +            ret = SSL_TLSEXT_ERR_OK;
2966 +        }
2967 +        Py_DECREF(result);
2968 +    }
2969 +
2970 +#ifdef WITH_THREAD
2971 +    PyGILState_Release(gstate);
2972 +#endif
2973 +    return ret;
2974 +
2975 +error:
2976 +    Py_DECREF(ssl_socket);
2977 +    *al = SSL_AD_INTERNAL_ERROR;
2978 +    ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2979 +#ifdef WITH_THREAD
2980 +    PyGILState_Release(gstate);
2981 +#endif
2982 +    return ret;
2983 +}
2984 +#endif
2985 +
2986 +PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2987 +"set_servername_callback(method)\n\
2988 +\n\
2989 +This sets a callback that will be called when a server name is provided by\n\
2990 +the SSL/TLS client in the SNI extension.\n\
2991 +\n\
2992 +If the argument is None then the callback is disabled. The method is called\n\
2993 +with the SSLSocket, the server name as a string, and the SSLContext object.\n\
2994 +See RFC 6066 for details of the SNI extension.");
2995 +
2996 +static PyObject *
2997 +set_servername_callback(PySSLContext *self, PyObject *args)
2998 +{
2999 +#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3000 +    PyObject *cb;
3001 +
3002 +    if (!PyArg_ParseTuple(args, "O", &cb))
3003 +        return NULL;
3004 +
3005 +    Py_CLEAR(self->set_hostname);
3006 +    if (cb == Py_None) {
3007 +        SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3008 +    }
3009 +    else {
3010 +        if (!PyCallable_Check(cb)) {
3011 +            SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3012 +            PyErr_SetString(PyExc_TypeError,
3013 +                            "not a callable object");
3014 +            return NULL;
3015 +        }
3016 +        Py_INCREF(cb);
3017 +        self->set_hostname = cb;
3018 +        SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3019 +        SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3020 +    }
3021 +    Py_RETURN_NONE;
3022 +#else
3023 +    PyErr_SetString(PyExc_NotImplementedError,
3024 +                    "The TLS extension servername callback, "
3025 +                    "SSL_CTX_set_tlsext_servername_callback, "
3026 +                    "is not in the current OpenSSL library.");
3027 +    return NULL;
3028 +#endif
3029 +}
3030 +
3031 +PyDoc_STRVAR(PySSL_get_stats_doc,
3032 +"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3033 +\n\
3034 +Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3035 +CA extension and certificate revocation lists inside the context's cert\n\
3036 +store.\n\
3037 +NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3038 +been used at least once.");
3039 +
3040 +static PyObject *
3041 +cert_store_stats(PySSLContext *self)
3042 +{
3043 +    X509_STORE *store;
3044 +    X509_OBJECT *obj;
3045 +    int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3046 +
3047 +    store = SSL_CTX_get_cert_store(self->ctx);
3048 +    for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3049 +        obj = sk_X509_OBJECT_value(store->objs, i);
3050 +        switch (obj->type) {
3051 +            case X509_LU_X509:
3052 +                x509++;
3053 +                if (X509_check_ca(obj->data.x509)) {
3054 +                    ca++;
3055 +                }
3056 +                break;
3057 +            case X509_LU_CRL:
3058 +                crl++;
3059 +                break;
3060 +            case X509_LU_PKEY:
3061 +                pkey++;
3062 +                break;
3063 +            default:
3064 +                /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3065 +                 * As far as I can tell they are internal states and never
3066 +                 * stored in a cert store */
3067 +                break;
3068 +        }
3069 +    }
3070 +    return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3071 +        "x509_ca", ca);
3072 +}
3073 +
3074 +PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3075 +"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3076 +\n\
3077 +Returns a list of dicts with information of loaded CA certs. If the\n\
3078 +optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3079 +NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3080 +been used at least once.");
3081 +
3082 +static PyObject *
3083 +get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3084 +{
3085 +    char *kwlist[] = {"binary_form", NULL};
3086 +    X509_STORE *store;
3087 +    PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
3088 +    int i;
3089 +    int binary_mode = 0;
3090 +
3091 +    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3092 +                                     kwlist, &py_binary_mode)) {
3093 +        return NULL;
3094 +    }
3095 +    binary_mode = PyObject_IsTrue(py_binary_mode);
3096 +    if (binary_mode < 0) {
3097 +        return NULL;
3098 +    }
3099 +
3100 +    if ((rlist = PyList_New(0)) == NULL) {
3101 +        return NULL;
3102 +    }
3103 +
3104 +    store = SSL_CTX_get_cert_store(self->ctx);
3105 +    for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3106 +        X509_OBJECT *obj;
3107 +        X509 *cert;
3108 +
3109 +        obj = sk_X509_OBJECT_value(store->objs, i);
3110 +        if (obj->type != X509_LU_X509) {
3111 +            /* not a x509 cert */
3112 +            continue;
3113 +        }
3114 +        /* CA for any purpose */
3115 +        cert = obj->data.x509;
3116 +        if (!X509_check_ca(cert)) {
3117 +            continue;
3118 +        }
3119 +        if (binary_mode) {
3120 +            ci = _certificate_to_der(cert);
3121 +        } else {
3122 +            ci = _decode_certificate(cert);
3123 +        }
3124 +        if (ci == NULL) {
3125 +            goto error;
3126 +        }
3127 +        if (PyList_Append(rlist, ci) == -1) {
3128 +            goto error;
3129 +        }
3130 +        Py_CLEAR(ci);
3131 +    }
3132 +    return rlist;
3133 +
3134 +  error:
3135 +    Py_XDECREF(ci);
3136 +    Py_XDECREF(rlist);
3137 +    return NULL;
3138 +}
3139 +
3140 +
3141 +static PyGetSetDef context_getsetlist[] = {
3142 +    {"check_hostname", (getter) get_check_hostname,
3143 +                       (setter) set_check_hostname, NULL},
3144 +    {"options", (getter) get_options,
3145 +                (setter) set_options, NULL},
3146 +#ifdef HAVE_OPENSSL_VERIFY_PARAM
3147 +    {"verify_flags", (getter) get_verify_flags,
3148 +                     (setter) set_verify_flags, NULL},
3149 +#endif
3150 +    {"verify_mode", (getter) get_verify_mode,
3151 +                    (setter) set_verify_mode, NULL},
3152 +    {NULL},            /* sentinel */
3153 +};
3154 +
3155 +static struct PyMethodDef context_methods[] = {
3156 +    {"_wrap_socket", (PyCFunction) context_wrap_socket,
3157 +                       METH_VARARGS | METH_KEYWORDS, NULL},
3158 +    {"set_ciphers", (PyCFunction) set_ciphers,
3159 +                    METH_VARARGS, NULL},
3160 +    {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3161 +                           METH_VARARGS, NULL},
3162 +    {"load_cert_chain", (PyCFunction) load_cert_chain,
3163 +                        METH_VARARGS | METH_KEYWORDS, NULL},
3164 +    {"load_dh_params", (PyCFunction) load_dh_params,
3165 +                       METH_O, NULL},
3166 +    {"load_verify_locations", (PyCFunction) load_verify_locations,
3167 +                              METH_VARARGS | METH_KEYWORDS, NULL},
3168 +    {"session_stats", (PyCFunction) session_stats,
3169 +                      METH_NOARGS, NULL},
3170 +    {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3171 +                                 METH_NOARGS, NULL},
3172 +#ifndef OPENSSL_NO_ECDH
3173 +    {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3174 +                       METH_O, NULL},
3175 +#endif
3176 +    {"set_servername_callback", (PyCFunction) set_servername_callback,
3177 +                    METH_VARARGS, PySSL_set_servername_callback_doc},
3178 +    {"cert_store_stats", (PyCFunction) cert_store_stats,
3179 +                    METH_NOARGS, PySSL_get_stats_doc},
3180 +    {"get_ca_certs", (PyCFunction) get_ca_certs,
3181 +                    METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3182 +    {NULL, NULL}        /* sentinel */
3183 +};
3184 +
3185 +static PyTypeObject PySSLContext_Type = {
3186 +    PyVarObject_HEAD_INIT(NULL, 0)
3187 +    "_ssl._SSLContext",                        /*tp_name*/
3188 +    sizeof(PySSLContext),                      /*tp_basicsize*/
3189 +    0,                                         /*tp_itemsize*/
3190 +    (destructor)context_dealloc,               /*tp_dealloc*/
3191 +    0,                                         /*tp_print*/
3192 +    0,                                         /*tp_getattr*/
3193 +    0,                                         /*tp_setattr*/
3194 +    0,                                         /*tp_reserved*/
3195 +    0,                                         /*tp_repr*/
3196 +    0,                                         /*tp_as_number*/
3197 +    0,                                         /*tp_as_sequence*/
3198 +    0,                                         /*tp_as_mapping*/
3199 +    0,                                         /*tp_hash*/
3200 +    0,                                         /*tp_call*/
3201 +    0,                                         /*tp_str*/
3202 +    0,                                         /*tp_getattro*/
3203 +    0,                                         /*tp_setattro*/
3204 +    0,                                         /*tp_as_buffer*/
3205 +    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3206 +    0,                                         /*tp_doc*/
3207 +    (traverseproc) context_traverse,           /*tp_traverse*/
3208 +    (inquiry) context_clear,                   /*tp_clear*/
3209 +    0,                                         /*tp_richcompare*/
3210 +    0,                                         /*tp_weaklistoffset*/
3211 +    0,                                         /*tp_iter*/
3212 +    0,                                         /*tp_iternext*/
3213 +    context_methods,                           /*tp_methods*/
3214 +    0,                                         /*tp_members*/
3215 +    context_getsetlist,                        /*tp_getset*/
3216 +    0,                                         /*tp_base*/
3217 +    0,                                         /*tp_dict*/
3218 +    0,                                         /*tp_descr_get*/
3219 +    0,                                         /*tp_descr_set*/
3220 +    0,                                         /*tp_dictoffset*/
3221 +    0,                                         /*tp_init*/
3222 +    0,                                         /*tp_alloc*/
3223 +    context_new,                               /*tp_new*/
3224 +};
3225 +
3226 +
3227 +
3228 +#ifdef HAVE_OPENSSL_RAND
3229 +
3230 +/* helper routines for seeding the SSL PRNG */
3231 +static PyObject *
3232 +PySSL_RAND_add(PyObject *self, PyObject *args)
3233 +{
3234 +    char *buf;
3235 +    Py_ssize_t len, written;
3236 +    double entropy;
3237 +
3238 +    if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
3239 +        return NULL;
3240 +    do {
3241 +        if (len >= INT_MAX) {
3242 +            written = INT_MAX;
3243 +        } else {
3244 +            written = len;
3245 +        }
3246 +        RAND_add(buf, (int)written, entropy);
3247 +        buf += written;
3248 +        len -= written;
3249 +    } while (len);
3250 +    Py_INCREF(Py_None);
3251 +    return Py_None;
3252 +}
3253 +
3254 +PyDoc_STRVAR(PySSL_RAND_add_doc,
3255 +"RAND_add(string, entropy)\n\
3256 +\n\
3257 +Mix string into the OpenSSL PRNG state.  entropy (a float) is a lower\n\
3258 +bound on the entropy contained in string.  See RFC 1750.");
3259 +
3260 +static PyObject *
3261 +PySSL_RAND_status(PyObject *self)
3262 +{
3263 +    return PyLong_FromLong(RAND_status());
3264 +}
3265 +
3266 +PyDoc_STRVAR(PySSL_RAND_status_doc,
3267 +"RAND_status() -> 0 or 1\n\
3268 +\n\
3269 +Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3270 +It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3271 +using the ssl() function.");
3272 +
3273 +static PyObject *
3274 +PySSL_RAND_egd(PyObject *self, PyObject *arg)
3275 +{
3276 +    int bytes;
3277 +
3278 +    if (!PyString_Check(arg))
3279 +        return PyErr_Format(PyExc_TypeError,
3280 +                            "RAND_egd() expected string, found %s",
3281 +                            Py_TYPE(arg)->tp_name);
3282 +    bytes = RAND_egd(PyString_AS_STRING(arg));
3283 +    if (bytes == -1) {
3284 +        PyErr_SetString(PySSLErrorObject,
3285 +                        "EGD connection failed or EGD did not return "
3286 +                        "enough data to seed the PRNG");
3287 +        return NULL;
3288 +    }
3289 +    return PyInt_FromLong(bytes);
3290 +}
3291 +
3292 +PyDoc_STRVAR(PySSL_RAND_egd_doc,
3293 +"RAND_egd(path) -> bytes\n\
3294 +\n\
3295 +Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3296 +Returns number of bytes read.  Raises SSLError if connection to EGD\n\
3297 +fails or if it does not provide enough data to seed PRNG.");
3298 +
3299 +#endif /* HAVE_OPENSSL_RAND */
3300 +
3301 +
3302 +PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3303 +"get_default_verify_paths() -> tuple\n\
3304 +\n\
3305 +Return search paths and environment vars that are used by SSLContext's\n\
3306 +set_default_verify_paths() to load default CAs. The values are\n\
3307 +'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3308 +
3309 +static PyObject *
3310 +PySSL_get_default_verify_paths(PyObject *self)
3311 +{
3312 +    PyObject *ofile_env = NULL;
3313 +    PyObject *ofile = NULL;
3314 +    PyObject *odir_env = NULL;
3315 +    PyObject *odir = NULL;
3316 +
3317 +#define convert(info, target) { \
3318 +        const char *tmp = (info); \
3319 +        target = NULL; \
3320 +        if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3321 +        else { target = PyBytes_FromString(tmp); } \
3322 +        if (!target) goto error; \
3323 +    } while(0)
3324 +
3325 +    convert(X509_get_default_cert_file_env(), ofile_env);
3326 +    convert(X509_get_default_cert_file(), ofile);
3327 +    convert(X509_get_default_cert_dir_env(), odir_env);
3328 +    convert(X509_get_default_cert_dir(), odir);
3329 +#undef convert
3330 +
3331 +    return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3332 +
3333 +  error:
3334 +    Py_XDECREF(ofile_env);
3335 +    Py_XDECREF(ofile);
3336 +    Py_XDECREF(odir_env);
3337 +    Py_XDECREF(odir);
3338 +    return NULL;
3339 +}
3340 +
3341 +static PyObject*
3342 +asn1obj2py(ASN1_OBJECT *obj)
3343 +{
3344 +    int nid;
3345 +    const char *ln, *sn;
3346 +    char buf[100];
3347 +    Py_ssize_t buflen;
3348 +
3349 +    nid = OBJ_obj2nid(obj);
3350 +    if (nid == NID_undef) {
3351 +        PyErr_Format(PyExc_ValueError, "Unknown object");
3352 +        return NULL;
3353 +    }
3354 +    sn = OBJ_nid2sn(nid);
3355 +    ln = OBJ_nid2ln(nid);
3356 +    buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3357 +    if (buflen < 0) {
3358 +        _setSSLError(NULL, 0, __FILE__, __LINE__);
3359 +        return NULL;
3360 +    }
3361 +    if (buflen) {
3362 +        return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3363 +    } else {
3364 +        return Py_BuildValue("issO", nid, sn, ln, Py_None);
3365 +    }
3366 +}
3367 +
3368 +PyDoc_STRVAR(PySSL_txt2obj_doc,
3369 +"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3370 +\n\
3371 +Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3372 +objects are looked up by OID. With name=True short and long name are also\n\
3373 +matched.");
3374 +
3375 +static PyObject*
3376 +PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3377 +{
3378 +    char *kwlist[] = {"txt", "name", NULL};
3379 +    PyObject *result = NULL;
3380 +    char *txt;
3381 +    PyObject *pyname = Py_None;
3382 +    int name = 0;
3383 +    ASN1_OBJECT *obj;
3384 +
3385 +    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3386 +                                     kwlist, &txt, &pyname)) {
3387 +        return NULL;
3388 +    }
3389 +    name = PyObject_IsTrue(pyname);
3390 +    if (name < 0)
3391 +        return NULL;
3392 +    obj = OBJ_txt2obj(txt, name ? 0 : 1);
3393 +    if (obj == NULL) {
3394 +        PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3395 +        return NULL;
3396 +    }
3397 +    result = asn1obj2py(obj);
3398 +    ASN1_OBJECT_free(obj);
3399 +    return result;
3400 +}
3401 +
3402 +PyDoc_STRVAR(PySSL_nid2obj_doc,
3403 +"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3404 +\n\
3405 +Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3406 +
3407 +static PyObject*
3408 +PySSL_nid2obj(PyObject *self, PyObject *args)
3409 +{
3410 +    PyObject *result = NULL;
3411 +    int nid;
3412 +    ASN1_OBJECT *obj;
3413 +
3414 +    if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3415 +        return NULL;
3416 +    }
3417 +    if (nid < NID_undef) {
3418 +        PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3419 +        return NULL;
3420 +    }
3421 +    obj = OBJ_nid2obj(nid);
3422 +    if (obj == NULL) {
3423 +        PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3424 +        return NULL;
3425 +    }
3426 +    result = asn1obj2py(obj);
3427 +    ASN1_OBJECT_free(obj);
3428 +    return result;
3429 +}
3430 +
3431 +#ifdef _MSC_VER
3432 +
3433 +static PyObject*
3434 +certEncodingType(DWORD encodingType)
3435 +{
3436 +    static PyObject *x509_asn = NULL;
3437 +    static PyObject *pkcs_7_asn = NULL;
3438 +
3439 +    if (x509_asn == NULL) {
3440 +        x509_asn = PyString_InternFromString("x509_asn");
3441 +        if (x509_asn == NULL)
3442 +            return NULL;
3443 +    }
3444 +    if (pkcs_7_asn == NULL) {
3445 +        pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
3446 +        if (pkcs_7_asn == NULL)
3447 +            return NULL;
3448 +    }
3449 +    switch(encodingType) {
3450 +    case X509_ASN_ENCODING:
3451 +        Py_INCREF(x509_asn);
3452 +        return x509_asn;
3453 +    case PKCS_7_ASN_ENCODING:
3454 +        Py_INCREF(pkcs_7_asn);
3455 +        return pkcs_7_asn;
3456 +    default:
3457 +        return PyInt_FromLong(encodingType);
3458 +    }
3459 +}
3460 +
3461 +static PyObject*
3462 +parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3463 +{
3464 +    CERT_ENHKEY_USAGE *usage;
3465 +    DWORD size, error, i;
3466 +    PyObject *retval;
3467 +
3468 +    if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3469 +        error = GetLastError();
3470 +        if (error == CRYPT_E_NOT_FOUND) {
3471 +            Py_RETURN_TRUE;
3472 +        }
3473 +        return PyErr_SetFromWindowsErr(error);
3474 +    }
3475 +
3476 +    usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3477 +    if (usage == NULL) {
3478 +        return PyErr_NoMemory();
3479 +    }
3480 +
3481 +    /* Now get the actual enhanced usage property */
3482 +    if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3483 +        PyMem_Free(usage);
3484 +        error = GetLastError();
3485 +        if (error == CRYPT_E_NOT_FOUND) {
3486 +            Py_RETURN_TRUE;
3487 +        }
3488 +        return PyErr_SetFromWindowsErr(error);
3489 +    }
3490 +    retval = PySet_New(NULL);
3491 +    if (retval == NULL) {
3492 +        goto error;
3493 +    }
3494 +    for (i = 0; i < usage->cUsageIdentifier; ++i) {
3495 +        if (usage->rgpszUsageIdentifier[i]) {
3496 +            PyObject *oid;
3497 +            int err;
3498 +            oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
3499 +            if (oid == NULL) {
3500 +                Py_CLEAR(retval);
3501 +                goto error;
3502 +            }
3503 +            err = PySet_Add(retval, oid);
3504 +            Py_DECREF(oid);
3505 +            if (err == -1) {
3506 +                Py_CLEAR(retval);
3507 +                goto error;
3508 +            }
3509 +        }
3510 +    }
3511 +  error:
3512 +    PyMem_Free(usage);
3513 +    return retval;
3514 +}
3515 +
3516 +PyDoc_STRVAR(PySSL_enum_certificates_doc,
3517 +"enum_certificates(store_name) -> []\n\
3518 +\n\
3519 +Retrieve certificates from Windows' cert store. store_name may be one of\n\
3520 +'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3521 +The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3522 +encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3523 +PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3524 +boolean True.");
3525 +
3526 +static PyObject *
3527 +PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3528 +{
3529 +    char *kwlist[] = {"store_name", NULL};
3530 +    char *store_name;
3531 +    HCERTSTORE hStore = NULL;
3532 +    PCCERT_CONTEXT pCertCtx = NULL;
3533 +    PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3534 +    PyObject *result = NULL;
3535 +
3536 +    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
3537 +                                     kwlist, &store_name)) {
3538 +        return NULL;
3539 +    }
3540 +    result = PyList_New(0);
3541 +    if (result == NULL) {
3542 +        return NULL;
3543 +    }
3544 +    hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3545 +    if (hStore == NULL) {
3546 +        Py_DECREF(result);
3547 +        return PyErr_SetFromWindowsErr(GetLastError());
3548 +    }
3549 +
3550 +    while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3551 +        cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3552 +                                            pCertCtx->cbCertEncoded);
3553 +        if (!cert) {
3554 +            Py_CLEAR(result);
3555 +            break;
3556 +        }
3557 +        if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3558 +            Py_CLEAR(result);
3559 +            break;
3560 +        }
3561 +        keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3562 +        if (keyusage == Py_True) {
3563 +            Py_DECREF(keyusage);
3564 +            keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3565 +        }
3566 +        if (keyusage == NULL) {
3567 +            Py_CLEAR(result);
3568 +            break;
3569 +        }
3570 +        if ((tup = PyTuple_New(3)) == NULL) {
3571 +            Py_CLEAR(result);
3572 +            break;
3573 +        }
3574 +        PyTuple_SET_ITEM(tup, 0, cert);
3575 +        cert = NULL;
3576 +        PyTuple_SET_ITEM(tup, 1, enc);
3577 +        enc = NULL;
3578 +        PyTuple_SET_ITEM(tup, 2, keyusage);
3579 +        keyusage = NULL;
3580 +        if (PyList_Append(result, tup) < 0) {
3581 +            Py_CLEAR(result);
3582 +            break;
3583 +        }
3584 +        Py_CLEAR(tup);
3585 +    }
3586 +    if (pCertCtx) {
3587 +        /* loop ended with an error, need to clean up context manually */
3588 +        CertFreeCertificateContext(pCertCtx);
3589 +    }
3590 +
3591 +    /* In error cases cert, enc and tup may not be NULL */
3592 +    Py_XDECREF(cert);
3593 +    Py_XDECREF(enc);
3594 +    Py_XDECREF(keyusage);
3595 +    Py_XDECREF(tup);
3596 +
3597 +    if (!CertCloseStore(hStore, 0)) {
3598 +        /* This error case might shadow another exception.*/
3599 +        Py_XDECREF(result);
3600 +        return PyErr_SetFromWindowsErr(GetLastError());
3601 +    }
3602 +    return result;
3603 +}
3604 +
3605 +PyDoc_STRVAR(PySSL_enum_crls_doc,
3606 +"enum_crls(store_name) -> []\n\
3607 +\n\
3608 +Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3609 +'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3610 +The function returns a list of (bytes, encoding_type) tuples. The\n\
3611 +encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3612 +PKCS_7_ASN_ENCODING.");
3613 +
3614 +static PyObject *
3615 +PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3616 +{
3617 +    char *kwlist[] = {"store_name", NULL};
3618 +    char *store_name;
3619 +    HCERTSTORE hStore = NULL;
3620 +    PCCRL_CONTEXT pCrlCtx = NULL;
3621 +    PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3622 +    PyObject *result = NULL;
3623 +
3624 +    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
3625 +                                     kwlist, &store_name)) {
3626 +        return NULL;
3627 +    }
3628 +    result = PyList_New(0);
3629 +    if (result == NULL) {
3630 +        return NULL;
3631 +    }
3632 +    hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3633 +    if (hStore == NULL) {
3634 +        Py_DECREF(result);
3635 +        return PyErr_SetFromWindowsErr(GetLastError());
3636 +    }
3637 +
3638 +    while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3639 +        crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3640 +                                            pCrlCtx->cbCrlEncoded);
3641 +        if (!crl) {
3642 +            Py_CLEAR(result);
3643 +            break;
3644 +        }
3645 +        if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3646 +            Py_CLEAR(result);
3647 +            break;
3648 +        }
3649 +        if ((tup = PyTuple_New(2)) == NULL) {
3650 +            Py_CLEAR(result);
3651 +            break;
3652 +        }
3653 +        PyTuple_SET_ITEM(tup, 0, crl);
3654 +        crl = NULL;
3655 +        PyTuple_SET_ITEM(tup, 1, enc);
3656 +        enc = NULL;
3657 +
3658 +        if (PyList_Append(result, tup) < 0) {
3659 +            Py_CLEAR(result);
3660 +            break;
3661 +        }
3662 +        Py_CLEAR(tup);
3663 +    }
3664 +    if (pCrlCtx) {
3665 +        /* loop ended with an error, need to clean up context manually */
3666 +        CertFreeCRLContext(pCrlCtx);
3667 +    }
3668 +
3669 +    /* In error cases cert, enc and tup may not be NULL */
3670 +    Py_XDECREF(crl);
3671 +    Py_XDECREF(enc);
3672 +    Py_XDECREF(tup);
3673 +
3674 +    if (!CertCloseStore(hStore, 0)) {
3675 +        /* This error case might shadow another exception.*/
3676 +        Py_XDECREF(result);
3677 +        return PyErr_SetFromWindowsErr(GetLastError());
3678 +    }
3679 +    return result;
3680 +}
3681 +
3682 +#endif /* _MSC_VER */
3683 +
3684 +/* List of functions exported by this module. */
3685  
3686  static PyMethodDef PySSL_methods[] = {
3687 -    {"sslwrap",             PySSL_sslwrap,
3688 -     METH_VARARGS, ssl_doc},
3689      {"_test_decode_cert",       PySSL_test_decode_certificate,
3690       METH_VARARGS},
3691  #ifdef HAVE_OPENSSL_RAND
3692      {"RAND_add",            PySSL_RAND_add, METH_VARARGS,
3693       PySSL_RAND_add_doc},
3694 -    {"RAND_egd",            PySSL_RAND_egd, METH_O,
3695 +    {"RAND_egd",            PySSL_RAND_egd, METH_VARARGS,
3696       PySSL_RAND_egd_doc},
3697      {"RAND_status",         (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3698       PySSL_RAND_status_doc},
3699  #endif
3700 +    {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3701 +     METH_NOARGS, PySSL_get_default_verify_paths_doc},
3702 +#ifdef _MSC_VER
3703 +    {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3704 +     METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3705 +    {"enum_crls", (PyCFunction)PySSL_enum_crls,
3706 +     METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
3707 +#endif
3708 +    {"txt2obj", (PyCFunction)PySSL_txt2obj,
3709 +     METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3710 +    {"nid2obj", (PyCFunction)PySSL_nid2obj,
3711 +     METH_VARARGS, PySSL_nid2obj_doc},
3712      {NULL,                  NULL}            /* Sentinel */
3713  };
3714  
3715 @@ -1656,16 +3701,17 @@ static unsigned long _ssl_thread_id_func
3716      return PyThread_get_thread_ident();
3717  }
3718  
3719 -static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) {
3720 +static void _ssl_thread_locking_function
3721 +    (int mode, int n, const char *file, int line) {
3722      /* this function is needed to perform locking on shared data
3723         structures. (Note that OpenSSL uses a number of global data
3724 -       structures that will be implicitly shared whenever multiple threads
3725 -       use OpenSSL.) Multi-threaded applications will crash at random if
3726 -       it is not set.
3727 -
3728 -       locking_function() must be able to handle up to CRYPTO_num_locks()
3729 -       different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
3730 -       releases it otherwise.
3731 +       structures that will be implicitly shared whenever multiple
3732 +       threads use OpenSSL.) Multi-threaded applications will
3733 +       crash at random if it is not set.
3734 +
3735 +       locking_function() must be able to handle up to
3736 +       CRYPTO_num_locks() different mutex locks. It sets the n-th
3737 +       lock if mode & CRYPTO_LOCK, and releases it otherwise.
3738  
3739         file and line are the file number of the function setting the
3740         lock. They can be useful for debugging.
3741 @@ -1689,10 +3735,11 @@ static int _setup_ssl_threads(void) {
3742      if (_ssl_locks == NULL) {
3743          _ssl_locks_count = CRYPTO_num_locks();
3744          _ssl_locks = (PyThread_type_lock *)
3745 -            malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
3746 +            PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
3747          if (_ssl_locks == NULL)
3748              return 0;
3749 -        memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count);
3750 +        memset(_ssl_locks, 0,
3751 +               sizeof(PyThread_type_lock) * _ssl_locks_count);
3752          for (i = 0;  i < _ssl_locks_count;  i++) {
3753              _ssl_locks[i] = PyThread_allocate_lock();
3754              if (_ssl_locks[i] == NULL) {
3755 @@ -1700,7 +3747,7 @@ static int _setup_ssl_threads(void) {
3756                  for (j = 0;  j < i;  j++) {
3757                      PyThread_free_lock(_ssl_locks[j]);
3758                  }
3759 -                free(_ssl_locks);
3760 +                PyMem_Free(_ssl_locks);
3761                  return 0;
3762              }
3763          }
3764 @@ -1716,14 +3763,39 @@ PyDoc_STRVAR(module_doc,
3765  "Implementation module for SSL socket operations.  See the socket module\n\
3766  for documentation.");
3767  
3768 +
3769 +
3770 +
3771 +static void
3772 +parse_openssl_version(unsigned long libver,
3773 +                      unsigned int *major, unsigned int *minor,
3774 +                      unsigned int *fix, unsigned int *patch,
3775 +                      unsigned int *status)
3776 +{
3777 +    *status = libver & 0xF;
3778 +    libver >>= 4;
3779 +    *patch = libver & 0xFF;
3780 +    libver >>= 8;
3781 +    *fix = libver & 0xFF;
3782 +    libver >>= 8;
3783 +    *minor = libver & 0xFF;
3784 +    libver >>= 8;
3785 +    *major = libver & 0xFF;
3786 +}
3787 +
3788  PyMODINIT_FUNC
3789  init_ssl(void)
3790  {
3791      PyObject *m, *d, *r;
3792      unsigned long libver;
3793      unsigned int major, minor, fix, patch, status;
3794 +    struct py_ssl_error_code *errcode;
3795 +    struct py_ssl_library_code *libcode;
3796  
3797 -    Py_TYPE(&PySSL_Type) = &PyType_Type;
3798 +    if (PyType_Ready(&PySSLContext_Type) < 0)
3799 +        return;
3800 +    if (PyType_Ready(&PySSLSocket_Type) < 0)
3801 +        return;
3802  
3803      m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
3804      if (m == NULL)
3805 @@ -1746,15 +3818,53 @@ init_ssl(void)
3806      OpenSSL_add_all_algorithms();
3807  
3808      /* Add symbols to module dict */
3809 -    PySSLErrorObject = PyErr_NewException("ssl.SSLError",
3810 -                                          PySocketModule.error,
3811 -                                          NULL);
3812 +    PySSLErrorObject = PyErr_NewExceptionWithDoc(
3813 +        "ssl.SSLError", SSLError_doc,
3814 +        PySocketModule.error, NULL);
3815      if (PySSLErrorObject == NULL)
3816          return;
3817 -    if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
3818 +    ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
3819 +
3820 +    PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3821 +        "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3822 +        PySSLErrorObject, NULL);
3823 +    PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3824 +        "ssl.SSLWantReadError", SSLWantReadError_doc,
3825 +        PySSLErrorObject, NULL);
3826 +    PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3827 +        "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3828 +        PySSLErrorObject, NULL);
3829 +    PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3830 +        "ssl.SSLSyscallError", SSLSyscallError_doc,
3831 +        PySSLErrorObject, NULL);
3832 +    PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3833 +        "ssl.SSLEOFError", SSLEOFError_doc,
3834 +        PySSLErrorObject, NULL);
3835 +    if (PySSLZeroReturnErrorObject == NULL
3836 +        || PySSLWantReadErrorObject == NULL
3837 +        || PySSLWantWriteErrorObject == NULL
3838 +        || PySSLSyscallErrorObject == NULL
3839 +        || PySSLEOFErrorObject == NULL)
3840 +        return;
3841 +
3842 +    ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
3843 +    ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
3844 +    ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
3845 +    ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
3846 +    ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
3847 +
3848 +    if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3849 +        || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3850 +        || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3851 +        || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3852 +        || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3853 +        || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
3854 +        return;
3855 +    if (PyDict_SetItemString(d, "_SSLContext",
3856 +                             (PyObject *)&PySSLContext_Type) != 0)
3857          return;
3858 -    if (PyDict_SetItemString(d, "SSLType",
3859 -                             (PyObject *)&PySSL_Type) != 0)
3860 +    if (PyDict_SetItemString(d, "_SSLSocket",
3861 +                             (PyObject *)&PySSLSocket_Type) != 0)
3862          return;
3863      PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3864                              PY_SSL_ERROR_ZERO_RETURN);
3865 @@ -1782,6 +3892,66 @@ init_ssl(void)
3866                              PY_SSL_CERT_OPTIONAL);
3867      PyModule_AddIntConstant(m, "CERT_REQUIRED",
3868                              PY_SSL_CERT_REQUIRED);
3869 +    /* CRL verification for verification_flags */
3870 +    PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
3871 +                            0);
3872 +    PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
3873 +                            X509_V_FLAG_CRL_CHECK);
3874 +    PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
3875 +                            X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
3876 +    PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
3877 +                            X509_V_FLAG_X509_STRICT);
3878 +
3879 +    /* Alert Descriptions from ssl.h */
3880 +    /* note RESERVED constants no longer intended for use have been removed */
3881 +    /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3882 +
3883 +#define ADD_AD_CONSTANT(s) \
3884 +    PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3885 +                            SSL_AD_##s)
3886 +
3887 +    ADD_AD_CONSTANT(CLOSE_NOTIFY);
3888 +    ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3889 +    ADD_AD_CONSTANT(BAD_RECORD_MAC);
3890 +    ADD_AD_CONSTANT(RECORD_OVERFLOW);
3891 +    ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3892 +    ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3893 +    ADD_AD_CONSTANT(BAD_CERTIFICATE);
3894 +    ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3895 +    ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3896 +    ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3897 +    ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3898 +    ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3899 +    ADD_AD_CONSTANT(UNKNOWN_CA);
3900 +    ADD_AD_CONSTANT(ACCESS_DENIED);
3901 +    ADD_AD_CONSTANT(DECODE_ERROR);
3902 +    ADD_AD_CONSTANT(DECRYPT_ERROR);
3903 +    ADD_AD_CONSTANT(PROTOCOL_VERSION);
3904 +    ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3905 +    ADD_AD_CONSTANT(INTERNAL_ERROR);
3906 +    ADD_AD_CONSTANT(USER_CANCELLED);
3907 +    ADD_AD_CONSTANT(NO_RENEGOTIATION);
3908 +    /* Not all constants are in old OpenSSL versions */
3909 +#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3910 +    ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3911 +#endif
3912 +#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3913 +    ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3914 +#endif
3915 +#ifdef SSL_AD_UNRECOGNIZED_NAME
3916 +    ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3917 +#endif
3918 +#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3919 +    ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3920 +#endif
3921 +#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3922 +    ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3923 +#endif
3924 +#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3925 +    ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3926 +#endif
3927 +
3928 +#undef ADD_AD_CONSTANT
3929  
3930      /* protocol versions */
3931  #ifndef OPENSSL_NO_SSL2
3932 @@ -1794,6 +3964,109 @@ init_ssl(void)
3933                              PY_SSL_VERSION_SSL23);
3934      PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3935                              PY_SSL_VERSION_TLS1);
3936 +#if HAVE_TLSv1_2
3937 +    PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3938 +                            PY_SSL_VERSION_TLS1_1);
3939 +    PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3940 +                            PY_SSL_VERSION_TLS1_2);
3941 +#endif
3942 +
3943 +    /* protocol options */
3944 +    PyModule_AddIntConstant(m, "OP_ALL",
3945 +                            SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
3946 +    PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3947 +    PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3948 +    PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
3949 +#if HAVE_TLSv1_2
3950 +    PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3951 +    PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3952 +#endif
3953 +    PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3954 +                            SSL_OP_CIPHER_SERVER_PREFERENCE);
3955 +    PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
3956 +#ifdef SSL_OP_SINGLE_ECDH_USE
</