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