_ssl.c 17.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/* SSL socket module 

   SSL support based on patches by Brian E Gallew and Laszlo Kovacs.

   This module is imported by socket.py. It should *not* be used
   directly.

*/

#include "Python.h"
11 12 13 14 15 16 17 18 19 20 21 22 23 24
enum py_ssl_error {
	/* these mirror ssl.h */
	PY_SSL_ERROR_NONE,                 
	PY_SSL_ERROR_SSL,                   
	PY_SSL_ERROR_WANT_READ,             
	PY_SSL_ERROR_WANT_WRITE,            
	PY_SSL_ERROR_WANT_X509_LOOKUP,      
	PY_SSL_ERROR_SYSCALL,     /* look at error stack/return value/errno */
	PY_SSL_ERROR_ZERO_RETURN,           
	PY_SSL_ERROR_WANT_CONNECT,
	/* start of non ssl.h errorcodes */ 
	PY_SSL_ERROR_EOF,         /* special case of SSL_ERROR_SYSCALL */
	PY_SSL_ERROR_INVALID_ERROR_CODE
};
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

/* Include symbols from _socket module */
#include "socketmodule.h"

/* Include OpenSSL header files */
#include "openssl/rsa.h"
#include "openssl/crypto.h"
#include "openssl/x509.h"
#include "openssl/pem.h"
#include "openssl/ssl.h"
#include "openssl/err.h"
#include "openssl/rand.h"

/* SSL error object */
static PyObject *PySSLErrorObject;

/* SSL socket object */

#define X509_NAME_MAXLEN 256

/* RAND_* APIs got added to OpenSSL in 0.9.5 */
#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
# define HAVE_OPENSSL_RAND 1
#else
# undef HAVE_OPENSSL_RAND
#endif

typedef struct {
	PyObject_HEAD
	PySocketSockObject *Socket;	/* Socket on which we're layered */
	SSL_CTX* 	ctx;
	SSL*     	ssl;
	X509*    	server_cert;
	BIO*		sbio;
	char    	server[X509_NAME_MAXLEN];
	char		issuer[X509_NAME_MAXLEN];

} PySSLObject;

64 65 66
static PyTypeObject PySSL_Type;
static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
67 68
static int check_socket_and_wait_for_timeout(PySocketSockObject *s, 
					     int writing);
69 70 71

#define PySSLObject_Check(v)	((v)->ob_type == &PySSL_Type)

72 73 74 75 76 77 78 79
typedef enum {
	SOCKET_IS_NONBLOCKING,
	SOCKET_IS_BLOCKING,
	SOCKET_HAS_TIMED_OUT,
	SOCKET_HAS_BEEN_CLOSED,
	SOCKET_OPERATION_OK
} timeout_state;

80 81 82 83 84 85 86 87 88 89 90
/* XXX It might be helpful to augment the error message generated
   below with the name of the SSL function that generated the error.
   I expect it's obvious most of the time.
*/

static PyObject *
PySSL_SetError(PySSLObject *obj, int ret)
{
	PyObject *v, *n, *s;
	char *errstr;
	int err;
91
	enum py_ssl_error p;
92 93 94 95 96

	assert(ret <= 0);
    
	err = SSL_get_error(obj->ssl, ret);

97
	switch (err) {
98 99
	case SSL_ERROR_ZERO_RETURN:
		errstr = "TLS/SSL connection has been closed";
100
		p = PY_SSL_ERROR_ZERO_RETURN;
101 102 103
		break;
	case SSL_ERROR_WANT_READ:
		errstr = "The operation did not complete (read)";
104
		p = PY_SSL_ERROR_WANT_READ;
105 106
		break;
	case SSL_ERROR_WANT_WRITE:
107
		p = PY_SSL_ERROR_WANT_WRITE;
108 109 110
		errstr = "The operation did not complete (write)";
		break;
	case SSL_ERROR_WANT_X509_LOOKUP:
111
		p = PY_SSL_ERROR_WANT_X509_LOOKUP;
112 113
		errstr = "The operation did not complete (X509 lookup)";
		break;
114
	case SSL_ERROR_WANT_CONNECT:
115
		p = PY_SSL_ERROR_WANT_CONNECT;
116 117
		errstr = "The operation did not complete (connect)";
		break;
118 119 120
	case SSL_ERROR_SYSCALL:
	{
		unsigned long e = ERR_get_error();
121
		if (e == 0) {
122
			if (ret == 0 || !obj->Socket) {
123
				p = PY_SSL_ERROR_EOF;
124
				errstr = "EOF occurred in violation of protocol";
125
			} else if (ret == -1) {
126 127
				/* the underlying BIO reported an I/O error */
				return obj->Socket->errorhandler();
128 129
			} else {  /* possible? */
				p = PY_SSL_ERROR_SYSCALL;
130 131
				errstr = "Some I/O error occurred";
			}
132
		} else {
133
			p = PY_SSL_ERROR_SYSCALL;
134 135 136 137 138 139 140 141
			/* XXX Protected by global interpreter lock */
			errstr = ERR_error_string(e, NULL);
		}
		break;
	}   
	case SSL_ERROR_SSL:
	{
		unsigned long e = ERR_get_error();
142 143
		p = PY_SSL_ERROR_SSL;
		if (e != 0) 
144 145
			/* XXX Protected by global interpreter lock */
			errstr = ERR_error_string(e, NULL);
146 147
		else { /* possible? */
			errstr = "A failure in the SSL library occurred";
148 149 150 151
		}
		break;
	}
	default:
152
		p = PY_SSL_ERROR_INVALID_ERROR_CODE;
153 154
		errstr = "Invalid error code";
	}
155 156 157 158 159 160 161 162 163
	n = PyInt_FromLong((long) p);
	if (n == NULL)
		return NULL;
	v = PyTuple_New(2);
	if (v == NULL) {
		Py_DECREF(n);
		return NULL;
	}

164 165 166 167 168 169 170 171
	s = PyString_FromString(errstr);
	if (s == NULL) {
		Py_DECREF(v);
		Py_DECREF(n);
	}
	PyTuple_SET_ITEM(v, 0, n);
	PyTuple_SET_ITEM(v, 1, s);
	PyErr_SetObject(PySSLErrorObject, v);
172
	Py_DECREF(v);
173 174 175 176 177 178 179 180 181
	return NULL;
}

static PySSLObject *
newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file)
{
	PySSLObject *self;
	char *errstr = NULL;
	int ret;
182
	int err;
183
	int sockstate;
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

	self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
	if (self == NULL){
		errstr = "newPySSLObject error";
		goto fail;
	}
	memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN);
	memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);
	self->server_cert = NULL;
	self->ssl = NULL;
	self->ctx = NULL;
	self->Socket = NULL;

	if ((key_file && !cert_file) || (!key_file && cert_file)) {
		errstr = "Both the key & certificate files must be specified";
		goto fail;
	}

202
	Py_BEGIN_ALLOW_THREADS
203
	self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
204
	Py_END_ALLOW_THREADS
205 206 207 208 209 210
	if (self->ctx == NULL) {
		errstr = "SSL_CTX_new error";
		goto fail;
	}

	if (key_file) {
211 212 213 214 215
		Py_BEGIN_ALLOW_THREADS
		ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
						SSL_FILETYPE_PEM);
		Py_END_ALLOW_THREADS
		if (ret < 1) {
216 217 218 219
			errstr = "SSL_CTX_use_PrivateKey_file error";
			goto fail;
		}

220 221 222 223
		Py_BEGIN_ALLOW_THREADS
		ret = SSL_CTX_use_certificate_chain_file(self->ctx,
						       cert_file);
		Py_END_ALLOW_THREADS
224
		SSL_CTX_set_options(self->ctx, SSL_OP_ALL); /* ssl compatibility */
225
		if (ret < 1) {
226 227 228 229 230
			errstr = "SSL_CTX_use_certificate_chain_file error";
			goto fail;
		}
	}

231
	Py_BEGIN_ALLOW_THREADS
232 233 234
	SSL_CTX_set_verify(self->ctx,
			   SSL_VERIFY_NONE, NULL); /* set verify lvl */
	self->ssl = SSL_new(self->ctx); /* New ssl struct */
235
	Py_END_ALLOW_THREADS
236
	SSL_set_fd(self->ssl, Sock->sock_fd);	/* Set the socket for SSL */
237

238
	/* If the socket is in non-blocking mode or timeout mode, set the BIO
239 240 241 242 243 244 245 246
	 * to non-blocking mode (blocking is the default)
	 */
	if (Sock->sock_timeout >= 0.0) {
		/* Set both the read and write BIO's to non-blocking mode */
		BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
		BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
	}

247
	Py_BEGIN_ALLOW_THREADS
248
	SSL_set_connect_state(self->ssl);
249
	Py_END_ALLOW_THREADS
250

251 252
	/* Actually negotiate SSL connection */
	/* XXX If SSL_connect() returns 0, it's also a failure. */
253
	sockstate = 0;
254 255 256 257 258
	do {
		Py_BEGIN_ALLOW_THREADS
		ret = SSL_connect(self->ssl);
		err = SSL_get_error(self->ssl, ret);
		Py_END_ALLOW_THREADS
259 260 261
		if(PyErr_CheckSignals()) {
                        goto fail;
		}
262
		if (err == SSL_ERROR_WANT_READ) {
263
			sockstate = check_socket_and_wait_for_timeout(Sock, 0);
264
		} else if (err == SSL_ERROR_WANT_WRITE) {
265 266 267
			sockstate = check_socket_and_wait_for_timeout(Sock, 1);
		} else {
			sockstate = SOCKET_OPERATION_OK;
268
		}
269 270
	    if (sockstate == SOCKET_HAS_TIMED_OUT) {
			PyErr_SetString(PySSLErrorObject, "The connect operation timed out");
271
			goto fail;
272 273 274 275 276
		} else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
			PyErr_SetString(PySSLErrorObject, "Underlying socket has been closed.");
			goto fail;
		} else if (sockstate == SOCKET_IS_NONBLOCKING) {
			break;
277 278
		}
	} while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
279 280 281 282 283 284
	if (ret <= 0) {
		PySSL_SetError(self, ret);
		goto fail;
	}
	self->ssl->debug = 1;

285
	Py_BEGIN_ALLOW_THREADS
286 287 288 289 290 291
	if ((self->server_cert = SSL_get_peer_certificate(self->ssl))) {
		X509_NAME_oneline(X509_get_subject_name(self->server_cert),
				  self->server, X509_NAME_MAXLEN);
		X509_NAME_oneline(X509_get_issuer_name(self->server_cert),
				  self->issuer, X509_NAME_MAXLEN);
	}
292
	Py_END_ALLOW_THREADS
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
	self->Socket = Sock;
	Py_INCREF(self->Socket);
	return self;
 fail:
	if (errstr)
		PyErr_SetString(PySSLErrorObject, errstr);
	Py_DECREF(self);
	return NULL;
}

static PyObject *
PySocket_ssl(PyObject *self, PyObject *args)
{
	PySSLObject *rv;
	PySocketSockObject *Sock;
	char *key_file = NULL;
	char *cert_file = NULL;

	if (!PyArg_ParseTuple(args, "O!|zz:ssl",
			      PySocketModule.Sock_Type,
			      (PyObject*)&Sock,
			      &key_file, &cert_file))
		return NULL;

	rv = newPySSLObject(Sock, key_file, cert_file);
	if (rv == NULL)
		return NULL;
	return (PyObject *)rv;
}

323 324
PyDoc_STRVAR(ssl_doc,
"ssl(socket, [keyfile, certfile]) -> sslobject");
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

/* SSL object methods */

static PyObject *
PySSL_server(PySSLObject *self)
{
	return PyString_FromString(self->server);
}

static PyObject *
PySSL_issuer(PySSLObject *self)
{
	return PyString_FromString(self->issuer);
}


static void PySSL_dealloc(PySSLObject *self)
{
	if (self->server_cert)	/* Possible not to have one? */
		X509_free (self->server_cert);
	if (self->ssl)
	    SSL_free(self->ssl);
	if (self->ctx)
	    SSL_CTX_free(self->ctx);
	Py_XDECREF(self->Socket);
	PyObject_Del(self);
}

353 354
/* If the socket has a timeout, do a select() on the socket.
   The argument writing indicates the direction.
355
   Returns one of the possibilities in the timeout_state enum (above).
356
 */
357

358
static int
359
check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
360 361 362 363 364 365
{
	fd_set fds;
	struct timeval tv;
	int rc;

	/* Nothing to do unless we're in timeout mode (not non-blocking) */
366 367 368 369
	if (s->sock_timeout < 0.0)
		return SOCKET_IS_BLOCKING;
	else if (s->sock_timeout == 0.0)
		return SOCKET_IS_NONBLOCKING;
370 371 372

	/* Guard against closed socket */
	if (s->sock_fd < 0)
373
		return SOCKET_HAS_BEEN_CLOSED;
374 375 376 377 378 379 380 381

	/* Construct the arguments to select */
	tv.tv_sec = (int)s->sock_timeout;
	tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
	FD_ZERO(&fds);
	FD_SET(s->sock_fd, &fds);

	/* See if the socket is ready */
382
	Py_BEGIN_ALLOW_THREADS
383 384 385 386
	if (writing)
		rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
	else
		rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
387
	Py_END_ALLOW_THREADS
388

389 390 391
	/* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
	   (when we are able to write or when there's something to read) */
	return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
392 393
}

394 395 396 397
static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
{
	char *data;
	int len;
398
	int count;
399
	int sockstate;
400
	int err;
401

402
	if (!PyArg_ParseTuple(args, "s#:write", &data, &count))
403 404
		return NULL;

405 406
	sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
	if (sockstate == SOCKET_HAS_TIMED_OUT) {
407 408
		PyErr_SetString(PySSLErrorObject, "The write operation timed out");
		return NULL;
409 410 411
	} else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
		PyErr_SetString(PySSLErrorObject, "Underlying socket has been closed.");
		return NULL;
412
	}
413 414 415
	do {
		err = 0;
		Py_BEGIN_ALLOW_THREADS
416
		len = SSL_write(self->ssl, data, count);
417 418
		err = SSL_get_error(self->ssl, len);
		Py_END_ALLOW_THREADS
419 420 421
		if(PyErr_CheckSignals()) {
			return NULL;
		}
422
		if (err == SSL_ERROR_WANT_READ) {
423
			sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
424
		} else if (err == SSL_ERROR_WANT_WRITE) {
425 426 427
			sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
		} else {
			sockstate = SOCKET_OPERATION_OK;
428
		}
429
	    if (sockstate == SOCKET_HAS_TIMED_OUT) {
430 431
			PyErr_SetString(PySSLErrorObject, "The write operation timed out");
			return NULL;
432 433 434 435 436
		} else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
			PyErr_SetString(PySSLErrorObject, "Underlying socket has been closed.");
			return NULL;
		} else if (sockstate == SOCKET_IS_NONBLOCKING) {
			break;
437 438
		}
	} while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
439 440 441 442 443 444
	if (len > 0)
		return PyInt_FromLong(len);
	else
		return PySSL_SetError(self, len);
}

445
PyDoc_STRVAR(PySSL_SSLwrite_doc,
446 447 448
"write(s) -> len\n\
\n\
Writes the string s into the SSL object.  Returns the number\n\
449
of bytes written.");
450 451 452 453 454 455

static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
{
	PyObject *buf;
	int count = 0;
	int len = 1024;
456
	int sockstate;
457
	int err;
458 459 460 461 462 463 464

	if (!PyArg_ParseTuple(args, "|i:read", &len))
		return NULL;

	if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
		return NULL;

465 466
	sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
	if (sockstate == SOCKET_HAS_TIMED_OUT) {
467
		PyErr_SetString(PySSLErrorObject, "The read operation timed out");
468
		Py_DECREF(buf);
469 470
		return NULL;
	}
471 472 473 474 475 476
	do {
		err = 0;
		Py_BEGIN_ALLOW_THREADS
		count = SSL_read(self->ssl, PyString_AsString(buf), len);
		err = SSL_get_error(self->ssl, count);
		Py_END_ALLOW_THREADS
477 478 479 480
		if(PyErr_CheckSignals()) {
			Py_DECREF(buf);
			return NULL;
		}
481
		if (err == SSL_ERROR_WANT_READ) {
482
			sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
483
		} else if (err == SSL_ERROR_WANT_WRITE) {
484 485 486
			sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
		} else {
			sockstate = SOCKET_OPERATION_OK;
487
		}
488
	    if (sockstate == SOCKET_HAS_TIMED_OUT) {
489
			PyErr_SetString(PySSLErrorObject, "The read operation timed out");
490
			Py_DECREF(buf);
491
			return NULL;
492 493
		} else if (sockstate == SOCKET_IS_NONBLOCKING) {
			break;
494 495
		}
	} while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
496 497 498 499
 	if (count <= 0) {
		Py_DECREF(buf);
		return PySSL_SetError(self, count);
	}
500 501
	if (count != len)
		_PyString_Resize(&buf, count);
502 503 504
	return buf;
}

505
PyDoc_STRVAR(PySSL_SSLread_doc,
506 507
"read([len]) -> string\n\
\n\
508
Read up to len bytes from the SSL socket.");
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524

static PyMethodDef PySSLMethods[] = {
	{"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
	          PySSL_SSLwrite_doc},
	{"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
	          PySSL_SSLread_doc},
	{"server", (PyCFunction)PySSL_server, METH_NOARGS},
	{"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
	{NULL, NULL}
};

static PyObject *PySSL_getattr(PySSLObject *self, char *name)
{
	return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
}

525
static PyTypeObject PySSL_Type = {
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
	PyObject_HEAD_INIT(NULL)
	0,				/*ob_size*/
	"socket.SSL",			/*tp_name*/
	sizeof(PySSLObject),		/*tp_basicsize*/
	0,				/*tp_itemsize*/
	/* methods */
	(destructor)PySSL_dealloc,	/*tp_dealloc*/
	0,				/*tp_print*/
	(getattrfunc)PySSL_getattr,	/*tp_getattr*/
	0,				/*tp_setattr*/
	0,				/*tp_compare*/
	0,				/*tp_repr*/
	0,				/*tp_as_number*/
	0,				/*tp_as_sequence*/
	0,				/*tp_as_mapping*/
	0,				/*tp_hash*/
};

#ifdef HAVE_OPENSSL_RAND

/* helper routines for seeding the SSL PRNG */
static PyObject *
PySSL_RAND_add(PyObject *self, PyObject *args)
{
    char *buf;
    int len;
    double entropy;

    if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
	return NULL;
    RAND_add(buf, len, entropy);
    Py_INCREF(Py_None);
    return Py_None;
}

561
PyDoc_STRVAR(PySSL_RAND_add_doc,
562 563 564
"RAND_add(string, entropy)\n\
\n\
Mix string into the OpenSSL PRNG state.  entropy (a float) is a lower\n\
565
bound on the entropy contained in string.");
566 567 568 569 570 571 572

static PyObject *
PySSL_RAND_status(PyObject *self)
{
    return PyInt_FromLong(RAND_status());
}

573
PyDoc_STRVAR(PySSL_RAND_status_doc,
574 575 576 577
"RAND_status() -> 0 or 1\n\
\n\
Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
578
using the ssl() function.");
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598

static PyObject *
PySSL_RAND_egd(PyObject *self, PyObject *arg)
{
    int bytes;

    if (!PyString_Check(arg))
	return PyErr_Format(PyExc_TypeError,
			    "RAND_egd() expected string, found %s",
			    arg->ob_type->tp_name);
    bytes = RAND_egd(PyString_AS_STRING(arg));
    if (bytes == -1) {
	PyErr_SetString(PySSLErrorObject,
			"EGD connection failed or EGD did not return "
			"enough data to seed the PRNG");
	return NULL;
    }
    return PyInt_FromLong(bytes);
}

599
PyDoc_STRVAR(PySSL_RAND_egd_doc,
600 601 602 603
"RAND_egd(path) -> bytes\n\
\n\
Queries the entropy gather daemon (EGD) on socket path.  Returns number\n\
of bytes read.  Raises socket.sslerror if connection to EGD fails or\n\
604
if it does provide enough data to seed PRNG.");
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624

#endif

/* List of functions exported by this module. */

static PyMethodDef PySSL_methods[] = {
	{"ssl",			PySocket_ssl,
	 METH_VARARGS, ssl_doc},
#ifdef HAVE_OPENSSL_RAND
	{"RAND_add",            PySSL_RAND_add, METH_VARARGS, 
	 PySSL_RAND_add_doc},
	{"RAND_egd",            PySSL_RAND_egd, METH_O,
	 PySSL_RAND_egd_doc},
	{"RAND_status",         (PyCFunction)PySSL_RAND_status, METH_NOARGS,
	 PySSL_RAND_status_doc},
#endif
	{NULL,			NULL}		 /* Sentinel */
};


625
PyDoc_STRVAR(module_doc,
626
"Implementation module for SSL socket operations.  See the socket module\n\
627
for documentation.");
628

629
PyMODINIT_FUNC
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
init_ssl(void)
{
	PyObject *m, *d;

	PySSL_Type.ob_type = &PyType_Type;

	m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
	d = PyModule_GetDict(m);

	/* Load _socket module and its C API */
	if (PySocketModule_ImportModuleAndAPI())
 	    	return;

	/* Init OpenSSL */
	SSL_load_error_strings();
	SSLeay_add_ssl_algorithms();

	/* Add symbols to module dict */
648 649 650
	PySSLErrorObject = PyErr_NewException("socket.sslerror",
                                               PySocketModule.error,
                                               NULL);
651 652 653 654 655 656 657
	if (PySSLErrorObject == NULL)
		return;
	PyDict_SetItemString(d, "sslerror", PySSLErrorObject);
	if (PyDict_SetItemString(d, "SSLType",
				 (PyObject *)&PySSL_Type) != 0)
		return;
	PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
658
				PY_SSL_ERROR_ZERO_RETURN);
659
	PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
660
				PY_SSL_ERROR_WANT_READ);
661
	PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
662
				PY_SSL_ERROR_WANT_WRITE);
663
	PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
664
				PY_SSL_ERROR_WANT_X509_LOOKUP);
665
	PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
666
				PY_SSL_ERROR_SYSCALL);
667
	PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
668 669 670 671 672 673 674 675 676
				PY_SSL_ERROR_SSL);
	PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
				PY_SSL_ERROR_WANT_CONNECT);
	/* non ssl.h errorcodes */
	PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
				PY_SSL_ERROR_EOF);
	PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
				PY_SSL_ERROR_INVALID_ERROR_CODE);

677
}