blob: f2881d3f9dbf32c243d5f25fb4d4c0a58b72c255 [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 *
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500334ssl_Connection_send(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500335 int len, ret, err, flags;
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500336 char *buf;
337
338#if PY_VERSION_HEX >= 0x02060000
339 Py_buffer pbuf;
340
341 if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
342 return NULL;
343
344 buf = pbuf.buf;
345 len = pbuf.len;
346#else
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500347
348 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
349 return NULL;
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500350#endif
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500351
352 MY_BEGIN_ALLOW_THREADS(self->tstate)
353 ret = SSL_write(self->ssl, buf, len);
354 MY_END_ALLOW_THREADS(self->tstate)
355
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500356#if PY_VERSION_HEX >= 0x02060000
357 PyBuffer_Release(&pbuf);
358#endif
359
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500360 if (PyErr_Occurred())
361 {
362 flush_error_queue();
363 return NULL;
364 }
365
366 err = SSL_get_error(self->ssl, ret);
367 if (err == SSL_ERROR_NONE)
368 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400369 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500370 }
371 else
372 {
373 handle_ssl_errors(self->ssl, err, ret);
374 return NULL;
375 }
376}
377
378static char ssl_Connection_sendall_doc[] = "\n\
379Send \"all\" data on the connection. This calls send() repeatedly until\n\
380all data is sent. If an error occurs, it's impossible to tell how much data\n\
381has been sent.\n\
382\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400383@param buf: The string to send\n\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500384@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400385 API, the value is ignored\n\
386@return: The number of bytes written\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500387";
388static PyObject *
389ssl_Connection_sendall(ssl_ConnectionObj *self, PyObject *args)
390{
391 char *buf;
392 int len, ret, err, flags;
393 PyObject *pyret = Py_None;
394
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500395#if PY_VERSION_HEX >= 0x02060000
396 Py_buffer pbuf;
397
398 if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
399 return NULL;
400
401 buf = pbuf.buf;
402 len = pbuf.len;
403#else
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500404 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
405 return NULL;
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500406#endif
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500407
408 do {
409 MY_BEGIN_ALLOW_THREADS(self->tstate)
410 ret = SSL_write(self->ssl, buf, len);
411 MY_END_ALLOW_THREADS(self->tstate)
412 if (PyErr_Occurred())
413 {
414 flush_error_queue();
415 pyret = NULL;
416 break;
417 }
418 err = SSL_get_error(self->ssl, ret);
419 if (err == SSL_ERROR_NONE)
420 {
421 buf += ret;
422 len -= ret;
423 }
424 else if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL ||
425 err == SSL_ERROR_ZERO_RETURN)
426 {
427 handle_ssl_errors(self->ssl, err, ret);
428 pyret = NULL;
429 break;
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500430 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500431 } while (len > 0);
432
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500433#if PY_VERSION_HEX >= 0x02060000
434 PyBuffer_Release(&pbuf);
435#endif
436
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500437 Py_XINCREF(pyret);
438 return pyret;
439}
440
441static char ssl_Connection_recv_doc[] = "\n\
442Receive data on the connection. NOTE: If you get one of the WantRead,\n\
443WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
444method again with the SAME buffer.\n\
445\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400446@param bufsiz: The maximum number of bytes to read\n\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500447@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400448 API, the value is ignored\n\
449@return: The string read from the Connection\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500450";
451static PyObject *
452ssl_Connection_recv(ssl_ConnectionObj *self, PyObject *args)
453{
454 int bufsiz, ret, err, flags;
455 PyObject *buf;
456
457 if (!PyArg_ParseTuple(args, "i|i:recv", &bufsiz, &flags))
458 return NULL;
459
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400460 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500461 if (buf == NULL)
462 return NULL;
463
464 MY_BEGIN_ALLOW_THREADS(self->tstate)
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400465 ret = SSL_read(self->ssl, PyBytes_AsString(buf), bufsiz);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500466 MY_END_ALLOW_THREADS(self->tstate)
467
468 if (PyErr_Occurred())
469 {
470 Py_DECREF(buf);
471 flush_error_queue();
472 return NULL;
473 }
474
475 err = SSL_get_error(self->ssl, ret);
476 if (err == SSL_ERROR_NONE)
477 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400478 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500479 return NULL;
480 return buf;
481 }
482 else
483 {
484 handle_ssl_errors(self->ssl, err, ret);
485 Py_DECREF(buf);
486 return NULL;
487 }
488}
489
Rick Deanb71c0d22009-04-01 14:09:23 -0500490static char ssl_Connection_bio_read_doc[] = "\n\
491When using non-socket connections this function reads\n\
492the \"dirty\" data that would have traveled away on the network.\n\
493\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400494@param bufsiz: The maximum number of bytes to read\n\
495@return: The string read.\n\
Rick Deanb71c0d22009-04-01 14:09:23 -0500496";
497static PyObject *
498ssl_Connection_bio_read(ssl_ConnectionObj *self, PyObject *args)
499{
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400500 int bufsiz, ret;
Rick Deanb71c0d22009-04-01 14:09:23 -0500501 PyObject *buf;
502
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400503 if (self->from_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -0500504 {
505 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
506 return NULL;
507 }
508
509 if (!PyArg_ParseTuple(args, "i:bio_read", &bufsiz))
510 return NULL;
511
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400512 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
Rick Deanb71c0d22009-04-01 14:09:23 -0500513 if (buf == NULL)
514 return NULL;
515
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400516 ret = BIO_read(self->from_ssl, PyBytes_AsString(buf), bufsiz);
Rick Deanb71c0d22009-04-01 14:09:23 -0500517
518 if (PyErr_Occurred())
519 {
520 Py_DECREF(buf);
521 flush_error_queue();
522 return NULL;
523 }
524
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400525 if (ret <= 0) {
526 /*
527 * There was a problem with the BIO_read of some sort.
528 */
529 handle_bio_errors(self->from_ssl, ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500530 Py_DECREF(buf);
531 return NULL;
532 }
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400533
534 /*
535 * Shrink the string to match the number of bytes we actually read.
536 */
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400537 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400538 {
539 Py_DECREF(buf);
540 return NULL;
541 }
542 return buf;
Rick Deanb71c0d22009-04-01 14:09:23 -0500543}
544
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500545static char ssl_Connection_renegotiate_doc[] = "\n\
546Renegotiate the session\n\
547\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400548@return: True if the renegotiation can be started, false otherwise\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500549";
550static PyObject *
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400551ssl_Connection_renegotiate(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500552 int ret;
553
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400554 if (!PyArg_ParseTuple(args, ":renegotiate")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500555 return NULL;
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400556 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500557
558 MY_BEGIN_ALLOW_THREADS(self->tstate);
559 ret = SSL_renegotiate(self->ssl);
560 MY_END_ALLOW_THREADS(self->tstate);
561
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400562 if (PyErr_Occurred()) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500563 flush_error_queue();
564 return NULL;
565 }
566
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400567 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500568}
569
570static char ssl_Connection_do_handshake_doc[] = "\n\
571Perform an SSL handshake (usually called after renegotiate() or one of\n\
572set_*_state()). This can raise the same exceptions as send and recv.\n\
573\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400574@return: None.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500575";
576static PyObject *
577ssl_Connection_do_handshake(ssl_ConnectionObj *self, PyObject *args)
578{
579 int ret, err;
580
581 if (!PyArg_ParseTuple(args, ":do_handshake"))
582 return NULL;
583
584 MY_BEGIN_ALLOW_THREADS(self->tstate);
585 ret = SSL_do_handshake(self->ssl);
586 MY_END_ALLOW_THREADS(self->tstate);
587
588 if (PyErr_Occurred())
589 {
590 flush_error_queue();
591 return NULL;
592 }
593
594 err = SSL_get_error(self->ssl, ret);
595 if (err == SSL_ERROR_NONE)
596 {
597 Py_INCREF(Py_None);
598 return Py_None;
599 }
600 else
601 {
602 handle_ssl_errors(self->ssl, err, ret);
603 return NULL;
604 }
605}
606
607#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
608static char ssl_Connection_renegotiate_pending_doc[] = "\n\
609Check if there's a renegotiation in progress, it will return false once\n\
610a renegotiation is finished.\n\
611\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400612@return: Whether there's a renegotiation in progress\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500613";
614static PyObject *
615ssl_Connection_renegotiate_pending(ssl_ConnectionObj *self, PyObject *args)
616{
617 if (!PyArg_ParseTuple(args, ":renegotiate_pending"))
618 return NULL;
619
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400620 return PyLong_FromLong((long)SSL_renegotiate_pending(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500621}
622#endif
623
624static char ssl_Connection_total_renegotiations_doc[] = "\n\
625Find out the total number of renegotiations.\n\
626\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400627@return: The number of renegotiations.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500628";
629static PyObject *
630ssl_Connection_total_renegotiations(ssl_ConnectionObj *self, PyObject *args)
631{
632 if (!PyArg_ParseTuple(args, ":total_renegotiations"))
633 return NULL;
634
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400635 return PyLong_FromLong(SSL_total_renegotiations(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500636}
637
638static char ssl_Connection_set_accept_state_doc[] = "\n\
639Set the connection to work in server mode. The handshake will be handled\n\
640automatically by read/write.\n\
641\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400642@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500643";
644static PyObject *
645ssl_Connection_set_accept_state(ssl_ConnectionObj *self, PyObject *args)
646{
647 if (!PyArg_ParseTuple(args, ":set_accept_state"))
648 return NULL;
649
650 SSL_set_accept_state(self->ssl);
651
652 Py_INCREF(Py_None);
653 return Py_None;
654}
655
656static char ssl_Connection_set_connect_state_doc[] = "\n\
657Set the connection to work in client mode. The handshake will be handled\n\
658automatically by read/write.\n\
659\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400660@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500661";
662static PyObject *
663ssl_Connection_set_connect_state(ssl_ConnectionObj *self, PyObject *args)
664{
665 if (!PyArg_ParseTuple(args, ":set_connect_state"))
666 return NULL;
667
668 SSL_set_connect_state(self->ssl);
669
670 Py_INCREF(Py_None);
671 return Py_None;
672}
673
674static char ssl_Connection_connect_doc[] = "\n\
675Connect to remote host and set up client-side SSL\n\
676\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400677@param addr: A remote address\n\
678@return: What the socket's connect method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500679";
680static PyObject *
681ssl_Connection_connect(ssl_ConnectionObj *self, PyObject *args)
682{
683 PyObject *meth, *ret;
684
685 if ((meth = PyObject_GetAttrString(self->socket, "connect")) == NULL)
686 return NULL;
687
688 SSL_set_connect_state(self->ssl);
689
690 ret = PyEval_CallObject(meth, args);
691 Py_DECREF(meth);
692 if (ret == NULL)
693 return NULL;
694
695 return ret;
696}
697
698static char ssl_Connection_connect_ex_doc[] = "\n\
699Connect to remote host and set up client-side SSL. Note that if the socket's\n\
700connect_ex method doesn't return 0, SSL won't be initialized.\n\
701\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400702@param addr: A remove address\n\
703@return: What the socket's connect_ex method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500704";
705static PyObject *
706ssl_Connection_connect_ex(ssl_ConnectionObj *self, PyObject *args)
707{
708 PyObject *meth, *ret;
709
710 if ((meth = PyObject_GetAttrString(self->socket, "connect_ex")) == NULL)
711 return NULL;
712
713 SSL_set_connect_state(self->ssl);
714
715 ret = PyEval_CallObject(meth, args);
716 Py_DECREF(meth);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500717 return ret;
718}
719
720static char ssl_Connection_accept_doc[] = "\n\
721Accept incoming connection and set up SSL on it\n\
722\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400723@return: A (conn,addr) pair where conn is a Connection and addr is an\n\
724 address\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500725";
726static PyObject *
727ssl_Connection_accept(ssl_ConnectionObj *self, PyObject *args)
728{
729 PyObject *tuple, *socket, *address, *meth;
730 ssl_ConnectionObj *conn;
731
732 if ((meth = PyObject_GetAttrString(self->socket, "accept")) == NULL)
733 return NULL;
734 tuple = PyEval_CallObject(meth, args);
735 Py_DECREF(meth);
736 if (tuple == NULL)
737 return NULL;
738
739 socket = PyTuple_GetItem(tuple, 0);
740 Py_INCREF(socket);
741 address = PyTuple_GetItem(tuple, 1);
742 Py_INCREF(address);
743 Py_DECREF(tuple);
744
745 conn = ssl_Connection_New(self->context, socket);
746 Py_DECREF(socket);
747 if (conn == NULL)
748 {
749 Py_DECREF(address);
750 return NULL;
751 }
752
753 SSL_set_accept_state(conn->ssl);
754
755 tuple = Py_BuildValue("(OO)", conn, address);
756
757 Py_DECREF(conn);
758 Py_DECREF(address);
759
760 return tuple;
761}
762
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400763static char ssl_Connection_bio_shutdown_doc[] = "\n\
764When using non-socket connections this function signals end of\n\
765data on the input for this connection.\n\
766\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400767@return: None\n\
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400768";
769
770static PyObject *
771ssl_Connection_bio_shutdown(ssl_ConnectionObj *self, PyObject *args)
772{
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400773 if (self->from_ssl == NULL)
774 {
775 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
776 return NULL;
777 }
778
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400779 BIO_set_mem_eof_return(self->into_ssl, 0);
780 Py_INCREF(Py_None);
781 return Py_None;
782}
783
784
785
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500786static char ssl_Connection_shutdown_doc[] = "\n\
787Send closure alert\n\
788\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400789@return: True if the shutdown completed successfully (i.e. both sides\n\
790 have sent closure alerts), false otherwise (i.e. you have to\n\
791 wait for a ZeroReturnError on a recv() method call\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500792";
793static PyObject *
794ssl_Connection_shutdown(ssl_ConnectionObj *self, PyObject *args)
795{
796 int ret;
797
798 if (!PyArg_ParseTuple(args, ":shutdown"))
799 return NULL;
800
801 MY_BEGIN_ALLOW_THREADS(self->tstate)
802 ret = SSL_shutdown(self->ssl);
803 MY_END_ALLOW_THREADS(self->tstate)
804
805 if (PyErr_Occurred())
806 {
807 flush_error_queue();
808 return NULL;
809 }
810
811 if (ret < 0)
812 {
Rick Deand369c932009-07-08 11:48:33 -0500813 exception_from_error_queue(ssl_Error);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500814 return NULL;
815 }
816 else if (ret > 0)
817 {
818 Py_INCREF(Py_True);
819 return Py_True;
820 }
821 else
822 {
823 Py_INCREF(Py_False);
824 return Py_False;
825 }
826}
827
828static char ssl_Connection_get_cipher_list_doc[] = "\n\
829Get the session cipher list\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500830\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400831@return: A list of cipher strings\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500832";
833static PyObject *
834ssl_Connection_get_cipher_list(ssl_ConnectionObj *self, PyObject *args)
835{
836 int idx = 0;
837 const char *ret;
838 PyObject *lst, *item;
839
840 if (!PyArg_ParseTuple(args, ":get_cipher_list"))
841 return NULL;
842
843 lst = PyList_New(0);
844 while ((ret = SSL_get_cipher_list(self->ssl, idx)) != NULL)
845 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400846 item = PyText_FromString(ret);
Ziga Seilnachtfdeadb12009-09-01 16:35:50 +0200847 PyList_Append(lst, item);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500848 Py_DECREF(item);
849 idx++;
850 }
851 return lst;
852}
853
Ziga Seilnachtf93bf102009-10-23 09:51:07 +0200854static char ssl_Connection_get_client_ca_list_doc[] = "\n\
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200855Get CAs whose certificates are suggested for client authentication.\n\
856\n\
Jean-Paul Calderone35788902009-10-24 13:48:08 -0400857@return: If this is a server connection, a list of X509Names representing\n\
858 the acceptable CAs as set by L{OpenSSL.SSL.Context.set_client_ca_list} or\n\
859 L{OpenSSL.SSL.Context.add_client_ca}. If this is a client connection,\n\
860 the list of such X509Names sent by the server, or an empty list if that\n\
861 has not yet happened.\n\
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200862";
863
864static PyObject *
Jean-Paul Calderone6e2b6852009-10-24 14:04:30 -0400865ssl_Connection_get_client_ca_list(ssl_ConnectionObj *self, PyObject *args) {
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200866 STACK_OF(X509_NAME) *CANames;
867 PyObject *CAList;
868 int i, n;
869
Ziga Seilnachtf93bf102009-10-23 09:51:07 +0200870 if (!PyArg_ParseTuple(args, ":get_client_ca_list")) {
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200871 return NULL;
872 }
873 CANames = SSL_get_client_CA_list(self->ssl);
874 if (CANames == NULL) {
875 return PyList_New(0);
876 }
877 n = sk_X509_NAME_num(CANames);
878 CAList = PyList_New(n);
879 if (CAList == NULL) {
880 return NULL;
881 }
882 for (i = 0; i < n; i++) {
883 X509_NAME *CAName;
884 PyObject *CA;
885
886 CAName = X509_NAME_dup(sk_X509_NAME_value(CANames, i));
887 if (CAName == NULL) {
888 Py_DECREF(CAList);
889 exception_from_error_queue(ssl_Error);
890 return NULL;
891 }
Jean-Paul Calderone305626a2010-10-31 20:51:17 -0400892 CA = (PyObject *)new_x509name(CAName, 1);
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200893 if (CA == NULL) {
894 X509_NAME_free(CAName);
895 Py_DECREF(CAList);
896 return NULL;
897 }
898 if (PyList_SetItem(CAList, i, CA)) {
899 Py_DECREF(CA);
900 Py_DECREF(CAList);
901 return NULL;
902 }
903 }
904 return CAList;
905}
906
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500907static char ssl_Connection_makefile_doc[] = "\n\
908The makefile() method is not implemented, since there is no dup semantics\n\
909for SSL connections\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500910\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400911@raise NotImplementedError\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500912";
913static PyObject *
914ssl_Connection_makefile(ssl_ConnectionObj *self, PyObject *args)
915{
916 PyErr_SetString(PyExc_NotImplementedError, "Cannot make file object of SSL.Connection");
917 return NULL;
918}
919
920static char ssl_Connection_get_app_data_doc[] = "\n\
921Get application data\n\
922\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400923@return: The application data\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500924";
925static PyObject *
926ssl_Connection_get_app_data(ssl_ConnectionObj *self, PyObject *args)
927{
928 if (!PyArg_ParseTuple(args, ":get_app_data"))
929 return NULL;
930
931 Py_INCREF(self->app_data);
932 return self->app_data;
933}
934
935static char ssl_Connection_set_app_data_doc[] = "\n\
936Set application data\n\
937\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400938@param data - The application data\n\
939@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500940";
941static PyObject *
942ssl_Connection_set_app_data(ssl_ConnectionObj *self, PyObject *args)
943{
944 PyObject *data;
945
946 if (!PyArg_ParseTuple(args, "O:set_app_data", &data))
947 return NULL;
948
949 Py_DECREF(self->app_data);
950 Py_INCREF(data);
951 self->app_data = data;
952
953 Py_INCREF(Py_None);
954 return Py_None;
955}
956
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500957static char ssl_Connection_get_shutdown_doc[] = "\n\
958Get shutdown state\n\
959\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400960@return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500961";
962static PyObject *
963ssl_Connection_get_shutdown(ssl_ConnectionObj *self, PyObject *args)
964{
965 if (!PyArg_ParseTuple(args, ":get_shutdown"))
966 return NULL;
967
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400968 return PyLong_FromLong((long)SSL_get_shutdown(self->ssl));
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500969}
970
971static char ssl_Connection_set_shutdown_doc[] = "\n\
972Set shutdown state\n\
973\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400974@param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
975@return: None\n\
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500976";
977static PyObject *
978ssl_Connection_set_shutdown(ssl_ConnectionObj *self, PyObject *args)
979{
980 int shutdown;
981
982 if (!PyArg_ParseTuple(args, "i:set_shutdown", &shutdown))
983 return NULL;
984
985 SSL_set_shutdown(self->ssl, shutdown);
986 Py_INCREF(Py_None);
987 return Py_None;
988}
989
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500990static char ssl_Connection_state_string_doc[] = "\n\
991Get a verbose state description\n\
992\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400993@return: A string representing the state\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500994";
995static PyObject *
996ssl_Connection_state_string(ssl_ConnectionObj *self, PyObject *args)
997{
998 if (!PyArg_ParseTuple(args, ":state_string"))
999 return NULL;
1000
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001001 return PyText_FromString(SSL_state_string_long(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001002}
1003
Rick Deanb71c0d22009-04-01 14:09:23 -05001004static char ssl_Connection_client_random_doc[] = "\n\
1005Get a copy of the client hello nonce.\n\
1006\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001007@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001008";
1009static PyObject *
1010ssl_Connection_client_random(ssl_ConnectionObj *self, PyObject *args)
1011{
1012 if (!PyArg_ParseTuple(args, ":client_random"))
1013 return NULL;
1014
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001015 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001016 Py_INCREF(Py_None);
1017 return Py_None;
1018 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001019 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->client_random, SSL3_RANDOM_SIZE);
Rick Deanb71c0d22009-04-01 14:09:23 -05001020}
1021
1022static char ssl_Connection_server_random_doc[] = "\n\
1023Get a copy of the server hello nonce.\n\
1024\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001025@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001026";
1027static PyObject *
1028ssl_Connection_server_random(ssl_ConnectionObj *self, PyObject *args)
1029{
1030 if (!PyArg_ParseTuple(args, ":server_random"))
1031 return NULL;
1032
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001033 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001034 Py_INCREF(Py_None);
1035 return Py_None;
1036 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001037 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->server_random, SSL3_RANDOM_SIZE);
Rick Deanb71c0d22009-04-01 14:09:23 -05001038}
1039
1040static char ssl_Connection_master_key_doc[] = "\n\
1041Get a copy of the master key.\n\
1042\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001043@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001044";
1045static PyObject *
1046ssl_Connection_master_key(ssl_ConnectionObj *self, PyObject *args)
1047{
1048 if (!PyArg_ParseTuple(args, ":master_key"))
1049 return NULL;
1050
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001051 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001052 Py_INCREF(Py_None);
1053 return Py_None;
1054 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001055 return PyBytes_FromStringAndSize( (const char *) self->ssl->session->master_key, self->ssl->session->master_key_length);
Rick Deanb71c0d22009-04-01 14:09:23 -05001056}
1057
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001058static char ssl_Connection_sock_shutdown_doc[] = "\n\
1059See shutdown(2)\n\
1060\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001061@return: What the socket's shutdown() method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001062";
1063static PyObject *
1064ssl_Connection_sock_shutdown(ssl_ConnectionObj *self, PyObject *args)
1065{
1066 PyObject *meth, *ret;
1067
1068 if ((meth = PyObject_GetAttrString(self->socket, "shutdown")) == NULL)
1069 return NULL;
1070 ret = PyEval_CallObject(meth, args);
1071 Py_DECREF(meth);
1072 return ret;
1073}
1074
1075static char ssl_Connection_get_peer_certificate_doc[] = "\n\
1076Retrieve the other side's certificate (if any)\n\
1077\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001078@return: The peer's certificate\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001079";
1080static PyObject *
1081ssl_Connection_get_peer_certificate(ssl_ConnectionObj *self, PyObject *args)
1082{
1083 X509 *cert;
1084
1085 if (!PyArg_ParseTuple(args, ":get_peer_certificate"))
1086 return NULL;
1087
1088 cert = SSL_get_peer_certificate(self->ssl);
1089 if (cert != NULL)
1090 {
Jean-Paul Calderone5c0f1f62010-10-31 21:36:43 -04001091 return (PyObject *)new_x509(cert, 1);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001092 }
1093 else
1094 {
1095 Py_INCREF(Py_None);
1096 return Py_None;
1097 }
1098}
1099
1100static char ssl_Connection_want_read_doc[] = "\n\
1101Checks if more data has to be read from the transport layer to complete an\n\
1102operation.\n\
1103\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001104@return: True iff more data has to be read\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001105";
1106static PyObject *
1107ssl_Connection_want_read(ssl_ConnectionObj *self, PyObject *args)
1108{
1109 if (!PyArg_ParseTuple(args, ":want_read"))
1110 return NULL;
1111
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001112 return PyLong_FromLong((long)SSL_want_read(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001113}
1114
1115static char ssl_Connection_want_write_doc[] = "\n\
1116Checks if there is data to write to the transport layer to complete an\n\
1117operation.\n\
1118\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001119@return: True iff there is data to write\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001120";
1121static PyObject *
1122ssl_Connection_want_write(ssl_ConnectionObj *self, PyObject *args)
1123{
1124 if (!PyArg_ParseTuple(args, ":want_write"))
1125 return NULL;
1126
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001127 return PyLong_FromLong((long)SSL_want_write(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001128}
1129
1130/*
1131 * Member methods in the Connection object
1132 * ADD_METHOD(name) expands to a correct PyMethodDef declaration
1133 * { 'name', (PyCFunction)ssl_Connection_name, METH_VARARGS }
1134 * for convenience
1135 * ADD_ALIAS(name,real) creates an "alias" of the ssl_Connection_real
1136 * function with the name 'name'
1137 */
1138#define ADD_METHOD(name) \
1139 { #name, (PyCFunction)ssl_Connection_##name, METH_VARARGS, ssl_Connection_##name##_doc }
1140#define ADD_ALIAS(name,real) \
1141 { #name, (PyCFunction)ssl_Connection_##real, METH_VARARGS, ssl_Connection_##real##_doc }
1142static PyMethodDef ssl_Connection_methods[] =
1143{
1144 ADD_METHOD(get_context),
1145 ADD_METHOD(pending),
1146 ADD_METHOD(send),
1147 ADD_ALIAS (write, send),
1148 ADD_METHOD(sendall),
1149 ADD_METHOD(recv),
1150 ADD_ALIAS (read, recv),
Rick Deanb71c0d22009-04-01 14:09:23 -05001151 ADD_METHOD(bio_read),
1152 ADD_METHOD(bio_write),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001153 ADD_METHOD(renegotiate),
1154 ADD_METHOD(do_handshake),
1155#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
1156 ADD_METHOD(renegotiate_pending),
1157#endif
1158 ADD_METHOD(total_renegotiations),
1159 ADD_METHOD(connect),
1160 ADD_METHOD(connect_ex),
1161 ADD_METHOD(accept),
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04001162 ADD_METHOD(bio_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001163 ADD_METHOD(shutdown),
1164 ADD_METHOD(get_cipher_list),
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02001165 ADD_METHOD(get_client_ca_list),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001166 ADD_METHOD(makefile),
1167 ADD_METHOD(get_app_data),
1168 ADD_METHOD(set_app_data),
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001169 ADD_METHOD(get_shutdown),
1170 ADD_METHOD(set_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001171 ADD_METHOD(state_string),
Rick Deanb71c0d22009-04-01 14:09:23 -05001172 ADD_METHOD(server_random),
1173 ADD_METHOD(client_random),
1174 ADD_METHOD(master_key),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001175 ADD_METHOD(sock_shutdown),
1176 ADD_METHOD(get_peer_certificate),
1177 ADD_METHOD(want_read),
1178 ADD_METHOD(want_write),
1179 ADD_METHOD(set_accept_state),
1180 ADD_METHOD(set_connect_state),
1181 { NULL, NULL }
1182};
1183#undef ADD_ALIAS
1184#undef ADD_METHOD
1185
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001186static char ssl_Connection_doc[] = "\n\
1187Connection(context, socket) -> Connection instance\n\
1188\n\
1189Create a new Connection object, using the given OpenSSL.SSL.Context instance\n\
1190and socket.\n\
1191\n\
1192@param context: An SSL Context to use for this connection\n\
1193@param socket: The socket to use for transport layer\n\
1194";
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001195
1196/*
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001197 * Initializer used by ssl_Connection_new and ssl_Connection_New. *Not*
1198 * tp_init. This takes an already allocated ssl_ConnectionObj, a context, and
1199 * a optionally a socket, and glues them all together.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001200 */
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001201static ssl_ConnectionObj*
1202ssl_Connection_init(ssl_ConnectionObj *self, ssl_ContextObj *ctx, PyObject *sock) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001203 int fd;
1204
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001205 Py_INCREF(ctx);
1206 self->context = ctx;
1207
1208 Py_INCREF(sock);
1209 self->socket = sock;
1210
1211 self->ssl = NULL;
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04001212 self->from_ssl = NULL;
1213 self->into_ssl = NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001214
1215 Py_INCREF(Py_None);
1216 self->app_data = Py_None;
1217
1218 self->tstate = NULL;
1219
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001220 self->ssl = SSL_new(self->context->ctx);
1221 SSL_set_app_data(self->ssl, self);
Rick Deanb71c0d22009-04-01 14:09:23 -05001222
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001223 if (self->socket == Py_None)
Rick Deanb71c0d22009-04-01 14:09:23 -05001224 {
1225 /* If it's not a socket or file, treat it like a memory buffer,
1226 * so crazy people can do things like EAP-TLS. */
1227 self->into_ssl = BIO_new(BIO_s_mem());
1228 self->from_ssl = BIO_new(BIO_s_mem());
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001229 if (self->into_ssl == NULL || self->from_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -05001230 goto error;
1231 SSL_set_bio(self->ssl, self->into_ssl, self->from_ssl);
1232 }
1233 else
1234 {
1235 fd = PyObject_AsFileDescriptor(self->socket);
1236 if (fd < 0)
1237 {
1238 Py_DECREF(self);
1239 return NULL;
1240 }
1241 else
1242 {
1243 SSL_set_fd(self->ssl, (SOCKET_T)fd);
1244 }
1245 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001246 return self;
Rick Deanb71c0d22009-04-01 14:09:23 -05001247
1248error:
1249 BIO_free(self->into_ssl); /* NULL safe */
1250 BIO_free(self->from_ssl); /* NULL safe */
1251 Py_DECREF(self);
1252 return NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001253}
1254
1255/*
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001256 * Constructor for Connection objects
1257 *
1258 * Arguments: ctx - An SSL Context to use for this connection
1259 * sock - The socket to use for transport layer
1260 * Returns: The newly created Connection object
1261 */
1262ssl_ConnectionObj *
1263ssl_Connection_New(ssl_ContextObj *ctx, PyObject *sock) {
1264 ssl_ConnectionObj *self;
1265
1266 self = PyObject_GC_New(ssl_ConnectionObj, &ssl_Connection_Type);
1267 if (self == NULL) {
1268 return NULL;
1269 }
1270 self = ssl_Connection_init(self, ctx, sock);
1271 if (self == NULL) {
1272 return NULL;
1273 }
1274 PyObject_GC_Track((PyObject *)self);
1275 return self;
1276}
1277
1278static PyObject*
1279ssl_Connection_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs) {
1280 ssl_ConnectionObj *self;
1281 ssl_ContextObj *ctx;
1282 PyObject *sock;
1283 static char *kwlist[] = {"context", "socket", NULL};
1284
1285 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O:Connection", kwlist,
1286 &ssl_Context_Type, &ctx, &sock)) {
1287 return NULL;
1288 }
1289
1290 self = (ssl_ConnectionObj *)subtype->tp_alloc(subtype, 1);
1291 if (self == NULL) {
1292 return NULL;
1293 }
1294
1295 return (PyObject *)ssl_Connection_init(self, ctx, sock);
1296}
1297
1298/*
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001299 * Find attribute
1300 *
1301 * Arguments: self - The Connection object
1302 * name - The attribute name
1303 * Returns: A Python object for the attribute, or NULL if something went
1304 * wrong
1305 */
1306static PyObject *
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001307ssl_Connection_getattro(ssl_ConnectionObj *self, PyObject *nameobj) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001308 PyObject *meth;
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001309
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001310 meth = PyObject_GenericGetAttr((PyObject*)self, nameobj);
1311 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001312 PyErr_Clear();
1313 /* Try looking it up in the "socket" instead. */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001314 meth = PyObject_GenericGetAttr(self->socket, nameobj);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001315 }
1316
1317 return meth;
1318}
1319
1320/*
1321 * Call the visitproc on all contained objects.
1322 *
1323 * Arguments: self - The Connection object
1324 * visit - Function to call
1325 * arg - Extra argument to visit
1326 * Returns: 0 if all goes well, otherwise the return code from the first
1327 * call that gave non-zero result.
1328 */
1329static int
1330ssl_Connection_traverse(ssl_ConnectionObj *self, visitproc visit, void *arg)
1331{
1332 int ret = 0;
1333
1334 if (ret == 0 && self->context != NULL)
1335 ret = visit((PyObject *)self->context, arg);
1336 if (ret == 0 && self->socket != NULL)
1337 ret = visit(self->socket, arg);
1338 if (ret == 0 && self->app_data != NULL)
1339 ret = visit(self->app_data, arg);
1340 return ret;
1341}
1342
1343/*
1344 * Decref all contained objects and zero the pointers.
1345 *
1346 * Arguments: self - The Connection object
1347 * Returns: Always 0.
1348 */
1349static int
1350ssl_Connection_clear(ssl_ConnectionObj *self)
1351{
1352 Py_XDECREF(self->context);
1353 self->context = NULL;
1354 Py_XDECREF(self->socket);
1355 self->socket = NULL;
1356 Py_XDECREF(self->app_data);
1357 self->app_data = NULL;
Rick Deanb71c0d22009-04-01 14:09:23 -05001358 self->into_ssl = NULL; /* was cleaned up by SSL_free() */
1359 self->from_ssl = NULL; /* was cleaned up by SSL_free() */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001360 return 0;
1361}
1362
1363/*
1364 * Deallocate the memory used by the Connection object
1365 *
1366 * Arguments: self - The Connection object
1367 * Returns: None
1368 */
1369static void
1370ssl_Connection_dealloc(ssl_ConnectionObj *self)
1371{
1372 PyObject_GC_UnTrack(self);
1373 if (self->ssl != NULL)
1374 SSL_free(self->ssl);
1375 ssl_Connection_clear(self);
1376 PyObject_GC_Del(self);
1377}
1378
1379PyTypeObject ssl_Connection_Type = {
Jean-Paul Calderoneb6d75252010-08-11 23:55:45 -04001380 PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001381 "OpenSSL.SSL.Connection",
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001382 sizeof(ssl_ConnectionObj),
1383 0,
1384 (destructor)ssl_Connection_dealloc,
1385 NULL, /* print */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001386 NULL, /* tp_getattr */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001387 NULL, /* setattr */
1388 NULL, /* compare */
1389 NULL, /* repr */
1390 NULL, /* as_number */
1391 NULL, /* as_sequence */
1392 NULL, /* as_mapping */
1393 NULL, /* hash */
1394 NULL, /* call */
1395 NULL, /* str */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001396 (getattrofunc)ssl_Connection_getattro, /* getattro */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001397 NULL, /* setattro */
1398 NULL, /* as_buffer */
1399 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001400 ssl_Connection_doc, /* doc */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001401 (traverseproc)ssl_Connection_traverse,
1402 (inquiry)ssl_Connection_clear,
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001403 NULL, /* tp_richcompare */
1404 0, /* tp_weaklistoffset */
1405 NULL, /* tp_iter */
1406 NULL, /* tp_iternext */
1407 ssl_Connection_methods, /* tp_methods */
1408 NULL, /* tp_members */
1409 NULL, /* tp_getset */
1410 NULL, /* tp_base */
1411 NULL, /* tp_dict */
1412 NULL, /* tp_descr_get */
1413 NULL, /* tp_descr_set */
1414 0, /* tp_dictoffset */
1415 NULL, /* tp_init */
1416 NULL, /* tp_alloc */
1417 ssl_Connection_new, /* tp_new */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001418};
1419
1420
1421/*
1422 * Initiailze the Connection part of the SSL sub module
1423 *
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001424 * Arguments: dict - The OpenSSL.SSL module
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001425 * Returns: 1 for success, 0 otherwise
1426 */
1427int
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001428init_ssl_connection(PyObject *module) {
1429
1430 if (PyType_Ready(&ssl_Connection_Type) < 0) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001431 return 0;
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001432 }
1433
1434 if (PyModule_AddObject(module, "Connection", (PyObject *)&ssl_Connection_Type) != 0) {
1435 return 0;
1436 }
1437
1438 if (PyModule_AddObject(module, "ConnectionType", (PyObject *)&ssl_Connection_Type) != 0) {
1439 return 0;
1440 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001441
1442 return 1;
1443}
1444