blob: 4cdd53d24ac4f73d0d91ad2308f1d248974f3212 [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
26#include <openssl/err.h>
27
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/*
128 * Handle errors raised by SSL I/O functions. NOTE: Not SSL_shutdown ;)
129 *
130 * Arguments: ssl - The SSL object
131 * err - The return code from SSL_get_error
132 * ret - The return code from the SSL I/O function
133 * Returns: None, the calling function should return NULL
134 */
135static void
136handle_ssl_errors(SSL *ssl, int err, int ret)
137{
138 switch (err)
139 {
140 /*
141 * Strange as it may seem, ZeroReturn is not an error per se. It means
142 * that the SSL Connection has been closed correctly (note, not the
143 * transport layer!), i.e. closure alerts have been exchanged. This is
144 * an exception since
145 * + There's an SSL "error" code for it
146 * + You have to deal with it in any case, close the transport layer
147 * etc
148 */
149 case SSL_ERROR_ZERO_RETURN:
150 PyErr_SetNone(ssl_ZeroReturnError);
151 break;
152
153 /*
154 * The WantXYZ exceptions don't mean that there's an error, just that
155 * nothing could be read/written just now, maybe because the transport
156 * layer would block on the operation, or that there's not enough data
157 * available to fill an entire SSL record.
158 */
159 case SSL_ERROR_WANT_READ:
160 PyErr_SetNone(ssl_WantReadError);
161 break;
162
163 case SSL_ERROR_WANT_WRITE:
164 PyErr_SetNone(ssl_WantWriteError);
165 break;
166
167 case SSL_ERROR_WANT_X509_LOOKUP:
168 PyErr_SetNone(ssl_WantX509LookupError);
169 break;
170
171 case SSL_ERROR_SYSCALL:
172 if (ERR_peek_error() == 0)
173 {
174 if (ret < 0)
175 {
176 syscall_from_errno();
177 }
178 else
179 {
180 PyObject *v;
181
182 v = Py_BuildValue("(is)", -1, "Unexpected EOF");
183 if (v != NULL)
184 {
185 PyErr_SetObject(ssl_SysCallError, v);
186 Py_DECREF(v);
187 }
188 }
189 break;
190 }
191
192 /* NOTE: Fall-through here, we don't want to duplicate code, right? */
193
194 case SSL_ERROR_SSL:
195 ;
196 default:
197 exception_from_error_queue();
198 break;
199 }
200}
201
202/*
203 * Here be member methods of the Connection "class"
204 */
205
206static char ssl_Connection_get_context_doc[] = "\n\
207Get session context\n\
208\n\
209Arguments: self - The Connection object\n\
210 args - The Python argument tuple, should be empty\n\
211Returns: A Context object\n\
212";
213static PyObject *
214ssl_Connection_get_context(ssl_ConnectionObj *self, PyObject *args)
215{
216 if (!PyArg_ParseTuple(args, ":get_context"))
217 return NULL;
218
219 Py_INCREF(self->context);
220 return (PyObject *)self->context;
221}
222
223static char ssl_Connection_pending_doc[] = "\n\
224Get the number of bytes that can be safely read from the connection\n\
225\n\
226Arguments: self - The Connection object\n\
227 args - The Python argument tuple, should be empty\n\
228Returns: \n\
229";
230static PyObject *
231ssl_Connection_pending(ssl_ConnectionObj *self, PyObject *args)
232{
233 int ret;
234
235 if (!PyArg_ParseTuple(args, ":pending"))
236 return NULL;
237
238 ret = SSL_pending(self->ssl);
239 return PyInt_FromLong((long)ret);
240}
241
Rick Deanb71c0d22009-04-01 14:09:23 -0500242static char ssl_Connection_bio_write_doc[] = "\n\
243When using non-socket connections this function sends\n\
244\"dirty\" data that would have traveled in on the network.\n\
245\n\
246Arguments: self - The Connection object\n\
247 args - The Python argument tuple, should be:\n\
248 buf - The string to bio_write\n\
249Returns: The number of bytes written\n\
250";
251static PyObject *
252ssl_Connection_bio_write(ssl_ConnectionObj *self, PyObject *args)
253{
254 char *buf;
255 int len, ret, err;
256
257 if(self->into_ssl == NULL)
258 {
259 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
260 return NULL;
261 }
262
263 if (!PyArg_ParseTuple(args, "s#|i:bio_read", &buf, &len))
264 return NULL;
265
266 ret = BIO_write(self->into_ssl, buf, len);
267
268 if (PyErr_Occurred())
269 {
270 flush_error_queue();
271 return NULL;
272 }
273
274 err = SSL_get_error(self->ssl, ret);
275 if (err == SSL_ERROR_NONE)
276 {
277 return PyInt_FromLong((long)ret);
278 }
279 else
280 {
281 handle_ssl_errors(self->ssl, err, ret);
282 return NULL;
283 }
284}
285
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500286static char ssl_Connection_send_doc[] = "\n\
287Send data on the connection. NOTE: If you get one of the WantRead,\n\
288WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
289method again with the SAME buffer.\n\
290\n\
291Arguments: self - The Connection object\n\
292 args - The Python argument tuple, should be:\n\
293 buf - The string to send\n\
294 flags - (optional) Included for compatability with the socket\n\
295 API, the value is ignored\n\
296Returns: The number of bytes written\n\
297";
298static PyObject *
299ssl_Connection_send(ssl_ConnectionObj *self, PyObject *args)
300{
301 char *buf;
302 int len, ret, err, flags;
303
304 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
305 return NULL;
306
307 MY_BEGIN_ALLOW_THREADS(self->tstate)
308 ret = SSL_write(self->ssl, buf, len);
309 MY_END_ALLOW_THREADS(self->tstate)
310
311 if (PyErr_Occurred())
312 {
313 flush_error_queue();
314 return NULL;
315 }
316
317 err = SSL_get_error(self->ssl, ret);
318 if (err == SSL_ERROR_NONE)
319 {
320 return PyInt_FromLong((long)ret);
321 }
322 else
323 {
324 handle_ssl_errors(self->ssl, err, ret);
325 return NULL;
326 }
327}
328
329static char ssl_Connection_sendall_doc[] = "\n\
330Send \"all\" data on the connection. This calls send() repeatedly until\n\
331all data is sent. If an error occurs, it's impossible to tell how much data\n\
332has been sent.\n\
333\n\
334Arguments: self - The Connection object\n\
335 args - The Python argument tuple, should be:\n\
336 buf - The string to send\n\
337 flags - (optional) Included for compatability with the socket\n\
338 API, the value is ignored\n\
339Returns: The number of bytes written\n\
340";
341static PyObject *
342ssl_Connection_sendall(ssl_ConnectionObj *self, PyObject *args)
343{
344 char *buf;
345 int len, ret, err, flags;
346 PyObject *pyret = Py_None;
347
348 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
349 return NULL;
350
351 do {
352 MY_BEGIN_ALLOW_THREADS(self->tstate)
353 ret = SSL_write(self->ssl, buf, len);
354 MY_END_ALLOW_THREADS(self->tstate)
355 if (PyErr_Occurred())
356 {
357 flush_error_queue();
358 pyret = NULL;
359 break;
360 }
361 err = SSL_get_error(self->ssl, ret);
362 if (err == SSL_ERROR_NONE)
363 {
364 buf += ret;
365 len -= ret;
366 }
367 else if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL ||
368 err == SSL_ERROR_ZERO_RETURN)
369 {
370 handle_ssl_errors(self->ssl, err, ret);
371 pyret = NULL;
372 break;
373 }
374 } while (len > 0);
375
376 Py_XINCREF(pyret);
377 return pyret;
378}
379
380static char ssl_Connection_recv_doc[] = "\n\
381Receive data on the connection. NOTE: If you get one of the WantRead,\n\
382WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
383method again with the SAME buffer.\n\
384\n\
385Arguments: self - The Connection object\n\
386 args - The Python argument tuple, should be:\n\
387 bufsiz - The maximum number of bytes to read\n\
388 flags - (optional) Included for compatability with the socket\n\
389 API, the value is ignored\n\
390Returns: The number of bytes read\n\
391";
392static PyObject *
393ssl_Connection_recv(ssl_ConnectionObj *self, PyObject *args)
394{
395 int bufsiz, ret, err, flags;
396 PyObject *buf;
397
398 if (!PyArg_ParseTuple(args, "i|i:recv", &bufsiz, &flags))
399 return NULL;
400
401 buf = PyString_FromStringAndSize(NULL, bufsiz);
402 if (buf == NULL)
403 return NULL;
404
405 MY_BEGIN_ALLOW_THREADS(self->tstate)
406 ret = SSL_read(self->ssl, PyString_AsString(buf), bufsiz);
407 MY_END_ALLOW_THREADS(self->tstate)
408
409 if (PyErr_Occurred())
410 {
411 Py_DECREF(buf);
412 flush_error_queue();
413 return NULL;
414 }
415
416 err = SSL_get_error(self->ssl, ret);
417 if (err == SSL_ERROR_NONE)
418 {
419 if (ret != bufsiz && _PyString_Resize(&buf, ret) < 0)
420 return NULL;
421 return buf;
422 }
423 else
424 {
425 handle_ssl_errors(self->ssl, err, ret);
426 Py_DECREF(buf);
427 return NULL;
428 }
429}
430
Rick Deanb71c0d22009-04-01 14:09:23 -0500431static char ssl_Connection_bio_read_doc[] = "\n\
432When using non-socket connections this function reads\n\
433the \"dirty\" data that would have traveled away on the network.\n\
434\n\
435Arguments: self - The Connection object\n\
436 args - The Python argument tuple, should be:\n\
437 bufsiz - The maximum number of bytes to read\n\
438Returns: The string read.\n\
439";
440static PyObject *
441ssl_Connection_bio_read(ssl_ConnectionObj *self, PyObject *args)
442{
443 int bufsiz, ret, err;
444 PyObject *buf;
445
446 if(self->from_ssl == NULL)
447 {
448 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
449 return NULL;
450 }
451
452 if (!PyArg_ParseTuple(args, "i:bio_read", &bufsiz))
453 return NULL;
454
455 buf = PyString_FromStringAndSize(NULL, bufsiz);
456 if (buf == NULL)
457 return NULL;
458
459 ret = BIO_read(self->from_ssl, PyString_AsString(buf), bufsiz);
460
461 if (PyErr_Occurred())
462 {
463 Py_DECREF(buf);
464 flush_error_queue();
465 return NULL;
466 }
467
468 err = SSL_get_error(self->ssl, ret);
469 if (err == SSL_ERROR_NONE)
470 {
471 if (ret != bufsiz && _PyString_Resize(&buf, ret) < 0)
472 return NULL;
473 return buf;
474 }
475 else
476 {
477 handle_ssl_errors(self->ssl, err, ret);
478 Py_DECREF(buf);
479 return NULL;
480 }
481}
482
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500483static char ssl_Connection_renegotiate_doc[] = "\n\
484Renegotiate the session\n\
485\n\
486Arguments: self - The Connection object\n\
487 args - The Python argument tuple, should be empty\n\
488Returns: True if the renegotiation can be started, false otherwise\n\
489";
490static PyObject *
491ssl_Connection_renegotiate(ssl_ConnectionObj *self, PyObject *args)
492{
493 int ret;
494
495 if (!PyArg_ParseTuple(args, ":renegotiate"))
496 return NULL;
497
498 MY_BEGIN_ALLOW_THREADS(self->tstate);
499 ret = SSL_renegotiate(self->ssl);
500 MY_END_ALLOW_THREADS(self->tstate);
501
502 if (PyErr_Occurred())
503 {
504 flush_error_queue();
505 return NULL;
506 }
507
508 return PyInt_FromLong((long)ret);
509}
510
511static char ssl_Connection_do_handshake_doc[] = "\n\
512Perform an SSL handshake (usually called after renegotiate() or one of\n\
513set_*_state()). This can raise the same exceptions as send and recv.\n\
514\n\
515Arguments: self - The Connection object\n\
516 args - The Python argument tuple, should be empty\n\
517Returns: None.\n\
518";
519static PyObject *
520ssl_Connection_do_handshake(ssl_ConnectionObj *self, PyObject *args)
521{
522 int ret, err;
523
524 if (!PyArg_ParseTuple(args, ":do_handshake"))
525 return NULL;
526
527 MY_BEGIN_ALLOW_THREADS(self->tstate);
528 ret = SSL_do_handshake(self->ssl);
529 MY_END_ALLOW_THREADS(self->tstate);
530
531 if (PyErr_Occurred())
532 {
533 flush_error_queue();
534 return NULL;
535 }
536
537 err = SSL_get_error(self->ssl, ret);
538 if (err == SSL_ERROR_NONE)
539 {
540 Py_INCREF(Py_None);
541 return Py_None;
542 }
543 else
544 {
545 handle_ssl_errors(self->ssl, err, ret);
546 return NULL;
547 }
548}
549
550#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
551static char ssl_Connection_renegotiate_pending_doc[] = "\n\
552Check if there's a renegotiation in progress, it will return false once\n\
553a renegotiation is finished.\n\
554\n\
555Arguments: self - The Connection object\n\
556 args - The Python argument tuple, should be empty\n\
557Returns: Whether there's a renegotiation in progress\n\
558";
559static PyObject *
560ssl_Connection_renegotiate_pending(ssl_ConnectionObj *self, PyObject *args)
561{
562 if (!PyArg_ParseTuple(args, ":renegotiate_pending"))
563 return NULL;
564
565 return PyInt_FromLong((long)SSL_renegotiate_pending(self->ssl));
566}
567#endif
568
569static char ssl_Connection_total_renegotiations_doc[] = "\n\
570Find out the total number of renegotiations.\n\
571\n\
572Arguments: self - The Connection object\n\
573 args - The Python argument tuple, should be empty\n\
574Returns: The number of renegotiations.\n\
575";
576static PyObject *
577ssl_Connection_total_renegotiations(ssl_ConnectionObj *self, PyObject *args)
578{
579 if (!PyArg_ParseTuple(args, ":total_renegotiations"))
580 return NULL;
581
582 return PyInt_FromLong(SSL_total_renegotiations(self->ssl));
583}
584
585static char ssl_Connection_set_accept_state_doc[] = "\n\
586Set the connection to work in server mode. The handshake will be handled\n\
587automatically by read/write.\n\
588\n\
589Arguments: self - The Connection object\n\
590 args - The Python argument tuple, should be empty\n\
591Returns: None\n\
592";
593static PyObject *
594ssl_Connection_set_accept_state(ssl_ConnectionObj *self, PyObject *args)
595{
596 if (!PyArg_ParseTuple(args, ":set_accept_state"))
597 return NULL;
598
599 SSL_set_accept_state(self->ssl);
600
601 Py_INCREF(Py_None);
602 return Py_None;
603}
604
605static char ssl_Connection_set_connect_state_doc[] = "\n\
606Set the connection to work in client mode. The handshake will be handled\n\
607automatically by read/write.\n\
608\n\
609Arguments: self - The Connection object\n\
610 args - The Python argument tuple, should be empty\n\
611Returns: None\n\
612";
613static PyObject *
614ssl_Connection_set_connect_state(ssl_ConnectionObj *self, PyObject *args)
615{
616 if (!PyArg_ParseTuple(args, ":set_connect_state"))
617 return NULL;
618
619 SSL_set_connect_state(self->ssl);
620
621 Py_INCREF(Py_None);
622 return Py_None;
623}
624
625static char ssl_Connection_connect_doc[] = "\n\
626Connect to remote host and set up client-side SSL\n\
627\n\
628Arguments: self - The Connection object\n\
629 args - The Python argument tuple, should be:\n\
630 addr - A remote address\n\
631Returns: What the socket's connect method returns\n\
632";
633static PyObject *
634ssl_Connection_connect(ssl_ConnectionObj *self, PyObject *args)
635{
636 PyObject *meth, *ret;
637
638 if ((meth = PyObject_GetAttrString(self->socket, "connect")) == NULL)
639 return NULL;
640
641 SSL_set_connect_state(self->ssl);
642
643 ret = PyEval_CallObject(meth, args);
644 Py_DECREF(meth);
645 if (ret == NULL)
646 return NULL;
647
648 return ret;
649}
650
651static char ssl_Connection_connect_ex_doc[] = "\n\
652Connect to remote host and set up client-side SSL. Note that if the socket's\n\
653connect_ex method doesn't return 0, SSL won't be initialized.\n\
654\n\
655Arguments: self - The Connection object\n\
656 args - The Python argument tuple, should be:\n\
657 addr - A remove address\n\
658Returns: What the socket's connect_ex method returns\n\
659";
660static PyObject *
661ssl_Connection_connect_ex(ssl_ConnectionObj *self, PyObject *args)
662{
663 PyObject *meth, *ret;
664
665 if ((meth = PyObject_GetAttrString(self->socket, "connect_ex")) == NULL)
666 return NULL;
667
668 SSL_set_connect_state(self->ssl);
669
670 ret = PyEval_CallObject(meth, args);
671 Py_DECREF(meth);
672 if (ret == NULL)
673 return NULL;
674 if (PyInt_Check(ret) && PyInt_AsLong(ret) != 0)
675 return ret;
676
677 return ret;
678}
679
680static char ssl_Connection_accept_doc[] = "\n\
681Accept incoming connection and set up SSL on it\n\
682\n\
683Arguments: self - The Connection object\n\
684 args - The Python argument tuple, should be empty\n\
685Returns: A (conn,addr) pair where conn is a Connection and addr is an\n\
686 address\n\
687";
688static PyObject *
689ssl_Connection_accept(ssl_ConnectionObj *self, PyObject *args)
690{
691 PyObject *tuple, *socket, *address, *meth;
692 ssl_ConnectionObj *conn;
693
694 if ((meth = PyObject_GetAttrString(self->socket, "accept")) == NULL)
695 return NULL;
696 tuple = PyEval_CallObject(meth, args);
697 Py_DECREF(meth);
698 if (tuple == NULL)
699 return NULL;
700
701 socket = PyTuple_GetItem(tuple, 0);
702 Py_INCREF(socket);
703 address = PyTuple_GetItem(tuple, 1);
704 Py_INCREF(address);
705 Py_DECREF(tuple);
706
707 conn = ssl_Connection_New(self->context, socket);
708 Py_DECREF(socket);
709 if (conn == NULL)
710 {
711 Py_DECREF(address);
712 return NULL;
713 }
714
715 SSL_set_accept_state(conn->ssl);
716
717 tuple = Py_BuildValue("(OO)", conn, address);
718
719 Py_DECREF(conn);
720 Py_DECREF(address);
721
722 return tuple;
723}
724
725static char ssl_Connection_shutdown_doc[] = "\n\
726Send closure alert\n\
727\n\
728Arguments: self - The Connection object\n\
729 args - The Python argument tuple, should be empty\n\
730Returns: True if the shutdown completed successfully (i.e. both sides\n\
731 have sent closure alerts), false otherwise (i.e. you have to\n\
732 wait for a ZeroReturnError on a recv() method call\n\
733";
734static PyObject *
735ssl_Connection_shutdown(ssl_ConnectionObj *self, PyObject *args)
736{
737 int ret;
738
739 if (!PyArg_ParseTuple(args, ":shutdown"))
740 return NULL;
741
742 MY_BEGIN_ALLOW_THREADS(self->tstate)
743 ret = SSL_shutdown(self->ssl);
744 MY_END_ALLOW_THREADS(self->tstate)
745
746 if (PyErr_Occurred())
747 {
748 flush_error_queue();
749 return NULL;
750 }
751
752 if (ret < 0)
753 {
754 exception_from_error_queue();
755 return NULL;
756 }
757 else if (ret > 0)
758 {
759 Py_INCREF(Py_True);
760 return Py_True;
761 }
762 else
763 {
764 Py_INCREF(Py_False);
765 return Py_False;
766 }
767}
768
769static char ssl_Connection_get_cipher_list_doc[] = "\n\
770Get the session cipher list\n\
771WARNING: API change! This used to take an optional argument, and return a\n\
772string.\n\
773\n\
774Arguments: self - The Connection object\n\
775 args - The Python argument tuple, should be empty\n\
776Returns: A list of cipher strings\n\
777";
778static PyObject *
779ssl_Connection_get_cipher_list(ssl_ConnectionObj *self, PyObject *args)
780{
781 int idx = 0;
782 const char *ret;
783 PyObject *lst, *item;
784
785 if (!PyArg_ParseTuple(args, ":get_cipher_list"))
786 return NULL;
787
788 lst = PyList_New(0);
789 while ((ret = SSL_get_cipher_list(self->ssl, idx)) != NULL)
790 {
791 item = PyString_FromString(ret);
792 PyList_Append(lst, item);
793 Py_DECREF(item);
794 idx++;
795 }
796 return lst;
797}
798
799static char ssl_Connection_makefile_doc[] = "\n\
800The makefile() method is not implemented, since there is no dup semantics\n\
801for SSL connections\n\
802XXX: Return self instead?\n\
803\n\
804Arguments: self - The Connection object\n\
805 args - The Python argument tuple, should be empty\n\
806Returns: NULL\n\
807";
808static PyObject *
809ssl_Connection_makefile(ssl_ConnectionObj *self, PyObject *args)
810{
811 PyErr_SetString(PyExc_NotImplementedError, "Cannot make file object of SSL.Connection");
812 return NULL;
813}
814
815static char ssl_Connection_get_app_data_doc[] = "\n\
816Get application data\n\
817\n\
818Arguments: self - The Connection object\n\
819 args - The Python argument tuple, should be empty\n\
820Returns: The application data\n\
821";
822static PyObject *
823ssl_Connection_get_app_data(ssl_ConnectionObj *self, PyObject *args)
824{
825 if (!PyArg_ParseTuple(args, ":get_app_data"))
826 return NULL;
827
828 Py_INCREF(self->app_data);
829 return self->app_data;
830}
831
832static char ssl_Connection_set_app_data_doc[] = "\n\
833Set application data\n\
834\n\
835Arguments: self - The Connection object\n\
836 args - The Python argument tuple, should be\n\
837 data - The application data\n\
838Returns: None\n\
839";
840static PyObject *
841ssl_Connection_set_app_data(ssl_ConnectionObj *self, PyObject *args)
842{
843 PyObject *data;
844
845 if (!PyArg_ParseTuple(args, "O:set_app_data", &data))
846 return NULL;
847
848 Py_DECREF(self->app_data);
849 Py_INCREF(data);
850 self->app_data = data;
851
852 Py_INCREF(Py_None);
853 return Py_None;
854}
855
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500856static char ssl_Connection_get_shutdown_doc[] = "\n\
857Get shutdown state\n\
858\n\
859Arguments: self - The Connection object\n\
860 args - The Python argument tuple, should be empty\n\
861Returns: The shutdown state, a bitmask of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
862";
863static PyObject *
864ssl_Connection_get_shutdown(ssl_ConnectionObj *self, PyObject *args)
865{
866 if (!PyArg_ParseTuple(args, ":get_shutdown"))
867 return NULL;
868
869 return PyInt_FromLong((long)SSL_get_shutdown(self->ssl));
870}
871
872static char ssl_Connection_set_shutdown_doc[] = "\n\
873Set shutdown state\n\
874\n\
875Arguments: self - The Connection object\n\
876 args - The Python argument tuple, should be\n\
877 shutdown state - bitmask of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
878Returns: None\n\
879";
880static PyObject *
881ssl_Connection_set_shutdown(ssl_ConnectionObj *self, PyObject *args)
882{
883 int shutdown;
884
885 if (!PyArg_ParseTuple(args, "i:set_shutdown", &shutdown))
886 return NULL;
887
888 SSL_set_shutdown(self->ssl, shutdown);
889 Py_INCREF(Py_None);
890 return Py_None;
891}
892
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500893static char ssl_Connection_state_string_doc[] = "\n\
894Get a verbose state description\n\
895\n\
896Arguments: self - The Connection object\n\
897 args - The Python argument tuple, should be empty\n\
898Returns: A string representing the state\n\
899";
900static PyObject *
901ssl_Connection_state_string(ssl_ConnectionObj *self, PyObject *args)
902{
903 if (!PyArg_ParseTuple(args, ":state_string"))
904 return NULL;
905
906 return PyString_FromString(SSL_state_string_long(self->ssl));
907}
908
Rick Deanb71c0d22009-04-01 14:09:23 -0500909static char ssl_Connection_client_random_doc[] = "\n\
910Get a copy of the client hello nonce.\n\
911\n\
912Arguments: self - The Connection object\n\
913 args - The Python argument tuple, should be empty\n\
914Returns: A string representing the state\n\
915";
916static PyObject *
917ssl_Connection_client_random(ssl_ConnectionObj *self, PyObject *args)
918{
919 if (!PyArg_ParseTuple(args, ":client_random"))
920 return NULL;
921
922 if( self->ssl->session == NULL) {
923 Py_INCREF(Py_None);
924 return Py_None;
925 }
926 return PyString_FromStringAndSize( (const char *) self->ssl->s3->client_random, SSL3_RANDOM_SIZE);
927}
928
929static char ssl_Connection_server_random_doc[] = "\n\
930Get a copy of the server hello nonce.\n\
931\n\
932Arguments: self - The Connection object\n\
933 args - The Python argument tuple, should be empty\n\
934Returns: A string representing the state\n\
935";
936static PyObject *
937ssl_Connection_server_random(ssl_ConnectionObj *self, PyObject *args)
938{
939 if (!PyArg_ParseTuple(args, ":server_random"))
940 return NULL;
941
942 if( self->ssl->session == NULL) {
943 Py_INCREF(Py_None);
944 return Py_None;
945 }
946 return PyString_FromStringAndSize( (const char *) self->ssl->s3->server_random, SSL3_RANDOM_SIZE);
947}
948
949static char ssl_Connection_master_key_doc[] = "\n\
950Get a copy of the master key.\n\
951\n\
952Arguments: self - The Connection object\n\
953 args - The Python argument tuple, should be empty\n\
954Returns: A string representing the state\n\
955";
956static PyObject *
957ssl_Connection_master_key(ssl_ConnectionObj *self, PyObject *args)
958{
959 if (!PyArg_ParseTuple(args, ":master_key"))
960 return NULL;
961
962 if( self->ssl->session == NULL) {
963 Py_INCREF(Py_None);
964 return Py_None;
965 }
966 return PyString_FromStringAndSize( (const char *) self->ssl->session->master_key, self->ssl->session->master_key_length);
967}
968
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500969static char ssl_Connection_sock_shutdown_doc[] = "\n\
970See shutdown(2)\n\
971\n\
972Arguments: self - The Connection object\n\
973 args - The Python argument tuple, should be whatever the\n\
974 socket's shutdown() method expects\n\
975Returns: What the socket's shutdown() method returns\n\
976";
977static PyObject *
978ssl_Connection_sock_shutdown(ssl_ConnectionObj *self, PyObject *args)
979{
980 PyObject *meth, *ret;
981
982 if ((meth = PyObject_GetAttrString(self->socket, "shutdown")) == NULL)
983 return NULL;
984 ret = PyEval_CallObject(meth, args);
985 Py_DECREF(meth);
986 return ret;
987}
988
989static char ssl_Connection_get_peer_certificate_doc[] = "\n\
990Retrieve the other side's certificate (if any)\n\
991\n\
992Arguments: self - The Connection object\n\
993 args - The Python argument tuple, should be empty\n\
994Returns: The peer's certificate\n\
995";
996static PyObject *
997ssl_Connection_get_peer_certificate(ssl_ConnectionObj *self, PyObject *args)
998{
999 X509 *cert;
1000
1001 if (!PyArg_ParseTuple(args, ":get_peer_certificate"))
1002 return NULL;
1003
1004 cert = SSL_get_peer_certificate(self->ssl);
1005 if (cert != NULL)
1006 {
1007 return (PyObject *)crypto_X509_New(cert, 1);
1008 }
1009 else
1010 {
1011 Py_INCREF(Py_None);
1012 return Py_None;
1013 }
1014}
1015
1016static char ssl_Connection_want_read_doc[] = "\n\
1017Checks if more data has to be read from the transport layer to complete an\n\
1018operation.\n\
1019\n\
1020Arguments: self - The Connection object\n\
1021 args - The Python argument tuple, should be empty\n\
1022Returns: True iff more data has to be read\n\
1023";
1024static PyObject *
1025ssl_Connection_want_read(ssl_ConnectionObj *self, PyObject *args)
1026{
1027 if (!PyArg_ParseTuple(args, ":want_read"))
1028 return NULL;
1029
1030 return PyInt_FromLong((long)SSL_want_read(self->ssl));
1031}
1032
1033static char ssl_Connection_want_write_doc[] = "\n\
1034Checks if there is data to write to the transport layer to complete an\n\
1035operation.\n\
1036\n\
1037Arguments: self - The Connection object\n\
1038 args - The Python argument tuple, should be empty\n\
1039Returns: True iff there is data to write\n\
1040";
1041static PyObject *
1042ssl_Connection_want_write(ssl_ConnectionObj *self, PyObject *args)
1043{
1044 if (!PyArg_ParseTuple(args, ":want_write"))
1045 return NULL;
1046
1047 return PyInt_FromLong((long)SSL_want_write(self->ssl));
1048}
1049
1050/*
1051 * Member methods in the Connection object
1052 * ADD_METHOD(name) expands to a correct PyMethodDef declaration
1053 * { 'name', (PyCFunction)ssl_Connection_name, METH_VARARGS }
1054 * for convenience
1055 * ADD_ALIAS(name,real) creates an "alias" of the ssl_Connection_real
1056 * function with the name 'name'
1057 */
1058#define ADD_METHOD(name) \
1059 { #name, (PyCFunction)ssl_Connection_##name, METH_VARARGS, ssl_Connection_##name##_doc }
1060#define ADD_ALIAS(name,real) \
1061 { #name, (PyCFunction)ssl_Connection_##real, METH_VARARGS, ssl_Connection_##real##_doc }
1062static PyMethodDef ssl_Connection_methods[] =
1063{
1064 ADD_METHOD(get_context),
1065 ADD_METHOD(pending),
1066 ADD_METHOD(send),
1067 ADD_ALIAS (write, send),
1068 ADD_METHOD(sendall),
1069 ADD_METHOD(recv),
1070 ADD_ALIAS (read, recv),
Rick Deanb71c0d22009-04-01 14:09:23 -05001071 ADD_METHOD(bio_read),
1072 ADD_METHOD(bio_write),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001073 ADD_METHOD(renegotiate),
1074 ADD_METHOD(do_handshake),
1075#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
1076 ADD_METHOD(renegotiate_pending),
1077#endif
1078 ADD_METHOD(total_renegotiations),
1079 ADD_METHOD(connect),
1080 ADD_METHOD(connect_ex),
1081 ADD_METHOD(accept),
1082 ADD_METHOD(shutdown),
1083 ADD_METHOD(get_cipher_list),
1084 ADD_METHOD(makefile),
1085 ADD_METHOD(get_app_data),
1086 ADD_METHOD(set_app_data),
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001087 ADD_METHOD(get_shutdown),
1088 ADD_METHOD(set_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001089 ADD_METHOD(state_string),
Rick Deanb71c0d22009-04-01 14:09:23 -05001090 ADD_METHOD(server_random),
1091 ADD_METHOD(client_random),
1092 ADD_METHOD(master_key),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001093 ADD_METHOD(sock_shutdown),
1094 ADD_METHOD(get_peer_certificate),
1095 ADD_METHOD(want_read),
1096 ADD_METHOD(want_write),
1097 ADD_METHOD(set_accept_state),
1098 ADD_METHOD(set_connect_state),
1099 { NULL, NULL }
1100};
1101#undef ADD_ALIAS
1102#undef ADD_METHOD
1103
1104
1105/*
1106 * Constructor for Connection objects
1107 *
1108 * Arguments: ctx - An SSL Context to use for this connection
1109 * sock - The socket to use for transport layer
1110 * Returns: The newly created Connection object
1111 */
1112ssl_ConnectionObj *
1113ssl_Connection_New(ssl_ContextObj *ctx, PyObject *sock)
1114{
1115 ssl_ConnectionObj *self;
1116 int fd;
1117
1118 self = PyObject_GC_New(ssl_ConnectionObj, &ssl_Connection_Type);
1119 if (self == NULL)
1120 return NULL;
1121
1122 Py_INCREF(ctx);
1123 self->context = ctx;
1124
1125 Py_INCREF(sock);
1126 self->socket = sock;
1127
1128 self->ssl = NULL;
1129
1130 Py_INCREF(Py_None);
1131 self->app_data = Py_None;
1132
1133 self->tstate = NULL;
1134
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001135 self->ssl = SSL_new(self->context->ctx);
1136 SSL_set_app_data(self->ssl, self);
Rick Deanb71c0d22009-04-01 14:09:23 -05001137
1138 if(self->socket == Py_None)
1139 {
1140 /* If it's not a socket or file, treat it like a memory buffer,
1141 * so crazy people can do things like EAP-TLS. */
1142 self->into_ssl = BIO_new(BIO_s_mem());
1143 self->from_ssl = BIO_new(BIO_s_mem());
1144 if(self->into_ssl == NULL || self->from_ssl == NULL)
1145 goto error;
1146 SSL_set_bio(self->ssl, self->into_ssl, self->from_ssl);
1147 }
1148 else
1149 {
1150 fd = PyObject_AsFileDescriptor(self->socket);
1151 if (fd < 0)
1152 {
1153 Py_DECREF(self);
1154 return NULL;
1155 }
1156 else
1157 {
1158 SSL_set_fd(self->ssl, (SOCKET_T)fd);
1159 }
1160 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001161
1162 PyObject_GC_Track(self);
1163
1164 return self;
Rick Deanb71c0d22009-04-01 14:09:23 -05001165
1166error:
1167 BIO_free(self->into_ssl); /* NULL safe */
1168 BIO_free(self->from_ssl); /* NULL safe */
1169 Py_DECREF(self);
1170 return NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001171}
1172
1173/*
1174 * Find attribute
1175 *
1176 * Arguments: self - The Connection object
1177 * name - The attribute name
1178 * Returns: A Python object for the attribute, or NULL if something went
1179 * wrong
1180 */
1181static PyObject *
1182ssl_Connection_getattr(ssl_ConnectionObj *self, char *name)
1183{
1184 PyObject *meth;
1185
1186 meth = Py_FindMethod(ssl_Connection_methods, (PyObject *)self, name);
1187
1188 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_AttributeError))
1189 {
1190 PyErr_Clear();
1191 /* Try looking it up in the "socket" instead. */
1192 meth = PyObject_GetAttrString(self->socket, name);
1193 }
1194
1195 return meth;
1196}
1197
1198/*
1199 * Call the visitproc on all contained objects.
1200 *
1201 * Arguments: self - The Connection object
1202 * visit - Function to call
1203 * arg - Extra argument to visit
1204 * Returns: 0 if all goes well, otherwise the return code from the first
1205 * call that gave non-zero result.
1206 */
1207static int
1208ssl_Connection_traverse(ssl_ConnectionObj *self, visitproc visit, void *arg)
1209{
1210 int ret = 0;
1211
1212 if (ret == 0 && self->context != NULL)
1213 ret = visit((PyObject *)self->context, arg);
1214 if (ret == 0 && self->socket != NULL)
1215 ret = visit(self->socket, arg);
1216 if (ret == 0 && self->app_data != NULL)
1217 ret = visit(self->app_data, arg);
1218 return ret;
1219}
1220
1221/*
1222 * Decref all contained objects and zero the pointers.
1223 *
1224 * Arguments: self - The Connection object
1225 * Returns: Always 0.
1226 */
1227static int
1228ssl_Connection_clear(ssl_ConnectionObj *self)
1229{
1230 Py_XDECREF(self->context);
1231 self->context = NULL;
1232 Py_XDECREF(self->socket);
1233 self->socket = NULL;
1234 Py_XDECREF(self->app_data);
1235 self->app_data = NULL;
Rick Deanb71c0d22009-04-01 14:09:23 -05001236 self->into_ssl = NULL; /* was cleaned up by SSL_free() */
1237 self->from_ssl = NULL; /* was cleaned up by SSL_free() */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001238 return 0;
1239}
1240
1241/*
1242 * Deallocate the memory used by the Connection object
1243 *
1244 * Arguments: self - The Connection object
1245 * Returns: None
1246 */
1247static void
1248ssl_Connection_dealloc(ssl_ConnectionObj *self)
1249{
1250 PyObject_GC_UnTrack(self);
1251 if (self->ssl != NULL)
1252 SSL_free(self->ssl);
1253 ssl_Connection_clear(self);
1254 PyObject_GC_Del(self);
1255}
1256
1257PyTypeObject ssl_Connection_Type = {
1258 PyObject_HEAD_INIT(NULL)
1259 0,
1260 "Connection",
1261 sizeof(ssl_ConnectionObj),
1262 0,
1263 (destructor)ssl_Connection_dealloc,
1264 NULL, /* print */
1265 (getattrfunc)ssl_Connection_getattr,
1266 NULL, /* setattr */
1267 NULL, /* compare */
1268 NULL, /* repr */
1269 NULL, /* as_number */
1270 NULL, /* as_sequence */
1271 NULL, /* as_mapping */
1272 NULL, /* hash */
1273 NULL, /* call */
1274 NULL, /* str */
1275 NULL, /* getattro */
1276 NULL, /* setattro */
1277 NULL, /* as_buffer */
1278 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
1279 NULL, /* doc */
1280 (traverseproc)ssl_Connection_traverse,
1281 (inquiry)ssl_Connection_clear,
1282};
1283
1284
1285/*
1286 * Initiailze the Connection part of the SSL sub module
1287 *
1288 * Arguments: dict - Dictionary of the OpenSSL.SSL module
1289 * Returns: 1 for success, 0 otherwise
1290 */
1291int
1292init_ssl_connection(PyObject *dict)
1293{
1294 ssl_Connection_Type.ob_type = &PyType_Type;
1295 Py_INCREF(&ssl_Connection_Type);
1296 if (PyDict_SetItemString(dict, "ConnectionType", (PyObject *)&ssl_Connection_Type) != 0)
1297 return 0;
1298
1299 return 1;
1300}
1301