blob: 9428376e0c217daf5347db9bb100e72b723df2f4 [file] [log] [blame]
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001/*
2 * connection.c
3 *
Jean-Paul Calderone8671c852011-03-02 19:26:20 -05004 * Copyright (C) AB Strakt
5 * Copyright (C) Jean-Paul Calderone
6 * See LICENSE for details.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05007 *
8 * SSL Connection objects and methods.
9 * See the file RATIONALE for a short explanation of why this module was written.
10 *
11 * Reviewed 2001-07-23
12 */
13#include <Python.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050014
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050015#ifndef MS_WINDOWS
16# include <sys/socket.h>
17# include <netinet/in.h>
18# if !(defined(__BEOS__) || defined(__CYGWIN__))
19# include <netinet/tcp.h>
20# endif
21#else
22# include <winsock.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050023# include <wincrypt.h>
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050024#endif
25
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050026#define SSL_MODULE
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -040027#include <openssl/bio.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050028#include <openssl/err.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050029#include "ssl.h"
30
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050031/**
32 * If we are on UNIX, fine, just use PyErr_SetFromErrno. If we are on Windows,
33 * apply some black winsock voodoo. This is basically just copied from Python's
34 * socketmodule.c
35 *
36 * Arguments: None
37 * Returns: None
38 */
39static void
40syscall_from_errno(void)
41{
42#ifdef MS_WINDOWS
43 int errnum = WSAGetLastError();
44 if (errnum)
45 {
46 static struct { int num; const char *msg; } *msgp, msgs[] = {
47 { WSAEINTR, "Interrupted system call" },
48 { WSAEBADF, "Bad file descriptor" },
49 { WSAEACCES, "Permission denied" },
50 { WSAEFAULT, "Bad address" },
51 { WSAEINVAL, "Invalid argument" },
52 { WSAEMFILE, "Too many open files" },
53 { WSAEWOULDBLOCK, "The socket operation could not complete "
54 "without blocking" },
55 { WSAEINPROGRESS, "Operation now in progress" },
56 { WSAEALREADY, "Operation already in progress" },
57 { WSAENOTSOCK, "Socket operation on non-socket" },
58 { WSAEDESTADDRREQ, "Destination address required" },
59 { WSAEMSGSIZE, "Message too long" },
60 { WSAEPROTOTYPE, "Protocol wrong type for socket" },
61 { WSAENOPROTOOPT, "Protocol not available" },
62 { WSAEPROTONOSUPPORT, "Protocol not supported" },
63 { WSAESOCKTNOSUPPORT, "Socket type not supported" },
64 { WSAEOPNOTSUPP, "Operation not supported" },
65 { WSAEPFNOSUPPORT, "Protocol family not supported" },
66 { WSAEAFNOSUPPORT, "Address family not supported" },
67 { WSAEADDRINUSE, "Address already in use" },
68 { WSAEADDRNOTAVAIL, "Can't assign requested address" },
69 { WSAENETDOWN, "Network is down" },
70 { WSAENETUNREACH, "Network is unreachable" },
71 { WSAENETRESET, "Network dropped connection on reset" },
72 { WSAECONNABORTED, "Software caused connection abort" },
73 { WSAECONNRESET, "Connection reset by peer" },
74 { WSAENOBUFS, "No buffer space available" },
75 { WSAEISCONN, "Socket is already connected" },
76 { WSAENOTCONN, "Socket is not connected" },
77 { WSAESHUTDOWN, "Can't send after socket shutdown" },
78 { WSAETOOMANYREFS, "Too many references: can't splice" },
79 { WSAETIMEDOUT, "Operation timed out" },
80 { WSAECONNREFUSED, "Connection refused" },
81 { WSAELOOP, "Too many levels of symbolic links" },
82 { WSAENAMETOOLONG, "File name too long" },
83 { WSAEHOSTDOWN, "Host is down" },
84 { WSAEHOSTUNREACH, "No route to host" },
85 { WSAENOTEMPTY, "Directory not empty" },
86 { WSAEPROCLIM, "Too many processes" },
87 { WSAEUSERS, "Too many users" },
88 { WSAEDQUOT, "Disc quota exceeded" },
89 { WSAESTALE, "Stale NFS file handle" },
90 { WSAEREMOTE, "Too many levels of remote in path" },
91 { WSASYSNOTREADY, "Network subsystem is unvailable" },
92 { WSAVERNOTSUPPORTED, "WinSock version is not supported" },
93 { WSANOTINITIALISED, "Successful WSAStartup() not yet performed" },
94 { WSAEDISCON, "Graceful shutdown in progress" },
95 /* Resolver errors */
96 { WSAHOST_NOT_FOUND, "No such host is known" },
97 { WSATRY_AGAIN, "Host not found, or server failed" },
98 { WSANO_RECOVERY, "Unexpected server error encountered" },
99 { WSANO_DATA, "Valid name without requested data" },
100 { WSANO_ADDRESS, "No address, look for MX record" },
101 { 0, NULL }
102 };
103 PyObject *v;
104 const char *msg = "winsock error";
105
106 for (msgp = msgs; msgp->msg; msgp++)
107 {
108 if (errnum == msgp->num)
109 {
110 msg = msgp->msg;
111 break;
112 }
113 }
114
115 v = Py_BuildValue("(is)", errnum, msg);
116 if (v != NULL)
117 {
118 PyErr_SetObject(ssl_SysCallError, v);
119 Py_DECREF(v);
120 }
121 return;
122 }
123#else
124 PyErr_SetFromErrno(ssl_SysCallError);
125#endif
126}
127
128/*
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400129 * Handle errors raised by BIO functions.
130 *
131 * Arguments: bio - The BIO object
132 * ret - The return value of the BIO_ function.
133 * Returns: None, the calling function should return NULL;
134 */
135static void
136handle_bio_errors(BIO* bio, int ret)
137{
138 if (BIO_should_retry(bio)) {
139 if (BIO_should_read(bio)) {
140 PyErr_SetNone(ssl_WantReadError);
141 } else if (BIO_should_write(bio)) {
142 PyErr_SetNone(ssl_WantWriteError);
143 } else if (BIO_should_io_special(bio)) {
144 /*
145 * It's somewhat unclear what this means. From the OpenSSL source,
146 * it seems like it should not be triggered by the memory BIO, so
147 * for the time being, this case shouldn't come up. The SSL BIO
148 * (which I think should be named the socket BIO) may trigger this
149 * case if its socket is not yet connected or it is busy doing
150 * something related to x509.
151 */
152 PyErr_SetString(PyExc_ValueError, "BIO_should_io_special");
153 } else {
154 /*
155 * I hope this is dead code. The BIO documentation suggests that
156 * one of the above three checks should always be true.
157 */
158 PyErr_SetString(PyExc_ValueError, "unknown bio failure");
159 }
160 } else {
161 /*
162 * If we aren't to retry, it's really an error, so fall back to the
163 * normal error reporting code. However, the BIO interface does not
164 * specify a uniform error reporting mechanism. We can only hope that
165 * the code which triggered the error also kindly pushed something onto
166 * the error stack.
167 */
Rick Deand369c932009-07-08 11:48:33 -0500168 exception_from_error_queue(ssl_Error);
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400169 }
170}
171
172/*
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500173 * Handle errors raised by SSL I/O functions. NOTE: Not SSL_shutdown ;)
174 *
175 * Arguments: ssl - The SSL object
176 * err - The return code from SSL_get_error
177 * ret - The return code from the SSL I/O function
178 * Returns: None, the calling function should return NULL
179 */
180static void
181handle_ssl_errors(SSL *ssl, int err, int ret)
182{
183 switch (err)
184 {
185 /*
186 * Strange as it may seem, ZeroReturn is not an error per se. It means
187 * that the SSL Connection has been closed correctly (note, not the
188 * transport layer!), i.e. closure alerts have been exchanged. This is
189 * an exception since
190 * + There's an SSL "error" code for it
191 * + You have to deal with it in any case, close the transport layer
192 * etc
193 */
194 case SSL_ERROR_ZERO_RETURN:
195 PyErr_SetNone(ssl_ZeroReturnError);
196 break;
197
198 /*
199 * The WantXYZ exceptions don't mean that there's an error, just that
200 * nothing could be read/written just now, maybe because the transport
201 * layer would block on the operation, or that there's not enough data
202 * available to fill an entire SSL record.
203 */
204 case SSL_ERROR_WANT_READ:
205 PyErr_SetNone(ssl_WantReadError);
206 break;
207
208 case SSL_ERROR_WANT_WRITE:
209 PyErr_SetNone(ssl_WantWriteError);
210 break;
211
212 case SSL_ERROR_WANT_X509_LOOKUP:
213 PyErr_SetNone(ssl_WantX509LookupError);
214 break;
215
216 case SSL_ERROR_SYSCALL:
217 if (ERR_peek_error() == 0)
218 {
219 if (ret < 0)
220 {
221 syscall_from_errno();
222 }
223 else
224 {
225 PyObject *v;
226
227 v = Py_BuildValue("(is)", -1, "Unexpected EOF");
228 if (v != NULL)
229 {
230 PyErr_SetObject(ssl_SysCallError, v);
231 Py_DECREF(v);
232 }
233 }
234 break;
235 }
236
237 /* NOTE: Fall-through here, we don't want to duplicate code, right? */
238
239 case SSL_ERROR_SSL:
240 ;
241 default:
Rick Deand369c932009-07-08 11:48:33 -0500242 exception_from_error_queue(ssl_Error);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500243 break;
244 }
245}
246
247/*
248 * Here be member methods of the Connection "class"
249 */
250
251static char ssl_Connection_get_context_doc[] = "\n\
252Get session context\n\
253\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900254:return: A Context object\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500255";
256static PyObject *
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400257ssl_Connection_get_context(ssl_ConnectionObj *self, PyObject *args) {
258 if (!PyArg_ParseTuple(args, ":get_context")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500259 return NULL;
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400260 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500261
262 Py_INCREF(self->context);
263 return (PyObject *)self->context;
264}
265
Jean-Paul Calderone95613b72011-05-25 22:30:21 -0400266static char ssl_Connection_set_context_doc[] = "\n\
267Switch this connection to a new session context\n\
268\n\
Jonathan Ballet648875f2011-07-16 14:14:58 +0900269:param context: A :py:class:`Context` instance giving the new session context to use.\n\
Jean-Paul Calderone95613b72011-05-25 22:30:21 -0400270\n\
271";
272static PyObject *
273ssl_Connection_set_context(ssl_ConnectionObj *self, PyObject *args) {
274 ssl_ContextObj *ctx;
275 ssl_ContextObj *old;
276
277 if (!PyArg_ParseTuple(args, "O!:set_context", &ssl_Context_Type, &ctx)) {
278 return NULL;
279 }
280
281 /* This Connection will hold on to this context now. Make sure it stays
282 * alive.
283 */
284 Py_INCREF(ctx);
285
286 /* XXX The unit tests don't actually verify that this call is made.
287 * They're satisfied if self->context gets updated.
288 */
289 SSL_set_SSL_CTX(self->ssl, ctx->ctx);
290
291 /* Swap the old out and the new in.
292 */
293 old = self->context;
294 self->context = ctx;
295
296 /* XXX The unit tests don't verify that this reference is dropped.
297 */
298 Py_DECREF(old);
299
300 Py_INCREF(Py_None);
301 return Py_None;
302}
303
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -0400304static char ssl_Connection_get_servername_doc[] = "\n\
305Retrieve the servername extension value if provided in the client hello\n\
306message, or None if there wasn't one.\n\
307\n\
Jonathan Ballet648875f2011-07-16 14:14:58 +0900308:return: A byte string giving the server name or :py:data:`None`.\n\
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -0400309\n\
310";
311static PyObject *
312ssl_Connection_get_servername(ssl_ConnectionObj *self, PyObject *args) {
313 int type = TLSEXT_NAMETYPE_host_name;
314 const char *name;
315
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -0400316 if (!PyArg_ParseTuple(args, ":get_servername")) {
317 return NULL;
318 }
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -0400319
320 name = SSL_get_servername(self->ssl, type);
321
322 if (name == NULL) {
323 Py_INCREF(Py_None);
324 return Py_None;
325 } else {
326 return PyBytes_FromString(name);
327 }
328}
329
330
331static char ssl_Connection_set_tlsext_host_name_doc[] = "\n\
332Set the value of the servername extension to send in the client hello.\n\
333\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900334:param name: A byte string giving the name.\n\
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -0400335\n\
336";
337static PyObject *
338ssl_Connection_set_tlsext_host_name(ssl_ConnectionObj *self, PyObject *args) {
339 char *buf;
340
341 if (!PyArg_ParseTuple(args, BYTESTRING_FMT ":set_tlsext_host_name", &buf)) {
342 return NULL;
343 }
344
345 /* XXX I guess this can fail sometimes? */
346 SSL_set_tlsext_host_name(self->ssl, buf);
347
348 Py_INCREF(Py_None);
349 return Py_None;
350}
351
352
Jean-Paul Calderone95613b72011-05-25 22:30:21 -0400353
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500354static char ssl_Connection_pending_doc[] = "\n\
355Get the number of bytes that can be safely read from the connection\n\
356\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900357:return: The number of bytes available in the receive buffer.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500358";
359static PyObject *
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400360ssl_Connection_pending(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500361 int ret;
362
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400363 if (!PyArg_ParseTuple(args, ":pending")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500364 return NULL;
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400365 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500366
367 ret = SSL_pending(self->ssl);
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400368 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500369}
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400370
Rick Deanb71c0d22009-04-01 14:09:23 -0500371static char ssl_Connection_bio_write_doc[] = "\n\
372When using non-socket connections this function sends\n\
373\"dirty\" data that would have traveled in on the network.\n\
374\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900375:param buf: The string to put into the memory BIO.\n\
376:return: The number of bytes written\n\
Rick Deanb71c0d22009-04-01 14:09:23 -0500377";
378static PyObject *
379ssl_Connection_bio_write(ssl_ConnectionObj *self, PyObject *args)
380{
381 char *buf;
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400382 int len, ret;
Rick Deanb71c0d22009-04-01 14:09:23 -0500383
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400384 if (self->into_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -0500385 {
386 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
387 return NULL;
388 }
389
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -0400390 if (!PyArg_ParseTuple(args, "s#|i:bio_write", &buf, &len))
Rick Deanb71c0d22009-04-01 14:09:23 -0500391 return NULL;
392
393 ret = BIO_write(self->into_ssl, buf, len);
394
395 if (PyErr_Occurred())
396 {
397 flush_error_queue();
398 return NULL;
399 }
400
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400401 if (ret <= 0) {
402 /*
403 * There was a problem with the BIO_write of some sort.
404 */
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400405 handle_bio_errors(self->into_ssl, ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500406 return NULL;
407 }
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400408
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400409 return PyLong_FromLong((long)ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500410}
411
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500412static char ssl_Connection_send_doc[] = "\n\
413Send data on the connection. NOTE: If you get one of the WantRead,\n\
414WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
415method again with the SAME buffer.\n\
416\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900417:param buf: The string to send\n\
418:param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400419 API, the value is ignored\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900420:return: The number of bytes written\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500421";
422static PyObject *
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500423ssl_Connection_send(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500424 int len, ret, err, flags;
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500425 char *buf;
426
Jean-Paul Calderone5163f572011-04-22 18:38:16 -0400427#if PY_VERSION_HEX >= 0x02060000
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500428
Jean-Paul Calderone4cc06a72012-03-10 17:18:02 -0800429 /*
430 * Sit back and I'll tell you a story of intrigue and corruption, deceit and
431 * murder.
432 *
433 * A Py_buffer is used to hold any kind of byte-like data - a string, a
434 * memoryview, a buffer, etc. PyArg_ParseTuple takes whatever kind of
435 * object was supplied, notices the "s*" format specifier, and tries to copy
436 * the metadata for that object into the Py_buffer also passed in.
437 *
438 * According to the Python documentation:
439 *
440 * ... the caller is responsible for calling PyBuffer_Release with the
441 * structure after it has processed the data.
442 *
443 * Correct use of PyBuffer_Release is necessary due to the fact that
444 * Py_buffer must hold a reference to the original Python object from which
445 * it was initialized. PyBuffer_Release will decrement the reference count
446 * of that original object, allowing it to eventually be deallocated - but
447 * only after the Py_buffer is no longer in use.
448 *
449 * To support failures partway through parsing a format string,
450 * PyArg_ParseTuple maintains an internal PyListObject of PyCObjects it has
451 * created so far. This allows it to easily clean up these objects when
452 * parsing fails, before returning an error to the caller (incidentally, it
453 * also makes sure to clean up the Py_buffer it initialized in this case, by
454 * calling PyBuffer_Release - which means the caller *must not* use
455 * PyBuffer_Release when PyArg_ParseTuple fails; not exactly what the
456 * documentation directs).
457 *
458 * The PyCObjects are given destructors which clean up some structure
459 * PyArg_ParseTuple has created (or initialized) - often another PyObject
460 * which needs to be decref'd.
461 *
462 * When parsing completes, the reference count of the PyListObject is merely
463 * decremented. The normal Python garbage collection logic (the reference
464 * counting logic, in this case) takes over and collects both the list and
465 * all of the objects in it. When each PyCObject in the list is collected,
466 * it triggers its destructor to clean up the structure it wraps. This all
467 * happens immediately, before the Py_XDECREF of the PyListObject returns.
468 *
469 * The PyListObject is similarly destroyed in the success case, but not
470 * until each PyCObject it contains has had its destructor set to NULL to
471 * prevent it from cleaning up its contents.
472 *
473 * When PyArg_ParseTuple returns in an error case, therefore,
474 * PyRelease_Buffer has already been used on the Py_buffer passed to
475 * PyArg_ParseTuple.
476 *
477 * This is fortuitous, as the Py_buffer is typically (always?) allocated on
478 * the stack of the caller of PyArg_ParseTuple. Once that caller returns,
479 * that stack memory is no longer valid, and the Py_buffer may no longer be
480 * used.
481 *
482 * On a Python runtime which does not use reference counting, the
483 * PyListObject may not actually be collected before Py_XDECREF returns. It
484 * may not even be collected before PyArg_ParseTuple returns. In fact, in
485 * particularly unfortunate cases, it may even not be collected before the
486 * caller of PyArg_ParseTuple returns. It may not be called until long,
487 * long after the stack memory the Py_buffer was allocated on has been
488 * re-used for some other function call, after the memory holding a pointer
489 * to the structure that owns the memory the Py_buffer wrapped has been
490 * overwritten. When PyBuffer_Release is used on the Py_buffer in this
491 * case, it will try to decrement a random integer - probably part of a
492 * local variable on some part of the stack.
493 *
494 * The PyPy runtime does not use reference counting.
495 *
496 * The solution adopted here is to allocate the Py_buffer on the heap,
497 * instead. As there is no mechanism for learning when the PyCObject used
498 * by PyArg_ParseTuple to do its internal cleanup has had its way with the
499 * Py_buffer, the Py_buffer is leaked in the error case, to ensure it is
500 * still valid whenever PyBuffer_Release is called on it.
501 *
502 * Real programs should rarely, if ever, trigger the error case of
503 * PyArg_ParseTuple, so this is probably okay. Plus, I'm tired of this
504 * stupid bug. -exarkun
505 */
506
Jean-Paul Calderone294dc1e2012-03-10 16:55:52 -0800507 Py_buffer *pbuf = PyMem_Malloc(sizeof *pbuf);
508
509 if (!PyArg_ParseTuple(args, "s*|i:send", pbuf, &flags)) {
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500510 return NULL;
Jean-Paul Calderone294dc1e2012-03-10 16:55:52 -0800511 }
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500512
Jean-Paul Calderone294dc1e2012-03-10 16:55:52 -0800513 buf = pbuf->buf;
514 len = pbuf->len;
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500515#else
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500516
Jean-Paul Calderone294dc1e2012-03-10 16:55:52 -0800517 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags)) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500518 return NULL;
Jean-Paul Calderone294dc1e2012-03-10 16:55:52 -0800519 }
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500520#endif
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500521
522 MY_BEGIN_ALLOW_THREADS(self->tstate)
523 ret = SSL_write(self->ssl, buf, len);
524 MY_END_ALLOW_THREADS(self->tstate)
525
Jean-Paul Calderone5163f572011-04-22 18:38:16 -0400526#if PY_VERSION_HEX >= 0x02060000
Jean-Paul Calderone294dc1e2012-03-10 16:55:52 -0800527 PyBuffer_Release(pbuf);
528 PyMem_Free(pbuf);
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500529#endif
530
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500531 if (PyErr_Occurred())
532 {
533 flush_error_queue();
534 return NULL;
535 }
536
537 err = SSL_get_error(self->ssl, ret);
538 if (err == SSL_ERROR_NONE)
539 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400540 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500541 }
542 else
543 {
544 handle_ssl_errors(self->ssl, err, ret);
545 return NULL;
546 }
547}
548
549static char ssl_Connection_sendall_doc[] = "\n\
550Send \"all\" data on the connection. This calls send() repeatedly until\n\
551all data is sent. If an error occurs, it's impossible to tell how much data\n\
552has been sent.\n\
553\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900554:param buf: The string to send\n\
555:param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400556 API, the value is ignored\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900557:return: The number of bytes written\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500558";
559static PyObject *
560ssl_Connection_sendall(ssl_ConnectionObj *self, PyObject *args)
561{
562 char *buf;
563 int len, ret, err, flags;
564 PyObject *pyret = Py_None;
565
Jean-Paul Calderone5163f572011-04-22 18:38:16 -0400566#if PY_VERSION_HEX >= 0x02060000
Jean-Paul Calderone294dc1e2012-03-10 16:55:52 -0800567 Py_buffer *pbuf = PyMem_Malloc(sizeof *pbuf);
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500568
Jean-Paul Calderone294dc1e2012-03-10 16:55:52 -0800569 if (!PyArg_ParseTuple(args, "s*|i:sendall", pbuf, &flags)) {
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500570 return NULL;
Jean-Paul Calderone294dc1e2012-03-10 16:55:52 -0800571 }
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500572
Jean-Paul Calderone294dc1e2012-03-10 16:55:52 -0800573 buf = pbuf->buf;
574 len = pbuf->len;
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500575#else
Jean-Paul Calderone294dc1e2012-03-10 16:55:52 -0800576 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags)) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500577 return NULL;
Jean-Paul Calderone294dc1e2012-03-10 16:55:52 -0800578 }
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500579#endif
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500580
581 do {
582 MY_BEGIN_ALLOW_THREADS(self->tstate)
583 ret = SSL_write(self->ssl, buf, len);
584 MY_END_ALLOW_THREADS(self->tstate)
585 if (PyErr_Occurred())
586 {
587 flush_error_queue();
588 pyret = NULL;
589 break;
590 }
591 err = SSL_get_error(self->ssl, ret);
592 if (err == SSL_ERROR_NONE)
593 {
594 buf += ret;
595 len -= ret;
596 }
597 else if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL ||
598 err == SSL_ERROR_ZERO_RETURN)
599 {
600 handle_ssl_errors(self->ssl, err, ret);
601 pyret = NULL;
602 break;
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500603 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500604 } while (len > 0);
605
Jean-Paul Calderone5163f572011-04-22 18:38:16 -0400606#if PY_VERSION_HEX >= 0x02060000
Jean-Paul Calderone294dc1e2012-03-10 16:55:52 -0800607 PyBuffer_Release(pbuf);
608 PyMem_Free(pbuf);
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500609#endif
610
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500611 Py_XINCREF(pyret);
612 return pyret;
613}
614
615static char ssl_Connection_recv_doc[] = "\n\
616Receive data on the connection. NOTE: If you get one of the WantRead,\n\
617WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
618method again with the SAME buffer.\n\
619\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900620:param bufsiz: The maximum number of bytes to read\n\
621:param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400622 API, the value is ignored\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900623:return: The string read from the Connection\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500624";
625static PyObject *
626ssl_Connection_recv(ssl_ConnectionObj *self, PyObject *args)
627{
628 int bufsiz, ret, err, flags;
629 PyObject *buf;
630
631 if (!PyArg_ParseTuple(args, "i|i:recv", &bufsiz, &flags))
632 return NULL;
633
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400634 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500635 if (buf == NULL)
636 return NULL;
637
638 MY_BEGIN_ALLOW_THREADS(self->tstate)
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400639 ret = SSL_read(self->ssl, PyBytes_AsString(buf), bufsiz);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500640 MY_END_ALLOW_THREADS(self->tstate)
641
642 if (PyErr_Occurred())
643 {
644 Py_DECREF(buf);
645 flush_error_queue();
646 return NULL;
647 }
648
649 err = SSL_get_error(self->ssl, ret);
650 if (err == SSL_ERROR_NONE)
651 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400652 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500653 return NULL;
654 return buf;
655 }
656 else
657 {
658 handle_ssl_errors(self->ssl, err, ret);
659 Py_DECREF(buf);
660 return NULL;
661 }
662}
663
Rick Deanb71c0d22009-04-01 14:09:23 -0500664static char ssl_Connection_bio_read_doc[] = "\n\
665When using non-socket connections this function reads\n\
666the \"dirty\" data that would have traveled away on the network.\n\
667\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900668:param bufsiz: The maximum number of bytes to read\n\
669:return: The string read.\n\
Rick Deanb71c0d22009-04-01 14:09:23 -0500670";
671static PyObject *
672ssl_Connection_bio_read(ssl_ConnectionObj *self, PyObject *args)
673{
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400674 int bufsiz, ret;
Rick Deanb71c0d22009-04-01 14:09:23 -0500675 PyObject *buf;
676
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400677 if (self->from_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -0500678 {
679 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
680 return NULL;
681 }
682
683 if (!PyArg_ParseTuple(args, "i:bio_read", &bufsiz))
684 return NULL;
685
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400686 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
Rick Deanb71c0d22009-04-01 14:09:23 -0500687 if (buf == NULL)
688 return NULL;
689
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400690 ret = BIO_read(self->from_ssl, PyBytes_AsString(buf), bufsiz);
Rick Deanb71c0d22009-04-01 14:09:23 -0500691
692 if (PyErr_Occurred())
693 {
694 Py_DECREF(buf);
695 flush_error_queue();
696 return NULL;
697 }
698
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400699 if (ret <= 0) {
700 /*
701 * There was a problem with the BIO_read of some sort.
702 */
703 handle_bio_errors(self->from_ssl, ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500704 Py_DECREF(buf);
705 return NULL;
706 }
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400707
708 /*
709 * Shrink the string to match the number of bytes we actually read.
710 */
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400711 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400712 {
713 Py_DECREF(buf);
714 return NULL;
715 }
716 return buf;
Rick Deanb71c0d22009-04-01 14:09:23 -0500717}
718
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500719static char ssl_Connection_renegotiate_doc[] = "\n\
720Renegotiate the session\n\
721\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900722:return: True if the renegotiation can be started, false otherwise\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500723";
724static PyObject *
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400725ssl_Connection_renegotiate(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500726 int ret;
727
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400728 if (!PyArg_ParseTuple(args, ":renegotiate")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500729 return NULL;
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400730 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500731
732 MY_BEGIN_ALLOW_THREADS(self->tstate);
733 ret = SSL_renegotiate(self->ssl);
734 MY_END_ALLOW_THREADS(self->tstate);
735
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400736 if (PyErr_Occurred()) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500737 flush_error_queue();
738 return NULL;
739 }
740
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400741 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500742}
743
744static char ssl_Connection_do_handshake_doc[] = "\n\
745Perform an SSL handshake (usually called after renegotiate() or one of\n\
746set_*_state()). This can raise the same exceptions as send and recv.\n\
747\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900748:return: None.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500749";
750static PyObject *
751ssl_Connection_do_handshake(ssl_ConnectionObj *self, PyObject *args)
752{
753 int ret, err;
754
755 if (!PyArg_ParseTuple(args, ":do_handshake"))
756 return NULL;
757
758 MY_BEGIN_ALLOW_THREADS(self->tstate);
759 ret = SSL_do_handshake(self->ssl);
760 MY_END_ALLOW_THREADS(self->tstate);
761
762 if (PyErr_Occurred())
763 {
764 flush_error_queue();
765 return NULL;
766 }
767
768 err = SSL_get_error(self->ssl, ret);
769 if (err == SSL_ERROR_NONE)
770 {
771 Py_INCREF(Py_None);
772 return Py_None;
773 }
774 else
775 {
776 handle_ssl_errors(self->ssl, err, ret);
777 return NULL;
778 }
779}
780
781#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
782static char ssl_Connection_renegotiate_pending_doc[] = "\n\
783Check if there's a renegotiation in progress, it will return false once\n\
784a renegotiation is finished.\n\
785\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900786:return: Whether there's a renegotiation in progress\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500787";
788static PyObject *
789ssl_Connection_renegotiate_pending(ssl_ConnectionObj *self, PyObject *args)
790{
791 if (!PyArg_ParseTuple(args, ":renegotiate_pending"))
792 return NULL;
793
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400794 return PyLong_FromLong((long)SSL_renegotiate_pending(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500795}
796#endif
797
798static char ssl_Connection_total_renegotiations_doc[] = "\n\
799Find out the total number of renegotiations.\n\
800\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900801:return: The number of renegotiations.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500802";
803static PyObject *
804ssl_Connection_total_renegotiations(ssl_ConnectionObj *self, PyObject *args)
805{
806 if (!PyArg_ParseTuple(args, ":total_renegotiations"))
807 return NULL;
808
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400809 return PyLong_FromLong(SSL_total_renegotiations(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500810}
811
812static char ssl_Connection_set_accept_state_doc[] = "\n\
813Set the connection to work in server mode. The handshake will be handled\n\
814automatically by read/write.\n\
815\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900816:return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500817";
818static PyObject *
819ssl_Connection_set_accept_state(ssl_ConnectionObj *self, PyObject *args)
820{
821 if (!PyArg_ParseTuple(args, ":set_accept_state"))
822 return NULL;
823
824 SSL_set_accept_state(self->ssl);
825
826 Py_INCREF(Py_None);
827 return Py_None;
828}
829
830static char ssl_Connection_set_connect_state_doc[] = "\n\
831Set the connection to work in client mode. The handshake will be handled\n\
832automatically by read/write.\n\
833\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900834:return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500835";
836static PyObject *
837ssl_Connection_set_connect_state(ssl_ConnectionObj *self, PyObject *args)
838{
839 if (!PyArg_ParseTuple(args, ":set_connect_state"))
840 return NULL;
841
842 SSL_set_connect_state(self->ssl);
843
844 Py_INCREF(Py_None);
845 return Py_None;
846}
847
848static char ssl_Connection_connect_doc[] = "\n\
849Connect to remote host and set up client-side SSL\n\
850\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900851:param addr: A remote address\n\
852:return: What the socket's connect method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500853";
854static PyObject *
855ssl_Connection_connect(ssl_ConnectionObj *self, PyObject *args)
856{
857 PyObject *meth, *ret;
858
859 if ((meth = PyObject_GetAttrString(self->socket, "connect")) == NULL)
860 return NULL;
861
862 SSL_set_connect_state(self->ssl);
863
864 ret = PyEval_CallObject(meth, args);
865 Py_DECREF(meth);
866 if (ret == NULL)
867 return NULL;
868
869 return ret;
870}
871
872static char ssl_Connection_connect_ex_doc[] = "\n\
873Connect to remote host and set up client-side SSL. Note that if the socket's\n\
874connect_ex method doesn't return 0, SSL won't be initialized.\n\
875\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900876:param addr: A remove address\n\
877:return: What the socket's connect_ex method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500878";
879static PyObject *
880ssl_Connection_connect_ex(ssl_ConnectionObj *self, PyObject *args)
881{
882 PyObject *meth, *ret;
883
884 if ((meth = PyObject_GetAttrString(self->socket, "connect_ex")) == NULL)
885 return NULL;
886
887 SSL_set_connect_state(self->ssl);
888
889 ret = PyEval_CallObject(meth, args);
890 Py_DECREF(meth);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500891 return ret;
892}
893
894static char ssl_Connection_accept_doc[] = "\n\
895Accept incoming connection and set up SSL on it\n\
896\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900897:return: A (conn,addr) pair where conn is a Connection and addr is an\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400898 address\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500899";
900static PyObject *
901ssl_Connection_accept(ssl_ConnectionObj *self, PyObject *args)
902{
903 PyObject *tuple, *socket, *address, *meth;
904 ssl_ConnectionObj *conn;
905
906 if ((meth = PyObject_GetAttrString(self->socket, "accept")) == NULL)
907 return NULL;
908 tuple = PyEval_CallObject(meth, args);
909 Py_DECREF(meth);
910 if (tuple == NULL)
911 return NULL;
912
913 socket = PyTuple_GetItem(tuple, 0);
914 Py_INCREF(socket);
915 address = PyTuple_GetItem(tuple, 1);
916 Py_INCREF(address);
917 Py_DECREF(tuple);
918
919 conn = ssl_Connection_New(self->context, socket);
920 Py_DECREF(socket);
921 if (conn == NULL)
922 {
923 Py_DECREF(address);
924 return NULL;
925 }
926
927 SSL_set_accept_state(conn->ssl);
928
929 tuple = Py_BuildValue("(OO)", conn, address);
930
931 Py_DECREF(conn);
932 Py_DECREF(address);
933
934 return tuple;
935}
936
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400937static char ssl_Connection_bio_shutdown_doc[] = "\n\
938When using non-socket connections this function signals end of\n\
939data on the input for this connection.\n\
940\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900941:return: None\n\
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400942";
943
944static PyObject *
945ssl_Connection_bio_shutdown(ssl_ConnectionObj *self, PyObject *args)
946{
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400947 if (self->from_ssl == NULL)
948 {
949 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
950 return NULL;
951 }
952
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400953 BIO_set_mem_eof_return(self->into_ssl, 0);
954 Py_INCREF(Py_None);
955 return Py_None;
956}
957
958
959
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500960static char ssl_Connection_shutdown_doc[] = "\n\
961Send closure alert\n\
962\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +0900963:return: True if the shutdown completed successfully (i.e. both sides\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400964 have sent closure alerts), false otherwise (i.e. you have to\n\
965 wait for a ZeroReturnError on a recv() method call\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500966";
967static PyObject *
968ssl_Connection_shutdown(ssl_ConnectionObj *self, PyObject *args)
969{
970 int ret;
971
972 if (!PyArg_ParseTuple(args, ":shutdown"))
973 return NULL;
974
975 MY_BEGIN_ALLOW_THREADS(self->tstate)
976 ret = SSL_shutdown(self->ssl);
977 MY_END_ALLOW_THREADS(self->tstate)
978
979 if (PyErr_Occurred())
980 {
981 flush_error_queue();
982 return NULL;
983 }
984
985 if (ret < 0)
986 {
Rick Deand369c932009-07-08 11:48:33 -0500987 exception_from_error_queue(ssl_Error);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500988 return NULL;
989 }
990 else if (ret > 0)
991 {
992 Py_INCREF(Py_True);
993 return Py_True;
994 }
995 else
996 {
997 Py_INCREF(Py_False);
998 return Py_False;
999 }
1000}
1001
1002static char ssl_Connection_get_cipher_list_doc[] = "\n\
1003Get the session cipher list\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001004\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001005:return: A list of cipher strings\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001006";
1007static PyObject *
1008ssl_Connection_get_cipher_list(ssl_ConnectionObj *self, PyObject *args)
1009{
1010 int idx = 0;
1011 const char *ret;
1012 PyObject *lst, *item;
1013
1014 if (!PyArg_ParseTuple(args, ":get_cipher_list"))
1015 return NULL;
1016
1017 lst = PyList_New(0);
1018 while ((ret = SSL_get_cipher_list(self->ssl, idx)) != NULL)
1019 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001020 item = PyText_FromString(ret);
Ziga Seilnachtfdeadb12009-09-01 16:35:50 +02001021 PyList_Append(lst, item);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001022 Py_DECREF(item);
1023 idx++;
1024 }
1025 return lst;
1026}
1027
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02001028static char ssl_Connection_get_client_ca_list_doc[] = "\n\
Ziga Seilnacht679c4262009-09-01 01:32:29 +02001029Get CAs whose certificates are suggested for client authentication.\n\
1030\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001031:return: If this is a server connection, a list of X509Names representing\n\
Jonathan Ballet648875f2011-07-16 14:14:58 +09001032 the acceptable CAs as set by :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or\n\
1033 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client connection,\n\
Jean-Paul Calderone35788902009-10-24 13:48:08 -04001034 the list of such X509Names sent by the server, or an empty list if that\n\
1035 has not yet happened.\n\
Ziga Seilnacht679c4262009-09-01 01:32:29 +02001036";
1037
1038static PyObject *
Jean-Paul Calderone6e2b6852009-10-24 14:04:30 -04001039ssl_Connection_get_client_ca_list(ssl_ConnectionObj *self, PyObject *args) {
Ziga Seilnacht679c4262009-09-01 01:32:29 +02001040 STACK_OF(X509_NAME) *CANames;
1041 PyObject *CAList;
1042 int i, n;
1043
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02001044 if (!PyArg_ParseTuple(args, ":get_client_ca_list")) {
Ziga Seilnacht679c4262009-09-01 01:32:29 +02001045 return NULL;
1046 }
1047 CANames = SSL_get_client_CA_list(self->ssl);
1048 if (CANames == NULL) {
1049 return PyList_New(0);
1050 }
1051 n = sk_X509_NAME_num(CANames);
1052 CAList = PyList_New(n);
1053 if (CAList == NULL) {
1054 return NULL;
1055 }
1056 for (i = 0; i < n; i++) {
1057 X509_NAME *CAName;
1058 PyObject *CA;
1059
1060 CAName = X509_NAME_dup(sk_X509_NAME_value(CANames, i));
1061 if (CAName == NULL) {
1062 Py_DECREF(CAList);
1063 exception_from_error_queue(ssl_Error);
1064 return NULL;
1065 }
Jean-Paul Calderone305626a2010-10-31 20:51:17 -04001066 CA = (PyObject *)new_x509name(CAName, 1);
Ziga Seilnacht679c4262009-09-01 01:32:29 +02001067 if (CA == NULL) {
1068 X509_NAME_free(CAName);
1069 Py_DECREF(CAList);
1070 return NULL;
1071 }
1072 if (PyList_SetItem(CAList, i, CA)) {
1073 Py_DECREF(CA);
1074 Py_DECREF(CAList);
1075 return NULL;
1076 }
1077 }
1078 return CAList;
1079}
1080
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001081static char ssl_Connection_makefile_doc[] = "\n\
1082The makefile() method is not implemented, since there is no dup semantics\n\
1083for SSL connections\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001084\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001085:raise NotImplementedError\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001086";
1087static PyObject *
1088ssl_Connection_makefile(ssl_ConnectionObj *self, PyObject *args)
1089{
1090 PyErr_SetString(PyExc_NotImplementedError, "Cannot make file object of SSL.Connection");
1091 return NULL;
1092}
1093
1094static char ssl_Connection_get_app_data_doc[] = "\n\
1095Get application data\n\
1096\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001097:return: The application data\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001098";
1099static PyObject *
1100ssl_Connection_get_app_data(ssl_ConnectionObj *self, PyObject *args)
1101{
1102 if (!PyArg_ParseTuple(args, ":get_app_data"))
1103 return NULL;
1104
1105 Py_INCREF(self->app_data);
1106 return self->app_data;
1107}
1108
1109static char ssl_Connection_set_app_data_doc[] = "\n\
1110Set application data\n\
1111\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001112:param data - The application data\n\
1113:return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001114";
1115static PyObject *
1116ssl_Connection_set_app_data(ssl_ConnectionObj *self, PyObject *args)
1117{
1118 PyObject *data;
1119
1120 if (!PyArg_ParseTuple(args, "O:set_app_data", &data))
1121 return NULL;
1122
1123 Py_DECREF(self->app_data);
1124 Py_INCREF(data);
1125 self->app_data = data;
1126
1127 Py_INCREF(Py_None);
1128 return Py_None;
1129}
1130
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001131static char ssl_Connection_get_shutdown_doc[] = "\n\
1132Get shutdown state\n\
1133\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001134:return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001135";
1136static PyObject *
1137ssl_Connection_get_shutdown(ssl_ConnectionObj *self, PyObject *args)
1138{
1139 if (!PyArg_ParseTuple(args, ":get_shutdown"))
1140 return NULL;
1141
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001142 return PyLong_FromLong((long)SSL_get_shutdown(self->ssl));
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001143}
1144
1145static char ssl_Connection_set_shutdown_doc[] = "\n\
1146Set shutdown state\n\
1147\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001148:param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
1149:return: None\n\
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001150";
1151static PyObject *
1152ssl_Connection_set_shutdown(ssl_ConnectionObj *self, PyObject *args)
1153{
1154 int shutdown;
1155
1156 if (!PyArg_ParseTuple(args, "i:set_shutdown", &shutdown))
1157 return NULL;
1158
1159 SSL_set_shutdown(self->ssl, shutdown);
1160 Py_INCREF(Py_None);
1161 return Py_None;
1162}
1163
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001164static char ssl_Connection_state_string_doc[] = "\n\
1165Get a verbose state description\n\
1166\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001167:return: A string representing the state\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001168";
1169static PyObject *
1170ssl_Connection_state_string(ssl_ConnectionObj *self, PyObject *args)
1171{
1172 if (!PyArg_ParseTuple(args, ":state_string"))
1173 return NULL;
1174
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001175 return PyText_FromString(SSL_state_string_long(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001176}
1177
Rick Deanb71c0d22009-04-01 14:09:23 -05001178static char ssl_Connection_client_random_doc[] = "\n\
1179Get a copy of the client hello nonce.\n\
1180\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001181:return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001182";
1183static PyObject *
1184ssl_Connection_client_random(ssl_ConnectionObj *self, PyObject *args)
1185{
1186 if (!PyArg_ParseTuple(args, ":client_random"))
1187 return NULL;
1188
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001189 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001190 Py_INCREF(Py_None);
1191 return Py_None;
1192 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001193 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->client_random, SSL3_RANDOM_SIZE);
Rick Deanb71c0d22009-04-01 14:09:23 -05001194}
1195
1196static char ssl_Connection_server_random_doc[] = "\n\
1197Get a copy of the server hello nonce.\n\
1198\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001199:return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001200";
1201static PyObject *
1202ssl_Connection_server_random(ssl_ConnectionObj *self, PyObject *args)
1203{
1204 if (!PyArg_ParseTuple(args, ":server_random"))
1205 return NULL;
1206
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001207 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001208 Py_INCREF(Py_None);
1209 return Py_None;
1210 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001211 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->server_random, SSL3_RANDOM_SIZE);
Rick Deanb71c0d22009-04-01 14:09:23 -05001212}
1213
1214static char ssl_Connection_master_key_doc[] = "\n\
1215Get a copy of the master key.\n\
1216\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001217:return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001218";
1219static PyObject *
1220ssl_Connection_master_key(ssl_ConnectionObj *self, PyObject *args)
1221{
1222 if (!PyArg_ParseTuple(args, ":master_key"))
1223 return NULL;
1224
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001225 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001226 Py_INCREF(Py_None);
1227 return Py_None;
1228 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001229 return PyBytes_FromStringAndSize( (const char *) self->ssl->session->master_key, self->ssl->session->master_key_length);
Rick Deanb71c0d22009-04-01 14:09:23 -05001230}
1231
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001232static char ssl_Connection_sock_shutdown_doc[] = "\n\
1233See shutdown(2)\n\
1234\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001235:return: What the socket's shutdown() method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001236";
1237static PyObject *
1238ssl_Connection_sock_shutdown(ssl_ConnectionObj *self, PyObject *args)
1239{
1240 PyObject *meth, *ret;
1241
1242 if ((meth = PyObject_GetAttrString(self->socket, "shutdown")) == NULL)
1243 return NULL;
1244 ret = PyEval_CallObject(meth, args);
1245 Py_DECREF(meth);
1246 return ret;
1247}
1248
1249static char ssl_Connection_get_peer_certificate_doc[] = "\n\
1250Retrieve the other side's certificate (if any)\n\
1251\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001252:return: The peer's certificate\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001253";
1254static PyObject *
1255ssl_Connection_get_peer_certificate(ssl_ConnectionObj *self, PyObject *args)
1256{
1257 X509 *cert;
1258
1259 if (!PyArg_ParseTuple(args, ":get_peer_certificate"))
1260 return NULL;
1261
1262 cert = SSL_get_peer_certificate(self->ssl);
1263 if (cert != NULL)
1264 {
Jean-Paul Calderone5c0f1f62010-10-31 21:36:43 -04001265 return (PyObject *)new_x509(cert, 1);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001266 }
1267 else
1268 {
1269 Py_INCREF(Py_None);
1270 return Py_None;
1271 }
1272}
1273
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001274static char ssl_Connection_get_peer_cert_chain_doc[] = "\n\
1275Retrieve the other side's certificate (if any)\n\
1276\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001277:return: A list of X509 instances giving the peer's certificate chain,\n\
Jean-Paul Calderone0a7e06a2011-05-19 18:49:35 -04001278 or None if it does not have one.\n\
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001279";
1280static PyObject *
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001281ssl_Connection_get_peer_cert_chain(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001282 STACK_OF(X509) *sk;
Jean-Paul Calderone0a7e06a2011-05-19 18:49:35 -04001283 PyObject *chain;
1284 crypto_X509Obj *cert;
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001285 Py_ssize_t i;
1286
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001287 if (!PyArg_ParseTuple(args, ":get_peer_cert_chain")) {
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001288 return NULL;
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001289 }
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001290
1291 sk = SSL_get_peer_cert_chain(self->ssl);
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001292 if (sk != NULL) {
Jean-Paul Calderone0a7e06a2011-05-19 18:49:35 -04001293 chain = PyList_New(sk_X509_num(sk));
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001294 for (i = 0; i < sk_X509_num(sk); i++) {
Jean-Paul Calderone13d190b2011-05-20 19:14:50 -04001295 cert = new_x509(sk_X509_value(sk, i), 1);
Jean-Paul Calderone0a7e06a2011-05-19 18:49:35 -04001296 if (!cert) {
1297 /* XXX Untested */
1298 Py_DECREF(chain);
1299 return NULL;
1300 }
1301 CRYPTO_add(&cert->x509->references, 1, CRYPTO_LOCK_X509);
1302 PyList_SET_ITEM(chain, i, (PyObject *)cert);
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001303 }
Jean-Paul Calderone0a7e06a2011-05-19 18:49:35 -04001304 return chain;
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001305 } else {
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001306 Py_INCREF(Py_None);
1307 return Py_None;
1308 }
1309
1310}
1311
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001312static char ssl_Connection_want_read_doc[] = "\n\
1313Checks if more data has to be read from the transport layer to complete an\n\
1314operation.\n\
1315\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001316:return: True iff more data has to be read\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001317";
1318static PyObject *
1319ssl_Connection_want_read(ssl_ConnectionObj *self, PyObject *args)
1320{
1321 if (!PyArg_ParseTuple(args, ":want_read"))
1322 return NULL;
1323
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001324 return PyLong_FromLong((long)SSL_want_read(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001325}
1326
1327static char ssl_Connection_want_write_doc[] = "\n\
1328Checks if there is data to write to the transport layer to complete an\n\
1329operation.\n\
1330\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001331:return: True iff there is data to write\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001332";
1333static PyObject *
1334ssl_Connection_want_write(ssl_ConnectionObj *self, PyObject *args)
1335{
1336 if (!PyArg_ParseTuple(args, ":want_write"))
1337 return NULL;
1338
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001339 return PyLong_FromLong((long)SSL_want_write(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001340}
1341
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001342static char ssl_Connection_get_session_doc[] = "\n\
1343Returns the Session currently used.\n\
1344\n\
1345@return: An instance of :py:class:`OpenSSL.SSL.Session` or :py:obj:`None` if\n\
1346 no session exists.\n\
1347";
1348static PyObject *
1349ssl_Connection_get_session(ssl_ConnectionObj *self, PyObject *args) {
1350 ssl_SessionObj *session;
1351 SSL_SESSION *native_session;
1352
1353 if (!PyArg_ParseTuple(args, ":get_session")) {
1354 return NULL;
1355 }
1356
1357 native_session = SSL_get1_session(self->ssl);
1358
1359 if (native_session == NULL) {
1360 Py_INCREF(Py_None);
1361 return Py_None;
1362 }
1363
1364 session = ssl_Session_from_SSL_SESSION(native_session);
1365 if (!session) {
1366 Py_INCREF(Py_None);
1367 return Py_None;
1368 }
1369
1370 return (PyObject*)session;
1371}
1372
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05001373static char ssl_Connection_set_session_doc[] = "\n\
1374Set the session to be used when the TLS/SSL connection is established.\n\
1375\n\
1376:param session: A Session instance representing the session to use.\n\
1377:returns: None\n\
1378";
1379static PyObject *
1380ssl_Connection_set_session(ssl_ConnectionObj *self, PyObject *args) {
1381 ssl_SessionObj *session;
1382
1383 if (!PyArg_ParseTuple(args, "O!:set_session", &ssl_Session_Type, &session)) {
1384 return NULL;
1385 }
1386
1387 if (SSL_set_session(self->ssl, session->session) == 0) {
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05001388 /* The only case which leads to this seems to be a mismatch, between
1389 * this connection and the session, of the SSL method.
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05001390 */
1391 exception_from_error_queue(ssl_Error);
1392 return NULL;
1393 }
1394
1395 Py_INCREF(Py_None);
1396 return Py_None;
1397}
1398
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001399/*
1400 * Member methods in the Connection object
1401 * ADD_METHOD(name) expands to a correct PyMethodDef declaration
1402 * { 'name', (PyCFunction)ssl_Connection_name, METH_VARARGS }
1403 * for convenience
1404 * ADD_ALIAS(name,real) creates an "alias" of the ssl_Connection_real
1405 * function with the name 'name'
1406 */
1407#define ADD_METHOD(name) \
1408 { #name, (PyCFunction)ssl_Connection_##name, METH_VARARGS, ssl_Connection_##name##_doc }
1409#define ADD_ALIAS(name,real) \
1410 { #name, (PyCFunction)ssl_Connection_##real, METH_VARARGS, ssl_Connection_##real##_doc }
1411static PyMethodDef ssl_Connection_methods[] =
1412{
1413 ADD_METHOD(get_context),
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001414 ADD_METHOD(set_context),
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001415 ADD_METHOD(get_servername),
1416 ADD_METHOD(set_tlsext_host_name),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001417 ADD_METHOD(pending),
1418 ADD_METHOD(send),
1419 ADD_ALIAS (write, send),
1420 ADD_METHOD(sendall),
1421 ADD_METHOD(recv),
1422 ADD_ALIAS (read, recv),
Rick Deanb71c0d22009-04-01 14:09:23 -05001423 ADD_METHOD(bio_read),
1424 ADD_METHOD(bio_write),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001425 ADD_METHOD(renegotiate),
1426 ADD_METHOD(do_handshake),
1427#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
1428 ADD_METHOD(renegotiate_pending),
1429#endif
1430 ADD_METHOD(total_renegotiations),
1431 ADD_METHOD(connect),
1432 ADD_METHOD(connect_ex),
1433 ADD_METHOD(accept),
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04001434 ADD_METHOD(bio_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001435 ADD_METHOD(shutdown),
1436 ADD_METHOD(get_cipher_list),
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02001437 ADD_METHOD(get_client_ca_list),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001438 ADD_METHOD(makefile),
1439 ADD_METHOD(get_app_data),
1440 ADD_METHOD(set_app_data),
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001441 ADD_METHOD(get_shutdown),
1442 ADD_METHOD(set_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001443 ADD_METHOD(state_string),
Rick Deanb71c0d22009-04-01 14:09:23 -05001444 ADD_METHOD(server_random),
1445 ADD_METHOD(client_random),
1446 ADD_METHOD(master_key),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001447 ADD_METHOD(sock_shutdown),
1448 ADD_METHOD(get_peer_certificate),
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001449 ADD_METHOD(get_peer_cert_chain),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001450 ADD_METHOD(want_read),
1451 ADD_METHOD(want_write),
1452 ADD_METHOD(set_accept_state),
1453 ADD_METHOD(set_connect_state),
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001454 ADD_METHOD(get_session),
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05001455 ADD_METHOD(set_session),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001456 { NULL, NULL }
1457};
1458#undef ADD_ALIAS
1459#undef ADD_METHOD
1460
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001461static char ssl_Connection_doc[] = "\n\
1462Connection(context, socket) -> Connection instance\n\
1463\n\
1464Create a new Connection object, using the given OpenSSL.SSL.Context instance\n\
1465and socket.\n\
1466\n\
Jonathan Ballet78b92a22011-07-16 08:07:26 +09001467:param context: An SSL Context to use for this connection\n\
1468:param socket: The socket to use for transport layer\n\
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001469";
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001470
1471/*
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001472 * Initializer used by ssl_Connection_new and ssl_Connection_New. *Not*
1473 * tp_init. This takes an already allocated ssl_ConnectionObj, a context, and
1474 * a optionally a socket, and glues them all together.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001475 */
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001476static ssl_ConnectionObj*
1477ssl_Connection_init(ssl_ConnectionObj *self, ssl_ContextObj *ctx, PyObject *sock) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001478 int fd;
1479
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001480 Py_INCREF(ctx);
1481 self->context = ctx;
1482
1483 Py_INCREF(sock);
1484 self->socket = sock;
1485
1486 self->ssl = NULL;
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04001487 self->from_ssl = NULL;
1488 self->into_ssl = NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001489
1490 Py_INCREF(Py_None);
1491 self->app_data = Py_None;
1492
1493 self->tstate = NULL;
1494
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001495 self->ssl = SSL_new(self->context->ctx);
1496 SSL_set_app_data(self->ssl, self);
Rick Deanb71c0d22009-04-01 14:09:23 -05001497
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001498 if (self->socket == Py_None)
Rick Deanb71c0d22009-04-01 14:09:23 -05001499 {
1500 /* If it's not a socket or file, treat it like a memory buffer,
1501 * so crazy people can do things like EAP-TLS. */
1502 self->into_ssl = BIO_new(BIO_s_mem());
1503 self->from_ssl = BIO_new(BIO_s_mem());
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001504 if (self->into_ssl == NULL || self->from_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -05001505 goto error;
1506 SSL_set_bio(self->ssl, self->into_ssl, self->from_ssl);
1507 }
1508 else
1509 {
1510 fd = PyObject_AsFileDescriptor(self->socket);
1511 if (fd < 0)
1512 {
1513 Py_DECREF(self);
1514 return NULL;
1515 }
1516 else
1517 {
1518 SSL_set_fd(self->ssl, (SOCKET_T)fd);
1519 }
1520 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001521 return self;
Rick Deanb71c0d22009-04-01 14:09:23 -05001522
1523error:
1524 BIO_free(self->into_ssl); /* NULL safe */
1525 BIO_free(self->from_ssl); /* NULL safe */
1526 Py_DECREF(self);
1527 return NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001528}
1529
1530/*
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001531 * Constructor for Connection objects
1532 *
1533 * Arguments: ctx - An SSL Context to use for this connection
1534 * sock - The socket to use for transport layer
1535 * Returns: The newly created Connection object
1536 */
1537ssl_ConnectionObj *
1538ssl_Connection_New(ssl_ContextObj *ctx, PyObject *sock) {
1539 ssl_ConnectionObj *self;
1540
1541 self = PyObject_GC_New(ssl_ConnectionObj, &ssl_Connection_Type);
1542 if (self == NULL) {
1543 return NULL;
1544 }
1545 self = ssl_Connection_init(self, ctx, sock);
1546 if (self == NULL) {
1547 return NULL;
1548 }
1549 PyObject_GC_Track((PyObject *)self);
1550 return self;
1551}
1552
1553static PyObject*
1554ssl_Connection_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs) {
1555 ssl_ConnectionObj *self;
1556 ssl_ContextObj *ctx;
1557 PyObject *sock;
1558 static char *kwlist[] = {"context", "socket", NULL};
1559
1560 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O:Connection", kwlist,
1561 &ssl_Context_Type, &ctx, &sock)) {
1562 return NULL;
1563 }
1564
1565 self = (ssl_ConnectionObj *)subtype->tp_alloc(subtype, 1);
1566 if (self == NULL) {
1567 return NULL;
1568 }
1569
1570 return (PyObject *)ssl_Connection_init(self, ctx, sock);
1571}
1572
1573/*
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001574 * Find attribute
1575 *
1576 * Arguments: self - The Connection object
1577 * name - The attribute name
1578 * Returns: A Python object for the attribute, or NULL if something went
1579 * wrong
1580 */
1581static PyObject *
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001582ssl_Connection_getattro(ssl_ConnectionObj *self, PyObject *nameobj) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001583 PyObject *meth;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001584
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001585 meth = PyObject_GenericGetAttr((PyObject*)self, nameobj);
1586 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001587 PyErr_Clear();
1588 /* Try looking it up in the "socket" instead. */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001589 meth = PyObject_GenericGetAttr(self->socket, nameobj);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001590 }
1591
1592 return meth;
1593}
1594
1595/*
1596 * Call the visitproc on all contained objects.
1597 *
1598 * Arguments: self - The Connection object
1599 * visit - Function to call
1600 * arg - Extra argument to visit
1601 * Returns: 0 if all goes well, otherwise the return code from the first
1602 * call that gave non-zero result.
1603 */
1604static int
1605ssl_Connection_traverse(ssl_ConnectionObj *self, visitproc visit, void *arg)
1606{
1607 int ret = 0;
1608
1609 if (ret == 0 && self->context != NULL)
1610 ret = visit((PyObject *)self->context, arg);
1611 if (ret == 0 && self->socket != NULL)
1612 ret = visit(self->socket, arg);
1613 if (ret == 0 && self->app_data != NULL)
1614 ret = visit(self->app_data, arg);
1615 return ret;
1616}
1617
1618/*
1619 * Decref all contained objects and zero the pointers.
1620 *
1621 * Arguments: self - The Connection object
1622 * Returns: Always 0.
1623 */
1624static int
1625ssl_Connection_clear(ssl_ConnectionObj *self)
1626{
1627 Py_XDECREF(self->context);
1628 self->context = NULL;
1629 Py_XDECREF(self->socket);
1630 self->socket = NULL;
1631 Py_XDECREF(self->app_data);
1632 self->app_data = NULL;
Rick Deanb71c0d22009-04-01 14:09:23 -05001633 self->into_ssl = NULL; /* was cleaned up by SSL_free() */
1634 self->from_ssl = NULL; /* was cleaned up by SSL_free() */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001635 return 0;
1636}
1637
1638/*
1639 * Deallocate the memory used by the Connection object
1640 *
1641 * Arguments: self - The Connection object
1642 * Returns: None
1643 */
1644static void
1645ssl_Connection_dealloc(ssl_ConnectionObj *self)
1646{
1647 PyObject_GC_UnTrack(self);
1648 if (self->ssl != NULL)
1649 SSL_free(self->ssl);
1650 ssl_Connection_clear(self);
1651 PyObject_GC_Del(self);
1652}
1653
1654PyTypeObject ssl_Connection_Type = {
Jean-Paul Calderoneb6d75252010-08-11 23:55:45 -04001655 PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001656 "OpenSSL.SSL.Connection",
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001657 sizeof(ssl_ConnectionObj),
1658 0,
1659 (destructor)ssl_Connection_dealloc,
1660 NULL, /* print */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001661 NULL, /* tp_getattr */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001662 NULL, /* setattr */
1663 NULL, /* compare */
1664 NULL, /* repr */
1665 NULL, /* as_number */
1666 NULL, /* as_sequence */
1667 NULL, /* as_mapping */
1668 NULL, /* hash */
1669 NULL, /* call */
1670 NULL, /* str */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001671 (getattrofunc)ssl_Connection_getattro, /* getattro */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001672 NULL, /* setattro */
1673 NULL, /* as_buffer */
1674 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001675 ssl_Connection_doc, /* doc */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001676 (traverseproc)ssl_Connection_traverse,
1677 (inquiry)ssl_Connection_clear,
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001678 NULL, /* tp_richcompare */
1679 0, /* tp_weaklistoffset */
1680 NULL, /* tp_iter */
1681 NULL, /* tp_iternext */
1682 ssl_Connection_methods, /* tp_methods */
1683 NULL, /* tp_members */
1684 NULL, /* tp_getset */
1685 NULL, /* tp_base */
1686 NULL, /* tp_dict */
1687 NULL, /* tp_descr_get */
1688 NULL, /* tp_descr_set */
1689 0, /* tp_dictoffset */
1690 NULL, /* tp_init */
1691 NULL, /* tp_alloc */
1692 ssl_Connection_new, /* tp_new */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001693};
1694
1695
1696/*
1697 * Initiailze the Connection part of the SSL sub module
1698 *
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001699 * Arguments: dict - The OpenSSL.SSL module
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001700 * Returns: 1 for success, 0 otherwise
1701 */
1702int
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001703init_ssl_connection(PyObject *module) {
1704
1705 if (PyType_Ready(&ssl_Connection_Type) < 0) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001706 return 0;
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001707 }
1708
Jean-Paul Calderone86ad7112010-05-11 16:08:45 -04001709 /* PyModule_AddObject steals a reference.
1710 */
1711 Py_INCREF((PyObject *)&ssl_Connection_Type);
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001712 if (PyModule_AddObject(module, "Connection", (PyObject *)&ssl_Connection_Type) != 0) {
1713 return 0;
1714 }
1715
Jean-Paul Calderoneaed23582011-03-12 22:45:02 -05001716 /* PyModule_AddObject steals a reference.
1717 */
1718 Py_INCREF((PyObject *)&ssl_Connection_Type);
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001719 if (PyModule_AddObject(module, "ConnectionType", (PyObject *)&ssl_Connection_Type) != 0) {
1720 return 0;
1721 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001722
1723 return 1;
1724}
1725