added OpenSSL handler
[NeonServV5.git] / src / ssl.c
1 /* ssl.c - NeonServ v5.2
2  * Copyright (C) 2011  Philipp Kreil (pk910)
3  * 
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License 
15  * along with this program. If not, see <http://www.gnu.org/licenses/>. 
16  */
17
18 #include "ssl.h"
19 #include "ClientSocket.h"
20
21 void ssl_init() {
22 #ifdef HAVE_SSL
23     SSL_library_init();
24 #endif
25 }
26
27 void ssl_connect(struct ClientSocket *client) {
28 #ifdef HAVE_SSL
29     client->sslconn = NULL;
30     if(!(client->flags & SOCKET_FLAG_CONNECTED)) return;
31     struct SSLConnection *sslconn = malloc(sizeof(*sslconn));
32     sslconn->sslContext = SSL_CTX_new(SSLv23_client_method());
33     if(!sslconn->sslContext) goto ssl_connect_err;
34     sslconn->sslHandle = SSL_new(sslconn->sslContext);
35     if(!sslconn->sslHandle) goto ssl_connect_err;
36     if(!SSL_set_fd(sslconn->sslHandle, client->sock)) goto ssl_connect_err;
37     if(SSL_connect(sslconn->sslHandle) != 1) goto ssl_connect_err;
38     client->sslconn = sslconn;
39 ssl_connect_err:
40     free(sslconn);
41 #endif    
42 }
43
44 void ssl_disconnect(struct ClientSocket *client) {
45 #ifdef HAVE_SSL
46     if(!client->sslconn) return;
47     SSL_shutdown(client->sslconn->sslHandle);
48     SSL_free(client->sslconn->sslHandle);
49     SSL_CTX_free(client->sslconn->sslContext);
50     free(client->sslconn);
51     client->sslconn = NULL;
52 #endif
53 }
54
55 int ssl_read(struct ClientSocket *client, char *buffer, int len) {
56 #ifdef HAVE_SSL
57     if(!client->sslconn) return -2;
58     return SSL_read(client->sslconn->sslHandle, buffer, len);
59 #endif
60     return -2;
61 }
62
63 int ssl_write(struct ClientSocket *client, char *buffer, int len) {
64 #ifdef HAVE_SSL
65     if(!client->sslconn) return -2;
66     return SSL_write(client->sslconn->sslHandle, buffer, len);
67 #endif
68     return -2;
69 }