-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.h
569 lines (489 loc) · 17.5 KB
/
net.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
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
323
324
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
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
561
562
563
564
565
566
567
568
569
/*
* Copyright (c) 2017 Sebastien Serre <ssbx@sysmo.io>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef NET_H
#define NET_H
#include <sys/types.h>
#include <sys/socket.h>
#ifdef __linux__
#include <sys/epoll.h>
#else
#include <sys/time.h>
#include <sys/event.h>
#endif
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#define CLASS(p) ((*(unsigned char*)(p))>>6)
#define NET_TCP 0
#define NET_UDP 1
#define NET_SYNC 0
#define NET_ASYNC 2
#define NET_NOSSL 0
#define NET_SSL 4
#define __USE_ASYNC(opts) (opts & NET_ASYNC)
#define __USE_UDP(opts) (opts & NET_UDP)
#define __USE_SSL(opts) (opts & NET_SSL)
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
typedef struct {
X509 *cert;
SSL_CTX *ctx;
SSL *ssl;
int fd;
int status;
int epoll_fd;
} NetSocket;
NetSocket netDial(char *server, int port, int opts);
int netWrite(NetSocket socket, char* payload, int size);
int netRead(NetSocket socket, char* payload, int size);
NetSocket netClose(NetSocket);
NetSocket netAnnounce(char *server, int port, int opts);
NetSocket netAccept(NetSocket net_socket, int opts);
char * netGetStatus(NetSocket socket);
void __parseUrl(char url[]);
int __parseIP(char *name, uint32_t *ip);
int __hostLookup(char *name, uint32_t *ip);
NetSocket __netDialSSL(char *server, int port, int opts);
NetSocket __netDialTCP(char *server, int port, int opts);
char ssl_error_none[] = "none";
char ssl_error_zero_return[] = "The TLS/SSL connection has been closed";
char ssl_error_want_write[] = "The Write operation did not complete";
char ssl_error_want_read[] = "The Read operation did not complete";
char ssl_error_want_connect[] = "The Connect opertation did not complete";
char ssl_error_want_accept[] = "The Accept opertation did not complete";
char ssl_error_want_x509_lookup[] = "The x509 lookup did not complete";
char ssl_error_ssl[] =
"A failure in the SSL library occurred (protocol error?)";
/*
* Opts can be:
* - NET_TCP/NET_UDP
* - NET_SYNC/NET_ASYNC
* - NET_NOSSL/NET_SSL
*
* Default (0) is the same as NET_TCP | NET_SYNC | NET_NOSSL
*
* IF NET_ASYNC:
* Next calls to connect, netRead and readWrite will return immediately if
* fd is not ready for various reason (asynchrnous):
* - return -1, with errno = EINPROGRESS for connect
* - return -1, with errno = EAGAIN for netRead/netWrite,
*
* It is the role of the user to handle this behaviour.
*
* If you do not understand, use netDial.
* This will presently fail for ssl connections.
*/
NetSocket
netDial(char *server, int port, int opts) {
if (__USE_SSL(opts)) {
return __netDialTCP(server, port, opts);
} else {
return __netDialSSL(server, port, opts);
}
}
/*
* Write to a socket
*/
int
netWrite(NetSocket socket, char* payload, int size) {
int c;
if (socket.ssl != NULL) {
return SSL_write(socket.ssl, payload, size);
} else {
return write(socket.fd, payload, size);
}
}
NetSocket
netEmptySocket() {
NetSocket s = {NULL, NULL, NULL, -1, 0, 0};
return s;
}
/*
* Read from SSL/TCP socket.
*/
int
netRead(NetSocket socket, char* payload, int size) {
if (socket.ssl != NULL) {
return SSL_read(socket.ssl, payload, size);
} else {
return read(socket.fd, payload, size);
}
}
/*
* Close/Cleanup netsocket structure.
*/
NetSocket
netClose(NetSocket socket) {
NetSocket empty = netEmptySocket();
if (socket.fd > 0) {
close(socket.fd);
}
if (socket.ssl != NULL) {
SSL_free(socket.ssl);
}
if (socket.cert != NULL) {
X509_free(socket.cert);
}
if (socket.ctx != NULL) {
SSL_CTX_free(socket.ctx);
}
return empty;
}
/*
* Opts can be:
* - NET_TCP/NET_UDP
* - NET_SYNC/NET_ASYNC
* - NET_NOSSL/NET_SSL
*
* Default (0) is the same as NET_TCP | NET_SYNC | NET_NOSSL
*/
NetSocket
netAnnounce(char *server, int port, int opts) {
int n, proto;
struct sockaddr_in sa;
socklen_t sn;
uint32_t ip;
NetSocket netsocket = netEmptySocket();
if (__USE_UDP(opts)) {
proto = SOCK_DGRAM;
} else {
proto = SOCK_STREAM;
}
memset(&sa, 0, sizeof sa);
sa.sin_family = AF_INET;
if (server != ((void*) 0) && strcmp(server, "*") != 0) {
if (__hostLookup(server, &ip) < 0)
return netsocket;
memmove(&sa.sin_addr, &ip, 4);
}
sa.sin_port = htons(port);
if ((netsocket.fd = socket(AF_INET, proto, 0)) < 0) {
return netClose(netsocket);
}
/* set reuse flag for tcp */
if ((!__USE_UDP(opts)) && getsockopt(netsocket.fd, SOL_SOCKET, SO_TYPE,
(void*) &n, &sn) >= 0) {
n = 1;
setsockopt(netsocket.fd, SOL_SOCKET,
SO_REUSEADDR, (char*) &n, sizeof n);
}
if (bind(netsocket.fd, (struct sockaddr*) &sa, sizeof sa) < 0) {
return netClose(netsocket);
}
if (proto == SOCK_STREAM)
listen(netsocket.fd, 16);
if (__USE_ASYNC(opts)) {
if ((fcntl(netsocket.fd, F_SETFL,
fcntl(netsocket.fd, F_GETFL) | O_NONBLOCK)) < 0) {
return netClose(netsocket);
}
}
return netsocket;
}
NetSocket
netAccept(NetSocket net_socket, int opts) {
int cfd, one, fd, port;
struct sockaddr_in sa;
unsigned char *ip;
char remote[100];
socklen_t len;
fd = net_socket.fd;
NetSocket rsocket = netEmptySocket();
len = sizeof sa;
if ((cfd = accept(fd, (void*) &sa, &len)) < 0) {
return netClose(rsocket);
}
ip = (unsigned char *) & sa.sin_addr;
port = ntohs(sa.sin_port);
// printf("connexion from %s port %i", ip, port);
one = 1;
setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, (char*) &one, sizeof one);
rsocket.fd = cfd;
if (__USE_ASYNC(opts)) {
if ((fcntl(rsocket.fd, F_SETFL,
fcntl(rsocket.fd, F_GETFL) | O_NONBLOCK)) < 0) {
return netClose(rsocket);
}
}
return rsocket;
}
char*
netGetStatus(NetSocket net_socket) {
if (net_socket.status < 9) {
switch (net_socket.status) {
case SSL_ERROR_NONE:
return ssl_error_none;
break;
case SSL_ERROR_ZERO_RETURN:
return ssl_error_zero_return;
break;
case SSL_ERROR_WANT_READ:
return ssl_error_want_read;
break;
case SSL_ERROR_WANT_WRITE:
return ssl_error_want_write;
break;
case SSL_ERROR_WANT_ACCEPT:
return ssl_error_want_accept;
break;
case SSL_ERROR_WANT_CONNECT:
return ssl_error_want_connect;
break;
case SSL_ERROR_WANT_X509_LOOKUP:
return ssl_error_want_x509_lookup;
break;
case SSL_ERROR_SSL:
return ssl_error_ssl;
break;
}
}
return strerror(net_socket.status);
}
/*
* TODO serious url parser
*/
void
__parseUrl(char url_str[]) {
char hostname[256] = "";
char portnum[6] = "443";
char proto[6] = "";
char *tmp_ptr = NULL;
int port;
struct hostent *host;
struct sockaddr_in dest_addr;
/* ---------------------------------------------------------- *
* Remove the final / from url_str, if there is one *
* ---------------------------------------------------------- */
if (url_str[strlen(url_str)] == '/')
url_str[strlen(url_str)] = '\0';
/* ---------------------------------------------------------- *
* the first : ends the protocol string, i.e. http *
* ---------------------------------------------------------- */
strncpy(proto, url_str, (strchr(url_str, ':') - url_str));
/* ---------------------------------------------------------- *
* the hostname starts after the "://" part *
* ---------------------------------------------------------- */
strncpy(hostname, strstr(url_str, "://") + 3, sizeof (hostname));
/* ---------------------------------------------------------- *
* if the hostname contains a colon :, we got a port number *
* ---------------------------------------------------------- */
if (strchr(hostname, ':')) {
tmp_ptr = strchr(hostname, ':');
/* the last : starts the port number, if avail, i.e. 8443 */
strncpy(portnum, tmp_ptr + 1, sizeof (portnum));
*tmp_ptr = '\0';
}
}
int
__parseIP(char *name, uint32_t *ip) {
unsigned char addr[4];
char *p;
int i, x;
p = name;
for (i = 0; i < 4 && *p; i++) {
x = strtoul(p, &p, 0);
if (x < 0 || x >= 256)
return -1;
if (*p != '.' && *p != 0)
return -1;
if (*p == '.')
p++;
addr[i] = x;
}
switch (CLASS(addr)) {
case 0:
case 1:
if (i == 3) {
addr[3] = addr[2];
addr[2] = addr[1];
addr[1] = 0;
} else if (i == 2) {
addr[3] = addr[1];
addr[2] = 0;
addr[1] = 0;
} else if (i != 4)
return -1;
break;
case 2:
if (i == 3) {
addr[3] = addr[2];
addr[2] = 0;
} else if (i != 4)
return -1;
break;
}
*ip = *(uint32_t*) addr;
return 0;
}
int
__hostLookup(char *name, uint32_t *ip) {
struct hostent *he;
if (__parseIP(name, ip) >= 0)
return 0;
if ((he = gethostbyname(name)) != 0) {
*ip = *(uint32_t*) he->h_addr_list[0];
return 0;
}
return -1;
}
/*
* Opts can be:
* - NET_TCP/NET_UDP
* - NET_SYNC/NET_ASYNC
* - NET_NOSSL/NET_SSL
*
* Default (0) is the same as NET_TCP | NET_SYNC | NET_NOSSL
*/
NetSocket
__netDialSSL(char *server, int port, int opts) {
int proto, n;
uint32_t ip;
struct sockaddr_in sa;
socklen_t sn;
NetSocket net_socket = netEmptySocket();
if (__hostLookup(server, &ip) < 0) {
return netClose(net_socket);
}
if (__USE_UDP(opts)) {
proto = SOCK_DGRAM;
} else {
proto = SOCK_STREAM;
}
if ((net_socket.fd = socket(AF_INET, proto, 0)) < 0) {
return netClose(net_socket);
}
/* for udp */
if (__USE_UDP(opts)) {
n = 1;
setsockopt(net_socket.fd, SOL_SOCKET, SO_BROADCAST, &n, sizeof n);
}
/* maybe async */
if (__USE_ASYNC(opts))
if ((fcntl(net_socket.fd, F_SETFL,
fcntl(net_socket.fd, F_GETFL) | O_NONBLOCK)) < 0)
return netClose(net_socket);
/* start connecting */
memset(&sa, 0, sizeof sa);
memmove(&sa.sin_addr, &ip, 4);
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
if (connect(net_socket.fd, (struct sockaddr*) &sa, sizeof sa) < 0
&& errno != EINPROGRESS)
return netClose(net_socket);
sn = sizeof sa;
if (getpeername(net_socket.fd, (struct sockaddr*) &sa, &sn) >= 0)
return net_socket;
/* report error */
sn = sizeof n;
getsockopt(net_socket.fd, SOL_SOCKET, SO_ERROR, (void*) &n, &sn);
if (n == 0)
n = ECONNREFUSED;
errno = n;
return netClose(net_socket);
}
NetSocket
__netDialTCP(char *server, int port, int opts) {
int err, err2;
BIO *certbio = NULL;
const SSL_METHOD *method;
NetSocket socket = netEmptySocket();
NetSocket tcpsocket = netEmptySocket();
/* ---------------------------------------------------------- *
* These function calls initialize openssl for correct work. *
* ---------------------------------------------------------- */
OpenSSL_add_all_algorithms();
ERR_load_BIO_strings();
ERR_load_crypto_strings();
SSL_load_error_strings();
/* ---------------------------------------------------------- *
* Create the Input/Output BIO's. *
* ---------------------------------------------------------- */
certbio = BIO_new(BIO_s_file());
/* ---------------------------------------------------------- *
* initialize SSL library and register algorithms *
* ---------------------------------------------------------- */
if (SSL_library_init() < 0) {
return netClose(socket);
}
/* ---------------------------------------------------------- *
* Set SSLv2 client hello, also announce SSLv3 and TLSv1 *
* ---------------------------------------------------------- */
method = SSLv23_client_method();
/* ---------------------------------------------------------- *
* Try to create a new SSL context *
* ---------------------------------------------------------- */
if ((socket.ctx = SSL_CTX_new(method)) == NULL) {
return netClose(socket);
}
/* ---------------------------------------------------------- *
* Disabling SSLv2 will leave v3 and TSLv1 for negotiation *
* ---------------------------------------------------------- */
SSL_CTX_set_options(socket.ctx, SSL_OP_NO_SSLv2);
/* ---------------------------------------------------------- *
* Create new SSL connection state object *
* ---------------------------------------------------------- */
socket.ssl = SSL_new(socket.ctx);
/* ---------------------------------------------------------- *
* Make the underlying TCP socket connection *
* ---------------------------------------------------------- */
tcpsocket = __netDialSSL(server, port, opts);
socket.fd = tcpsocket.fd;
if (socket.fd < 0)
return netClose(socket);
/* ---------------------------------------------------------- *
* Attach the SSL session to the socket descriptor *
* ---------------------------------------------------------- */
SSL_set_fd(socket.ssl, socket.fd);
/* ---------------------------------------------------------- *
* Try to SSL-connect here, returns 1 for success *
* ---------------------------------------------------------- */
if ((err = SSL_connect(socket.ssl)) != 1) {
if ((err2 = SSL_get_error(socket.ssl, err)) != SSL_ERROR_SYSCALL)
errno = err2;
return netClose(socket);
}
/* ---------------------------------------------------------- *
* Get the remote certificate into the X509 structure *
* ---------------------------------------------------------- */
if ((socket.cert = SSL_get_peer_certificate(socket.ssl)) == NULL)
return netClose(socket);
return socket;
}
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // NET_H