Initial import to Tizen
[profile/ivi/python-pyOpenSSL.git] / OpenSSL / ssl / connection.c
1 /*
2  * connection.c
3  *
4  * Copyright (C) AB Strakt
5  * Copyright (C) Jean-Paul Calderone
6  * See LICENSE for details.
7  *
8  * SSL Connection objects and methods.
9  * See the file RATIONALE for a short explanation of why this module was written.
10  *
11  * Reviewed 2001-07-23
12  */
13 #include <Python.h>
14
15 #ifndef MS_WINDOWS
16 #  include <sys/socket.h>
17 #  include <netinet/in.h>
18 #  if !(defined(__BEOS__) || defined(__CYGWIN__))
19 #    include <netinet/tcp.h>
20 #  endif
21 #else
22 #  include <winsock.h>
23 #  include <wincrypt.h>
24 #endif
25
26 #define SSL_MODULE
27 #include <openssl/bio.h>
28 #include <openssl/err.h>
29 #include "ssl.h"
30
31 /**
32  * If we are on UNIX, fine, just use PyErr_SetFromErrno. If we are on Windows,
33  * apply some black winsock voodoo. This is basically just copied from Python's
34  * socketmodule.c
35  *
36  * Arguments: None
37  * Returns:   None
38  */
39 static void
40 syscall_from_errno(void)
41 {
42 #ifdef MS_WINDOWS
43     int errnum = WSAGetLastError();
44     if (errnum)
45     {
46         static struct { int num; const char *msg; } *msgp, msgs[] = {
47             { WSAEINTR, "Interrupted system call" },
48             { WSAEBADF, "Bad file descriptor" },
49             { WSAEACCES, "Permission denied" },
50             { WSAEFAULT, "Bad address" },
51             { WSAEINVAL, "Invalid argument" },
52             { WSAEMFILE, "Too many open files" },
53             { WSAEWOULDBLOCK, "The socket operation could not complete "
54                     "without blocking" },
55             { WSAEINPROGRESS, "Operation now in progress" },
56             { WSAEALREADY, "Operation already in progress" },
57             { WSAENOTSOCK, "Socket operation on non-socket" },
58             { WSAEDESTADDRREQ, "Destination address required" },
59             { WSAEMSGSIZE, "Message too long" },
60             { WSAEPROTOTYPE, "Protocol wrong type for socket" },
61             { WSAENOPROTOOPT, "Protocol not available" },
62             { WSAEPROTONOSUPPORT, "Protocol not supported" },
63             { WSAESOCKTNOSUPPORT, "Socket type not supported" },
64             { WSAEOPNOTSUPP, "Operation not supported" },
65             { WSAEPFNOSUPPORT, "Protocol family not supported" },
66             { WSAEAFNOSUPPORT, "Address family not supported" },
67             { WSAEADDRINUSE, "Address already in use" },
68             { WSAEADDRNOTAVAIL, "Can't assign requested address" },
69             { WSAENETDOWN, "Network is down" },
70             { WSAENETUNREACH, "Network is unreachable" },
71             { WSAENETRESET, "Network dropped connection on reset" },
72             { WSAECONNABORTED, "Software caused connection abort" },
73             { WSAECONNRESET, "Connection reset by peer" },
74             { WSAENOBUFS, "No buffer space available" },
75             { WSAEISCONN, "Socket is already connected" },
76             { WSAENOTCONN, "Socket is not connected" },
77             { WSAESHUTDOWN, "Can't send after socket shutdown" },
78             { WSAETOOMANYREFS, "Too many references: can't splice" },
79             { WSAETIMEDOUT, "Operation timed out" },
80             { WSAECONNREFUSED, "Connection refused" },
81             { WSAELOOP, "Too many levels of symbolic links" },
82             { WSAENAMETOOLONG, "File name too long" },
83             { WSAEHOSTDOWN, "Host is down" },
84             { WSAEHOSTUNREACH, "No route to host" },
85             { WSAENOTEMPTY, "Directory not empty" },
86             { WSAEPROCLIM, "Too many processes" },
87             { WSAEUSERS, "Too many users" },
88             { WSAEDQUOT, "Disc quota exceeded" },
89             { WSAESTALE, "Stale NFS file handle" },
90             { WSAEREMOTE, "Too many levels of remote in path" },
91             { WSASYSNOTREADY, "Network subsystem is unvailable" },
92             { WSAVERNOTSUPPORTED, "WinSock version is not supported" },
93             { WSANOTINITIALISED, "Successful WSAStartup() not yet performed" },
94             { WSAEDISCON, "Graceful shutdown in progress" },
95             /* Resolver errors */
96             { WSAHOST_NOT_FOUND, "No such host is known" },
97             { WSATRY_AGAIN, "Host not found, or server failed" },
98             { WSANO_RECOVERY, "Unexpected server error encountered" },
99             { WSANO_DATA, "Valid name without requested data" },
100             { WSANO_ADDRESS, "No address, look for MX record" },
101             { 0, NULL }
102         };
103         PyObject *v;
104         const char *msg = "winsock error";
105
106         for (msgp = msgs; msgp->msg; msgp++)
107         {
108             if (errnum == msgp->num)
109             {
110                 msg = msgp->msg;
111                 break;
112             }
113         }
114
115         v = Py_BuildValue("(is)", errnum, msg);
116         if (v != NULL)
117         {
118             PyErr_SetObject(ssl_SysCallError, v);
119             Py_DECREF(v);
120         }
121         return;
122     }
123 #else
124     PyErr_SetFromErrno(ssl_SysCallError);
125 #endif
126 }
127
128 /*
129  * Handle errors raised by BIO functions.
130  *
131  * Arguments: bio - The BIO object
132  *            ret - The return value of the BIO_ function.
133  * Returns: None, the calling function should return NULL;
134  */
135 static void
136 handle_bio_errors(BIO* bio, int ret)
137 {
138     if (BIO_should_retry(bio)) {
139         if (BIO_should_read(bio)) {
140             PyErr_SetNone(ssl_WantReadError);
141         } else if (BIO_should_write(bio)) {
142             PyErr_SetNone(ssl_WantWriteError);
143         } else if (BIO_should_io_special(bio)) {
144             /*
145              * It's somewhat unclear what this means.  From the OpenSSL source,
146              * it seems like it should not be triggered by the memory BIO, so
147              * for the time being, this case shouldn't come up.  The SSL BIO
148              * (which I think should be named the socket BIO) may trigger this
149              * case if its socket is not yet connected or it is busy doing
150              * something related to x509.
151              */
152             PyErr_SetString(PyExc_ValueError, "BIO_should_io_special");
153         } else {
154             /*
155              * I hope this is dead code.  The BIO documentation suggests that
156              * one of the above three checks should always be true.
157              */
158             PyErr_SetString(PyExc_ValueError, "unknown bio failure");
159         }
160     } else {
161         /*
162          * If we aren't to retry, it's really an error, so fall back to the
163          * normal error reporting code.  However, the BIO interface does not
164          * specify a uniform error reporting mechanism.  We can only hope that
165          * the code which triggered the error also kindly pushed something onto
166          * the error stack.
167          */
168         exception_from_error_queue(ssl_Error);
169     }
170 }
171
172 /*
173  * Handle errors raised by SSL I/O functions. NOTE: Not SSL_shutdown ;)
174  *
175  * Arguments: ssl - The SSL object
176  *            err - The return code from SSL_get_error
177  *            ret - The return code from the SSL I/O function
178  * Returns:   None, the calling function should return NULL
179  */
180 static void
181 handle_ssl_errors(SSL *ssl, int err, int ret)
182 {
183     switch (err)
184     {
185         /*
186          * Strange as it may seem, ZeroReturn is not an error per se. It means
187          * that the SSL Connection has been closed correctly (note, not the
188          * transport layer!), i.e. closure alerts have been exchanged. This is
189          * an exception since
190          *  + There's an SSL "error" code for it
191          *  + You have to deal with it in any case, close the transport layer
192          *    etc
193          */
194         case SSL_ERROR_ZERO_RETURN:
195             PyErr_SetNone(ssl_ZeroReturnError);
196             break;
197
198         /*
199          * The WantXYZ exceptions don't mean that there's an error, just that
200          * nothing could be read/written just now, maybe because the transport
201          * layer would block on the operation, or that there's not enough data
202          * available to fill an entire SSL record.
203          */
204         case SSL_ERROR_WANT_READ:
205             PyErr_SetNone(ssl_WantReadError);
206             break;
207
208         case SSL_ERROR_WANT_WRITE:
209             PyErr_SetNone(ssl_WantWriteError);
210             break;
211
212         case SSL_ERROR_WANT_X509_LOOKUP:
213             PyErr_SetNone(ssl_WantX509LookupError);
214             break;
215
216         case SSL_ERROR_SYSCALL:
217             if (ERR_peek_error() == 0)
218             {
219                 if (ret < 0)
220                 {
221                     syscall_from_errno();
222                 }
223                 else
224                 {
225                     PyObject *v;
226
227                     v = Py_BuildValue("(is)", -1, "Unexpected EOF");
228                     if (v != NULL)
229                     {
230                         PyErr_SetObject(ssl_SysCallError, v);
231                         Py_DECREF(v);
232                     }
233                 }
234                 break;
235             }
236
237         /* NOTE: Fall-through here, we don't want to duplicate code, right? */
238
239         case SSL_ERROR_SSL:
240             ;
241         default:
242             exception_from_error_queue(ssl_Error);
243             break;
244     }
245 }
246
247 /*
248  * Here be member methods of the Connection "class"
249  */
250
251 static char ssl_Connection_get_context_doc[] = "\n\
252 Get session context\n\
253 \n\
254 @return: A Context object\n\
255 ";
256 static PyObject *
257 ssl_Connection_get_context(ssl_ConnectionObj *self, PyObject *args) {
258     if (!PyArg_ParseTuple(args, ":get_context")) {
259         return NULL;
260     }
261
262     Py_INCREF(self->context);
263     return (PyObject *)self->context;
264 }
265
266 static char ssl_Connection_pending_doc[] = "\n\
267 Get the number of bytes that can be safely read from the connection\n\
268 \n\
269 @return: The number of bytes available in the receive buffer.\n\
270 ";
271 static PyObject *
272 ssl_Connection_pending(ssl_ConnectionObj *self, PyObject *args) {
273     int ret;
274
275     if (!PyArg_ParseTuple(args, ":pending")) {
276         return NULL;
277     }
278
279     ret = SSL_pending(self->ssl);
280     return PyLong_FromLong((long)ret);
281 }
282
283 static char ssl_Connection_bio_write_doc[] = "\n\
284 When using non-socket connections this function sends\n\
285 \"dirty\" data that would have traveled in on the network.\n\
286 \n\
287 @param buf: The string to put into the memory BIO.\n\
288 @return: The number of bytes written\n\
289 ";
290 static PyObject *
291 ssl_Connection_bio_write(ssl_ConnectionObj *self, PyObject *args)
292 {
293     char *buf;
294     int len, ret;
295
296     if (self->into_ssl == NULL) 
297     {
298             PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
299             return NULL;
300     }
301
302     if (!PyArg_ParseTuple(args, "s#|i:bio_write", &buf, &len))
303         return NULL;
304
305     ret = BIO_write(self->into_ssl, buf, len);
306
307     if (PyErr_Occurred())
308     {
309         flush_error_queue();
310         return NULL;
311     }
312
313     if (ret <= 0) {
314         /*
315          * There was a problem with the BIO_write of some sort.
316          */
317         handle_bio_errors(self->into_ssl, ret);
318         return NULL;
319     }
320
321     return PyLong_FromLong((long)ret);
322 }
323
324 static char ssl_Connection_send_doc[] = "\n\
325 Send data on the connection. NOTE: If you get one of the WantRead,\n\
326 WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
327 method again with the SAME buffer.\n\
328 \n\
329 @param buf: The string to send\n\
330 @param flags: (optional) Included for compatibility with the socket\n\
331               API, the value is ignored\n\
332 @return: The number of bytes written\n\
333 ";
334 static PyObject *
335 ssl_Connection_send(ssl_ConnectionObj *self, PyObject *args) {
336     int len, ret, err, flags;
337     char *buf;
338
339 #if PY_VERSION_HEX >= 0x02060000
340     Py_buffer pbuf;
341
342     if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
343         return NULL;
344
345     buf = pbuf.buf;
346     len = pbuf.len;
347 #else
348
349     if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
350         return NULL;
351 #endif
352
353     MY_BEGIN_ALLOW_THREADS(self->tstate)
354     ret = SSL_write(self->ssl, buf, len);
355     MY_END_ALLOW_THREADS(self->tstate)
356
357 #if PY_VERSION_HEX >= 0x02060000
358     PyBuffer_Release(&pbuf);
359 #endif
360
361     if (PyErr_Occurred())
362     {
363         flush_error_queue();
364         return NULL;
365     }
366
367     err = SSL_get_error(self->ssl, ret);
368     if (err == SSL_ERROR_NONE)
369     {
370         return PyLong_FromLong((long)ret);
371     }
372     else
373     {
374         handle_ssl_errors(self->ssl, err, ret);
375         return NULL;
376     }
377 }
378
379 static char ssl_Connection_sendall_doc[] = "\n\
380 Send \"all\" data on the connection. This calls send() repeatedly until\n\
381 all data is sent. If an error occurs, it's impossible to tell how much data\n\
382 has been sent.\n\
383 \n\
384 @param buf: The string to send\n\
385 @param flags: (optional) Included for compatibility with the socket\n\
386               API, the value is ignored\n\
387 @return: The number of bytes written\n\
388 ";
389 static PyObject *
390 ssl_Connection_sendall(ssl_ConnectionObj *self, PyObject *args)
391 {
392     char *buf;
393     int len, ret, err, flags;
394     PyObject *pyret = Py_None;
395
396 #if PY_VERSION_HEX >= 0x02060000
397     Py_buffer pbuf;
398
399     if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
400         return NULL;
401
402     buf = pbuf.buf;
403     len = pbuf.len;
404 #else
405     if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
406         return NULL;
407 #endif
408
409     do {
410         MY_BEGIN_ALLOW_THREADS(self->tstate)
411         ret = SSL_write(self->ssl, buf, len);
412         MY_END_ALLOW_THREADS(self->tstate)
413         if (PyErr_Occurred())
414         {
415             flush_error_queue();
416             pyret = NULL;
417             break;
418         }
419         err = SSL_get_error(self->ssl, ret);
420         if (err == SSL_ERROR_NONE)
421         {
422             buf += ret;
423             len -= ret;
424         }
425         else if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL ||
426                  err == SSL_ERROR_ZERO_RETURN)
427         {
428             handle_ssl_errors(self->ssl, err, ret);
429             pyret = NULL;
430             break;
431         }
432     } while (len > 0);
433
434 #if PY_VERSION_HEX >= 0x02060000
435     PyBuffer_Release(&pbuf);
436 #endif
437
438     Py_XINCREF(pyret);
439     return pyret;
440 }
441
442 static char ssl_Connection_recv_doc[] = "\n\
443 Receive data on the connection. NOTE: If you get one of the WantRead,\n\
444 WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
445 method again with the SAME buffer.\n\
446 \n\
447 @param bufsiz: The maximum number of bytes to read\n\
448 @param flags: (optional) Included for compatibility with the socket\n\
449               API, the value is ignored\n\
450 @return: The string read from the Connection\n\
451 ";
452 static PyObject *
453 ssl_Connection_recv(ssl_ConnectionObj *self, PyObject *args)
454 {
455     int bufsiz, ret, err, flags;
456     PyObject *buf;
457
458     if (!PyArg_ParseTuple(args, "i|i:recv", &bufsiz, &flags))
459         return NULL;
460
461     buf = PyBytes_FromStringAndSize(NULL, bufsiz);
462     if (buf == NULL)
463         return NULL;
464
465     MY_BEGIN_ALLOW_THREADS(self->tstate)
466     ret = SSL_read(self->ssl, PyBytes_AsString(buf), bufsiz);
467     MY_END_ALLOW_THREADS(self->tstate)
468
469     if (PyErr_Occurred())
470     {
471         Py_DECREF(buf);
472         flush_error_queue();
473         return NULL;
474     }
475
476     err = SSL_get_error(self->ssl, ret);
477     if (err == SSL_ERROR_NONE)
478     {
479         if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
480             return NULL;
481         return buf;
482     }
483     else
484     {
485         handle_ssl_errors(self->ssl, err, ret);
486         Py_DECREF(buf);
487         return NULL;
488     }
489 }
490
491 static char ssl_Connection_bio_read_doc[] = "\n\
492 When using non-socket connections this function reads\n\
493 the \"dirty\" data that would have traveled away on the network.\n\
494 \n\
495 @param bufsiz: The maximum number of bytes to read\n\
496 @return: The string read.\n\
497 ";
498 static PyObject *
499 ssl_Connection_bio_read(ssl_ConnectionObj *self, PyObject *args)
500 {
501     int bufsiz, ret;
502     PyObject *buf;
503
504     if (self->from_ssl == NULL) 
505     {
506             PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
507             return NULL;
508     }
509
510     if (!PyArg_ParseTuple(args, "i:bio_read", &bufsiz))
511         return NULL;
512
513     buf = PyBytes_FromStringAndSize(NULL, bufsiz);
514     if (buf == NULL)
515         return NULL;
516
517     ret = BIO_read(self->from_ssl, PyBytes_AsString(buf), bufsiz);
518
519     if (PyErr_Occurred())
520     {
521         Py_DECREF(buf);
522         flush_error_queue();
523         return NULL;
524     }
525
526     if (ret <= 0) {
527         /*
528          * There was a problem with the BIO_read of some sort.
529          */
530         handle_bio_errors(self->from_ssl, ret);
531         Py_DECREF(buf);
532         return NULL;
533     }
534
535     /*
536      * Shrink the string to match the number of bytes we actually read.
537      */
538     if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
539     {
540         Py_DECREF(buf);
541         return NULL;
542     }
543     return buf;
544 }
545
546 static char ssl_Connection_renegotiate_doc[] = "\n\
547 Renegotiate the session\n\
548 \n\
549 @return: True if the renegotiation can be started, false otherwise\n\
550 ";
551 static PyObject *
552 ssl_Connection_renegotiate(ssl_ConnectionObj *self, PyObject *args) {
553     int ret;
554
555     if (!PyArg_ParseTuple(args, ":renegotiate")) {
556         return NULL;
557     }
558
559     MY_BEGIN_ALLOW_THREADS(self->tstate);
560     ret = SSL_renegotiate(self->ssl);
561     MY_END_ALLOW_THREADS(self->tstate);
562
563     if (PyErr_Occurred()) {
564         flush_error_queue();
565         return NULL;
566     }
567
568     return PyLong_FromLong((long)ret);
569 }
570
571 static char ssl_Connection_do_handshake_doc[] = "\n\
572 Perform an SSL handshake (usually called after renegotiate() or one of\n\
573 set_*_state()). This can raise the same exceptions as send and recv.\n\
574 \n\
575 @return: None.\n\
576 ";
577 static PyObject *
578 ssl_Connection_do_handshake(ssl_ConnectionObj *self, PyObject *args)
579 {
580     int ret, err;
581
582     if (!PyArg_ParseTuple(args, ":do_handshake"))
583         return NULL;
584
585     MY_BEGIN_ALLOW_THREADS(self->tstate);
586     ret = SSL_do_handshake(self->ssl);
587     MY_END_ALLOW_THREADS(self->tstate);
588
589     if (PyErr_Occurred())
590     {
591         flush_error_queue();
592         return NULL;
593     }
594
595     err = SSL_get_error(self->ssl, ret);
596     if (err == SSL_ERROR_NONE)
597     {
598         Py_INCREF(Py_None);
599         return Py_None;
600     }
601     else
602     {
603         handle_ssl_errors(self->ssl, err, ret);
604         return NULL;
605     }
606 }
607
608 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
609 static char ssl_Connection_renegotiate_pending_doc[] = "\n\
610 Check if there's a renegotiation in progress, it will return false once\n\
611 a renegotiation is finished.\n\
612 \n\
613 @return: Whether there's a renegotiation in progress\n\
614 ";
615 static PyObject *
616 ssl_Connection_renegotiate_pending(ssl_ConnectionObj *self, PyObject *args)
617 {
618     if (!PyArg_ParseTuple(args, ":renegotiate_pending"))
619         return NULL;
620
621     return PyLong_FromLong((long)SSL_renegotiate_pending(self->ssl));
622 }
623 #endif
624
625 static char ssl_Connection_total_renegotiations_doc[] = "\n\
626 Find out the total number of renegotiations.\n\
627 \n\
628 @return: The number of renegotiations.\n\
629 ";
630 static PyObject *
631 ssl_Connection_total_renegotiations(ssl_ConnectionObj *self, PyObject *args)
632 {
633     if (!PyArg_ParseTuple(args, ":total_renegotiations"))
634         return NULL;
635
636     return PyLong_FromLong(SSL_total_renegotiations(self->ssl));
637 }
638
639 static char ssl_Connection_set_accept_state_doc[] = "\n\
640 Set the connection to work in server mode. The handshake will be handled\n\
641 automatically by read/write.\n\
642 \n\
643 @return: None\n\
644 ";
645 static PyObject *
646 ssl_Connection_set_accept_state(ssl_ConnectionObj *self, PyObject *args)
647 {
648     if (!PyArg_ParseTuple(args, ":set_accept_state"))
649         return NULL;
650
651     SSL_set_accept_state(self->ssl);
652
653     Py_INCREF(Py_None);
654     return Py_None;
655 }
656
657 static char ssl_Connection_set_connect_state_doc[] = "\n\
658 Set the connection to work in client mode. The handshake will be handled\n\
659 automatically by read/write.\n\
660 \n\
661 @return: None\n\
662 ";
663 static PyObject *
664 ssl_Connection_set_connect_state(ssl_ConnectionObj *self, PyObject *args)
665 {
666     if (!PyArg_ParseTuple(args, ":set_connect_state"))
667         return NULL;
668
669     SSL_set_connect_state(self->ssl);
670
671     Py_INCREF(Py_None);
672     return Py_None;
673 }
674
675 static char ssl_Connection_connect_doc[] = "\n\
676 Connect to remote host and set up client-side SSL\n\
677 \n\
678 @param addr: A remote address\n\
679 @return: What the socket's connect method returns\n\
680 ";
681 static PyObject *
682 ssl_Connection_connect(ssl_ConnectionObj *self, PyObject *args)
683 {
684     PyObject *meth, *ret;
685
686     if ((meth = PyObject_GetAttrString(self->socket, "connect")) == NULL)
687         return NULL;
688
689     SSL_set_connect_state(self->ssl);
690
691     ret = PyEval_CallObject(meth, args);
692     Py_DECREF(meth);
693     if (ret == NULL)
694         return NULL;
695
696     return ret;
697 }
698
699 static char ssl_Connection_connect_ex_doc[] = "\n\
700 Connect to remote host and set up client-side SSL. Note that if the socket's\n\
701 connect_ex method doesn't return 0, SSL won't be initialized.\n\
702 \n\
703 @param addr: A remove address\n\
704 @return: What the socket's connect_ex method returns\n\
705 ";
706 static PyObject *
707 ssl_Connection_connect_ex(ssl_ConnectionObj *self, PyObject *args)
708 {
709     PyObject *meth, *ret;
710
711     if ((meth = PyObject_GetAttrString(self->socket, "connect_ex")) == NULL)
712         return NULL;
713
714     SSL_set_connect_state(self->ssl);
715
716     ret = PyEval_CallObject(meth, args);
717     Py_DECREF(meth);
718     return ret;
719 }
720
721 static char ssl_Connection_accept_doc[] = "\n\
722 Accept incoming connection and set up SSL on it\n\
723 \n\
724 @return: A (conn,addr) pair where conn is a Connection and addr is an\n\
725          address\n\
726 ";
727 static PyObject *
728 ssl_Connection_accept(ssl_ConnectionObj *self, PyObject *args)
729 {
730     PyObject *tuple, *socket, *address, *meth;
731     ssl_ConnectionObj *conn;
732
733     if ((meth = PyObject_GetAttrString(self->socket, "accept")) == NULL)
734         return NULL;
735     tuple = PyEval_CallObject(meth, args);
736     Py_DECREF(meth);
737     if (tuple == NULL)
738         return NULL;
739
740     socket  = PyTuple_GetItem(tuple, 0);
741     Py_INCREF(socket);
742     address = PyTuple_GetItem(tuple, 1);
743     Py_INCREF(address);
744     Py_DECREF(tuple);
745
746     conn = ssl_Connection_New(self->context, socket);
747     Py_DECREF(socket);
748     if (conn == NULL)
749     {
750         Py_DECREF(address);
751         return NULL;
752     }
753
754     SSL_set_accept_state(conn->ssl);
755
756     tuple = Py_BuildValue("(OO)", conn, address);
757
758     Py_DECREF(conn);
759     Py_DECREF(address);
760
761     return tuple;
762 }
763
764 static char ssl_Connection_bio_shutdown_doc[] = "\n\
765 When using non-socket connections this function signals end of\n\
766 data on the input for this connection.\n\
767 \n\
768 @return: None\n\
769 ";
770
771 static PyObject *
772 ssl_Connection_bio_shutdown(ssl_ConnectionObj *self, PyObject *args)
773 {
774     if (self->from_ssl == NULL) 
775     {
776             PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
777             return NULL;
778     }
779
780     BIO_set_mem_eof_return(self->into_ssl, 0);
781     Py_INCREF(Py_None);
782     return Py_None;
783 }
784
785
786
787 static char ssl_Connection_shutdown_doc[] = "\n\
788 Send closure alert\n\
789 \n\
790 @return: True if the shutdown completed successfully (i.e. both sides\n\
791          have sent closure alerts), false otherwise (i.e. you have to\n\
792          wait for a ZeroReturnError on a recv() method call\n\
793 ";
794 static PyObject *
795 ssl_Connection_shutdown(ssl_ConnectionObj *self, PyObject *args)
796 {
797     int ret;
798
799     if (!PyArg_ParseTuple(args, ":shutdown"))
800         return NULL;
801
802     MY_BEGIN_ALLOW_THREADS(self->tstate)
803     ret = SSL_shutdown(self->ssl);
804     MY_END_ALLOW_THREADS(self->tstate)
805
806     if (PyErr_Occurred())
807     {
808         flush_error_queue();
809         return NULL;
810     }
811
812     if (ret < 0)
813     {
814         exception_from_error_queue(ssl_Error);
815         return NULL;
816     }
817     else if (ret > 0)
818     {
819         Py_INCREF(Py_True);
820         return Py_True;
821     }
822     else
823     {
824         Py_INCREF(Py_False);
825         return Py_False;
826     }
827 }
828
829 static char ssl_Connection_get_cipher_list_doc[] = "\n\
830 Get the session cipher list\n\
831 \n\
832 @return: A list of cipher strings\n\
833 ";
834 static PyObject *
835 ssl_Connection_get_cipher_list(ssl_ConnectionObj *self, PyObject *args)
836 {
837     int idx = 0;
838     const char *ret;
839     PyObject *lst, *item;
840
841     if (!PyArg_ParseTuple(args, ":get_cipher_list"))
842         return NULL;
843
844     lst = PyList_New(0);
845     while ((ret = SSL_get_cipher_list(self->ssl, idx)) != NULL)
846     {
847         item = PyText_FromString(ret);
848         PyList_Append(lst, item);
849         Py_DECREF(item);
850         idx++;
851     }
852     return lst;
853 }
854
855 static char ssl_Connection_get_client_ca_list_doc[] = "\n\
856 Get CAs whose certificates are suggested for client authentication.\n\
857 \n\
858 @return: If this is a server connection, a list of X509Names representing\n\
859     the acceptable CAs as set by L{OpenSSL.SSL.Context.set_client_ca_list} or\n\
860     L{OpenSSL.SSL.Context.add_client_ca}.  If this is a client connection,\n\
861     the list of such X509Names sent by the server, or an empty list if that\n\
862     has not yet happened.\n\
863 ";
864
865 static PyObject *
866 ssl_Connection_get_client_ca_list(ssl_ConnectionObj *self, PyObject *args) {
867     STACK_OF(X509_NAME) *CANames;
868     PyObject *CAList;
869     int i, n;
870
871     if (!PyArg_ParseTuple(args, ":get_client_ca_list")) {
872         return NULL;
873     }
874     CANames = SSL_get_client_CA_list(self->ssl);
875     if (CANames == NULL) {
876         return PyList_New(0);
877     }
878     n = sk_X509_NAME_num(CANames);
879     CAList = PyList_New(n);
880     if (CAList == NULL) {
881         return NULL;
882     }
883     for (i = 0; i < n; i++) {
884         X509_NAME *CAName;
885         PyObject *CA;
886
887         CAName = X509_NAME_dup(sk_X509_NAME_value(CANames, i));
888         if (CAName == NULL) {
889             Py_DECREF(CAList);
890             exception_from_error_queue(ssl_Error);
891             return NULL;
892         }
893         CA = (PyObject *)new_x509name(CAName, 1);
894         if (CA == NULL) {
895             X509_NAME_free(CAName);
896             Py_DECREF(CAList);
897             return NULL;
898         }
899         if (PyList_SetItem(CAList, i, CA)) {
900             Py_DECREF(CA);
901             Py_DECREF(CAList);
902             return NULL;
903         }
904     }
905     return CAList;
906 }
907
908 static char ssl_Connection_makefile_doc[] = "\n\
909 The makefile() method is not implemented, since there is no dup semantics\n\
910 for SSL connections\n\
911 \n\
912 @raise NotImplementedError\n\
913 ";
914 static PyObject *
915 ssl_Connection_makefile(ssl_ConnectionObj *self, PyObject *args)
916 {
917     PyErr_SetString(PyExc_NotImplementedError, "Cannot make file object of SSL.Connection");
918     return NULL;
919 }
920
921 static char ssl_Connection_get_app_data_doc[] = "\n\
922 Get application data\n\
923 \n\
924 @return: The application data\n\
925 ";
926 static PyObject *
927 ssl_Connection_get_app_data(ssl_ConnectionObj *self, PyObject *args)
928 {
929     if (!PyArg_ParseTuple(args, ":get_app_data"))
930         return NULL;
931
932     Py_INCREF(self->app_data);
933     return self->app_data;
934 }
935
936 static char ssl_Connection_set_app_data_doc[] = "\n\
937 Set application data\n\
938 \n\
939 @param data - The application data\n\
940 @return: None\n\
941 ";
942 static PyObject *
943 ssl_Connection_set_app_data(ssl_ConnectionObj *self, PyObject *args)
944 {
945     PyObject *data;
946
947     if (!PyArg_ParseTuple(args, "O:set_app_data", &data))
948         return NULL;
949
950     Py_DECREF(self->app_data);
951     Py_INCREF(data);
952     self->app_data = data;
953
954     Py_INCREF(Py_None);
955     return Py_None;
956 }
957
958 static char ssl_Connection_get_shutdown_doc[] = "\n\
959 Get shutdown state\n\
960 \n\
961 @return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
962 ";
963 static PyObject *
964 ssl_Connection_get_shutdown(ssl_ConnectionObj *self, PyObject *args)
965 {
966     if (!PyArg_ParseTuple(args, ":get_shutdown"))
967         return NULL;
968
969     return PyLong_FromLong((long)SSL_get_shutdown(self->ssl));
970 }
971
972 static char ssl_Connection_set_shutdown_doc[] = "\n\
973 Set shutdown state\n\
974 \n\
975 @param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
976 @return: None\n\
977 ";
978 static PyObject *
979 ssl_Connection_set_shutdown(ssl_ConnectionObj *self, PyObject *args)
980 {
981     int shutdown;
982
983     if (!PyArg_ParseTuple(args, "i:set_shutdown", &shutdown))
984         return NULL;
985
986     SSL_set_shutdown(self->ssl, shutdown);
987     Py_INCREF(Py_None);
988     return Py_None;
989 }
990
991 static char ssl_Connection_state_string_doc[] = "\n\
992 Get a verbose state description\n\
993 \n\
994 @return: A string representing the state\n\
995 ";
996 static PyObject *
997 ssl_Connection_state_string(ssl_ConnectionObj *self, PyObject *args)
998 {
999     if (!PyArg_ParseTuple(args, ":state_string"))
1000         return NULL;
1001
1002     return PyText_FromString(SSL_state_string_long(self->ssl));
1003 }
1004
1005 static char ssl_Connection_client_random_doc[] = "\n\
1006 Get a copy of the client hello nonce.\n\
1007 \n\
1008 @return: A string representing the state\n\
1009 ";
1010 static PyObject *
1011 ssl_Connection_client_random(ssl_ConnectionObj *self, PyObject *args)
1012 {
1013     if (!PyArg_ParseTuple(args, ":client_random"))
1014         return NULL;
1015
1016     if (self->ssl->session == NULL) {
1017         Py_INCREF(Py_None);
1018         return Py_None;
1019     }
1020     return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->client_random, SSL3_RANDOM_SIZE);
1021 }
1022
1023 static char ssl_Connection_server_random_doc[] = "\n\
1024 Get a copy of the server hello nonce.\n\
1025 \n\
1026 @return: A string representing the state\n\
1027 ";
1028 static PyObject *
1029 ssl_Connection_server_random(ssl_ConnectionObj *self, PyObject *args)
1030 {
1031     if (!PyArg_ParseTuple(args, ":server_random"))
1032         return NULL;
1033
1034     if (self->ssl->session == NULL) {
1035         Py_INCREF(Py_None);
1036         return Py_None;
1037     }
1038     return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->server_random, SSL3_RANDOM_SIZE);
1039 }
1040
1041 static char ssl_Connection_master_key_doc[] = "\n\
1042 Get a copy of the master key.\n\
1043 \n\
1044 @return: A string representing the state\n\
1045 ";
1046 static PyObject *
1047 ssl_Connection_master_key(ssl_ConnectionObj *self, PyObject *args)
1048 {
1049     if (!PyArg_ParseTuple(args, ":master_key"))
1050         return NULL;
1051
1052     if (self->ssl->session == NULL) {
1053         Py_INCREF(Py_None);
1054         return Py_None;
1055     }
1056     return PyBytes_FromStringAndSize( (const char *) self->ssl->session->master_key, self->ssl->session->master_key_length);
1057 }
1058
1059 static char ssl_Connection_sock_shutdown_doc[] = "\n\
1060 See shutdown(2)\n\
1061 \n\
1062 @return: What the socket's shutdown() method returns\n\
1063 ";
1064 static PyObject *
1065 ssl_Connection_sock_shutdown(ssl_ConnectionObj *self, PyObject *args)
1066 {
1067     PyObject *meth, *ret;
1068
1069     if ((meth = PyObject_GetAttrString(self->socket, "shutdown")) == NULL)
1070         return NULL;
1071     ret = PyEval_CallObject(meth, args);
1072     Py_DECREF(meth);
1073     return ret;
1074 }
1075
1076 static char ssl_Connection_get_peer_certificate_doc[] = "\n\
1077 Retrieve the other side's certificate (if any)\n\
1078 \n\
1079 @return: The peer's certificate\n\
1080 ";
1081 static PyObject *
1082 ssl_Connection_get_peer_certificate(ssl_ConnectionObj *self, PyObject *args)
1083 {
1084     X509 *cert;
1085
1086     if (!PyArg_ParseTuple(args, ":get_peer_certificate"))
1087         return NULL;
1088
1089     cert = SSL_get_peer_certificate(self->ssl);
1090     if (cert != NULL)
1091     {
1092         return (PyObject *)new_x509(cert, 1);
1093     }
1094     else
1095     {
1096         Py_INCREF(Py_None);
1097         return Py_None;
1098     }
1099 }
1100
1101 static char ssl_Connection_want_read_doc[] = "\n\
1102 Checks if more data has to be read from the transport layer to complete an\n\
1103 operation.\n\
1104 \n\
1105 @return: True iff more data has to be read\n\
1106 ";
1107 static PyObject *
1108 ssl_Connection_want_read(ssl_ConnectionObj *self, PyObject *args)
1109 {
1110     if (!PyArg_ParseTuple(args, ":want_read"))
1111         return NULL;
1112
1113     return PyLong_FromLong((long)SSL_want_read(self->ssl));
1114 }
1115
1116 static char ssl_Connection_want_write_doc[] = "\n\
1117 Checks if there is data to write to the transport layer to complete an\n\
1118 operation.\n\
1119 \n\
1120 @return: True iff there is data to write\n\
1121 ";
1122 static PyObject *
1123 ssl_Connection_want_write(ssl_ConnectionObj *self, PyObject *args)
1124 {
1125     if (!PyArg_ParseTuple(args, ":want_write"))
1126         return NULL;
1127
1128     return PyLong_FromLong((long)SSL_want_write(self->ssl));
1129 }
1130
1131 /*
1132  * Member methods in the Connection object
1133  * ADD_METHOD(name) expands to a correct PyMethodDef declaration
1134  *   {  'name', (PyCFunction)ssl_Connection_name, METH_VARARGS }
1135  * for convenience
1136  * ADD_ALIAS(name,real) creates an "alias" of the ssl_Connection_real
1137  * function with the name 'name'
1138  */
1139 #define ADD_METHOD(name)        \
1140     { #name, (PyCFunction)ssl_Connection_##name, METH_VARARGS, ssl_Connection_##name##_doc }
1141 #define ADD_ALIAS(name,real)    \
1142     { #name, (PyCFunction)ssl_Connection_##real, METH_VARARGS, ssl_Connection_##real##_doc }
1143 static PyMethodDef ssl_Connection_methods[] =
1144 {
1145     ADD_METHOD(get_context),
1146     ADD_METHOD(pending),
1147     ADD_METHOD(send),
1148     ADD_ALIAS (write, send),
1149     ADD_METHOD(sendall),
1150     ADD_METHOD(recv),
1151     ADD_ALIAS (read, recv),
1152     ADD_METHOD(bio_read),
1153     ADD_METHOD(bio_write),
1154     ADD_METHOD(renegotiate),
1155     ADD_METHOD(do_handshake),
1156 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
1157     ADD_METHOD(renegotiate_pending),
1158 #endif
1159     ADD_METHOD(total_renegotiations),
1160     ADD_METHOD(connect),
1161     ADD_METHOD(connect_ex),
1162     ADD_METHOD(accept),
1163     ADD_METHOD(bio_shutdown),
1164     ADD_METHOD(shutdown),
1165     ADD_METHOD(get_cipher_list),
1166     ADD_METHOD(get_client_ca_list),
1167     ADD_METHOD(makefile),
1168     ADD_METHOD(get_app_data),
1169     ADD_METHOD(set_app_data),
1170     ADD_METHOD(get_shutdown),
1171     ADD_METHOD(set_shutdown),
1172     ADD_METHOD(state_string),
1173     ADD_METHOD(server_random),
1174     ADD_METHOD(client_random),
1175     ADD_METHOD(master_key),
1176     ADD_METHOD(sock_shutdown),
1177     ADD_METHOD(get_peer_certificate),
1178     ADD_METHOD(want_read),
1179     ADD_METHOD(want_write),
1180     ADD_METHOD(set_accept_state),
1181     ADD_METHOD(set_connect_state),
1182     { NULL, NULL }
1183 };
1184 #undef ADD_ALIAS
1185 #undef ADD_METHOD
1186
1187 static char ssl_Connection_doc[] = "\n\
1188 Connection(context, socket) -> Connection instance\n\
1189 \n\
1190 Create a new Connection object, using the given OpenSSL.SSL.Context instance\n\
1191 and socket.\n\
1192 \n\
1193 @param context: An SSL Context to use for this connection\n\
1194 @param socket: The socket to use for transport layer\n\
1195 ";
1196
1197 /*
1198  * Initializer used by ssl_Connection_new and ssl_Connection_New.  *Not*
1199  * tp_init.  This takes an already allocated ssl_ConnectionObj, a context, and
1200  * a optionally a socket, and glues them all together.
1201  */
1202 static ssl_ConnectionObj*
1203 ssl_Connection_init(ssl_ConnectionObj *self, ssl_ContextObj *ctx, PyObject *sock) {
1204     int fd;
1205
1206     Py_INCREF(ctx);
1207     self->context = ctx;
1208
1209     Py_INCREF(sock);
1210     self->socket = sock;
1211
1212     self->ssl = NULL;
1213     self->from_ssl = NULL;
1214     self->into_ssl = NULL;
1215
1216     Py_INCREF(Py_None);
1217     self->app_data = Py_None;
1218
1219     self->tstate = NULL;
1220
1221     self->ssl = SSL_new(self->context->ctx);
1222     SSL_set_app_data(self->ssl, self);
1223
1224     if (self->socket == Py_None)
1225     {
1226         /* If it's not a socket or file, treat it like a memory buffer, 
1227          * so crazy people can do things like EAP-TLS. */
1228         self->into_ssl = BIO_new(BIO_s_mem());
1229         self->from_ssl = BIO_new(BIO_s_mem());
1230         if (self->into_ssl == NULL || self->from_ssl == NULL)
1231             goto error;
1232         SSL_set_bio(self->ssl, self->into_ssl, self->from_ssl);
1233     } 
1234     else 
1235     {
1236         fd = PyObject_AsFileDescriptor(self->socket);
1237         if (fd < 0)
1238         {
1239             Py_DECREF(self);
1240             return NULL;
1241         } 
1242         else 
1243         {
1244             SSL_set_fd(self->ssl, (SOCKET_T)fd);
1245         }
1246     }
1247     return self;
1248
1249 error:
1250     BIO_free(self->into_ssl);  /* NULL safe */
1251     BIO_free(self->from_ssl);  /* NULL safe */
1252     Py_DECREF(self);
1253     return NULL;
1254 }
1255
1256 /*
1257  * Constructor for Connection objects
1258  *
1259  * Arguments: ctx  - An SSL Context to use for this connection
1260  *            sock - The socket to use for transport layer
1261  * Returns:   The newly created Connection object
1262  */
1263 ssl_ConnectionObj *
1264 ssl_Connection_New(ssl_ContextObj *ctx, PyObject *sock) {
1265     ssl_ConnectionObj *self;
1266
1267     self = PyObject_GC_New(ssl_ConnectionObj, &ssl_Connection_Type);
1268     if (self == NULL) {
1269         return NULL;
1270     }
1271     self = ssl_Connection_init(self, ctx, sock);
1272     if (self == NULL) {
1273         return NULL;
1274     }
1275     PyObject_GC_Track((PyObject *)self);
1276     return self;
1277 }
1278
1279 static PyObject*
1280 ssl_Connection_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs) {
1281     ssl_ConnectionObj *self;
1282     ssl_ContextObj *ctx;
1283     PyObject *sock;
1284     static char *kwlist[] = {"context", "socket", NULL};
1285
1286     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O:Connection", kwlist,
1287                                      &ssl_Context_Type, &ctx, &sock)) {
1288         return NULL;
1289     }
1290
1291     self = (ssl_ConnectionObj *)subtype->tp_alloc(subtype, 1);
1292     if (self == NULL) {
1293         return NULL;
1294     }
1295
1296     return (PyObject *)ssl_Connection_init(self, ctx, sock);
1297 }
1298
1299 /*
1300  * Find attribute
1301  *
1302  * Arguments: self - The Connection object
1303  *            name - The attribute name
1304  * Returns:   A Python object for the attribute, or NULL if something went
1305  *            wrong
1306  */
1307 static PyObject *
1308 ssl_Connection_getattro(ssl_ConnectionObj *self, PyObject *nameobj) {
1309     PyObject *meth;
1310
1311     meth = PyObject_GenericGetAttr((PyObject*)self, nameobj);
1312     if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1313         PyErr_Clear();
1314         /* Try looking it up in the "socket" instead. */
1315         meth = PyObject_GenericGetAttr(self->socket, nameobj);
1316     }
1317
1318     return meth;
1319 }
1320
1321 /*
1322  * Call the visitproc on all contained objects.
1323  *
1324  * Arguments: self - The Connection object
1325  *            visit - Function to call
1326  *            arg - Extra argument to visit
1327  * Returns:   0 if all goes well, otherwise the return code from the first
1328  *            call that gave non-zero result.
1329  */
1330 static int
1331 ssl_Connection_traverse(ssl_ConnectionObj *self, visitproc visit, void *arg)
1332 {
1333     int ret = 0;
1334
1335     if (ret == 0 && self->context != NULL)
1336         ret = visit((PyObject *)self->context, arg);
1337     if (ret == 0 && self->socket != NULL)
1338         ret = visit(self->socket, arg);
1339     if (ret == 0 && self->app_data != NULL)
1340         ret = visit(self->app_data, arg);
1341     return ret;
1342 }
1343
1344 /*
1345  * Decref all contained objects and zero the pointers.
1346  *
1347  * Arguments: self - The Connection object
1348  * Returns:   Always 0.
1349  */
1350 static int
1351 ssl_Connection_clear(ssl_ConnectionObj *self)
1352 {
1353     Py_XDECREF(self->context);
1354     self->context = NULL;
1355     Py_XDECREF(self->socket);
1356     self->socket = NULL;
1357     Py_XDECREF(self->app_data);
1358     self->app_data = NULL;
1359     self->into_ssl = NULL; /* was cleaned up by SSL_free() */
1360     self->from_ssl = NULL; /* was cleaned up by SSL_free() */
1361     return 0;
1362 }
1363
1364 /*
1365  * Deallocate the memory used by the Connection object
1366  *
1367  * Arguments: self - The Connection object
1368  * Returns:   None
1369  */
1370 static void
1371 ssl_Connection_dealloc(ssl_ConnectionObj *self)
1372 {
1373     PyObject_GC_UnTrack(self);
1374     if (self->ssl != NULL)
1375         SSL_free(self->ssl);
1376     ssl_Connection_clear(self);
1377     PyObject_GC_Del(self);
1378 }
1379
1380 PyTypeObject ssl_Connection_Type = {
1381     PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
1382     "OpenSSL.SSL.Connection",
1383     sizeof(ssl_ConnectionObj),
1384     0,
1385     (destructor)ssl_Connection_dealloc,
1386     NULL, /* print */
1387     NULL, /* tp_getattr */
1388     NULL, /* setattr */
1389     NULL, /* compare */
1390     NULL, /* repr */
1391     NULL, /* as_number */
1392     NULL, /* as_sequence */
1393     NULL, /* as_mapping */
1394     NULL, /* hash */
1395     NULL, /* call */
1396     NULL, /* str */
1397     (getattrofunc)ssl_Connection_getattro, /* getattro */
1398     NULL, /* setattro */
1399     NULL, /* as_buffer */
1400     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
1401     ssl_Connection_doc, /* doc */
1402     (traverseproc)ssl_Connection_traverse,
1403     (inquiry)ssl_Connection_clear,
1404     NULL, /* tp_richcompare */
1405     0, /* tp_weaklistoffset */
1406     NULL, /* tp_iter */
1407     NULL, /* tp_iternext */
1408     ssl_Connection_methods, /* tp_methods */
1409     NULL, /* tp_members */
1410     NULL, /* tp_getset */
1411     NULL, /* tp_base */
1412     NULL, /* tp_dict */
1413     NULL, /* tp_descr_get */
1414     NULL, /* tp_descr_set */
1415     0, /* tp_dictoffset */
1416     NULL, /* tp_init */
1417     NULL, /* tp_alloc */
1418     ssl_Connection_new, /* tp_new */
1419 };
1420
1421
1422 /*
1423  * Initiailze the Connection part of the SSL sub module
1424  *
1425  * Arguments: dict - The OpenSSL.SSL module
1426  * Returns:   1 for success, 0 otherwise
1427  */
1428 int
1429 init_ssl_connection(PyObject *module) {
1430
1431     if (PyType_Ready(&ssl_Connection_Type) < 0) {
1432         return 0;
1433     }
1434
1435     if (PyModule_AddObject(module, "Connection", (PyObject *)&ssl_Connection_Type) != 0) {
1436         return 0;
1437     }
1438
1439     if (PyModule_AddObject(module, "ConnectionType", (PyObject *)&ssl_Connection_Type) != 0) {
1440         return 0;
1441     }
1442
1443     return 1;
1444 }
1445