blob: 079635275fd191e96779565d5fec29fa2c3cb5ae [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 *
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400256ssl_Connection_get_context(ssl_ConnectionObj *self, PyObject *args) {
257 if (!PyArg_ParseTuple(args, ":get_context")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500258 return NULL;
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400259 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500260
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 *
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400271ssl_Connection_pending(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500272 int ret;
273
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400274 if (!PyArg_ParseTuple(args, ":pending")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500275 return NULL;
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400276 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500277
278 ret = SSL_pending(self->ssl);
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400279 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500280}
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400281
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
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400320 return PyLong_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\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500329@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400330 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 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400355 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500356 }
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\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500370@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400371 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\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500419@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400420 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
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400432 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500433 if (buf == NULL)
434 return NULL;
435
436 MY_BEGIN_ALLOW_THREADS(self->tstate)
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400437 ret = SSL_read(self->ssl, PyBytes_AsString(buf), bufsiz);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500438 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 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400450 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500451 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
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400484 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
Rick Deanb71c0d22009-04-01 14:09:23 -0500485 if (buf == NULL)
486 return NULL;
487
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400488 ret = BIO_read(self->from_ssl, PyBytes_AsString(buf), bufsiz);
Rick Deanb71c0d22009-04-01 14:09:23 -0500489
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 */
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400509 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400510 {
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 *
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400523ssl_Connection_renegotiate(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500524 int ret;
525
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400526 if (!PyArg_ParseTuple(args, ":renegotiate")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500527 return NULL;
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400528 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500529
530 MY_BEGIN_ALLOW_THREADS(self->tstate);
531 ret = SSL_renegotiate(self->ssl);
532 MY_END_ALLOW_THREADS(self->tstate);
533
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400534 if (PyErr_Occurred()) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500535 flush_error_queue();
536 return NULL;
537 }
538
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400539 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500540}
541
542static char ssl_Connection_do_handshake_doc[] = "\n\
543Perform an SSL handshake (usually called after renegotiate() or one of\n\
544set_*_state()). This can raise the same exceptions as send and recv.\n\
545\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400546@return: None.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500547";
548static PyObject *
549ssl_Connection_do_handshake(ssl_ConnectionObj *self, PyObject *args)
550{
551 int ret, err;
552
553 if (!PyArg_ParseTuple(args, ":do_handshake"))
554 return NULL;
555
556 MY_BEGIN_ALLOW_THREADS(self->tstate);
557 ret = SSL_do_handshake(self->ssl);
558 MY_END_ALLOW_THREADS(self->tstate);
559
560 if (PyErr_Occurred())
561 {
562 flush_error_queue();
563 return NULL;
564 }
565
566 err = SSL_get_error(self->ssl, ret);
567 if (err == SSL_ERROR_NONE)
568 {
569 Py_INCREF(Py_None);
570 return Py_None;
571 }
572 else
573 {
574 handle_ssl_errors(self->ssl, err, ret);
575 return NULL;
576 }
577}
578
579#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
580static char ssl_Connection_renegotiate_pending_doc[] = "\n\
581Check if there's a renegotiation in progress, it will return false once\n\
582a renegotiation is finished.\n\
583\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400584@return: Whether there's a renegotiation in progress\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500585";
586static PyObject *
587ssl_Connection_renegotiate_pending(ssl_ConnectionObj *self, PyObject *args)
588{
589 if (!PyArg_ParseTuple(args, ":renegotiate_pending"))
590 return NULL;
591
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400592 return PyLong_FromLong((long)SSL_renegotiate_pending(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500593}
594#endif
595
596static char ssl_Connection_total_renegotiations_doc[] = "\n\
597Find out the total number of renegotiations.\n\
598\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400599@return: The number of renegotiations.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500600";
601static PyObject *
602ssl_Connection_total_renegotiations(ssl_ConnectionObj *self, PyObject *args)
603{
604 if (!PyArg_ParseTuple(args, ":total_renegotiations"))
605 return NULL;
606
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400607 return PyLong_FromLong(SSL_total_renegotiations(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500608}
609
610static char ssl_Connection_set_accept_state_doc[] = "\n\
611Set the connection to work in server mode. The handshake will be handled\n\
612automatically by read/write.\n\
613\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400614@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500615";
616static PyObject *
617ssl_Connection_set_accept_state(ssl_ConnectionObj *self, PyObject *args)
618{
619 if (!PyArg_ParseTuple(args, ":set_accept_state"))
620 return NULL;
621
622 SSL_set_accept_state(self->ssl);
623
624 Py_INCREF(Py_None);
625 return Py_None;
626}
627
628static char ssl_Connection_set_connect_state_doc[] = "\n\
629Set the connection to work in client mode. The handshake will be handled\n\
630automatically by read/write.\n\
631\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400632@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500633";
634static PyObject *
635ssl_Connection_set_connect_state(ssl_ConnectionObj *self, PyObject *args)
636{
637 if (!PyArg_ParseTuple(args, ":set_connect_state"))
638 return NULL;
639
640 SSL_set_connect_state(self->ssl);
641
642 Py_INCREF(Py_None);
643 return Py_None;
644}
645
646static char ssl_Connection_connect_doc[] = "\n\
647Connect to remote host and set up client-side SSL\n\
648\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400649@param addr: A remote address\n\
650@return: What the socket's connect method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500651";
652static PyObject *
653ssl_Connection_connect(ssl_ConnectionObj *self, PyObject *args)
654{
655 PyObject *meth, *ret;
656
657 if ((meth = PyObject_GetAttrString(self->socket, "connect")) == NULL)
658 return NULL;
659
660 SSL_set_connect_state(self->ssl);
661
662 ret = PyEval_CallObject(meth, args);
663 Py_DECREF(meth);
664 if (ret == NULL)
665 return NULL;
666
667 return ret;
668}
669
670static char ssl_Connection_connect_ex_doc[] = "\n\
671Connect to remote host and set up client-side SSL. Note that if the socket's\n\
672connect_ex method doesn't return 0, SSL won't be initialized.\n\
673\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400674@param addr: A remove address\n\
675@return: What the socket's connect_ex method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500676";
677static PyObject *
678ssl_Connection_connect_ex(ssl_ConnectionObj *self, PyObject *args)
679{
680 PyObject *meth, *ret;
681
682 if ((meth = PyObject_GetAttrString(self->socket, "connect_ex")) == NULL)
683 return NULL;
684
685 SSL_set_connect_state(self->ssl);
686
687 ret = PyEval_CallObject(meth, args);
688 Py_DECREF(meth);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500689 return ret;
690}
691
692static char ssl_Connection_accept_doc[] = "\n\
693Accept incoming connection and set up SSL on it\n\
694\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400695@return: A (conn,addr) pair where conn is a Connection and addr is an\n\
696 address\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500697";
698static PyObject *
699ssl_Connection_accept(ssl_ConnectionObj *self, PyObject *args)
700{
701 PyObject *tuple, *socket, *address, *meth;
702 ssl_ConnectionObj *conn;
703
704 if ((meth = PyObject_GetAttrString(self->socket, "accept")) == NULL)
705 return NULL;
706 tuple = PyEval_CallObject(meth, args);
707 Py_DECREF(meth);
708 if (tuple == NULL)
709 return NULL;
710
711 socket = PyTuple_GetItem(tuple, 0);
712 Py_INCREF(socket);
713 address = PyTuple_GetItem(tuple, 1);
714 Py_INCREF(address);
715 Py_DECREF(tuple);
716
717 conn = ssl_Connection_New(self->context, socket);
718 Py_DECREF(socket);
719 if (conn == NULL)
720 {
721 Py_DECREF(address);
722 return NULL;
723 }
724
725 SSL_set_accept_state(conn->ssl);
726
727 tuple = Py_BuildValue("(OO)", conn, address);
728
729 Py_DECREF(conn);
730 Py_DECREF(address);
731
732 return tuple;
733}
734
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400735static char ssl_Connection_bio_shutdown_doc[] = "\n\
736When using non-socket connections this function signals end of\n\
737data on the input for this connection.\n\
738\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400739@return: None\n\
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400740";
741
742static PyObject *
743ssl_Connection_bio_shutdown(ssl_ConnectionObj *self, PyObject *args)
744{
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400745 if (self->from_ssl == NULL)
746 {
747 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
748 return NULL;
749 }
750
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400751 BIO_set_mem_eof_return(self->into_ssl, 0);
752 Py_INCREF(Py_None);
753 return Py_None;
754}
755
756
757
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500758static char ssl_Connection_shutdown_doc[] = "\n\
759Send closure alert\n\
760\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400761@return: True if the shutdown completed successfully (i.e. both sides\n\
762 have sent closure alerts), false otherwise (i.e. you have to\n\
763 wait for a ZeroReturnError on a recv() method call\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500764";
765static PyObject *
766ssl_Connection_shutdown(ssl_ConnectionObj *self, PyObject *args)
767{
768 int ret;
769
770 if (!PyArg_ParseTuple(args, ":shutdown"))
771 return NULL;
772
773 MY_BEGIN_ALLOW_THREADS(self->tstate)
774 ret = SSL_shutdown(self->ssl);
775 MY_END_ALLOW_THREADS(self->tstate)
776
777 if (PyErr_Occurred())
778 {
779 flush_error_queue();
780 return NULL;
781 }
782
783 if (ret < 0)
784 {
Rick Deand369c932009-07-08 11:48:33 -0500785 exception_from_error_queue(ssl_Error);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500786 return NULL;
787 }
788 else if (ret > 0)
789 {
790 Py_INCREF(Py_True);
791 return Py_True;
792 }
793 else
794 {
795 Py_INCREF(Py_False);
796 return Py_False;
797 }
798}
799
800static char ssl_Connection_get_cipher_list_doc[] = "\n\
801Get the session cipher list\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500802\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400803@return: A list of cipher strings\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500804";
805static PyObject *
806ssl_Connection_get_cipher_list(ssl_ConnectionObj *self, PyObject *args)
807{
808 int idx = 0;
809 const char *ret;
810 PyObject *lst, *item;
811
812 if (!PyArg_ParseTuple(args, ":get_cipher_list"))
813 return NULL;
814
815 lst = PyList_New(0);
816 while ((ret = SSL_get_cipher_list(self->ssl, idx)) != NULL)
817 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400818 item = PyText_FromString(ret);
Ziga Seilnachtfdeadb12009-09-01 16:35:50 +0200819 PyList_Append(lst, item);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500820 Py_DECREF(item);
821 idx++;
822 }
823 return lst;
824}
825
Ziga Seilnachtf93bf102009-10-23 09:51:07 +0200826static char ssl_Connection_get_client_ca_list_doc[] = "\n\
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200827Get CAs whose certificates are suggested for client authentication.\n\
828\n\
Jean-Paul Calderone35788902009-10-24 13:48:08 -0400829@return: If this is a server connection, a list of X509Names representing\n\
830 the acceptable CAs as set by L{OpenSSL.SSL.Context.set_client_ca_list} or\n\
831 L{OpenSSL.SSL.Context.add_client_ca}. If this is a client connection,\n\
832 the list of such X509Names sent by the server, or an empty list if that\n\
833 has not yet happened.\n\
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200834";
835
836static PyObject *
Jean-Paul Calderone6e2b6852009-10-24 14:04:30 -0400837ssl_Connection_get_client_ca_list(ssl_ConnectionObj *self, PyObject *args) {
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200838 STACK_OF(X509_NAME) *CANames;
839 PyObject *CAList;
840 int i, n;
841
Ziga Seilnachtf93bf102009-10-23 09:51:07 +0200842 if (!PyArg_ParseTuple(args, ":get_client_ca_list")) {
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200843 return NULL;
844 }
845 CANames = SSL_get_client_CA_list(self->ssl);
846 if (CANames == NULL) {
847 return PyList_New(0);
848 }
849 n = sk_X509_NAME_num(CANames);
850 CAList = PyList_New(n);
851 if (CAList == NULL) {
852 return NULL;
853 }
854 for (i = 0; i < n; i++) {
855 X509_NAME *CAName;
856 PyObject *CA;
857
858 CAName = X509_NAME_dup(sk_X509_NAME_value(CANames, i));
859 if (CAName == NULL) {
860 Py_DECREF(CAList);
861 exception_from_error_queue(ssl_Error);
862 return NULL;
863 }
Jean-Paul Calderone305626a2010-10-31 20:51:17 -0400864 CA = (PyObject *)new_x509name(CAName, 1);
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200865 if (CA == NULL) {
866 X509_NAME_free(CAName);
867 Py_DECREF(CAList);
868 return NULL;
869 }
870 if (PyList_SetItem(CAList, i, CA)) {
871 Py_DECREF(CA);
872 Py_DECREF(CAList);
873 return NULL;
874 }
875 }
876 return CAList;
877}
878
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500879static char ssl_Connection_makefile_doc[] = "\n\
880The makefile() method is not implemented, since there is no dup semantics\n\
881for SSL connections\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500882\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400883@raise NotImplementedError\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500884";
885static PyObject *
886ssl_Connection_makefile(ssl_ConnectionObj *self, PyObject *args)
887{
888 PyErr_SetString(PyExc_NotImplementedError, "Cannot make file object of SSL.Connection");
889 return NULL;
890}
891
892static char ssl_Connection_get_app_data_doc[] = "\n\
893Get application data\n\
894\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400895@return: The application data\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500896";
897static PyObject *
898ssl_Connection_get_app_data(ssl_ConnectionObj *self, PyObject *args)
899{
900 if (!PyArg_ParseTuple(args, ":get_app_data"))
901 return NULL;
902
903 Py_INCREF(self->app_data);
904 return self->app_data;
905}
906
907static char ssl_Connection_set_app_data_doc[] = "\n\
908Set application data\n\
909\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400910@param data - The application data\n\
911@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500912";
913static PyObject *
914ssl_Connection_set_app_data(ssl_ConnectionObj *self, PyObject *args)
915{
916 PyObject *data;
917
918 if (!PyArg_ParseTuple(args, "O:set_app_data", &data))
919 return NULL;
920
921 Py_DECREF(self->app_data);
922 Py_INCREF(data);
923 self->app_data = data;
924
925 Py_INCREF(Py_None);
926 return Py_None;
927}
928
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500929static char ssl_Connection_get_shutdown_doc[] = "\n\
930Get shutdown state\n\
931\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400932@return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500933";
934static PyObject *
935ssl_Connection_get_shutdown(ssl_ConnectionObj *self, PyObject *args)
936{
937 if (!PyArg_ParseTuple(args, ":get_shutdown"))
938 return NULL;
939
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400940 return PyLong_FromLong((long)SSL_get_shutdown(self->ssl));
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500941}
942
943static char ssl_Connection_set_shutdown_doc[] = "\n\
944Set shutdown state\n\
945\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400946@param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
947@return: None\n\
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500948";
949static PyObject *
950ssl_Connection_set_shutdown(ssl_ConnectionObj *self, PyObject *args)
951{
952 int shutdown;
953
954 if (!PyArg_ParseTuple(args, "i:set_shutdown", &shutdown))
955 return NULL;
956
957 SSL_set_shutdown(self->ssl, shutdown);
958 Py_INCREF(Py_None);
959 return Py_None;
960}
961
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500962static char ssl_Connection_state_string_doc[] = "\n\
963Get a verbose state description\n\
964\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400965@return: A string representing the state\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500966";
967static PyObject *
968ssl_Connection_state_string(ssl_ConnectionObj *self, PyObject *args)
969{
970 if (!PyArg_ParseTuple(args, ":state_string"))
971 return NULL;
972
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400973 return PyText_FromString(SSL_state_string_long(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500974}
975
Rick Deanb71c0d22009-04-01 14:09:23 -0500976static char ssl_Connection_client_random_doc[] = "\n\
977Get a copy of the client hello nonce.\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_client_random(ssl_ConnectionObj *self, PyObject *args)
983{
984 if (!PyArg_ParseTuple(args, ":client_random"))
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 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400991 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->client_random, SSL3_RANDOM_SIZE);
Rick Deanb71c0d22009-04-01 14:09:23 -0500992}
993
994static char ssl_Connection_server_random_doc[] = "\n\
995Get a copy of the server hello nonce.\n\
996\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400997@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -0500998";
999static PyObject *
1000ssl_Connection_server_random(ssl_ConnectionObj *self, PyObject *args)
1001{
1002 if (!PyArg_ParseTuple(args, ":server_random"))
1003 return NULL;
1004
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001005 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001006 Py_INCREF(Py_None);
1007 return Py_None;
1008 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001009 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->server_random, SSL3_RANDOM_SIZE);
Rick Deanb71c0d22009-04-01 14:09:23 -05001010}
1011
1012static char ssl_Connection_master_key_doc[] = "\n\
1013Get a copy of the master key.\n\
1014\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001015@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001016";
1017static PyObject *
1018ssl_Connection_master_key(ssl_ConnectionObj *self, PyObject *args)
1019{
1020 if (!PyArg_ParseTuple(args, ":master_key"))
1021 return NULL;
1022
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001023 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001024 Py_INCREF(Py_None);
1025 return Py_None;
1026 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001027 return PyBytes_FromStringAndSize( (const char *) self->ssl->session->master_key, self->ssl->session->master_key_length);
Rick Deanb71c0d22009-04-01 14:09:23 -05001028}
1029
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001030static char ssl_Connection_sock_shutdown_doc[] = "\n\
1031See shutdown(2)\n\
1032\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001033@return: What the socket's shutdown() method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001034";
1035static PyObject *
1036ssl_Connection_sock_shutdown(ssl_ConnectionObj *self, PyObject *args)
1037{
1038 PyObject *meth, *ret;
1039
1040 if ((meth = PyObject_GetAttrString(self->socket, "shutdown")) == NULL)
1041 return NULL;
1042 ret = PyEval_CallObject(meth, args);
1043 Py_DECREF(meth);
1044 return ret;
1045}
1046
1047static char ssl_Connection_get_peer_certificate_doc[] = "\n\
1048Retrieve the other side's certificate (if any)\n\
1049\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001050@return: The peer's certificate\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001051";
1052static PyObject *
1053ssl_Connection_get_peer_certificate(ssl_ConnectionObj *self, PyObject *args)
1054{
1055 X509 *cert;
1056
1057 if (!PyArg_ParseTuple(args, ":get_peer_certificate"))
1058 return NULL;
1059
1060 cert = SSL_get_peer_certificate(self->ssl);
1061 if (cert != NULL)
1062 {
1063 return (PyObject *)crypto_X509_New(cert, 1);
1064 }
1065 else
1066 {
1067 Py_INCREF(Py_None);
1068 return Py_None;
1069 }
1070}
1071
1072static char ssl_Connection_want_read_doc[] = "\n\
1073Checks if more data has to be read from the transport layer to complete an\n\
1074operation.\n\
1075\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001076@return: True iff more data has to be read\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001077";
1078static PyObject *
1079ssl_Connection_want_read(ssl_ConnectionObj *self, PyObject *args)
1080{
1081 if (!PyArg_ParseTuple(args, ":want_read"))
1082 return NULL;
1083
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001084 return PyLong_FromLong((long)SSL_want_read(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001085}
1086
1087static char ssl_Connection_want_write_doc[] = "\n\
1088Checks if there is data to write to the transport layer to complete an\n\
1089operation.\n\
1090\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001091@return: True iff there is data to write\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001092";
1093static PyObject *
1094ssl_Connection_want_write(ssl_ConnectionObj *self, PyObject *args)
1095{
1096 if (!PyArg_ParseTuple(args, ":want_write"))
1097 return NULL;
1098
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001099 return PyLong_FromLong((long)SSL_want_write(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001100}
1101
1102/*
1103 * Member methods in the Connection object
1104 * ADD_METHOD(name) expands to a correct PyMethodDef declaration
1105 * { 'name', (PyCFunction)ssl_Connection_name, METH_VARARGS }
1106 * for convenience
1107 * ADD_ALIAS(name,real) creates an "alias" of the ssl_Connection_real
1108 * function with the name 'name'
1109 */
1110#define ADD_METHOD(name) \
1111 { #name, (PyCFunction)ssl_Connection_##name, METH_VARARGS, ssl_Connection_##name##_doc }
1112#define ADD_ALIAS(name,real) \
1113 { #name, (PyCFunction)ssl_Connection_##real, METH_VARARGS, ssl_Connection_##real##_doc }
1114static PyMethodDef ssl_Connection_methods[] =
1115{
1116 ADD_METHOD(get_context),
1117 ADD_METHOD(pending),
1118 ADD_METHOD(send),
1119 ADD_ALIAS (write, send),
1120 ADD_METHOD(sendall),
1121 ADD_METHOD(recv),
1122 ADD_ALIAS (read, recv),
Rick Deanb71c0d22009-04-01 14:09:23 -05001123 ADD_METHOD(bio_read),
1124 ADD_METHOD(bio_write),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001125 ADD_METHOD(renegotiate),
1126 ADD_METHOD(do_handshake),
1127#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
1128 ADD_METHOD(renegotiate_pending),
1129#endif
1130 ADD_METHOD(total_renegotiations),
1131 ADD_METHOD(connect),
1132 ADD_METHOD(connect_ex),
1133 ADD_METHOD(accept),
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04001134 ADD_METHOD(bio_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001135 ADD_METHOD(shutdown),
1136 ADD_METHOD(get_cipher_list),
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02001137 ADD_METHOD(get_client_ca_list),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001138 ADD_METHOD(makefile),
1139 ADD_METHOD(get_app_data),
1140 ADD_METHOD(set_app_data),
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001141 ADD_METHOD(get_shutdown),
1142 ADD_METHOD(set_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001143 ADD_METHOD(state_string),
Rick Deanb71c0d22009-04-01 14:09:23 -05001144 ADD_METHOD(server_random),
1145 ADD_METHOD(client_random),
1146 ADD_METHOD(master_key),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001147 ADD_METHOD(sock_shutdown),
1148 ADD_METHOD(get_peer_certificate),
1149 ADD_METHOD(want_read),
1150 ADD_METHOD(want_write),
1151 ADD_METHOD(set_accept_state),
1152 ADD_METHOD(set_connect_state),
1153 { NULL, NULL }
1154};
1155#undef ADD_ALIAS
1156#undef ADD_METHOD
1157
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001158static char ssl_Connection_doc[] = "\n\
1159Connection(context, socket) -> Connection instance\n\
1160\n\
1161Create a new Connection object, using the given OpenSSL.SSL.Context instance\n\
1162and socket.\n\
1163\n\
1164@param context: An SSL Context to use for this connection\n\
1165@param socket: The socket to use for transport layer\n\
1166";
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001167
1168/*
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001169 * Initializer used by ssl_Connection_new and ssl_Connection_New. *Not*
1170 * tp_init. This takes an already allocated ssl_ConnectionObj, a context, and
1171 * a optionally a socket, and glues them all together.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001172 */
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001173static ssl_ConnectionObj*
1174ssl_Connection_init(ssl_ConnectionObj *self, ssl_ContextObj *ctx, PyObject *sock) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001175 int fd;
1176
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001177 Py_INCREF(ctx);
1178 self->context = ctx;
1179
1180 Py_INCREF(sock);
1181 self->socket = sock;
1182
1183 self->ssl = NULL;
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04001184 self->from_ssl = NULL;
1185 self->into_ssl = NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001186
1187 Py_INCREF(Py_None);
1188 self->app_data = Py_None;
1189
1190 self->tstate = NULL;
1191
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001192 self->ssl = SSL_new(self->context->ctx);
1193 SSL_set_app_data(self->ssl, self);
Rick Deanb71c0d22009-04-01 14:09:23 -05001194
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001195 if (self->socket == Py_None)
Rick Deanb71c0d22009-04-01 14:09:23 -05001196 {
1197 /* If it's not a socket or file, treat it like a memory buffer,
1198 * so crazy people can do things like EAP-TLS. */
1199 self->into_ssl = BIO_new(BIO_s_mem());
1200 self->from_ssl = BIO_new(BIO_s_mem());
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001201 if (self->into_ssl == NULL || self->from_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -05001202 goto error;
1203 SSL_set_bio(self->ssl, self->into_ssl, self->from_ssl);
1204 }
1205 else
1206 {
1207 fd = PyObject_AsFileDescriptor(self->socket);
1208 if (fd < 0)
1209 {
1210 Py_DECREF(self);
1211 return NULL;
1212 }
1213 else
1214 {
1215 SSL_set_fd(self->ssl, (SOCKET_T)fd);
1216 }
1217 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001218 return self;
Rick Deanb71c0d22009-04-01 14:09:23 -05001219
1220error:
1221 BIO_free(self->into_ssl); /* NULL safe */
1222 BIO_free(self->from_ssl); /* NULL safe */
1223 Py_DECREF(self);
1224 return NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001225}
1226
1227/*
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001228 * Constructor for Connection objects
1229 *
1230 * Arguments: ctx - An SSL Context to use for this connection
1231 * sock - The socket to use for transport layer
1232 * Returns: The newly created Connection object
1233 */
1234ssl_ConnectionObj *
1235ssl_Connection_New(ssl_ContextObj *ctx, PyObject *sock) {
1236 ssl_ConnectionObj *self;
1237
1238 self = PyObject_GC_New(ssl_ConnectionObj, &ssl_Connection_Type);
1239 if (self == NULL) {
1240 return NULL;
1241 }
1242 self = ssl_Connection_init(self, ctx, sock);
1243 if (self == NULL) {
1244 return NULL;
1245 }
1246 PyObject_GC_Track((PyObject *)self);
1247 return self;
1248}
1249
1250static PyObject*
1251ssl_Connection_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs) {
1252 ssl_ConnectionObj *self;
1253 ssl_ContextObj *ctx;
1254 PyObject *sock;
1255 static char *kwlist[] = {"context", "socket", NULL};
1256
1257 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O:Connection", kwlist,
1258 &ssl_Context_Type, &ctx, &sock)) {
1259 return NULL;
1260 }
1261
1262 self = (ssl_ConnectionObj *)subtype->tp_alloc(subtype, 1);
1263 if (self == NULL) {
1264 return NULL;
1265 }
1266
1267 return (PyObject *)ssl_Connection_init(self, ctx, sock);
1268}
1269
1270/*
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001271 * Find attribute
1272 *
1273 * Arguments: self - The Connection object
1274 * name - The attribute name
1275 * Returns: A Python object for the attribute, or NULL if something went
1276 * wrong
1277 */
1278static PyObject *
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001279ssl_Connection_getattro(ssl_ConnectionObj *self, PyObject *nameobj) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001280 PyObject *meth;
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001281
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001282 meth = PyObject_GenericGetAttr((PyObject*)self, nameobj);
1283 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001284 PyErr_Clear();
1285 /* Try looking it up in the "socket" instead. */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001286 meth = PyObject_GenericGetAttr(self->socket, nameobj);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001287 }
1288
1289 return meth;
1290}
1291
1292/*
1293 * Call the visitproc on all contained objects.
1294 *
1295 * Arguments: self - The Connection object
1296 * visit - Function to call
1297 * arg - Extra argument to visit
1298 * Returns: 0 if all goes well, otherwise the return code from the first
1299 * call that gave non-zero result.
1300 */
1301static int
1302ssl_Connection_traverse(ssl_ConnectionObj *self, visitproc visit, void *arg)
1303{
1304 int ret = 0;
1305
1306 if (ret == 0 && self->context != NULL)
1307 ret = visit((PyObject *)self->context, arg);
1308 if (ret == 0 && self->socket != NULL)
1309 ret = visit(self->socket, arg);
1310 if (ret == 0 && self->app_data != NULL)
1311 ret = visit(self->app_data, arg);
1312 return ret;
1313}
1314
1315/*
1316 * Decref all contained objects and zero the pointers.
1317 *
1318 * Arguments: self - The Connection object
1319 * Returns: Always 0.
1320 */
1321static int
1322ssl_Connection_clear(ssl_ConnectionObj *self)
1323{
1324 Py_XDECREF(self->context);
1325 self->context = NULL;
1326 Py_XDECREF(self->socket);
1327 self->socket = NULL;
1328 Py_XDECREF(self->app_data);
1329 self->app_data = NULL;
Rick Deanb71c0d22009-04-01 14:09:23 -05001330 self->into_ssl = NULL; /* was cleaned up by SSL_free() */
1331 self->from_ssl = NULL; /* was cleaned up by SSL_free() */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001332 return 0;
1333}
1334
1335/*
1336 * Deallocate the memory used by the Connection object
1337 *
1338 * Arguments: self - The Connection object
1339 * Returns: None
1340 */
1341static void
1342ssl_Connection_dealloc(ssl_ConnectionObj *self)
1343{
1344 PyObject_GC_UnTrack(self);
1345 if (self->ssl != NULL)
1346 SSL_free(self->ssl);
1347 ssl_Connection_clear(self);
1348 PyObject_GC_Del(self);
1349}
1350
1351PyTypeObject ssl_Connection_Type = {
Jean-Paul Calderoneb6d75252010-08-11 23:55:45 -04001352 PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001353 "OpenSSL.SSL.Connection",
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001354 sizeof(ssl_ConnectionObj),
1355 0,
1356 (destructor)ssl_Connection_dealloc,
1357 NULL, /* print */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001358 NULL, /* tp_getattr */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001359 NULL, /* setattr */
1360 NULL, /* compare */
1361 NULL, /* repr */
1362 NULL, /* as_number */
1363 NULL, /* as_sequence */
1364 NULL, /* as_mapping */
1365 NULL, /* hash */
1366 NULL, /* call */
1367 NULL, /* str */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001368 (getattrofunc)ssl_Connection_getattro, /* getattro */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001369 NULL, /* setattro */
1370 NULL, /* as_buffer */
1371 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001372 ssl_Connection_doc, /* doc */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001373 (traverseproc)ssl_Connection_traverse,
1374 (inquiry)ssl_Connection_clear,
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001375 NULL, /* tp_richcompare */
1376 0, /* tp_weaklistoffset */
1377 NULL, /* tp_iter */
1378 NULL, /* tp_iternext */
1379 ssl_Connection_methods, /* tp_methods */
1380 NULL, /* tp_members */
1381 NULL, /* tp_getset */
1382 NULL, /* tp_base */
1383 NULL, /* tp_dict */
1384 NULL, /* tp_descr_get */
1385 NULL, /* tp_descr_set */
1386 0, /* tp_dictoffset */
1387 NULL, /* tp_init */
1388 NULL, /* tp_alloc */
1389 ssl_Connection_new, /* tp_new */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001390};
1391
1392
1393/*
1394 * Initiailze the Connection part of the SSL sub module
1395 *
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001396 * Arguments: dict - The OpenSSL.SSL module
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001397 * Returns: 1 for success, 0 otherwise
1398 */
1399int
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001400init_ssl_connection(PyObject *module) {
1401
1402 if (PyType_Ready(&ssl_Connection_Type) < 0) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001403 return 0;
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001404 }
1405
1406 if (PyModule_AddObject(module, "Connection", (PyObject *)&ssl_Connection_Type) != 0) {
1407 return 0;
1408 }
1409
1410 if (PyModule_AddObject(module, "ConnectionType", (PyObject *)&ssl_Connection_Type) != 0) {
1411 return 0;
1412 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001413
1414 return 1;
1415}
1416