blob: ccefcc808e3ab7ad8412609aade2cc8e90011ff8 [file] [log] [blame]
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001/*
2 * connection.c
3 *
4 * Copyright (C) AB Strakt 2001, All rights reserved
Jean-Paul Calderone8b63d452008-03-21 18:31:12 -04005 * Copyright (C) Jean-Paul Calderone 2008, All rights reserved
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05006 *
7 * SSL Connection objects and methods.
8 * See the file RATIONALE for a short explanation of why this module was written.
9 *
10 * Reviewed 2001-07-23
11 */
12#include <Python.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050013
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050014#ifndef MS_WINDOWS
15# include <sys/socket.h>
16# include <netinet/in.h>
17# if !(defined(__BEOS__) || defined(__CYGWIN__))
18# include <netinet/tcp.h>
19# endif
20#else
21# include <winsock.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050022# include <wincrypt.h>
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050023#endif
24
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050025#define SSL_MODULE
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -040026#include <openssl/bio.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050027#include <openssl/err.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050028#include "ssl.h"
29
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050030/**
31 * If we are on UNIX, fine, just use PyErr_SetFromErrno. If we are on Windows,
32 * apply some black winsock voodoo. This is basically just copied from Python's
33 * socketmodule.c
34 *
35 * Arguments: None
36 * Returns: None
37 */
38static void
39syscall_from_errno(void)
40{
41#ifdef MS_WINDOWS
42 int errnum = WSAGetLastError();
43 if (errnum)
44 {
45 static struct { int num; const char *msg; } *msgp, msgs[] = {
46 { WSAEINTR, "Interrupted system call" },
47 { WSAEBADF, "Bad file descriptor" },
48 { WSAEACCES, "Permission denied" },
49 { WSAEFAULT, "Bad address" },
50 { WSAEINVAL, "Invalid argument" },
51 { WSAEMFILE, "Too many open files" },
52 { WSAEWOULDBLOCK, "The socket operation could not complete "
53 "without blocking" },
54 { WSAEINPROGRESS, "Operation now in progress" },
55 { WSAEALREADY, "Operation already in progress" },
56 { WSAENOTSOCK, "Socket operation on non-socket" },
57 { WSAEDESTADDRREQ, "Destination address required" },
58 { WSAEMSGSIZE, "Message too long" },
59 { WSAEPROTOTYPE, "Protocol wrong type for socket" },
60 { WSAENOPROTOOPT, "Protocol not available" },
61 { WSAEPROTONOSUPPORT, "Protocol not supported" },
62 { WSAESOCKTNOSUPPORT, "Socket type not supported" },
63 { WSAEOPNOTSUPP, "Operation not supported" },
64 { WSAEPFNOSUPPORT, "Protocol family not supported" },
65 { WSAEAFNOSUPPORT, "Address family not supported" },
66 { WSAEADDRINUSE, "Address already in use" },
67 { WSAEADDRNOTAVAIL, "Can't assign requested address" },
68 { WSAENETDOWN, "Network is down" },
69 { WSAENETUNREACH, "Network is unreachable" },
70 { WSAENETRESET, "Network dropped connection on reset" },
71 { WSAECONNABORTED, "Software caused connection abort" },
72 { WSAECONNRESET, "Connection reset by peer" },
73 { WSAENOBUFS, "No buffer space available" },
74 { WSAEISCONN, "Socket is already connected" },
75 { WSAENOTCONN, "Socket is not connected" },
76 { WSAESHUTDOWN, "Can't send after socket shutdown" },
77 { WSAETOOMANYREFS, "Too many references: can't splice" },
78 { WSAETIMEDOUT, "Operation timed out" },
79 { WSAECONNREFUSED, "Connection refused" },
80 { WSAELOOP, "Too many levels of symbolic links" },
81 { WSAENAMETOOLONG, "File name too long" },
82 { WSAEHOSTDOWN, "Host is down" },
83 { WSAEHOSTUNREACH, "No route to host" },
84 { WSAENOTEMPTY, "Directory not empty" },
85 { WSAEPROCLIM, "Too many processes" },
86 { WSAEUSERS, "Too many users" },
87 { WSAEDQUOT, "Disc quota exceeded" },
88 { WSAESTALE, "Stale NFS file handle" },
89 { WSAEREMOTE, "Too many levels of remote in path" },
90 { WSASYSNOTREADY, "Network subsystem is unvailable" },
91 { WSAVERNOTSUPPORTED, "WinSock version is not supported" },
92 { WSANOTINITIALISED, "Successful WSAStartup() not yet performed" },
93 { WSAEDISCON, "Graceful shutdown in progress" },
94 /* Resolver errors */
95 { WSAHOST_NOT_FOUND, "No such host is known" },
96 { WSATRY_AGAIN, "Host not found, or server failed" },
97 { WSANO_RECOVERY, "Unexpected server error encountered" },
98 { WSANO_DATA, "Valid name without requested data" },
99 { WSANO_ADDRESS, "No address, look for MX record" },
100 { 0, NULL }
101 };
102 PyObject *v;
103 const char *msg = "winsock error";
104
105 for (msgp = msgs; msgp->msg; msgp++)
106 {
107 if (errnum == msgp->num)
108 {
109 msg = msgp->msg;
110 break;
111 }
112 }
113
114 v = Py_BuildValue("(is)", errnum, msg);
115 if (v != NULL)
116 {
117 PyErr_SetObject(ssl_SysCallError, v);
118 Py_DECREF(v);
119 }
120 return;
121 }
122#else
123 PyErr_SetFromErrno(ssl_SysCallError);
124#endif
125}
126
127/*
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400128 * Handle errors raised by BIO functions.
129 *
130 * Arguments: bio - The BIO object
131 * ret - The return value of the BIO_ function.
132 * Returns: None, the calling function should return NULL;
133 */
134static void
135handle_bio_errors(BIO* bio, int ret)
136{
137 if (BIO_should_retry(bio)) {
138 if (BIO_should_read(bio)) {
139 PyErr_SetNone(ssl_WantReadError);
140 } else if (BIO_should_write(bio)) {
141 PyErr_SetNone(ssl_WantWriteError);
142 } else if (BIO_should_io_special(bio)) {
143 /*
144 * It's somewhat unclear what this means. From the OpenSSL source,
145 * it seems like it should not be triggered by the memory BIO, so
146 * for the time being, this case shouldn't come up. The SSL BIO
147 * (which I think should be named the socket BIO) may trigger this
148 * case if its socket is not yet connected or it is busy doing
149 * something related to x509.
150 */
151 PyErr_SetString(PyExc_ValueError, "BIO_should_io_special");
152 } else {
153 /*
154 * I hope this is dead code. The BIO documentation suggests that
155 * one of the above three checks should always be true.
156 */
157 PyErr_SetString(PyExc_ValueError, "unknown bio failure");
158 }
159 } else {
160 /*
161 * If we aren't to retry, it's really an error, so fall back to the
162 * normal error reporting code. However, the BIO interface does not
163 * specify a uniform error reporting mechanism. We can only hope that
164 * the code which triggered the error also kindly pushed something onto
165 * the error stack.
166 */
Rick Deand369c932009-07-08 11:48:33 -0500167 exception_from_error_queue(ssl_Error);
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400168 }
169}
170
171/*
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500172 * Handle errors raised by SSL I/O functions. NOTE: Not SSL_shutdown ;)
173 *
174 * Arguments: ssl - The SSL object
175 * err - The return code from SSL_get_error
176 * ret - The return code from the SSL I/O function
177 * Returns: None, the calling function should return NULL
178 */
179static void
180handle_ssl_errors(SSL *ssl, int err, int ret)
181{
182 switch (err)
183 {
184 /*
185 * Strange as it may seem, ZeroReturn is not an error per se. It means
186 * that the SSL Connection has been closed correctly (note, not the
187 * transport layer!), i.e. closure alerts have been exchanged. This is
188 * an exception since
189 * + There's an SSL "error" code for it
190 * + You have to deal with it in any case, close the transport layer
191 * etc
192 */
193 case SSL_ERROR_ZERO_RETURN:
194 PyErr_SetNone(ssl_ZeroReturnError);
195 break;
196
197 /*
198 * The WantXYZ exceptions don't mean that there's an error, just that
199 * nothing could be read/written just now, maybe because the transport
200 * layer would block on the operation, or that there's not enough data
201 * available to fill an entire SSL record.
202 */
203 case SSL_ERROR_WANT_READ:
204 PyErr_SetNone(ssl_WantReadError);
205 break;
206
207 case SSL_ERROR_WANT_WRITE:
208 PyErr_SetNone(ssl_WantWriteError);
209 break;
210
211 case SSL_ERROR_WANT_X509_LOOKUP:
212 PyErr_SetNone(ssl_WantX509LookupError);
213 break;
214
215 case SSL_ERROR_SYSCALL:
216 if (ERR_peek_error() == 0)
217 {
218 if (ret < 0)
219 {
220 syscall_from_errno();
221 }
222 else
223 {
224 PyObject *v;
225
226 v = Py_BuildValue("(is)", -1, "Unexpected EOF");
227 if (v != NULL)
228 {
229 PyErr_SetObject(ssl_SysCallError, v);
230 Py_DECREF(v);
231 }
232 }
233 break;
234 }
235
236 /* NOTE: Fall-through here, we don't want to duplicate code, right? */
237
238 case SSL_ERROR_SSL:
239 ;
240 default:
Rick Deand369c932009-07-08 11:48:33 -0500241 exception_from_error_queue(ssl_Error);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500242 break;
243 }
244}
245
246/*
247 * Here be member methods of the Connection "class"
248 */
249
250static char ssl_Connection_get_context_doc[] = "\n\
251Get session context\n\
252\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400253@return: A Context object\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500254";
255static PyObject *
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400256ssl_Connection_get_context(ssl_ConnectionObj *self, PyObject *args) {
257 if (!PyArg_ParseTuple(args, ":get_context")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500258 return NULL;
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400259 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500260
261 Py_INCREF(self->context);
262 return (PyObject *)self->context;
263}
264
265static char ssl_Connection_pending_doc[] = "\n\
266Get the number of bytes that can be safely read from the connection\n\
267\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400268@return: The number of bytes available in the receive buffer.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500269";
270static PyObject *
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400271ssl_Connection_pending(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500272 int ret;
273
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400274 if (!PyArg_ParseTuple(args, ":pending")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500275 return NULL;
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400276 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500277
278 ret = SSL_pending(self->ssl);
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400279 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500280}
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -0400281
Rick Deanb71c0d22009-04-01 14:09:23 -0500282static char ssl_Connection_bio_write_doc[] = "\n\
283When using non-socket connections this function sends\n\
284\"dirty\" data that would have traveled in on the network.\n\
285\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400286@param buf: The string to put into the memory BIO.\n\
287@return: The number of bytes written\n\
Rick Deanb71c0d22009-04-01 14:09:23 -0500288";
289static PyObject *
290ssl_Connection_bio_write(ssl_ConnectionObj *self, PyObject *args)
291{
292 char *buf;
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400293 int len, ret;
Rick Deanb71c0d22009-04-01 14:09:23 -0500294
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400295 if (self->into_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -0500296 {
297 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
298 return NULL;
299 }
300
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -0400301 if (!PyArg_ParseTuple(args, "s#|i:bio_write", &buf, &len))
Rick Deanb71c0d22009-04-01 14:09:23 -0500302 return NULL;
303
304 ret = BIO_write(self->into_ssl, buf, len);
305
306 if (PyErr_Occurred())
307 {
308 flush_error_queue();
309 return NULL;
310 }
311
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400312 if (ret <= 0) {
313 /*
314 * There was a problem with the BIO_write of some sort.
315 */
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400316 handle_bio_errors(self->into_ssl, ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500317 return NULL;
318 }
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400319
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400320 return PyLong_FromLong((long)ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500321}
322
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500323static char ssl_Connection_send_doc[] = "\n\
324Send data on the connection. NOTE: If you get one of the WantRead,\n\
325WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
326method again with the SAME buffer.\n\
327\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400328@param buf: The string to send\n\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500329@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400330 API, the value is ignored\n\
331@return: The number of bytes written\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500332";
333static PyObject *
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500334ssl_Connection_send(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500335 int len, ret, err, flags;
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500336 char *buf;
337
338#if PY_VERSION_HEX >= 0x02060000
339 Py_buffer pbuf;
340
341 if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
342 return NULL;
343
344 buf = pbuf.buf;
345 len = pbuf.len;
346#else
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500347
348 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
349 return NULL;
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500350#endif
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500351
352 MY_BEGIN_ALLOW_THREADS(self->tstate)
353 ret = SSL_write(self->ssl, buf, len);
354 MY_END_ALLOW_THREADS(self->tstate)
355
Jean-Paul Calderonea5d6ea62011-01-05 19:57:08 -0500356#if PY_VERSION_HEX >= 0x02060000
357 PyBuffer_Release(&pbuf);
358#endif
359
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500360 if (PyErr_Occurred())
361 {
362 flush_error_queue();
363 return NULL;
364 }
365
366 err = SSL_get_error(self->ssl, ret);
367 if (err == SSL_ERROR_NONE)
368 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400369 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500370 }
371 else
372 {
373 handle_ssl_errors(self->ssl, err, ret);
374 return NULL;
375 }
376}
377
378static char ssl_Connection_sendall_doc[] = "\n\
379Send \"all\" data on the connection. This calls send() repeatedly until\n\
380all data is sent. If an error occurs, it's impossible to tell how much data\n\
381has been sent.\n\
382\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400383@param buf: The string to send\n\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500384@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400385 API, the value is ignored\n\
386@return: The number of bytes written\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500387";
388static PyObject *
389ssl_Connection_sendall(ssl_ConnectionObj *self, PyObject *args)
390{
391 char *buf;
392 int len, ret, err, flags;
393 PyObject *pyret = Py_None;
394
395 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
396 return NULL;
397
398 do {
399 MY_BEGIN_ALLOW_THREADS(self->tstate)
400 ret = SSL_write(self->ssl, buf, len);
401 MY_END_ALLOW_THREADS(self->tstate)
402 if (PyErr_Occurred())
403 {
404 flush_error_queue();
405 pyret = NULL;
406 break;
407 }
408 err = SSL_get_error(self->ssl, ret);
409 if (err == SSL_ERROR_NONE)
410 {
411 buf += ret;
412 len -= ret;
413 }
414 else if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL ||
415 err == SSL_ERROR_ZERO_RETURN)
416 {
417 handle_ssl_errors(self->ssl, err, ret);
418 pyret = NULL;
419 break;
420 }
421 } while (len > 0);
422
423 Py_XINCREF(pyret);
424 return pyret;
425}
426
427static char ssl_Connection_recv_doc[] = "\n\
428Receive data on the connection. NOTE: If you get one of the WantRead,\n\
429WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
430method again with the SAME buffer.\n\
431\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400432@param bufsiz: The maximum number of bytes to read\n\
Jean-Paul Calderone40b32a22010-01-27 16:56:44 -0500433@param flags: (optional) Included for compatibility with the socket\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400434 API, the value is ignored\n\
435@return: The string read from the Connection\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500436";
437static PyObject *
438ssl_Connection_recv(ssl_ConnectionObj *self, PyObject *args)
439{
440 int bufsiz, ret, err, flags;
441 PyObject *buf;
442
443 if (!PyArg_ParseTuple(args, "i|i:recv", &bufsiz, &flags))
444 return NULL;
445
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400446 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500447 if (buf == NULL)
448 return NULL;
449
450 MY_BEGIN_ALLOW_THREADS(self->tstate)
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400451 ret = SSL_read(self->ssl, PyBytes_AsString(buf), bufsiz);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500452 MY_END_ALLOW_THREADS(self->tstate)
453
454 if (PyErr_Occurred())
455 {
456 Py_DECREF(buf);
457 flush_error_queue();
458 return NULL;
459 }
460
461 err = SSL_get_error(self->ssl, ret);
462 if (err == SSL_ERROR_NONE)
463 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400464 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500465 return NULL;
466 return buf;
467 }
468 else
469 {
470 handle_ssl_errors(self->ssl, err, ret);
471 Py_DECREF(buf);
472 return NULL;
473 }
474}
475
Rick Deanb71c0d22009-04-01 14:09:23 -0500476static char ssl_Connection_bio_read_doc[] = "\n\
477When using non-socket connections this function reads\n\
478the \"dirty\" data that would have traveled away on the network.\n\
479\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400480@param bufsiz: The maximum number of bytes to read\n\
481@return: The string read.\n\
Rick Deanb71c0d22009-04-01 14:09:23 -0500482";
483static PyObject *
484ssl_Connection_bio_read(ssl_ConnectionObj *self, PyObject *args)
485{
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400486 int bufsiz, ret;
Rick Deanb71c0d22009-04-01 14:09:23 -0500487 PyObject *buf;
488
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400489 if (self->from_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -0500490 {
491 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
492 return NULL;
493 }
494
495 if (!PyArg_ParseTuple(args, "i:bio_read", &bufsiz))
496 return NULL;
497
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400498 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
Rick Deanb71c0d22009-04-01 14:09:23 -0500499 if (buf == NULL)
500 return NULL;
501
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400502 ret = BIO_read(self->from_ssl, PyBytes_AsString(buf), bufsiz);
Rick Deanb71c0d22009-04-01 14:09:23 -0500503
504 if (PyErr_Occurred())
505 {
506 Py_DECREF(buf);
507 flush_error_queue();
508 return NULL;
509 }
510
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400511 if (ret <= 0) {
512 /*
513 * There was a problem with the BIO_read of some sort.
514 */
515 handle_bio_errors(self->from_ssl, ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500516 Py_DECREF(buf);
517 return NULL;
518 }
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400519
520 /*
521 * Shrink the string to match the number of bytes we actually read.
522 */
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400523 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400524 {
525 Py_DECREF(buf);
526 return NULL;
527 }
528 return buf;
Rick Deanb71c0d22009-04-01 14:09:23 -0500529}
530
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500531static char ssl_Connection_renegotiate_doc[] = "\n\
532Renegotiate the session\n\
533\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400534@return: True if the renegotiation can be started, false otherwise\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500535";
536static PyObject *
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400537ssl_Connection_renegotiate(ssl_ConnectionObj *self, PyObject *args) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500538 int ret;
539
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400540 if (!PyArg_ParseTuple(args, ":renegotiate")) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500541 return NULL;
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400542 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500543
544 MY_BEGIN_ALLOW_THREADS(self->tstate);
545 ret = SSL_renegotiate(self->ssl);
546 MY_END_ALLOW_THREADS(self->tstate);
547
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -0400548 if (PyErr_Occurred()) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500549 flush_error_queue();
550 return NULL;
551 }
552
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400553 return PyLong_FromLong((long)ret);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500554}
555
556static char ssl_Connection_do_handshake_doc[] = "\n\
557Perform an SSL handshake (usually called after renegotiate() or one of\n\
558set_*_state()). This can raise the same exceptions as send and recv.\n\
559\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400560@return: None.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500561";
562static PyObject *
563ssl_Connection_do_handshake(ssl_ConnectionObj *self, PyObject *args)
564{
565 int ret, err;
566
567 if (!PyArg_ParseTuple(args, ":do_handshake"))
568 return NULL;
569
570 MY_BEGIN_ALLOW_THREADS(self->tstate);
571 ret = SSL_do_handshake(self->ssl);
572 MY_END_ALLOW_THREADS(self->tstate);
573
574 if (PyErr_Occurred())
575 {
576 flush_error_queue();
577 return NULL;
578 }
579
580 err = SSL_get_error(self->ssl, ret);
581 if (err == SSL_ERROR_NONE)
582 {
583 Py_INCREF(Py_None);
584 return Py_None;
585 }
586 else
587 {
588 handle_ssl_errors(self->ssl, err, ret);
589 return NULL;
590 }
591}
592
593#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
594static char ssl_Connection_renegotiate_pending_doc[] = "\n\
595Check if there's a renegotiation in progress, it will return false once\n\
596a renegotiation is finished.\n\
597\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400598@return: Whether there's a renegotiation in progress\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500599";
600static PyObject *
601ssl_Connection_renegotiate_pending(ssl_ConnectionObj *self, PyObject *args)
602{
603 if (!PyArg_ParseTuple(args, ":renegotiate_pending"))
604 return NULL;
605
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400606 return PyLong_FromLong((long)SSL_renegotiate_pending(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500607}
608#endif
609
610static char ssl_Connection_total_renegotiations_doc[] = "\n\
611Find out the total number of renegotiations.\n\
612\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400613@return: The number of renegotiations.\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500614";
615static PyObject *
616ssl_Connection_total_renegotiations(ssl_ConnectionObj *self, PyObject *args)
617{
618 if (!PyArg_ParseTuple(args, ":total_renegotiations"))
619 return NULL;
620
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400621 return PyLong_FromLong(SSL_total_renegotiations(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500622}
623
624static char ssl_Connection_set_accept_state_doc[] = "\n\
625Set the connection to work in server mode. The handshake will be handled\n\
626automatically by read/write.\n\
627\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400628@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500629";
630static PyObject *
631ssl_Connection_set_accept_state(ssl_ConnectionObj *self, PyObject *args)
632{
633 if (!PyArg_ParseTuple(args, ":set_accept_state"))
634 return NULL;
635
636 SSL_set_accept_state(self->ssl);
637
638 Py_INCREF(Py_None);
639 return Py_None;
640}
641
642static char ssl_Connection_set_connect_state_doc[] = "\n\
643Set the connection to work in client mode. The handshake will be handled\n\
644automatically by read/write.\n\
645\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400646@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500647";
648static PyObject *
649ssl_Connection_set_connect_state(ssl_ConnectionObj *self, PyObject *args)
650{
651 if (!PyArg_ParseTuple(args, ":set_connect_state"))
652 return NULL;
653
654 SSL_set_connect_state(self->ssl);
655
656 Py_INCREF(Py_None);
657 return Py_None;
658}
659
660static char ssl_Connection_connect_doc[] = "\n\
661Connect to remote host and set up client-side SSL\n\
662\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400663@param addr: A remote address\n\
664@return: What the socket's connect method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500665";
666static PyObject *
667ssl_Connection_connect(ssl_ConnectionObj *self, PyObject *args)
668{
669 PyObject *meth, *ret;
670
671 if ((meth = PyObject_GetAttrString(self->socket, "connect")) == NULL)
672 return NULL;
673
674 SSL_set_connect_state(self->ssl);
675
676 ret = PyEval_CallObject(meth, args);
677 Py_DECREF(meth);
678 if (ret == NULL)
679 return NULL;
680
681 return ret;
682}
683
684static char ssl_Connection_connect_ex_doc[] = "\n\
685Connect to remote host and set up client-side SSL. Note that if the socket's\n\
686connect_ex method doesn't return 0, SSL won't be initialized.\n\
687\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400688@param addr: A remove address\n\
689@return: What the socket's connect_ex method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500690";
691static PyObject *
692ssl_Connection_connect_ex(ssl_ConnectionObj *self, PyObject *args)
693{
694 PyObject *meth, *ret;
695
696 if ((meth = PyObject_GetAttrString(self->socket, "connect_ex")) == NULL)
697 return NULL;
698
699 SSL_set_connect_state(self->ssl);
700
701 ret = PyEval_CallObject(meth, args);
702 Py_DECREF(meth);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500703 return ret;
704}
705
706static char ssl_Connection_accept_doc[] = "\n\
707Accept incoming connection and set up SSL on it\n\
708\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400709@return: A (conn,addr) pair where conn is a Connection and addr is an\n\
710 address\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500711";
712static PyObject *
713ssl_Connection_accept(ssl_ConnectionObj *self, PyObject *args)
714{
715 PyObject *tuple, *socket, *address, *meth;
716 ssl_ConnectionObj *conn;
717
718 if ((meth = PyObject_GetAttrString(self->socket, "accept")) == NULL)
719 return NULL;
720 tuple = PyEval_CallObject(meth, args);
721 Py_DECREF(meth);
722 if (tuple == NULL)
723 return NULL;
724
725 socket = PyTuple_GetItem(tuple, 0);
726 Py_INCREF(socket);
727 address = PyTuple_GetItem(tuple, 1);
728 Py_INCREF(address);
729 Py_DECREF(tuple);
730
731 conn = ssl_Connection_New(self->context, socket);
732 Py_DECREF(socket);
733 if (conn == NULL)
734 {
735 Py_DECREF(address);
736 return NULL;
737 }
738
739 SSL_set_accept_state(conn->ssl);
740
741 tuple = Py_BuildValue("(OO)", conn, address);
742
743 Py_DECREF(conn);
744 Py_DECREF(address);
745
746 return tuple;
747}
748
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400749static char ssl_Connection_bio_shutdown_doc[] = "\n\
750When using non-socket connections this function signals end of\n\
751data on the input for this connection.\n\
752\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400753@return: None\n\
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400754";
755
756static PyObject *
757ssl_Connection_bio_shutdown(ssl_ConnectionObj *self, PyObject *args)
758{
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -0400759 if (self->from_ssl == NULL)
760 {
761 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
762 return NULL;
763 }
764
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -0400765 BIO_set_mem_eof_return(self->into_ssl, 0);
766 Py_INCREF(Py_None);
767 return Py_None;
768}
769
770
771
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500772static char ssl_Connection_shutdown_doc[] = "\n\
773Send closure alert\n\
774\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400775@return: True if the shutdown completed successfully (i.e. both sides\n\
776 have sent closure alerts), false otherwise (i.e. you have to\n\
777 wait for a ZeroReturnError on a recv() method call\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500778";
779static PyObject *
780ssl_Connection_shutdown(ssl_ConnectionObj *self, PyObject *args)
781{
782 int ret;
783
784 if (!PyArg_ParseTuple(args, ":shutdown"))
785 return NULL;
786
787 MY_BEGIN_ALLOW_THREADS(self->tstate)
788 ret = SSL_shutdown(self->ssl);
789 MY_END_ALLOW_THREADS(self->tstate)
790
791 if (PyErr_Occurred())
792 {
793 flush_error_queue();
794 return NULL;
795 }
796
797 if (ret < 0)
798 {
Rick Deand369c932009-07-08 11:48:33 -0500799 exception_from_error_queue(ssl_Error);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500800 return NULL;
801 }
802 else if (ret > 0)
803 {
804 Py_INCREF(Py_True);
805 return Py_True;
806 }
807 else
808 {
809 Py_INCREF(Py_False);
810 return Py_False;
811 }
812}
813
814static char ssl_Connection_get_cipher_list_doc[] = "\n\
815Get the session cipher list\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500816\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400817@return: A list of cipher strings\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500818";
819static PyObject *
820ssl_Connection_get_cipher_list(ssl_ConnectionObj *self, PyObject *args)
821{
822 int idx = 0;
823 const char *ret;
824 PyObject *lst, *item;
825
826 if (!PyArg_ParseTuple(args, ":get_cipher_list"))
827 return NULL;
828
829 lst = PyList_New(0);
830 while ((ret = SSL_get_cipher_list(self->ssl, idx)) != NULL)
831 {
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400832 item = PyText_FromString(ret);
Ziga Seilnachtfdeadb12009-09-01 16:35:50 +0200833 PyList_Append(lst, item);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500834 Py_DECREF(item);
835 idx++;
836 }
837 return lst;
838}
839
Ziga Seilnachtf93bf102009-10-23 09:51:07 +0200840static char ssl_Connection_get_client_ca_list_doc[] = "\n\
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200841Get CAs whose certificates are suggested for client authentication.\n\
842\n\
Jean-Paul Calderone35788902009-10-24 13:48:08 -0400843@return: If this is a server connection, a list of X509Names representing\n\
844 the acceptable CAs as set by L{OpenSSL.SSL.Context.set_client_ca_list} or\n\
845 L{OpenSSL.SSL.Context.add_client_ca}. If this is a client connection,\n\
846 the list of such X509Names sent by the server, or an empty list if that\n\
847 has not yet happened.\n\
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200848";
849
850static PyObject *
Jean-Paul Calderone6e2b6852009-10-24 14:04:30 -0400851ssl_Connection_get_client_ca_list(ssl_ConnectionObj *self, PyObject *args) {
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200852 STACK_OF(X509_NAME) *CANames;
853 PyObject *CAList;
854 int i, n;
855
Ziga Seilnachtf93bf102009-10-23 09:51:07 +0200856 if (!PyArg_ParseTuple(args, ":get_client_ca_list")) {
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200857 return NULL;
858 }
859 CANames = SSL_get_client_CA_list(self->ssl);
860 if (CANames == NULL) {
861 return PyList_New(0);
862 }
863 n = sk_X509_NAME_num(CANames);
864 CAList = PyList_New(n);
865 if (CAList == NULL) {
866 return NULL;
867 }
868 for (i = 0; i < n; i++) {
869 X509_NAME *CAName;
870 PyObject *CA;
871
872 CAName = X509_NAME_dup(sk_X509_NAME_value(CANames, i));
873 if (CAName == NULL) {
874 Py_DECREF(CAList);
875 exception_from_error_queue(ssl_Error);
876 return NULL;
877 }
Jean-Paul Calderone305626a2010-10-31 20:51:17 -0400878 CA = (PyObject *)new_x509name(CAName, 1);
Ziga Seilnacht679c4262009-09-01 01:32:29 +0200879 if (CA == NULL) {
880 X509_NAME_free(CAName);
881 Py_DECREF(CAList);
882 return NULL;
883 }
884 if (PyList_SetItem(CAList, i, CA)) {
885 Py_DECREF(CA);
886 Py_DECREF(CAList);
887 return NULL;
888 }
889 }
890 return CAList;
891}
892
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500893static char ssl_Connection_makefile_doc[] = "\n\
894The makefile() method is not implemented, since there is no dup semantics\n\
895for SSL connections\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500896\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400897@raise NotImplementedError\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500898";
899static PyObject *
900ssl_Connection_makefile(ssl_ConnectionObj *self, PyObject *args)
901{
902 PyErr_SetString(PyExc_NotImplementedError, "Cannot make file object of SSL.Connection");
903 return NULL;
904}
905
906static char ssl_Connection_get_app_data_doc[] = "\n\
907Get application data\n\
908\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400909@return: The application data\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500910";
911static PyObject *
912ssl_Connection_get_app_data(ssl_ConnectionObj *self, PyObject *args)
913{
914 if (!PyArg_ParseTuple(args, ":get_app_data"))
915 return NULL;
916
917 Py_INCREF(self->app_data);
918 return self->app_data;
919}
920
921static char ssl_Connection_set_app_data_doc[] = "\n\
922Set application data\n\
923\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400924@param data - The application data\n\
925@return: None\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500926";
927static PyObject *
928ssl_Connection_set_app_data(ssl_ConnectionObj *self, PyObject *args)
929{
930 PyObject *data;
931
932 if (!PyArg_ParseTuple(args, "O:set_app_data", &data))
933 return NULL;
934
935 Py_DECREF(self->app_data);
936 Py_INCREF(data);
937 self->app_data = data;
938
939 Py_INCREF(Py_None);
940 return Py_None;
941}
942
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500943static char ssl_Connection_get_shutdown_doc[] = "\n\
944Get shutdown state\n\
945\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400946@return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500947";
948static PyObject *
949ssl_Connection_get_shutdown(ssl_ConnectionObj *self, PyObject *args)
950{
951 if (!PyArg_ParseTuple(args, ":get_shutdown"))
952 return NULL;
953
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400954 return PyLong_FromLong((long)SSL_get_shutdown(self->ssl));
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500955}
956
957static char ssl_Connection_set_shutdown_doc[] = "\n\
958Set shutdown state\n\
959\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400960@param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
961@return: None\n\
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500962";
963static PyObject *
964ssl_Connection_set_shutdown(ssl_ConnectionObj *self, PyObject *args)
965{
966 int shutdown;
967
968 if (!PyArg_ParseTuple(args, "i:set_shutdown", &shutdown))
969 return NULL;
970
971 SSL_set_shutdown(self->ssl, shutdown);
972 Py_INCREF(Py_None);
973 return Py_None;
974}
975
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500976static char ssl_Connection_state_string_doc[] = "\n\
977Get a verbose state description\n\
978\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400979@return: A string representing the state\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500980";
981static PyObject *
982ssl_Connection_state_string(ssl_ConnectionObj *self, PyObject *args)
983{
984 if (!PyArg_ParseTuple(args, ":state_string"))
985 return NULL;
986
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -0400987 return PyText_FromString(SSL_state_string_long(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500988}
989
Rick Deanb71c0d22009-04-01 14:09:23 -0500990static char ssl_Connection_client_random_doc[] = "\n\
991Get a copy of the client hello nonce.\n\
992\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -0400993@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -0500994";
995static PyObject *
996ssl_Connection_client_random(ssl_ConnectionObj *self, PyObject *args)
997{
998 if (!PyArg_ParseTuple(args, ":client_random"))
999 return NULL;
1000
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001001 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001002 Py_INCREF(Py_None);
1003 return Py_None;
1004 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001005 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->client_random, SSL3_RANDOM_SIZE);
Rick Deanb71c0d22009-04-01 14:09:23 -05001006}
1007
1008static char ssl_Connection_server_random_doc[] = "\n\
1009Get a copy of the server hello nonce.\n\
1010\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001011@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001012";
1013static PyObject *
1014ssl_Connection_server_random(ssl_ConnectionObj *self, PyObject *args)
1015{
1016 if (!PyArg_ParseTuple(args, ":server_random"))
1017 return NULL;
1018
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001019 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001020 Py_INCREF(Py_None);
1021 return Py_None;
1022 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001023 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->server_random, SSL3_RANDOM_SIZE);
Rick Deanb71c0d22009-04-01 14:09:23 -05001024}
1025
1026static char ssl_Connection_master_key_doc[] = "\n\
1027Get a copy of the master key.\n\
1028\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001029@return: A string representing the state\n\
Rick Deanb71c0d22009-04-01 14:09:23 -05001030";
1031static PyObject *
1032ssl_Connection_master_key(ssl_ConnectionObj *self, PyObject *args)
1033{
1034 if (!PyArg_ParseTuple(args, ":master_key"))
1035 return NULL;
1036
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001037 if (self->ssl->session == NULL) {
Rick Deanb71c0d22009-04-01 14:09:23 -05001038 Py_INCREF(Py_None);
1039 return Py_None;
1040 }
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001041 return PyBytes_FromStringAndSize( (const char *) self->ssl->session->master_key, self->ssl->session->master_key_length);
Rick Deanb71c0d22009-04-01 14:09:23 -05001042}
1043
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001044static char ssl_Connection_sock_shutdown_doc[] = "\n\
1045See shutdown(2)\n\
1046\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001047@return: What the socket's shutdown() method returns\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001048";
1049static PyObject *
1050ssl_Connection_sock_shutdown(ssl_ConnectionObj *self, PyObject *args)
1051{
1052 PyObject *meth, *ret;
1053
1054 if ((meth = PyObject_GetAttrString(self->socket, "shutdown")) == NULL)
1055 return NULL;
1056 ret = PyEval_CallObject(meth, args);
1057 Py_DECREF(meth);
1058 return ret;
1059}
1060
1061static char ssl_Connection_get_peer_certificate_doc[] = "\n\
1062Retrieve the other side's certificate (if any)\n\
1063\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001064@return: The peer's certificate\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001065";
1066static PyObject *
1067ssl_Connection_get_peer_certificate(ssl_ConnectionObj *self, PyObject *args)
1068{
1069 X509 *cert;
1070
1071 if (!PyArg_ParseTuple(args, ":get_peer_certificate"))
1072 return NULL;
1073
1074 cert = SSL_get_peer_certificate(self->ssl);
1075 if (cert != NULL)
1076 {
Jean-Paul Calderone5c0f1f62010-10-31 21:36:43 -04001077 return (PyObject *)new_x509(cert, 1);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001078 }
1079 else
1080 {
1081 Py_INCREF(Py_None);
1082 return Py_None;
1083 }
1084}
1085
1086static char ssl_Connection_want_read_doc[] = "\n\
1087Checks if more data has to be read from the transport layer to complete an\n\
1088operation.\n\
1089\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001090@return: True iff more data has to be read\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001091";
1092static PyObject *
1093ssl_Connection_want_read(ssl_ConnectionObj *self, PyObject *args)
1094{
1095 if (!PyArg_ParseTuple(args, ":want_read"))
1096 return NULL;
1097
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001098 return PyLong_FromLong((long)SSL_want_read(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001099}
1100
1101static char ssl_Connection_want_write_doc[] = "\n\
1102Checks if there is data to write to the transport layer to complete an\n\
1103operation.\n\
1104\n\
Jean-Paul Calderone54bcc832009-05-27 14:06:48 -04001105@return: True iff there is data to write\n\
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001106";
1107static PyObject *
1108ssl_Connection_want_write(ssl_ConnectionObj *self, PyObject *args)
1109{
1110 if (!PyArg_ParseTuple(args, ":want_write"))
1111 return NULL;
1112
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001113 return PyLong_FromLong((long)SSL_want_write(self->ssl));
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001114}
1115
1116/*
1117 * Member methods in the Connection object
1118 * ADD_METHOD(name) expands to a correct PyMethodDef declaration
1119 * { 'name', (PyCFunction)ssl_Connection_name, METH_VARARGS }
1120 * for convenience
1121 * ADD_ALIAS(name,real) creates an "alias" of the ssl_Connection_real
1122 * function with the name 'name'
1123 */
1124#define ADD_METHOD(name) \
1125 { #name, (PyCFunction)ssl_Connection_##name, METH_VARARGS, ssl_Connection_##name##_doc }
1126#define ADD_ALIAS(name,real) \
1127 { #name, (PyCFunction)ssl_Connection_##real, METH_VARARGS, ssl_Connection_##real##_doc }
1128static PyMethodDef ssl_Connection_methods[] =
1129{
1130 ADD_METHOD(get_context),
1131 ADD_METHOD(pending),
1132 ADD_METHOD(send),
1133 ADD_ALIAS (write, send),
1134 ADD_METHOD(sendall),
1135 ADD_METHOD(recv),
1136 ADD_ALIAS (read, recv),
Rick Deanb71c0d22009-04-01 14:09:23 -05001137 ADD_METHOD(bio_read),
1138 ADD_METHOD(bio_write),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001139 ADD_METHOD(renegotiate),
1140 ADD_METHOD(do_handshake),
1141#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
1142 ADD_METHOD(renegotiate_pending),
1143#endif
1144 ADD_METHOD(total_renegotiations),
1145 ADD_METHOD(connect),
1146 ADD_METHOD(connect_ex),
1147 ADD_METHOD(accept),
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04001148 ADD_METHOD(bio_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001149 ADD_METHOD(shutdown),
1150 ADD_METHOD(get_cipher_list),
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02001151 ADD_METHOD(get_client_ca_list),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001152 ADD_METHOD(makefile),
1153 ADD_METHOD(get_app_data),
1154 ADD_METHOD(set_app_data),
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001155 ADD_METHOD(get_shutdown),
1156 ADD_METHOD(set_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001157 ADD_METHOD(state_string),
Rick Deanb71c0d22009-04-01 14:09:23 -05001158 ADD_METHOD(server_random),
1159 ADD_METHOD(client_random),
1160 ADD_METHOD(master_key),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001161 ADD_METHOD(sock_shutdown),
1162 ADD_METHOD(get_peer_certificate),
1163 ADD_METHOD(want_read),
1164 ADD_METHOD(want_write),
1165 ADD_METHOD(set_accept_state),
1166 ADD_METHOD(set_connect_state),
1167 { NULL, NULL }
1168};
1169#undef ADD_ALIAS
1170#undef ADD_METHOD
1171
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001172static char ssl_Connection_doc[] = "\n\
1173Connection(context, socket) -> Connection instance\n\
1174\n\
1175Create a new Connection object, using the given OpenSSL.SSL.Context instance\n\
1176and socket.\n\
1177\n\
1178@param context: An SSL Context to use for this connection\n\
1179@param socket: The socket to use for transport layer\n\
1180";
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001181
1182/*
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001183 * Initializer used by ssl_Connection_new and ssl_Connection_New. *Not*
1184 * tp_init. This takes an already allocated ssl_ConnectionObj, a context, and
1185 * a optionally a socket, and glues them all together.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001186 */
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001187static ssl_ConnectionObj*
1188ssl_Connection_init(ssl_ConnectionObj *self, ssl_ContextObj *ctx, PyObject *sock) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001189 int fd;
1190
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001191 Py_INCREF(ctx);
1192 self->context = ctx;
1193
1194 Py_INCREF(sock);
1195 self->socket = sock;
1196
1197 self->ssl = NULL;
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04001198 self->from_ssl = NULL;
1199 self->into_ssl = NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001200
1201 Py_INCREF(Py_None);
1202 self->app_data = Py_None;
1203
1204 self->tstate = NULL;
1205
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001206 self->ssl = SSL_new(self->context->ctx);
1207 SSL_set_app_data(self->ssl, self);
Rick Deanb71c0d22009-04-01 14:09:23 -05001208
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001209 if (self->socket == Py_None)
Rick Deanb71c0d22009-04-01 14:09:23 -05001210 {
1211 /* If it's not a socket or file, treat it like a memory buffer,
1212 * so crazy people can do things like EAP-TLS. */
1213 self->into_ssl = BIO_new(BIO_s_mem());
1214 self->from_ssl = BIO_new(BIO_s_mem());
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04001215 if (self->into_ssl == NULL || self->from_ssl == NULL)
Rick Deanb71c0d22009-04-01 14:09:23 -05001216 goto error;
1217 SSL_set_bio(self->ssl, self->into_ssl, self->from_ssl);
1218 }
1219 else
1220 {
1221 fd = PyObject_AsFileDescriptor(self->socket);
1222 if (fd < 0)
1223 {
1224 Py_DECREF(self);
1225 return NULL;
1226 }
1227 else
1228 {
1229 SSL_set_fd(self->ssl, (SOCKET_T)fd);
1230 }
1231 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001232 return self;
Rick Deanb71c0d22009-04-01 14:09:23 -05001233
1234error:
1235 BIO_free(self->into_ssl); /* NULL safe */
1236 BIO_free(self->from_ssl); /* NULL safe */
1237 Py_DECREF(self);
1238 return NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001239}
1240
1241/*
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001242 * Constructor for Connection objects
1243 *
1244 * Arguments: ctx - An SSL Context to use for this connection
1245 * sock - The socket to use for transport layer
1246 * Returns: The newly created Connection object
1247 */
1248ssl_ConnectionObj *
1249ssl_Connection_New(ssl_ContextObj *ctx, PyObject *sock) {
1250 ssl_ConnectionObj *self;
1251
1252 self = PyObject_GC_New(ssl_ConnectionObj, &ssl_Connection_Type);
1253 if (self == NULL) {
1254 return NULL;
1255 }
1256 self = ssl_Connection_init(self, ctx, sock);
1257 if (self == NULL) {
1258 return NULL;
1259 }
1260 PyObject_GC_Track((PyObject *)self);
1261 return self;
1262}
1263
1264static PyObject*
1265ssl_Connection_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs) {
1266 ssl_ConnectionObj *self;
1267 ssl_ContextObj *ctx;
1268 PyObject *sock;
1269 static char *kwlist[] = {"context", "socket", NULL};
1270
1271 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O:Connection", kwlist,
1272 &ssl_Context_Type, &ctx, &sock)) {
1273 return NULL;
1274 }
1275
1276 self = (ssl_ConnectionObj *)subtype->tp_alloc(subtype, 1);
1277 if (self == NULL) {
1278 return NULL;
1279 }
1280
1281 return (PyObject *)ssl_Connection_init(self, ctx, sock);
1282}
1283
1284/*
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001285 * Find attribute
1286 *
1287 * Arguments: self - The Connection object
1288 * name - The attribute name
1289 * Returns: A Python object for the attribute, or NULL if something went
1290 * wrong
1291 */
1292static PyObject *
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001293ssl_Connection_getattro(ssl_ConnectionObj *self, PyObject *nameobj) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001294 PyObject *meth;
Jean-Paul Calderone83dbcfd2010-08-11 20:20:57 -04001295
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001296 meth = PyObject_GenericGetAttr((PyObject*)self, nameobj);
1297 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001298 PyErr_Clear();
1299 /* Try looking it up in the "socket" instead. */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001300 meth = PyObject_GenericGetAttr(self->socket, nameobj);
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001301 }
1302
1303 return meth;
1304}
1305
1306/*
1307 * Call the visitproc on all contained objects.
1308 *
1309 * Arguments: self - The Connection object
1310 * visit - Function to call
1311 * arg - Extra argument to visit
1312 * Returns: 0 if all goes well, otherwise the return code from the first
1313 * call that gave non-zero result.
1314 */
1315static int
1316ssl_Connection_traverse(ssl_ConnectionObj *self, visitproc visit, void *arg)
1317{
1318 int ret = 0;
1319
1320 if (ret == 0 && self->context != NULL)
1321 ret = visit((PyObject *)self->context, arg);
1322 if (ret == 0 && self->socket != NULL)
1323 ret = visit(self->socket, arg);
1324 if (ret == 0 && self->app_data != NULL)
1325 ret = visit(self->app_data, arg);
1326 return ret;
1327}
1328
1329/*
1330 * Decref all contained objects and zero the pointers.
1331 *
1332 * Arguments: self - The Connection object
1333 * Returns: Always 0.
1334 */
1335static int
1336ssl_Connection_clear(ssl_ConnectionObj *self)
1337{
1338 Py_XDECREF(self->context);
1339 self->context = NULL;
1340 Py_XDECREF(self->socket);
1341 self->socket = NULL;
1342 Py_XDECREF(self->app_data);
1343 self->app_data = NULL;
Rick Deanb71c0d22009-04-01 14:09:23 -05001344 self->into_ssl = NULL; /* was cleaned up by SSL_free() */
1345 self->from_ssl = NULL; /* was cleaned up by SSL_free() */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001346 return 0;
1347}
1348
1349/*
1350 * Deallocate the memory used by the Connection object
1351 *
1352 * Arguments: self - The Connection object
1353 * Returns: None
1354 */
1355static void
1356ssl_Connection_dealloc(ssl_ConnectionObj *self)
1357{
1358 PyObject_GC_UnTrack(self);
1359 if (self->ssl != NULL)
1360 SSL_free(self->ssl);
1361 ssl_Connection_clear(self);
1362 PyObject_GC_Del(self);
1363}
1364
1365PyTypeObject ssl_Connection_Type = {
Jean-Paul Calderoneb6d75252010-08-11 23:55:45 -04001366 PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001367 "OpenSSL.SSL.Connection",
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001368 sizeof(ssl_ConnectionObj),
1369 0,
1370 (destructor)ssl_Connection_dealloc,
1371 NULL, /* print */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001372 NULL, /* tp_getattr */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001373 NULL, /* setattr */
1374 NULL, /* compare */
1375 NULL, /* repr */
1376 NULL, /* as_number */
1377 NULL, /* as_sequence */
1378 NULL, /* as_mapping */
1379 NULL, /* hash */
1380 NULL, /* call */
1381 NULL, /* str */
Jean-Paul Calderone997be7e2010-08-11 22:40:07 -04001382 (getattrofunc)ssl_Connection_getattro, /* getattro */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001383 NULL, /* setattro */
1384 NULL, /* as_buffer */
1385 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001386 ssl_Connection_doc, /* doc */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001387 (traverseproc)ssl_Connection_traverse,
1388 (inquiry)ssl_Connection_clear,
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001389 NULL, /* tp_richcompare */
1390 0, /* tp_weaklistoffset */
1391 NULL, /* tp_iter */
1392 NULL, /* tp_iternext */
1393 ssl_Connection_methods, /* tp_methods */
1394 NULL, /* tp_members */
1395 NULL, /* tp_getset */
1396 NULL, /* tp_base */
1397 NULL, /* tp_dict */
1398 NULL, /* tp_descr_get */
1399 NULL, /* tp_descr_set */
1400 0, /* tp_dictoffset */
1401 NULL, /* tp_init */
1402 NULL, /* tp_alloc */
1403 ssl_Connection_new, /* tp_new */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001404};
1405
1406
1407/*
1408 * Initiailze the Connection part of the SSL sub module
1409 *
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001410 * Arguments: dict - The OpenSSL.SSL module
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001411 * Returns: 1 for success, 0 otherwise
1412 */
1413int
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001414init_ssl_connection(PyObject *module) {
1415
1416 if (PyType_Ready(&ssl_Connection_Type) < 0) {
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001417 return 0;
Jean-Paul Calderone1bd11fa2009-05-27 17:09:15 -04001418 }
1419
1420 if (PyModule_AddObject(module, "Connection", (PyObject *)&ssl_Connection_Type) != 0) {
1421 return 0;
1422 }
1423
1424 if (PyModule_AddObject(module, "ConnectionType", (PyObject *)&ssl_Connection_Type) != 0) {
1425 return 0;
1426 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001427
1428 return 1;
1429}
1430