blob: 201eb45122ab0e618eedad7ebc40c34a3fc60396 [file] [log] [blame]
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001/*
2 * connection.c
3 *
Jean-Paul Calderone8671c852011-03-02 19:26:20 -05004 * Copyright (C) AB Strakt
5 * Copyright (C) Jean-Paul Calderone
6 * See LICENSE for details.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05007 *
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>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050014
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050015#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>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050023# include <wincrypt.h>
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050024#endif
25
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050026#define SSL_MODULE
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -040027#include <openssl/bio.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050028#include <openssl/err.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050029#include "ssl.h"
30
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050031/**
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 */
39static void
40syscall_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/*
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400129 * 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 */
135static void
136handle_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 */
Rick Deand369c932009-07-08 11:48:33 -0500168 exception_from_error_queue(ssl_Error);
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400169 }
170}
171
172/*
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500173 * 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 */
180static void
181handle_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:
Rick Deand369c932009-07-08 11:48:33 -0500242 exception_from_error_queue(ssl_Error);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500243 break;
244 }
245}
246
247/*
248 * Here be member methods of the Connection "class"
249 */
250
251static char ssl_Connection_get_context_doc[] = "\n\
252Get session context\n\
253\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400254@return: A Context object\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500255";
256static PyObject *
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400257ssl_Connection_get_context(ssl_ConnectionObj *self, PyObject *args) {
258 if (!PyArg_ParseTuple(args, ":get_context")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500259 return NULL;
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400260 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500261
262 Py_INCREF(self->context);
263 return (PyObject *)self->context;
264}
265
266static char ssl_Connection_pending_doc[] = "\n\
267Get the number of bytes that can be safely read from the connection\n\
268\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400269@return: The number of bytes available in the receive buffer.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500270";
271static PyObject *
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400272ssl_Connection_pending(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500273 int ret;
274
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400275 if (!PyArg_ParseTuple(args, ":pending")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500276 return NULL;
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400277 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500278
279 ret = SSL_pending(self->ssl);
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400280 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500281}
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400282
Rick Deanb71c0d22009-04-01 14:09:23 -0500283static char ssl_Connection_bio_write_doc[] = "\n\
284When using non-socket connections this function sends\n\
285\"dirty\" data that would have traveled in on the network.\n\
286\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400287@param buf: The string to put into the memory BIO.\n\
288@return: The number of bytes written\n\
Rick Deanb71c0d22009-04-01 14:09:23 -0500289";
290static PyObject *
291ssl_Connection_bio_write(ssl_ConnectionObj *self, PyObject *args)
292{
293 char *buf;
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400294 int len, ret;
Rick Deanb71c0d22009-04-01 14:09:23 -0500295
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400296 if (self->into_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -0500297 {
298 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
299 return NULL;
300 }
301
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -0400302 if (!PyArg_ParseTuple(args, "s#|i:bio_write", &buf, &len))
Rick Deanb71c0d22009-04-01 14:09:23 -0500303 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
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400313 if (ret <= 0) {
314 /*
315 * There was a problem with the BIO_write of some sort.
316 */
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400317 handle_bio_errors(self->into_ssl, ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500318 return NULL;
319 }
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400320
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400321 return PyLong_FromLong((long)ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500322}
323
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500324static char ssl_Connection_send_doc[] = "\n\
325Send data on the connection. NOTE: If you get one of the WantRead,\n\
326WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
327method again with the SAME buffer.\n\
328\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400329@param buf: The string to send\n\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500330@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400331 API, the value is ignored\n\
332@return: The number of bytes written\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500333";
334static PyObject *
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500335ssl_Connection_send(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500336 int len, ret, err, flags;
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500337 char *buf;
338
Jean-Paul Calderone5163f572011-04-22 18:38:16 -0400339#if PY_VERSION_HEX >= 0x02060000
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500340 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
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500348
349 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
350 return NULL;
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500351#endif
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500352
353 MY_BEGIN_ALLOW_THREADS(self->tstate)
354 ret = SSL_write(self->ssl, buf, len);
355 MY_END_ALLOW_THREADS(self->tstate)
356
Jean-Paul Calderone5163f572011-04-22 18:38:16 -0400357#if PY_VERSION_HEX >= 0x02060000
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500358 PyBuffer_Release(&pbuf);
359#endif
360
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500361 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 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400370 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500371 }
372 else
373 {
374 handle_ssl_errors(self->ssl, err, ret);
375 return NULL;
376 }
377}
378
379static char ssl_Connection_sendall_doc[] = "\n\
380Send \"all\" data on the connection. This calls send() repeatedly until\n\
381all data is sent. If an error occurs, it's impossible to tell how much data\n\
382has been sent.\n\
383\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400384@param buf: The string to send\n\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500385@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400386 API, the value is ignored\n\
387@return: The number of bytes written\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500388";
389static PyObject *
390ssl_Connection_sendall(ssl_ConnectionObj *self, PyObject *args)
391{
392 char *buf;
393 int len, ret, err, flags;
394 PyObject *pyret = Py_None;
395
Jean-Paul Calderone5163f572011-04-22 18:38:16 -0400396#if PY_VERSION_HEX >= 0x02060000
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500397 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
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500405 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
406 return NULL;
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500407#endif
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500408
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;
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500431 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500432 } while (len > 0);
433
Jean-Paul Calderone5163f572011-04-22 18:38:16 -0400434#if PY_VERSION_HEX >= 0x02060000
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500435 PyBuffer_Release(&pbuf);
436#endif
437
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500438 Py_XINCREF(pyret);
439 return pyret;
440}
441
442static char ssl_Connection_recv_doc[] = "\n\
443Receive data on the connection. NOTE: If you get one of the WantRead,\n\
444WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
445method again with the SAME buffer.\n\
446\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400447@param bufsiz: The maximum number of bytes to read\n\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500448@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400449 API, the value is ignored\n\
450@return: The string read from the Connection\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500451";
452static PyObject *
453ssl_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
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400461 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500462 if (buf == NULL)
463 return NULL;
464
465 MY_BEGIN_ALLOW_THREADS(self->tstate)
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400466 ret = SSL_read(self->ssl, PyBytes_AsString(buf), bufsiz);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500467 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 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400479 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500480 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
Rick Deanb71c0d22009-04-01 14:09:23 -0500491static char ssl_Connection_bio_read_doc[] = "\n\
492When using non-socket connections this function reads\n\
493the \"dirty\" data that would have traveled away on the network.\n\
494\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400495@param bufsiz: The maximum number of bytes to read\n\
496@return: The string read.\n\
Rick Deanb71c0d22009-04-01 14:09:23 -0500497";
498static PyObject *
499ssl_Connection_bio_read(ssl_ConnectionObj *self, PyObject *args)
500{
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400501 int bufsiz, ret;
Rick Deanb71c0d22009-04-01 14:09:23 -0500502 PyObject *buf;
503
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400504 if (self->from_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -0500505 {
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
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400513 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
Rick Deanb71c0d22009-04-01 14:09:23 -0500514 if (buf == NULL)
515 return NULL;
516
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400517 ret = BIO_read(self->from_ssl, PyBytes_AsString(buf), bufsiz);
Rick Deanb71c0d22009-04-01 14:09:23 -0500518
519 if (PyErr_Occurred())
520 {
521 Py_DECREF(buf);
522 flush_error_queue();
523 return NULL;
524 }
525
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400526 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);
Rick Deanb71c0d22009-04-01 14:09:23 -0500531 Py_DECREF(buf);
532 return NULL;
533 }
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400534
535 /*
536 * Shrink the string to match the number of bytes we actually read.
537 */
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400538 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400539 {
540 Py_DECREF(buf);
541 return NULL;
542 }
543 return buf;
Rick Deanb71c0d22009-04-01 14:09:23 -0500544}
545
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500546static char ssl_Connection_renegotiate_doc[] = "\n\
547Renegotiate the session\n\
548\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400549@return: True if the renegotiation can be started, false otherwise\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500550";
551static PyObject *
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400552ssl_Connection_renegotiate(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500553 int ret;
554
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400555 if (!PyArg_ParseTuple(args, ":renegotiate")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500556 return NULL;
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400557 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500558
559 MY_BEGIN_ALLOW_THREADS(self->tstate);
560 ret = SSL_renegotiate(self->ssl);
561 MY_END_ALLOW_THREADS(self->tstate);
562
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400563 if (PyErr_Occurred()) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500564 flush_error_queue();
565 return NULL;
566 }
567
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400568 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500569}
570
571static char ssl_Connection_do_handshake_doc[] = "\n\
572Perform an SSL handshake (usually called after renegotiate() or one of\n\
573set_*_state()). This can raise the same exceptions as send and recv.\n\
574\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400575@return: None.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500576";
577static PyObject *
578ssl_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
609static char ssl_Connection_renegotiate_pending_doc[] = "\n\
610Check if there's a renegotiation in progress, it will return false once\n\
611a renegotiation is finished.\n\
612\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400613@return: Whether there's a renegotiation in progress\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500614";
615static PyObject *
616ssl_Connection_renegotiate_pending(ssl_ConnectionObj *self, PyObject *args)
617{
618 if (!PyArg_ParseTuple(args, ":renegotiate_pending"))
619 return NULL;
620
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400621 return PyLong_FromLong((long)SSL_renegotiate_pending(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500622}
623#endif
624
625static char ssl_Connection_total_renegotiations_doc[] = "\n\
626Find out the total number of renegotiations.\n\
627\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400628@return: The number of renegotiations.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500629";
630static PyObject *
631ssl_Connection_total_renegotiations(ssl_ConnectionObj *self, PyObject *args)
632{
633 if (!PyArg_ParseTuple(args, ":total_renegotiations"))
634 return NULL;
635
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400636 return PyLong_FromLong(SSL_total_renegotiations(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500637}
638
639static char ssl_Connection_set_accept_state_doc[] = "\n\
640Set the connection to work in server mode. The handshake will be handled\n\
641automatically by read/write.\n\
642\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400643@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500644";
645static PyObject *
646ssl_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
657static char ssl_Connection_set_connect_state_doc[] = "\n\
658Set the connection to work in client mode. The handshake will be handled\n\
659automatically by read/write.\n\
660\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400661@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500662";
663static PyObject *
664ssl_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
675static char ssl_Connection_connect_doc[] = "\n\
676Connect to remote host and set up client-side SSL\n\
677\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400678@param addr: A remote address\n\
679@return: What the socket's connect method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500680";
681static PyObject *
682ssl_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
699static char ssl_Connection_connect_ex_doc[] = "\n\
700Connect to remote host and set up client-side SSL. Note that if the socket's\n\
701connect_ex method doesn't return 0, SSL won't be initialized.\n\
702\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400703@param addr: A remove address\n\
704@return: What the socket's connect_ex method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500705";
706static PyObject *
707ssl_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);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500718 return ret;
719}
720
721static char ssl_Connection_accept_doc[] = "\n\
722Accept incoming connection and set up SSL on it\n\
723\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400724@return: A (conn,addr) pair where conn is a Connection and addr is an\n\
725 address\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500726";
727static PyObject *
728ssl_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
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400764static char ssl_Connection_bio_shutdown_doc[] = "\n\
765When using non-socket connections this function signals end of\n\
766data on the input for this connection.\n\
767\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400768@return: None\n\
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400769";
770
771static PyObject *
772ssl_Connection_bio_shutdown(ssl_ConnectionObj *self, PyObject *args)
773{
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400774 if (self->from_ssl == NULL)
775 {
776 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
777 return NULL;
778 }
779
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400780 BIO_set_mem_eof_return(self->into_ssl, 0);
781 Py_INCREF(Py_None);
782 return Py_None;
783}
784
785
786
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500787static char ssl_Connection_shutdown_doc[] = "\n\
788Send closure alert\n\
789\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400790@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\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500793";
794static PyObject *
795ssl_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 {
Rick Deand369c932009-07-08 11:48:33 -0500814 exception_from_error_queue(ssl_Error);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500815 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
829static char ssl_Connection_get_cipher_list_doc[] = "\n\
830Get the session cipher list\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500831\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400832@return: A list of cipher strings\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500833";
834static PyObject *
835ssl_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 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400847 item = PyText_FromString(ret);
Ziga Seilnachtfdeadb12009-09-01 16:35:50 +0200848 PyList_Append(lst, item);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500849 Py_DECREF(item);
850 idx++;
851 }
852 return lst;
853}
854
Ziga Seilnachtf93bf102009-10-23 09:51:07 +0200855static char ssl_Connection_get_client_ca_list_doc[] = "\n\
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200856Get CAs whose certificates are suggested for client authentication.\n\
857\n\
Jean-Paul Calderone35788902009-10-24 13:48:08 -0400858@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\
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200863";
864
865static PyObject *
Jean-Paul Calderone6e2b6852009-10-24 14:04:30 -0400866ssl_Connection_get_client_ca_list(ssl_ConnectionObj *self, PyObject *args) {
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200867 STACK_OF(X509_NAME) *CANames;
868 PyObject *CAList;
869 int i, n;
870
Ziga Seilnachtf93bf102009-10-23 09:51:07 +0200871 if (!PyArg_ParseTuple(args, ":get_client_ca_list")) {
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200872 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 }
Jean-Paul Calderone305626a2010-10-31 20:51:17 -0400893 CA = (PyObject *)new_x509name(CAName, 1);
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200894 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
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500908static char ssl_Connection_makefile_doc[] = "\n\
909The makefile() method is not implemented, since there is no dup semantics\n\
910for SSL connections\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500911\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400912@raise NotImplementedError\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500913";
914static PyObject *
915ssl_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
921static char ssl_Connection_get_app_data_doc[] = "\n\
922Get application data\n\
923\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400924@return: The application data\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500925";
926static PyObject *
927ssl_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
936static char ssl_Connection_set_app_data_doc[] = "\n\
937Set application data\n\
938\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400939@param data - The application data\n\
940@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500941";
942static PyObject *
943ssl_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
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500958static char ssl_Connection_get_shutdown_doc[] = "\n\
959Get shutdown state\n\
960\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400961@return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500962";
963static PyObject *
964ssl_Connection_get_shutdown(ssl_ConnectionObj *self, PyObject *args)
965{
966 if (!PyArg_ParseTuple(args, ":get_shutdown"))
967 return NULL;
968
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400969 return PyLong_FromLong((long)SSL_get_shutdown(self->ssl));
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500970}
971
972static char ssl_Connection_set_shutdown_doc[] = "\n\
973Set shutdown state\n\
974\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400975@param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
976@return: None\n\
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500977";
978static PyObject *
979ssl_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
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500991static char ssl_Connection_state_string_doc[] = "\n\
992Get a verbose state description\n\
993\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400994@return: A string representing the state\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500995";
996static PyObject *
997ssl_Connection_state_string(ssl_ConnectionObj *self, PyObject *args)
998{
999 if (!PyArg_ParseTuple(args, ":state_string"))
1000 return NULL;
1001
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001002 return PyText_FromString(SSL_state_string_long(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001003}
1004
Rick Deanb71c0d22009-04-01 14:09:23 -05001005static char ssl_Connection_client_random_doc[] = "\n\
1006Get a copy of the client hello nonce.\n\
1007\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001008@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001009";
1010static PyObject *
1011ssl_Connection_client_random(ssl_ConnectionObj *self, PyObject *args)
1012{
1013 if (!PyArg_ParseTuple(args, ":client_random"))
1014 return NULL;
1015
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001016 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001017 Py_INCREF(Py_None);
1018 return Py_None;
1019 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001020 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->client_random, SSL3_RANDOM_SIZE);
Rick Deanb71c0d22009-04-01 14:09:23 -05001021}
1022
1023static char ssl_Connection_server_random_doc[] = "\n\
1024Get a copy of the server hello nonce.\n\
1025\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001026@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001027";
1028static PyObject *
1029ssl_Connection_server_random(ssl_ConnectionObj *self, PyObject *args)
1030{
1031 if (!PyArg_ParseTuple(args, ":server_random"))
1032 return NULL;
1033
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001034 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001035 Py_INCREF(Py_None);
1036 return Py_None;
1037 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001038 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->server_random, SSL3_RANDOM_SIZE);
Rick Deanb71c0d22009-04-01 14:09:23 -05001039}
1040
1041static char ssl_Connection_master_key_doc[] = "\n\
1042Get a copy of the master key.\n\
1043\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001044@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001045";
1046static PyObject *
1047ssl_Connection_master_key(ssl_ConnectionObj *self, PyObject *args)
1048{
1049 if (!PyArg_ParseTuple(args, ":master_key"))
1050 return NULL;
1051
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001052 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001053 Py_INCREF(Py_None);
1054 return Py_None;
1055 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001056 return PyBytes_FromStringAndSize( (const char *) self->ssl->session->master_key, self->ssl->session->master_key_length);
Rick Deanb71c0d22009-04-01 14:09:23 -05001057}
1058
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001059static char ssl_Connection_sock_shutdown_doc[] = "\n\
1060See shutdown(2)\n\
1061\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001062@return: What the socket's shutdown() method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001063";
1064static PyObject *
1065ssl_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
1076static char ssl_Connection_get_peer_certificate_doc[] = "\n\
1077Retrieve the other side's certificate (if any)\n\
1078\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001079@return: The peer's certificate\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001080";
1081static PyObject *
1082ssl_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 {
Jean-Paul Calderone5c0f1f62010-10-31 21:36:43 -04001092 return (PyObject *)new_x509(cert, 1);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001093 }
1094 else
1095 {
1096 Py_INCREF(Py_None);
1097 return Py_None;
1098 }
1099}
1100
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001101static char ssl_Connection_get_peer_cert_chain_doc[] = "\n\
1102Retrieve the other side's certificate (if any)\n\
1103\n\
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001104@return: A tuple of X509 instances giving the peer's certificate chain.\n\
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001105";
1106static PyObject *
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001107ssl_Connection_get_peer_cert_chain(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001108 STACK_OF(X509) *sk;
1109 PyObject *tpl, *item;
1110 Py_ssize_t i;
1111
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001112 if (!PyArg_ParseTuple(args, ":get_peer_cert_chain")) {
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001113 return NULL;
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001114 }
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001115
1116 sk = SSL_get_peer_cert_chain(self->ssl);
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001117 if (sk != NULL) {
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001118 tpl = PyTuple_New(sk_X509_num(sk));
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001119 for (i = 0; i < sk_X509_num(sk); i++) {
1120 item = (PyObject *)crypto_X509_New(sk_X509_value(sk, i), 1);
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001121 Py_INCREF(item);
1122 PyTuple_SET_ITEM(tpl, i, item);
1123 }
1124 return tpl;
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001125 } else {
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001126 Py_INCREF(Py_None);
1127 return Py_None;
1128 }
1129
1130}
1131
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001132static char ssl_Connection_want_read_doc[] = "\n\
1133Checks if more data has to be read from the transport layer to complete an\n\
1134operation.\n\
1135\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001136@return: True iff more data has to be read\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001137";
1138static PyObject *
1139ssl_Connection_want_read(ssl_ConnectionObj *self, PyObject *args)
1140{
1141 if (!PyArg_ParseTuple(args, ":want_read"))
1142 return NULL;
1143
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001144 return PyLong_FromLong((long)SSL_want_read(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001145}
1146
1147static char ssl_Connection_want_write_doc[] = "\n\
1148Checks if there is data to write to the transport layer to complete an\n\
1149operation.\n\
1150\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001151@return: True iff there is data to write\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001152";
1153static PyObject *
1154ssl_Connection_want_write(ssl_ConnectionObj *self, PyObject *args)
1155{
1156 if (!PyArg_ParseTuple(args, ":want_write"))
1157 return NULL;
1158
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001159 return PyLong_FromLong((long)SSL_want_write(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001160}
1161
1162/*
1163 * Member methods in the Connection object
1164 * ADD_METHOD(name) expands to a correct PyMethodDef declaration
1165 * { 'name', (PyCFunction)ssl_Connection_name, METH_VARARGS }
1166 * for convenience
1167 * ADD_ALIAS(name,real) creates an "alias" of the ssl_Connection_real
1168 * function with the name 'name'
1169 */
1170#define ADD_METHOD(name) \
1171 { #name, (PyCFunction)ssl_Connection_##name, METH_VARARGS, ssl_Connection_##name##_doc }
1172#define ADD_ALIAS(name,real) \
1173 { #name, (PyCFunction)ssl_Connection_##real, METH_VARARGS, ssl_Connection_##real##_doc }
1174static PyMethodDef ssl_Connection_methods[] =
1175{
1176 ADD_METHOD(get_context),
1177 ADD_METHOD(pending),
1178 ADD_METHOD(send),
1179 ADD_ALIAS (write, send),
1180 ADD_METHOD(sendall),
1181 ADD_METHOD(recv),
1182 ADD_ALIAS (read, recv),
Rick Deanb71c0d22009-04-01 14:09:23 -05001183 ADD_METHOD(bio_read),
1184 ADD_METHOD(bio_write),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001185 ADD_METHOD(renegotiate),
1186 ADD_METHOD(do_handshake),
1187#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
1188 ADD_METHOD(renegotiate_pending),
1189#endif
1190 ADD_METHOD(total_renegotiations),
1191 ADD_METHOD(connect),
1192 ADD_METHOD(connect_ex),
1193 ADD_METHOD(accept),
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04001194 ADD_METHOD(bio_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001195 ADD_METHOD(shutdown),
1196 ADD_METHOD(get_cipher_list),
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02001197 ADD_METHOD(get_client_ca_list),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001198 ADD_METHOD(makefile),
1199 ADD_METHOD(get_app_data),
1200 ADD_METHOD(set_app_data),
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001201 ADD_METHOD(get_shutdown),
1202 ADD_METHOD(set_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001203 ADD_METHOD(state_string),
Rick Deanb71c0d22009-04-01 14:09:23 -05001204 ADD_METHOD(server_random),
1205 ADD_METHOD(client_random),
1206 ADD_METHOD(master_key),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001207 ADD_METHOD(sock_shutdown),
1208 ADD_METHOD(get_peer_certificate),
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001209 ADD_METHOD(get_peer_cert_chain),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001210 ADD_METHOD(want_read),
1211 ADD_METHOD(want_write),
1212 ADD_METHOD(set_accept_state),
1213 ADD_METHOD(set_connect_state),
1214 { NULL, NULL }
1215};
1216#undef ADD_ALIAS
1217#undef ADD_METHOD
1218
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001219static char ssl_Connection_doc[] = "\n\
1220Connection(context, socket) -> Connection instance\n\
1221\n\
1222Create a new Connection object, using the given OpenSSL.SSL.Context instance\n\
1223and socket.\n\
1224\n\
1225@param context: An SSL Context to use for this connection\n\
1226@param socket: The socket to use for transport layer\n\
1227";
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001228
1229/*
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001230 * Initializer used by ssl_Connection_new and ssl_Connection_New. *Not*
1231 * tp_init. This takes an already allocated ssl_ConnectionObj, a context, and
1232 * a optionally a socket, and glues them all together.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001233 */
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001234static ssl_ConnectionObj*
1235ssl_Connection_init(ssl_ConnectionObj *self, ssl_ContextObj *ctx, PyObject *sock) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001236 int fd;
1237
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001238 Py_INCREF(ctx);
1239 self->context = ctx;
1240
1241 Py_INCREF(sock);
1242 self->socket = sock;
1243
1244 self->ssl = NULL;
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04001245 self->from_ssl = NULL;
1246 self->into_ssl = NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001247
1248 Py_INCREF(Py_None);
1249 self->app_data = Py_None;
1250
1251 self->tstate = NULL;
1252
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001253 self->ssl = SSL_new(self->context->ctx);
1254 SSL_set_app_data(self->ssl, self);
Rick Deanb71c0d22009-04-01 14:09:23 -05001255
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001256 if (self->socket == Py_None)
Rick Deanb71c0d22009-04-01 14:09:23 -05001257 {
1258 /* If it's not a socket or file, treat it like a memory buffer,
1259 * so crazy people can do things like EAP-TLS. */
1260 self->into_ssl = BIO_new(BIO_s_mem());
1261 self->from_ssl = BIO_new(BIO_s_mem());
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001262 if (self->into_ssl == NULL || self->from_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -05001263 goto error;
1264 SSL_set_bio(self->ssl, self->into_ssl, self->from_ssl);
1265 }
1266 else
1267 {
1268 fd = PyObject_AsFileDescriptor(self->socket);
1269 if (fd < 0)
1270 {
1271 Py_DECREF(self);
1272 return NULL;
1273 }
1274 else
1275 {
1276 SSL_set_fd(self->ssl, (SOCKET_T)fd);
1277 }
1278 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001279 return self;
Rick Deanb71c0d22009-04-01 14:09:23 -05001280
1281error:
1282 BIO_free(self->into_ssl); /* NULL safe */
1283 BIO_free(self->from_ssl); /* NULL safe */
1284 Py_DECREF(self);
1285 return NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001286}
1287
1288/*
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001289 * Constructor for Connection objects
1290 *
1291 * Arguments: ctx - An SSL Context to use for this connection
1292 * sock - The socket to use for transport layer
1293 * Returns: The newly created Connection object
1294 */
1295ssl_ConnectionObj *
1296ssl_Connection_New(ssl_ContextObj *ctx, PyObject *sock) {
1297 ssl_ConnectionObj *self;
1298
1299 self = PyObject_GC_New(ssl_ConnectionObj, &ssl_Connection_Type);
1300 if (self == NULL) {
1301 return NULL;
1302 }
1303 self = ssl_Connection_init(self, ctx, sock);
1304 if (self == NULL) {
1305 return NULL;
1306 }
1307 PyObject_GC_Track((PyObject *)self);
1308 return self;
1309}
1310
1311static PyObject*
1312ssl_Connection_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs) {
1313 ssl_ConnectionObj *self;
1314 ssl_ContextObj *ctx;
1315 PyObject *sock;
1316 static char *kwlist[] = {"context", "socket", NULL};
1317
1318 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O:Connection", kwlist,
1319 &ssl_Context_Type, &ctx, &sock)) {
1320 return NULL;
1321 }
1322
1323 self = (ssl_ConnectionObj *)subtype->tp_alloc(subtype, 1);
1324 if (self == NULL) {
1325 return NULL;
1326 }
1327
1328 return (PyObject *)ssl_Connection_init(self, ctx, sock);
1329}
1330
1331/*
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001332 * Find attribute
1333 *
1334 * Arguments: self - The Connection object
1335 * name - The attribute name
1336 * Returns: A Python object for the attribute, or NULL if something went
1337 * wrong
1338 */
1339static PyObject *
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001340ssl_Connection_getattro(ssl_ConnectionObj *self, PyObject *nameobj) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001341 PyObject *meth;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001342
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001343 meth = PyObject_GenericGetAttr((PyObject*)self, nameobj);
1344 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001345 PyErr_Clear();
1346 /* Try looking it up in the "socket" instead. */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001347 meth = PyObject_GenericGetAttr(self->socket, nameobj);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001348 }
1349
1350 return meth;
1351}
1352
1353/*
1354 * Call the visitproc on all contained objects.
1355 *
1356 * Arguments: self - The Connection object
1357 * visit - Function to call
1358 * arg - Extra argument to visit
1359 * Returns: 0 if all goes well, otherwise the return code from the first
1360 * call that gave non-zero result.
1361 */
1362static int
1363ssl_Connection_traverse(ssl_ConnectionObj *self, visitproc visit, void *arg)
1364{
1365 int ret = 0;
1366
1367 if (ret == 0 && self->context != NULL)
1368 ret = visit((PyObject *)self->context, arg);
1369 if (ret == 0 && self->socket != NULL)
1370 ret = visit(self->socket, arg);
1371 if (ret == 0 && self->app_data != NULL)
1372 ret = visit(self->app_data, arg);
1373 return ret;
1374}
1375
1376/*
1377 * Decref all contained objects and zero the pointers.
1378 *
1379 * Arguments: self - The Connection object
1380 * Returns: Always 0.
1381 */
1382static int
1383ssl_Connection_clear(ssl_ConnectionObj *self)
1384{
1385 Py_XDECREF(self->context);
1386 self->context = NULL;
1387 Py_XDECREF(self->socket);
1388 self->socket = NULL;
1389 Py_XDECREF(self->app_data);
1390 self->app_data = NULL;
Rick Deanb71c0d22009-04-01 14:09:23 -05001391 self->into_ssl = NULL; /* was cleaned up by SSL_free() */
1392 self->from_ssl = NULL; /* was cleaned up by SSL_free() */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001393 return 0;
1394}
1395
1396/*
1397 * Deallocate the memory used by the Connection object
1398 *
1399 * Arguments: self - The Connection object
1400 * Returns: None
1401 */
1402static void
1403ssl_Connection_dealloc(ssl_ConnectionObj *self)
1404{
1405 PyObject_GC_UnTrack(self);
1406 if (self->ssl != NULL)
1407 SSL_free(self->ssl);
1408 ssl_Connection_clear(self);
1409 PyObject_GC_Del(self);
1410}
1411
1412PyTypeObject ssl_Connection_Type = {
Jean-Paul Calderoneb6d75252010-08-11 23:55:45 -04001413 PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001414 "OpenSSL.SSL.Connection",
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001415 sizeof(ssl_ConnectionObj),
1416 0,
1417 (destructor)ssl_Connection_dealloc,
1418 NULL, /* print */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001419 NULL, /* tp_getattr */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001420 NULL, /* setattr */
1421 NULL, /* compare */
1422 NULL, /* repr */
1423 NULL, /* as_number */
1424 NULL, /* as_sequence */
1425 NULL, /* as_mapping */
1426 NULL, /* hash */
1427 NULL, /* call */
1428 NULL, /* str */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001429 (getattrofunc)ssl_Connection_getattro, /* getattro */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001430 NULL, /* setattro */
1431 NULL, /* as_buffer */
1432 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001433 ssl_Connection_doc, /* doc */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001434 (traverseproc)ssl_Connection_traverse,
1435 (inquiry)ssl_Connection_clear,
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001436 NULL, /* tp_richcompare */
1437 0, /* tp_weaklistoffset */
1438 NULL, /* tp_iter */
1439 NULL, /* tp_iternext */
1440 ssl_Connection_methods, /* tp_methods */
1441 NULL, /* tp_members */
1442 NULL, /* tp_getset */
1443 NULL, /* tp_base */
1444 NULL, /* tp_dict */
1445 NULL, /* tp_descr_get */
1446 NULL, /* tp_descr_set */
1447 0, /* tp_dictoffset */
1448 NULL, /* tp_init */
1449 NULL, /* tp_alloc */
1450 ssl_Connection_new, /* tp_new */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001451};
1452
1453
1454/*
1455 * Initiailze the Connection part of the SSL sub module
1456 *
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001457 * Arguments: dict - The OpenSSL.SSL module
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001458 * Returns: 1 for success, 0 otherwise
1459 */
1460int
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001461init_ssl_connection(PyObject *module) {
1462
1463 if (PyType_Ready(&ssl_Connection_Type) < 0) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001464 return 0;
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001465 }
1466
Jean-Paul Calderone86ad7112010-05-11 16:08:45 -04001467 /* PyModule_AddObject steals a reference.
1468 */
1469 Py_INCREF((PyObject *)&ssl_Connection_Type);
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001470 if (PyModule_AddObject(module, "Connection", (PyObject *)&ssl_Connection_Type) != 0) {
1471 return 0;
1472 }
1473
Jean-Paul Calderoneaed23582011-03-12 22:45:02 -05001474 /* PyModule_AddObject steals a reference.
1475 */
1476 Py_INCREF((PyObject *)&ssl_Connection_Type);
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001477 if (PyModule_AddObject(module, "ConnectionType", (PyObject *)&ssl_Connection_Type) != 0) {
1478 return 0;
1479 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001480
1481 return 1;
1482}
1483