blob: a8dfa58739bb8e549ee2e6712264251641a9e6d9 [file] [log] [blame]
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001/*
2 * connection.c
3 *
Jean-Paul Calderone8671c852011-03-02 19:26:20 -05004 * Copyright (C) AB Strakt
5 * Copyright (C) Jean-Paul Calderone
6 * See LICENSE for details.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05007 *
8 * SSL Connection objects and methods.
9 * See the file RATIONALE for a short explanation of why this module was written.
10 *
11 * Reviewed 2001-07-23
12 */
13#include <Python.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050014
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050015#ifndef MS_WINDOWS
16# include <sys/socket.h>
17# include <netinet/in.h>
18# if !(defined(__BEOS__) || defined(__CYGWIN__))
19# include <netinet/tcp.h>
20# endif
21#else
22# include <winsock.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050023# include <wincrypt.h>
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050024#endif
25
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050026#define SSL_MODULE
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -040027#include <openssl/bio.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050028#include <openssl/err.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050029#include "ssl.h"
30
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050031/**
32 * If we are on UNIX, fine, just use PyErr_SetFromErrno. If we are on Windows,
33 * apply some black winsock voodoo. This is basically just copied from Python's
34 * socketmodule.c
35 *
36 * Arguments: None
37 * Returns: None
38 */
39static void
40syscall_from_errno(void)
41{
42#ifdef MS_WINDOWS
43 int errnum = WSAGetLastError();
44 if (errnum)
45 {
46 static struct { int num; const char *msg; } *msgp, msgs[] = {
47 { WSAEINTR, "Interrupted system call" },
48 { WSAEBADF, "Bad file descriptor" },
49 { WSAEACCES, "Permission denied" },
50 { WSAEFAULT, "Bad address" },
51 { WSAEINVAL, "Invalid argument" },
52 { WSAEMFILE, "Too many open files" },
53 { WSAEWOULDBLOCK, "The socket operation could not complete "
54 "without blocking" },
55 { WSAEINPROGRESS, "Operation now in progress" },
56 { WSAEALREADY, "Operation already in progress" },
57 { WSAENOTSOCK, "Socket operation on non-socket" },
58 { WSAEDESTADDRREQ, "Destination address required" },
59 { WSAEMSGSIZE, "Message too long" },
60 { WSAEPROTOTYPE, "Protocol wrong type for socket" },
61 { WSAENOPROTOOPT, "Protocol not available" },
62 { WSAEPROTONOSUPPORT, "Protocol not supported" },
63 { WSAESOCKTNOSUPPORT, "Socket type not supported" },
64 { WSAEOPNOTSUPP, "Operation not supported" },
65 { WSAEPFNOSUPPORT, "Protocol family not supported" },
66 { WSAEAFNOSUPPORT, "Address family not supported" },
67 { WSAEADDRINUSE, "Address already in use" },
68 { WSAEADDRNOTAVAIL, "Can't assign requested address" },
69 { WSAENETDOWN, "Network is down" },
70 { WSAENETUNREACH, "Network is unreachable" },
71 { WSAENETRESET, "Network dropped connection on reset" },
72 { WSAECONNABORTED, "Software caused connection abort" },
73 { WSAECONNRESET, "Connection reset by peer" },
74 { WSAENOBUFS, "No buffer space available" },
75 { WSAEISCONN, "Socket is already connected" },
76 { WSAENOTCONN, "Socket is not connected" },
77 { WSAESHUTDOWN, "Can't send after socket shutdown" },
78 { WSAETOOMANYREFS, "Too many references: can't splice" },
79 { WSAETIMEDOUT, "Operation timed out" },
80 { WSAECONNREFUSED, "Connection refused" },
81 { WSAELOOP, "Too many levels of symbolic links" },
82 { WSAENAMETOOLONG, "File name too long" },
83 { WSAEHOSTDOWN, "Host is down" },
84 { WSAEHOSTUNREACH, "No route to host" },
85 { WSAENOTEMPTY, "Directory not empty" },
86 { WSAEPROCLIM, "Too many processes" },
87 { WSAEUSERS, "Too many users" },
88 { WSAEDQUOT, "Disc quota exceeded" },
89 { WSAESTALE, "Stale NFS file handle" },
90 { WSAEREMOTE, "Too many levels of remote in path" },
91 { WSASYSNOTREADY, "Network subsystem is unvailable" },
92 { WSAVERNOTSUPPORTED, "WinSock version is not supported" },
93 { WSANOTINITIALISED, "Successful WSAStartup() not yet performed" },
94 { WSAEDISCON, "Graceful shutdown in progress" },
95 /* Resolver errors */
96 { WSAHOST_NOT_FOUND, "No such host is known" },
97 { WSATRY_AGAIN, "Host not found, or server failed" },
98 { WSANO_RECOVERY, "Unexpected server error encountered" },
99 { WSANO_DATA, "Valid name without requested data" },
100 { WSANO_ADDRESS, "No address, look for MX record" },
101 { 0, NULL }
102 };
103 PyObject *v;
104 const char *msg = "winsock error";
105
106 for (msgp = msgs; msgp->msg; msgp++)
107 {
108 if (errnum == msgp->num)
109 {
110 msg = msgp->msg;
111 break;
112 }
113 }
114
115 v = Py_BuildValue("(is)", errnum, msg);
116 if (v != NULL)
117 {
118 PyErr_SetObject(ssl_SysCallError, v);
119 Py_DECREF(v);
120 }
121 return;
122 }
123#else
124 PyErr_SetFromErrno(ssl_SysCallError);
125#endif
126}
127
128/*
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400129 * Handle errors raised by BIO functions.
130 *
131 * Arguments: bio - The BIO object
132 * ret - The return value of the BIO_ function.
133 * Returns: None, the calling function should return NULL;
134 */
135static void
136handle_bio_errors(BIO* bio, int ret)
137{
138 if (BIO_should_retry(bio)) {
139 if (BIO_should_read(bio)) {
140 PyErr_SetNone(ssl_WantReadError);
141 } else if (BIO_should_write(bio)) {
142 PyErr_SetNone(ssl_WantWriteError);
143 } else if (BIO_should_io_special(bio)) {
144 /*
145 * It's somewhat unclear what this means. From the OpenSSL source,
146 * it seems like it should not be triggered by the memory BIO, so
147 * for the time being, this case shouldn't come up. The SSL BIO
148 * (which I think should be named the socket BIO) may trigger this
149 * case if its socket is not yet connected or it is busy doing
150 * something related to x509.
151 */
152 PyErr_SetString(PyExc_ValueError, "BIO_should_io_special");
153 } else {
154 /*
155 * I hope this is dead code. The BIO documentation suggests that
156 * one of the above three checks should always be true.
157 */
158 PyErr_SetString(PyExc_ValueError, "unknown bio failure");
159 }
160 } else {
161 /*
162 * If we aren't to retry, it's really an error, so fall back to the
163 * normal error reporting code. However, the BIO interface does not
164 * specify a uniform error reporting mechanism. We can only hope that
165 * the code which triggered the error also kindly pushed something onto
166 * the error stack.
167 */
Rick Deand369c932009-07-08 11:48:33 -0500168 exception_from_error_queue(ssl_Error);
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400169 }
170}
171
172/*
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500173 * Handle errors raised by SSL I/O functions. NOTE: Not SSL_shutdown ;)
174 *
175 * Arguments: ssl - The SSL object
176 * err - The return code from SSL_get_error
177 * ret - The return code from the SSL I/O function
178 * Returns: None, the calling function should return NULL
179 */
180static void
181handle_ssl_errors(SSL *ssl, int err, int ret)
182{
183 switch (err)
184 {
185 /*
186 * Strange as it may seem, ZeroReturn is not an error per se. It means
187 * that the SSL Connection has been closed correctly (note, not the
188 * transport layer!), i.e. closure alerts have been exchanged. This is
189 * an exception since
190 * + There's an SSL "error" code for it
191 * + You have to deal with it in any case, close the transport layer
192 * etc
193 */
194 case SSL_ERROR_ZERO_RETURN:
195 PyErr_SetNone(ssl_ZeroReturnError);
196 break;
197
198 /*
199 * The WantXYZ exceptions don't mean that there's an error, just that
200 * nothing could be read/written just now, maybe because the transport
201 * layer would block on the operation, or that there's not enough data
202 * available to fill an entire SSL record.
203 */
204 case SSL_ERROR_WANT_READ:
205 PyErr_SetNone(ssl_WantReadError);
206 break;
207
208 case SSL_ERROR_WANT_WRITE:
209 PyErr_SetNone(ssl_WantWriteError);
210 break;
211
212 case SSL_ERROR_WANT_X509_LOOKUP:
213 PyErr_SetNone(ssl_WantX509LookupError);
214 break;
215
216 case SSL_ERROR_SYSCALL:
217 if (ERR_peek_error() == 0)
218 {
219 if (ret < 0)
220 {
221 syscall_from_errno();
222 }
223 else
224 {
225 PyObject *v;
226
227 v = Py_BuildValue("(is)", -1, "Unexpected EOF");
228 if (v != NULL)
229 {
230 PyErr_SetObject(ssl_SysCallError, v);
231 Py_DECREF(v);
232 }
233 }
234 break;
235 }
236
237 /* NOTE: Fall-through here, we don't want to duplicate code, right? */
238
239 case SSL_ERROR_SSL:
240 ;
241 default:
Rick Deand369c932009-07-08 11:48:33 -0500242 exception_from_error_queue(ssl_Error);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500243 break;
244 }
245}
246
247/*
248 * Here be member methods of the Connection "class"
249 */
250
251static char ssl_Connection_get_context_doc[] = "\n\
252Get session context\n\
253\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400254@return: A Context object\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500255";
256static PyObject *
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400257ssl_Connection_get_context(ssl_ConnectionObj *self, PyObject *args) {
258 if (!PyArg_ParseTuple(args, ":get_context")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500259 return NULL;
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400260 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500261
262 Py_INCREF(self->context);
263 return (PyObject *)self->context;
264}
265
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\
269@param context: A L{Context} instance giving the new session context to use.\n\
270\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
304
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500305static char ssl_Connection_pending_doc[] = "\n\
306Get the number of bytes that can be safely read from the connection\n\
307\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400308@return: The number of bytes available in the receive buffer.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500309";
310static PyObject *
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400311ssl_Connection_pending(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500312 int ret;
313
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400314 if (!PyArg_ParseTuple(args, ":pending")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500315 return NULL;
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400316 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500317
318 ret = SSL_pending(self->ssl);
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400319 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500320}
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400321
Rick Deanb71c0d22009-04-01 14:09:23 -0500322static char ssl_Connection_bio_write_doc[] = "\n\
323When using non-socket connections this function sends\n\
324\"dirty\" data that would have traveled in on the network.\n\
325\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400326@param buf: The string to put into the memory BIO.\n\
327@return: The number of bytes written\n\
Rick Deanb71c0d22009-04-01 14:09:23 -0500328";
329static PyObject *
330ssl_Connection_bio_write(ssl_ConnectionObj *self, PyObject *args)
331{
332 char *buf;
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400333 int len, ret;
Rick Deanb71c0d22009-04-01 14:09:23 -0500334
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400335 if (self->into_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -0500336 {
337 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
338 return NULL;
339 }
340
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -0400341 if (!PyArg_ParseTuple(args, "s#|i:bio_write", &buf, &len))
Rick Deanb71c0d22009-04-01 14:09:23 -0500342 return NULL;
343
344 ret = BIO_write(self->into_ssl, buf, len);
345
346 if (PyErr_Occurred())
347 {
348 flush_error_queue();
349 return NULL;
350 }
351
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400352 if (ret <= 0) {
353 /*
354 * There was a problem with the BIO_write of some sort.
355 */
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400356 handle_bio_errors(self->into_ssl, ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500357 return NULL;
358 }
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400359
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400360 return PyLong_FromLong((long)ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500361}
362
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500363static char ssl_Connection_send_doc[] = "\n\
364Send data on the connection. NOTE: If you get one of the WantRead,\n\
365WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
366method again with the SAME buffer.\n\
367\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400368@param buf: The string to send\n\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500369@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400370 API, the value is ignored\n\
371@return: The number of bytes written\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500372";
373static PyObject *
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500374ssl_Connection_send(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500375 int len, ret, err, flags;
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500376 char *buf;
377
Jean-Paul Calderone5163f572011-04-22 18:38:16 -0400378#if PY_VERSION_HEX >= 0x02060000
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500379 Py_buffer pbuf;
380
381 if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
382 return NULL;
383
384 buf = pbuf.buf;
385 len = pbuf.len;
386#else
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500387
388 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
389 return NULL;
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500390#endif
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500391
392 MY_BEGIN_ALLOW_THREADS(self->tstate)
393 ret = SSL_write(self->ssl, buf, len);
394 MY_END_ALLOW_THREADS(self->tstate)
395
Jean-Paul Calderone5163f572011-04-22 18:38:16 -0400396#if PY_VERSION_HEX >= 0x02060000
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500397 PyBuffer_Release(&pbuf);
398#endif
399
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500400 if (PyErr_Occurred())
401 {
402 flush_error_queue();
403 return NULL;
404 }
405
406 err = SSL_get_error(self->ssl, ret);
407 if (err == SSL_ERROR_NONE)
408 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400409 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500410 }
411 else
412 {
413 handle_ssl_errors(self->ssl, err, ret);
414 return NULL;
415 }
416}
417
418static char ssl_Connection_sendall_doc[] = "\n\
419Send \"all\" data on the connection. This calls send() repeatedly until\n\
420all data is sent. If an error occurs, it's impossible to tell how much data\n\
421has been sent.\n\
422\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400423@param buf: The string to send\n\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500424@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400425 API, the value is ignored\n\
426@return: The number of bytes written\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500427";
428static PyObject *
429ssl_Connection_sendall(ssl_ConnectionObj *self, PyObject *args)
430{
431 char *buf;
432 int len, ret, err, flags;
433 PyObject *pyret = Py_None;
434
Jean-Paul Calderone5163f572011-04-22 18:38:16 -0400435#if PY_VERSION_HEX >= 0x02060000
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500436 Py_buffer pbuf;
437
438 if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
439 return NULL;
440
441 buf = pbuf.buf;
442 len = pbuf.len;
443#else
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500444 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
445 return NULL;
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500446#endif
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500447
448 do {
449 MY_BEGIN_ALLOW_THREADS(self->tstate)
450 ret = SSL_write(self->ssl, buf, len);
451 MY_END_ALLOW_THREADS(self->tstate)
452 if (PyErr_Occurred())
453 {
454 flush_error_queue();
455 pyret = NULL;
456 break;
457 }
458 err = SSL_get_error(self->ssl, ret);
459 if (err == SSL_ERROR_NONE)
460 {
461 buf += ret;
462 len -= ret;
463 }
464 else if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL ||
465 err == SSL_ERROR_ZERO_RETURN)
466 {
467 handle_ssl_errors(self->ssl, err, ret);
468 pyret = NULL;
469 break;
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500470 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500471 } while (len > 0);
472
Jean-Paul Calderone5163f572011-04-22 18:38:16 -0400473#if PY_VERSION_HEX >= 0x02060000
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -0500474 PyBuffer_Release(&pbuf);
475#endif
476
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500477 Py_XINCREF(pyret);
478 return pyret;
479}
480
481static char ssl_Connection_recv_doc[] = "\n\
482Receive data on the connection. NOTE: If you get one of the WantRead,\n\
483WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
484method again with the SAME buffer.\n\
485\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400486@param bufsiz: The maximum number of bytes to read\n\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500487@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400488 API, the value is ignored\n\
489@return: The string read from the Connection\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500490";
491static PyObject *
492ssl_Connection_recv(ssl_ConnectionObj *self, PyObject *args)
493{
494 int bufsiz, ret, err, flags;
495 PyObject *buf;
496
497 if (!PyArg_ParseTuple(args, "i|i:recv", &bufsiz, &flags))
498 return NULL;
499
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400500 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500501 if (buf == NULL)
502 return NULL;
503
504 MY_BEGIN_ALLOW_THREADS(self->tstate)
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400505 ret = SSL_read(self->ssl, PyBytes_AsString(buf), bufsiz);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500506 MY_END_ALLOW_THREADS(self->tstate)
507
508 if (PyErr_Occurred())
509 {
510 Py_DECREF(buf);
511 flush_error_queue();
512 return NULL;
513 }
514
515 err = SSL_get_error(self->ssl, ret);
516 if (err == SSL_ERROR_NONE)
517 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400518 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500519 return NULL;
520 return buf;
521 }
522 else
523 {
524 handle_ssl_errors(self->ssl, err, ret);
525 Py_DECREF(buf);
526 return NULL;
527 }
528}
529
Rick Deanb71c0d22009-04-01 14:09:23 -0500530static char ssl_Connection_bio_read_doc[] = "\n\
531When using non-socket connections this function reads\n\
532the \"dirty\" data that would have traveled away on the network.\n\
533\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400534@param bufsiz: The maximum number of bytes to read\n\
535@return: The string read.\n\
Rick Deanb71c0d22009-04-01 14:09:23 -0500536";
537static PyObject *
538ssl_Connection_bio_read(ssl_ConnectionObj *self, PyObject *args)
539{
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400540 int bufsiz, ret;
Rick Deanb71c0d22009-04-01 14:09:23 -0500541 PyObject *buf;
542
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400543 if (self->from_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -0500544 {
545 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
546 return NULL;
547 }
548
549 if (!PyArg_ParseTuple(args, "i:bio_read", &bufsiz))
550 return NULL;
551
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400552 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
Rick Deanb71c0d22009-04-01 14:09:23 -0500553 if (buf == NULL)
554 return NULL;
555
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400556 ret = BIO_read(self->from_ssl, PyBytes_AsString(buf), bufsiz);
Rick Deanb71c0d22009-04-01 14:09:23 -0500557
558 if (PyErr_Occurred())
559 {
560 Py_DECREF(buf);
561 flush_error_queue();
562 return NULL;
563 }
564
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400565 if (ret <= 0) {
566 /*
567 * There was a problem with the BIO_read of some sort.
568 */
569 handle_bio_errors(self->from_ssl, ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500570 Py_DECREF(buf);
571 return NULL;
572 }
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400573
574 /*
575 * Shrink the string to match the number of bytes we actually read.
576 */
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400577 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400578 {
579 Py_DECREF(buf);
580 return NULL;
581 }
582 return buf;
Rick Deanb71c0d22009-04-01 14:09:23 -0500583}
584
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500585static char ssl_Connection_renegotiate_doc[] = "\n\
586Renegotiate the session\n\
587\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400588@return: True if the renegotiation can be started, false otherwise\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500589";
590static PyObject *
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400591ssl_Connection_renegotiate(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500592 int ret;
593
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400594 if (!PyArg_ParseTuple(args, ":renegotiate")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500595 return NULL;
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400596 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500597
598 MY_BEGIN_ALLOW_THREADS(self->tstate);
599 ret = SSL_renegotiate(self->ssl);
600 MY_END_ALLOW_THREADS(self->tstate);
601
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400602 if (PyErr_Occurred()) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500603 flush_error_queue();
604 return NULL;
605 }
606
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400607 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500608}
609
610static char ssl_Connection_do_handshake_doc[] = "\n\
611Perform an SSL handshake (usually called after renegotiate() or one of\n\
612set_*_state()). This can raise the same exceptions as send and recv.\n\
613\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400614@return: None.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500615";
616static PyObject *
617ssl_Connection_do_handshake(ssl_ConnectionObj *self, PyObject *args)
618{
619 int ret, err;
620
621 if (!PyArg_ParseTuple(args, ":do_handshake"))
622 return NULL;
623
624 MY_BEGIN_ALLOW_THREADS(self->tstate);
625 ret = SSL_do_handshake(self->ssl);
626 MY_END_ALLOW_THREADS(self->tstate);
627
628 if (PyErr_Occurred())
629 {
630 flush_error_queue();
631 return NULL;
632 }
633
634 err = SSL_get_error(self->ssl, ret);
635 if (err == SSL_ERROR_NONE)
636 {
637 Py_INCREF(Py_None);
638 return Py_None;
639 }
640 else
641 {
642 handle_ssl_errors(self->ssl, err, ret);
643 return NULL;
644 }
645}
646
647#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
648static char ssl_Connection_renegotiate_pending_doc[] = "\n\
649Check if there's a renegotiation in progress, it will return false once\n\
650a renegotiation is finished.\n\
651\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400652@return: Whether there's a renegotiation in progress\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500653";
654static PyObject *
655ssl_Connection_renegotiate_pending(ssl_ConnectionObj *self, PyObject *args)
656{
657 if (!PyArg_ParseTuple(args, ":renegotiate_pending"))
658 return NULL;
659
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400660 return PyLong_FromLong((long)SSL_renegotiate_pending(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500661}
662#endif
663
664static char ssl_Connection_total_renegotiations_doc[] = "\n\
665Find out the total number of renegotiations.\n\
666\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400667@return: The number of renegotiations.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500668";
669static PyObject *
670ssl_Connection_total_renegotiations(ssl_ConnectionObj *self, PyObject *args)
671{
672 if (!PyArg_ParseTuple(args, ":total_renegotiations"))
673 return NULL;
674
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400675 return PyLong_FromLong(SSL_total_renegotiations(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500676}
677
678static char ssl_Connection_set_accept_state_doc[] = "\n\
679Set the connection to work in server mode. The handshake will be handled\n\
680automatically by read/write.\n\
681\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400682@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500683";
684static PyObject *
685ssl_Connection_set_accept_state(ssl_ConnectionObj *self, PyObject *args)
686{
687 if (!PyArg_ParseTuple(args, ":set_accept_state"))
688 return NULL;
689
690 SSL_set_accept_state(self->ssl);
691
692 Py_INCREF(Py_None);
693 return Py_None;
694}
695
696static char ssl_Connection_set_connect_state_doc[] = "\n\
697Set the connection to work in client mode. The handshake will be handled\n\
698automatically by read/write.\n\
699\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400700@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500701";
702static PyObject *
703ssl_Connection_set_connect_state(ssl_ConnectionObj *self, PyObject *args)
704{
705 if (!PyArg_ParseTuple(args, ":set_connect_state"))
706 return NULL;
707
708 SSL_set_connect_state(self->ssl);
709
710 Py_INCREF(Py_None);
711 return Py_None;
712}
713
714static char ssl_Connection_connect_doc[] = "\n\
715Connect to remote host and set up client-side SSL\n\
716\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400717@param addr: A remote address\n\
718@return: What the socket's connect method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500719";
720static PyObject *
721ssl_Connection_connect(ssl_ConnectionObj *self, PyObject *args)
722{
723 PyObject *meth, *ret;
724
725 if ((meth = PyObject_GetAttrString(self->socket, "connect")) == NULL)
726 return NULL;
727
728 SSL_set_connect_state(self->ssl);
729
730 ret = PyEval_CallObject(meth, args);
731 Py_DECREF(meth);
732 if (ret == NULL)
733 return NULL;
734
735 return ret;
736}
737
738static char ssl_Connection_connect_ex_doc[] = "\n\
739Connect to remote host and set up client-side SSL. Note that if the socket's\n\
740connect_ex method doesn't return 0, SSL won't be initialized.\n\
741\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400742@param addr: A remove address\n\
743@return: What the socket's connect_ex method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500744";
745static PyObject *
746ssl_Connection_connect_ex(ssl_ConnectionObj *self, PyObject *args)
747{
748 PyObject *meth, *ret;
749
750 if ((meth = PyObject_GetAttrString(self->socket, "connect_ex")) == NULL)
751 return NULL;
752
753 SSL_set_connect_state(self->ssl);
754
755 ret = PyEval_CallObject(meth, args);
756 Py_DECREF(meth);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500757 return ret;
758}
759
760static char ssl_Connection_accept_doc[] = "\n\
761Accept incoming connection and set up SSL on it\n\
762\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400763@return: A (conn,addr) pair where conn is a Connection and addr is an\n\
764 address\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500765";
766static PyObject *
767ssl_Connection_accept(ssl_ConnectionObj *self, PyObject *args)
768{
769 PyObject *tuple, *socket, *address, *meth;
770 ssl_ConnectionObj *conn;
771
772 if ((meth = PyObject_GetAttrString(self->socket, "accept")) == NULL)
773 return NULL;
774 tuple = PyEval_CallObject(meth, args);
775 Py_DECREF(meth);
776 if (tuple == NULL)
777 return NULL;
778
779 socket = PyTuple_GetItem(tuple, 0);
780 Py_INCREF(socket);
781 address = PyTuple_GetItem(tuple, 1);
782 Py_INCREF(address);
783 Py_DECREF(tuple);
784
785 conn = ssl_Connection_New(self->context, socket);
786 Py_DECREF(socket);
787 if (conn == NULL)
788 {
789 Py_DECREF(address);
790 return NULL;
791 }
792
793 SSL_set_accept_state(conn->ssl);
794
795 tuple = Py_BuildValue("(OO)", conn, address);
796
797 Py_DECREF(conn);
798 Py_DECREF(address);
799
800 return tuple;
801}
802
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400803static char ssl_Connection_bio_shutdown_doc[] = "\n\
804When using non-socket connections this function signals end of\n\
805data on the input for this connection.\n\
806\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400807@return: None\n\
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400808";
809
810static PyObject *
811ssl_Connection_bio_shutdown(ssl_ConnectionObj *self, PyObject *args)
812{
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400813 if (self->from_ssl == NULL)
814 {
815 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
816 return NULL;
817 }
818
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400819 BIO_set_mem_eof_return(self->into_ssl, 0);
820 Py_INCREF(Py_None);
821 return Py_None;
822}
823
824
825
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500826static char ssl_Connection_shutdown_doc[] = "\n\
827Send closure alert\n\
828\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400829@return: True if the shutdown completed successfully (i.e. both sides\n\
830 have sent closure alerts), false otherwise (i.e. you have to\n\
831 wait for a ZeroReturnError on a recv() method call\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500832";
833static PyObject *
834ssl_Connection_shutdown(ssl_ConnectionObj *self, PyObject *args)
835{
836 int ret;
837
838 if (!PyArg_ParseTuple(args, ":shutdown"))
839 return NULL;
840
841 MY_BEGIN_ALLOW_THREADS(self->tstate)
842 ret = SSL_shutdown(self->ssl);
843 MY_END_ALLOW_THREADS(self->tstate)
844
845 if (PyErr_Occurred())
846 {
847 flush_error_queue();
848 return NULL;
849 }
850
851 if (ret < 0)
852 {
Rick Deand369c932009-07-08 11:48:33 -0500853 exception_from_error_queue(ssl_Error);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500854 return NULL;
855 }
856 else if (ret > 0)
857 {
858 Py_INCREF(Py_True);
859 return Py_True;
860 }
861 else
862 {
863 Py_INCREF(Py_False);
864 return Py_False;
865 }
866}
867
868static char ssl_Connection_get_cipher_list_doc[] = "\n\
869Get the session cipher list\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500870\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400871@return: A list of cipher strings\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500872";
873static PyObject *
874ssl_Connection_get_cipher_list(ssl_ConnectionObj *self, PyObject *args)
875{
876 int idx = 0;
877 const char *ret;
878 PyObject *lst, *item;
879
880 if (!PyArg_ParseTuple(args, ":get_cipher_list"))
881 return NULL;
882
883 lst = PyList_New(0);
884 while ((ret = SSL_get_cipher_list(self->ssl, idx)) != NULL)
885 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400886 item = PyText_FromString(ret);
Ziga Seilnachtfdeadb12009-09-01 16:35:50 +0200887 PyList_Append(lst, item);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500888 Py_DECREF(item);
889 idx++;
890 }
891 return lst;
892}
893
Ziga Seilnachtf93bf102009-10-23 09:51:07 +0200894static char ssl_Connection_get_client_ca_list_doc[] = "\n\
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200895Get CAs whose certificates are suggested for client authentication.\n\
896\n\
Jean-Paul Calderone35788902009-10-24 13:48:08 -0400897@return: If this is a server connection, a list of X509Names representing\n\
898 the acceptable CAs as set by L{OpenSSL.SSL.Context.set_client_ca_list} or\n\
899 L{OpenSSL.SSL.Context.add_client_ca}. If this is a client connection,\n\
900 the list of such X509Names sent by the server, or an empty list if that\n\
901 has not yet happened.\n\
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200902";
903
904static PyObject *
Jean-Paul Calderone6e2b6852009-10-24 14:04:30 -0400905ssl_Connection_get_client_ca_list(ssl_ConnectionObj *self, PyObject *args) {
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200906 STACK_OF(X509_NAME) *CANames;
907 PyObject *CAList;
908 int i, n;
909
Ziga Seilnachtf93bf102009-10-23 09:51:07 +0200910 if (!PyArg_ParseTuple(args, ":get_client_ca_list")) {
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200911 return NULL;
912 }
913 CANames = SSL_get_client_CA_list(self->ssl);
914 if (CANames == NULL) {
915 return PyList_New(0);
916 }
917 n = sk_X509_NAME_num(CANames);
918 CAList = PyList_New(n);
919 if (CAList == NULL) {
920 return NULL;
921 }
922 for (i = 0; i < n; i++) {
923 X509_NAME *CAName;
924 PyObject *CA;
925
926 CAName = X509_NAME_dup(sk_X509_NAME_value(CANames, i));
927 if (CAName == NULL) {
928 Py_DECREF(CAList);
929 exception_from_error_queue(ssl_Error);
930 return NULL;
931 }
Jean-Paul Calderone305626a2010-10-31 20:51:17 -0400932 CA = (PyObject *)new_x509name(CAName, 1);
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200933 if (CA == NULL) {
934 X509_NAME_free(CAName);
935 Py_DECREF(CAList);
936 return NULL;
937 }
938 if (PyList_SetItem(CAList, i, CA)) {
939 Py_DECREF(CA);
940 Py_DECREF(CAList);
941 return NULL;
942 }
943 }
944 return CAList;
945}
946
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500947static char ssl_Connection_makefile_doc[] = "\n\
948The makefile() method is not implemented, since there is no dup semantics\n\
949for SSL connections\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500950\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400951@raise NotImplementedError\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500952";
953static PyObject *
954ssl_Connection_makefile(ssl_ConnectionObj *self, PyObject *args)
955{
956 PyErr_SetString(PyExc_NotImplementedError, "Cannot make file object of SSL.Connection");
957 return NULL;
958}
959
960static char ssl_Connection_get_app_data_doc[] = "\n\
961Get application data\n\
962\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400963@return: The application data\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500964";
965static PyObject *
966ssl_Connection_get_app_data(ssl_ConnectionObj *self, PyObject *args)
967{
968 if (!PyArg_ParseTuple(args, ":get_app_data"))
969 return NULL;
970
971 Py_INCREF(self->app_data);
972 return self->app_data;
973}
974
975static char ssl_Connection_set_app_data_doc[] = "\n\
976Set application data\n\
977\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400978@param data - The application data\n\
979@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500980";
981static PyObject *
982ssl_Connection_set_app_data(ssl_ConnectionObj *self, PyObject *args)
983{
984 PyObject *data;
985
986 if (!PyArg_ParseTuple(args, "O:set_app_data", &data))
987 return NULL;
988
989 Py_DECREF(self->app_data);
990 Py_INCREF(data);
991 self->app_data = data;
992
993 Py_INCREF(Py_None);
994 return Py_None;
995}
996
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500997static char ssl_Connection_get_shutdown_doc[] = "\n\
998Get shutdown state\n\
999\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001000@return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001001";
1002static PyObject *
1003ssl_Connection_get_shutdown(ssl_ConnectionObj *self, PyObject *args)
1004{
1005 if (!PyArg_ParseTuple(args, ":get_shutdown"))
1006 return NULL;
1007
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001008 return PyLong_FromLong((long)SSL_get_shutdown(self->ssl));
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001009}
1010
1011static char ssl_Connection_set_shutdown_doc[] = "\n\
1012Set shutdown state\n\
1013\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001014@param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
1015@return: None\n\
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001016";
1017static PyObject *
1018ssl_Connection_set_shutdown(ssl_ConnectionObj *self, PyObject *args)
1019{
1020 int shutdown;
1021
1022 if (!PyArg_ParseTuple(args, "i:set_shutdown", &shutdown))
1023 return NULL;
1024
1025 SSL_set_shutdown(self->ssl, shutdown);
1026 Py_INCREF(Py_None);
1027 return Py_None;
1028}
1029
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001030static char ssl_Connection_state_string_doc[] = "\n\
1031Get a verbose state description\n\
1032\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001033@return: A string representing the state\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001034";
1035static PyObject *
1036ssl_Connection_state_string(ssl_ConnectionObj *self, PyObject *args)
1037{
1038 if (!PyArg_ParseTuple(args, ":state_string"))
1039 return NULL;
1040
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001041 return PyText_FromString(SSL_state_string_long(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001042}
1043
Rick Deanb71c0d22009-04-01 14:09:23 -05001044static char ssl_Connection_client_random_doc[] = "\n\
1045Get a copy of the client hello nonce.\n\
1046\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001047@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001048";
1049static PyObject *
1050ssl_Connection_client_random(ssl_ConnectionObj *self, PyObject *args)
1051{
1052 if (!PyArg_ParseTuple(args, ":client_random"))
1053 return NULL;
1054
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001055 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001056 Py_INCREF(Py_None);
1057 return Py_None;
1058 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001059 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->client_random, SSL3_RANDOM_SIZE);
Rick Deanb71c0d22009-04-01 14:09:23 -05001060}
1061
1062static char ssl_Connection_server_random_doc[] = "\n\
1063Get a copy of the server hello nonce.\n\
1064\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001065@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001066";
1067static PyObject *
1068ssl_Connection_server_random(ssl_ConnectionObj *self, PyObject *args)
1069{
1070 if (!PyArg_ParseTuple(args, ":server_random"))
1071 return NULL;
1072
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001073 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001074 Py_INCREF(Py_None);
1075 return Py_None;
1076 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001077 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->server_random, SSL3_RANDOM_SIZE);
Rick Deanb71c0d22009-04-01 14:09:23 -05001078}
1079
1080static char ssl_Connection_master_key_doc[] = "\n\
1081Get a copy of the master key.\n\
1082\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001083@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001084";
1085static PyObject *
1086ssl_Connection_master_key(ssl_ConnectionObj *self, PyObject *args)
1087{
1088 if (!PyArg_ParseTuple(args, ":master_key"))
1089 return NULL;
1090
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001091 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001092 Py_INCREF(Py_None);
1093 return Py_None;
1094 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001095 return PyBytes_FromStringAndSize( (const char *) self->ssl->session->master_key, self->ssl->session->master_key_length);
Rick Deanb71c0d22009-04-01 14:09:23 -05001096}
1097
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001098static char ssl_Connection_sock_shutdown_doc[] = "\n\
1099See shutdown(2)\n\
1100\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001101@return: What the socket's shutdown() method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001102";
1103static PyObject *
1104ssl_Connection_sock_shutdown(ssl_ConnectionObj *self, PyObject *args)
1105{
1106 PyObject *meth, *ret;
1107
1108 if ((meth = PyObject_GetAttrString(self->socket, "shutdown")) == NULL)
1109 return NULL;
1110 ret = PyEval_CallObject(meth, args);
1111 Py_DECREF(meth);
1112 return ret;
1113}
1114
1115static char ssl_Connection_get_peer_certificate_doc[] = "\n\
1116Retrieve the other side's certificate (if any)\n\
1117\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001118@return: The peer's certificate\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001119";
1120static PyObject *
1121ssl_Connection_get_peer_certificate(ssl_ConnectionObj *self, PyObject *args)
1122{
1123 X509 *cert;
1124
1125 if (!PyArg_ParseTuple(args, ":get_peer_certificate"))
1126 return NULL;
1127
1128 cert = SSL_get_peer_certificate(self->ssl);
1129 if (cert != NULL)
1130 {
Jean-Paul Calderone5c0f1f62010-10-31 21:36:43 -04001131 return (PyObject *)new_x509(cert, 1);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001132 }
1133 else
1134 {
1135 Py_INCREF(Py_None);
1136 return Py_None;
1137 }
1138}
1139
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001140static char ssl_Connection_get_peer_cert_chain_doc[] = "\n\
1141Retrieve the other side's certificate (if any)\n\
1142\n\
Jean-Paul Calderone0a7e06a2011-05-19 18:49:35 -04001143@return: A list of X509 instances giving the peer's certificate chain,\n\
1144 or None if it does not have one.\n\
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001145";
1146static PyObject *
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001147ssl_Connection_get_peer_cert_chain(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001148 STACK_OF(X509) *sk;
Jean-Paul Calderone0a7e06a2011-05-19 18:49:35 -04001149 PyObject *chain;
1150 crypto_X509Obj *cert;
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001151 Py_ssize_t i;
1152
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001153 if (!PyArg_ParseTuple(args, ":get_peer_cert_chain")) {
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001154 return NULL;
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001155 }
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001156
1157 sk = SSL_get_peer_cert_chain(self->ssl);
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001158 if (sk != NULL) {
Jean-Paul Calderone0a7e06a2011-05-19 18:49:35 -04001159 chain = PyList_New(sk_X509_num(sk));
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001160 for (i = 0; i < sk_X509_num(sk); i++) {
Jean-Paul Calderone13d190b2011-05-20 19:14:50 -04001161 cert = new_x509(sk_X509_value(sk, i), 1);
Jean-Paul Calderone0a7e06a2011-05-19 18:49:35 -04001162 if (!cert) {
1163 /* XXX Untested */
1164 Py_DECREF(chain);
1165 return NULL;
1166 }
1167 CRYPTO_add(&cert->x509->references, 1, CRYPTO_LOCK_X509);
1168 PyList_SET_ITEM(chain, i, (PyObject *)cert);
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001169 }
Jean-Paul Calderone0a7e06a2011-05-19 18:49:35 -04001170 return chain;
Jean-Paul Calderonefcced2a2011-05-19 18:02:11 -04001171 } else {
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001172 Py_INCREF(Py_None);
1173 return Py_None;
1174 }
1175
1176}
1177
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001178static char ssl_Connection_want_read_doc[] = "\n\
1179Checks if more data has to be read from the transport layer to complete an\n\
1180operation.\n\
1181\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001182@return: True iff more data has to be read\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001183";
1184static PyObject *
1185ssl_Connection_want_read(ssl_ConnectionObj *self, PyObject *args)
1186{
1187 if (!PyArg_ParseTuple(args, ":want_read"))
1188 return NULL;
1189
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001190 return PyLong_FromLong((long)SSL_want_read(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001191}
1192
1193static char ssl_Connection_want_write_doc[] = "\n\
1194Checks if there is data to write to the transport layer to complete an\n\
1195operation.\n\
1196\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001197@return: True iff there is data to write\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001198";
1199static PyObject *
1200ssl_Connection_want_write(ssl_ConnectionObj *self, PyObject *args)
1201{
1202 if (!PyArg_ParseTuple(args, ":want_write"))
1203 return NULL;
1204
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001205 return PyLong_FromLong((long)SSL_want_write(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001206}
1207
1208/*
1209 * Member methods in the Connection object
1210 * ADD_METHOD(name) expands to a correct PyMethodDef declaration
1211 * { 'name', (PyCFunction)ssl_Connection_name, METH_VARARGS }
1212 * for convenience
1213 * ADD_ALIAS(name,real) creates an "alias" of the ssl_Connection_real
1214 * function with the name 'name'
1215 */
1216#define ADD_METHOD(name) \
1217 { #name, (PyCFunction)ssl_Connection_##name, METH_VARARGS, ssl_Connection_##name##_doc }
1218#define ADD_ALIAS(name,real) \
1219 { #name, (PyCFunction)ssl_Connection_##real, METH_VARARGS, ssl_Connection_##real##_doc }
1220static PyMethodDef ssl_Connection_methods[] =
1221{
1222 ADD_METHOD(get_context),
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001223 ADD_METHOD(set_context),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001224 ADD_METHOD(pending),
1225 ADD_METHOD(send),
1226 ADD_ALIAS (write, send),
1227 ADD_METHOD(sendall),
1228 ADD_METHOD(recv),
1229 ADD_ALIAS (read, recv),
Rick Deanb71c0d22009-04-01 14:09:23 -05001230 ADD_METHOD(bio_read),
1231 ADD_METHOD(bio_write),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001232 ADD_METHOD(renegotiate),
1233 ADD_METHOD(do_handshake),
1234#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
1235 ADD_METHOD(renegotiate_pending),
1236#endif
1237 ADD_METHOD(total_renegotiations),
1238 ADD_METHOD(connect),
1239 ADD_METHOD(connect_ex),
1240 ADD_METHOD(accept),
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04001241 ADD_METHOD(bio_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001242 ADD_METHOD(shutdown),
1243 ADD_METHOD(get_cipher_list),
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02001244 ADD_METHOD(get_client_ca_list),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001245 ADD_METHOD(makefile),
1246 ADD_METHOD(get_app_data),
1247 ADD_METHOD(set_app_data),
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001248 ADD_METHOD(get_shutdown),
1249 ADD_METHOD(set_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001250 ADD_METHOD(state_string),
Rick Deanb71c0d22009-04-01 14:09:23 -05001251 ADD_METHOD(server_random),
1252 ADD_METHOD(client_random),
1253 ADD_METHOD(master_key),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001254 ADD_METHOD(sock_shutdown),
1255 ADD_METHOD(get_peer_certificate),
Jean-Paul Calderone95b92c72011-05-17 15:45:21 -04001256 ADD_METHOD(get_peer_cert_chain),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001257 ADD_METHOD(want_read),
1258 ADD_METHOD(want_write),
1259 ADD_METHOD(set_accept_state),
1260 ADD_METHOD(set_connect_state),
1261 { NULL, NULL }
1262};
1263#undef ADD_ALIAS
1264#undef ADD_METHOD
1265
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001266static char ssl_Connection_doc[] = "\n\
1267Connection(context, socket) -> Connection instance\n\
1268\n\
1269Create a new Connection object, using the given OpenSSL.SSL.Context instance\n\
1270and socket.\n\
1271\n\
1272@param context: An SSL Context to use for this connection\n\
1273@param socket: The socket to use for transport layer\n\
1274";
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001275
1276/*
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001277 * Initializer used by ssl_Connection_new and ssl_Connection_New. *Not*
1278 * tp_init. This takes an already allocated ssl_ConnectionObj, a context, and
1279 * a optionally a socket, and glues them all together.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001280 */
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001281static ssl_ConnectionObj*
1282ssl_Connection_init(ssl_ConnectionObj *self, ssl_ContextObj *ctx, PyObject *sock) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001283 int fd;
1284
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001285 Py_INCREF(ctx);
1286 self->context = ctx;
1287
1288 Py_INCREF(sock);
1289 self->socket = sock;
1290
1291 self->ssl = NULL;
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04001292 self->from_ssl = NULL;
1293 self->into_ssl = NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001294
1295 Py_INCREF(Py_None);
1296 self->app_data = Py_None;
1297
1298 self->tstate = NULL;
1299
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001300 self->ssl = SSL_new(self->context->ctx);
1301 SSL_set_app_data(self->ssl, self);
Rick Deanb71c0d22009-04-01 14:09:23 -05001302
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001303 if (self->socket == Py_None)
Rick Deanb71c0d22009-04-01 14:09:23 -05001304 {
1305 /* If it's not a socket or file, treat it like a memory buffer,
1306 * so crazy people can do things like EAP-TLS. */
1307 self->into_ssl = BIO_new(BIO_s_mem());
1308 self->from_ssl = BIO_new(BIO_s_mem());
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001309 if (self->into_ssl == NULL || self->from_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -05001310 goto error;
1311 SSL_set_bio(self->ssl, self->into_ssl, self->from_ssl);
1312 }
1313 else
1314 {
1315 fd = PyObject_AsFileDescriptor(self->socket);
1316 if (fd < 0)
1317 {
1318 Py_DECREF(self);
1319 return NULL;
1320 }
1321 else
1322 {
1323 SSL_set_fd(self->ssl, (SOCKET_T)fd);
1324 }
1325 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001326 return self;
Rick Deanb71c0d22009-04-01 14:09:23 -05001327
1328error:
1329 BIO_free(self->into_ssl); /* NULL safe */
1330 BIO_free(self->from_ssl); /* NULL safe */
1331 Py_DECREF(self);
1332 return NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001333}
1334
1335/*
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001336 * Constructor for Connection objects
1337 *
1338 * Arguments: ctx - An SSL Context to use for this connection
1339 * sock - The socket to use for transport layer
1340 * Returns: The newly created Connection object
1341 */
1342ssl_ConnectionObj *
1343ssl_Connection_New(ssl_ContextObj *ctx, PyObject *sock) {
1344 ssl_ConnectionObj *self;
1345
1346 self = PyObject_GC_New(ssl_ConnectionObj, &ssl_Connection_Type);
1347 if (self == NULL) {
1348 return NULL;
1349 }
1350 self = ssl_Connection_init(self, ctx, sock);
1351 if (self == NULL) {
1352 return NULL;
1353 }
1354 PyObject_GC_Track((PyObject *)self);
1355 return self;
1356}
1357
1358static PyObject*
1359ssl_Connection_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs) {
1360 ssl_ConnectionObj *self;
1361 ssl_ContextObj *ctx;
1362 PyObject *sock;
1363 static char *kwlist[] = {"context", "socket", NULL};
1364
1365 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O:Connection", kwlist,
1366 &ssl_Context_Type, &ctx, &sock)) {
1367 return NULL;
1368 }
1369
1370 self = (ssl_ConnectionObj *)subtype->tp_alloc(subtype, 1);
1371 if (self == NULL) {
1372 return NULL;
1373 }
1374
1375 return (PyObject *)ssl_Connection_init(self, ctx, sock);
1376}
1377
1378/*
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001379 * Find attribute
1380 *
1381 * Arguments: self - The Connection object
1382 * name - The attribute name
1383 * Returns: A Python object for the attribute, or NULL if something went
1384 * wrong
1385 */
1386static PyObject *
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001387ssl_Connection_getattro(ssl_ConnectionObj *self, PyObject *nameobj) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001388 PyObject *meth;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001389
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001390 meth = PyObject_GenericGetAttr((PyObject*)self, nameobj);
1391 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001392 PyErr_Clear();
1393 /* Try looking it up in the "socket" instead. */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001394 meth = PyObject_GenericGetAttr(self->socket, nameobj);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001395 }
1396
1397 return meth;
1398}
1399
1400/*
1401 * Call the visitproc on all contained objects.
1402 *
1403 * Arguments: self - The Connection object
1404 * visit - Function to call
1405 * arg - Extra argument to visit
1406 * Returns: 0 if all goes well, otherwise the return code from the first
1407 * call that gave non-zero result.
1408 */
1409static int
1410ssl_Connection_traverse(ssl_ConnectionObj *self, visitproc visit, void *arg)
1411{
1412 int ret = 0;
1413
1414 if (ret == 0 && self->context != NULL)
1415 ret = visit((PyObject *)self->context, arg);
1416 if (ret == 0 && self->socket != NULL)
1417 ret = visit(self->socket, arg);
1418 if (ret == 0 && self->app_data != NULL)
1419 ret = visit(self->app_data, arg);
1420 return ret;
1421}
1422
1423/*
1424 * Decref all contained objects and zero the pointers.
1425 *
1426 * Arguments: self - The Connection object
1427 * Returns: Always 0.
1428 */
1429static int
1430ssl_Connection_clear(ssl_ConnectionObj *self)
1431{
1432 Py_XDECREF(self->context);
1433 self->context = NULL;
1434 Py_XDECREF(self->socket);
1435 self->socket = NULL;
1436 Py_XDECREF(self->app_data);
1437 self->app_data = NULL;
Rick Deanb71c0d22009-04-01 14:09:23 -05001438 self->into_ssl = NULL; /* was cleaned up by SSL_free() */
1439 self->from_ssl = NULL; /* was cleaned up by SSL_free() */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001440 return 0;
1441}
1442
1443/*
1444 * Deallocate the memory used by the Connection object
1445 *
1446 * Arguments: self - The Connection object
1447 * Returns: None
1448 */
1449static void
1450ssl_Connection_dealloc(ssl_ConnectionObj *self)
1451{
1452 PyObject_GC_UnTrack(self);
1453 if (self->ssl != NULL)
1454 SSL_free(self->ssl);
1455 ssl_Connection_clear(self);
1456 PyObject_GC_Del(self);
1457}
1458
1459PyTypeObject ssl_Connection_Type = {
Jean-Paul Calderoneb6d75252010-08-11 23:55:45 -04001460 PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001461 "OpenSSL.SSL.Connection",
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001462 sizeof(ssl_ConnectionObj),
1463 0,
1464 (destructor)ssl_Connection_dealloc,
1465 NULL, /* print */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001466 NULL, /* tp_getattr */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001467 NULL, /* setattr */
1468 NULL, /* compare */
1469 NULL, /* repr */
1470 NULL, /* as_number */
1471 NULL, /* as_sequence */
1472 NULL, /* as_mapping */
1473 NULL, /* hash */
1474 NULL, /* call */
1475 NULL, /* str */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001476 (getattrofunc)ssl_Connection_getattro, /* getattro */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001477 NULL, /* setattro */
1478 NULL, /* as_buffer */
1479 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001480 ssl_Connection_doc, /* doc */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001481 (traverseproc)ssl_Connection_traverse,
1482 (inquiry)ssl_Connection_clear,
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001483 NULL, /* tp_richcompare */
1484 0, /* tp_weaklistoffset */
1485 NULL, /* tp_iter */
1486 NULL, /* tp_iternext */
1487 ssl_Connection_methods, /* tp_methods */
1488 NULL, /* tp_members */
1489 NULL, /* tp_getset */
1490 NULL, /* tp_base */
1491 NULL, /* tp_dict */
1492 NULL, /* tp_descr_get */
1493 NULL, /* tp_descr_set */
1494 0, /* tp_dictoffset */
1495 NULL, /* tp_init */
1496 NULL, /* tp_alloc */
1497 ssl_Connection_new, /* tp_new */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001498};
1499
1500
1501/*
1502 * Initiailze the Connection part of the SSL sub module
1503 *
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001504 * Arguments: dict - The OpenSSL.SSL module
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001505 * Returns: 1 for success, 0 otherwise
1506 */
1507int
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001508init_ssl_connection(PyObject *module) {
1509
1510 if (PyType_Ready(&ssl_Connection_Type) < 0) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001511 return 0;
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001512 }
1513
Jean-Paul Calderone86ad7112010-05-11 16:08:45 -04001514 /* PyModule_AddObject steals a reference.
1515 */
1516 Py_INCREF((PyObject *)&ssl_Connection_Type);
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001517 if (PyModule_AddObject(module, "Connection", (PyObject *)&ssl_Connection_Type) != 0) {
1518 return 0;
1519 }
1520
Jean-Paul Calderoneaed23582011-03-12 22:45:02 -05001521 /* PyModule_AddObject steals a reference.
1522 */
1523 Py_INCREF((PyObject *)&ssl_Connection_Type);
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001524 if (PyModule_AddObject(module, "ConnectionType", (PyObject *)&ssl_Connection_Type) != 0) {
1525 return 0;
1526 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001527
1528 return 1;
1529}
1530