-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathnopoll_conn.c
More file actions
4963 lines (4310 loc) · 168 KB
/
nopoll_conn.c
File metadata and controls
4963 lines (4310 loc) · 168 KB
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* LibNoPoll: A websocket library
* Copyright (C) 2017 Advanced Software Production Line, S.L.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*
* You may find a copy of the license under this software is released
* at COPYING file. This is LGPL software: you are welcome to develop
* proprietary applications using this library without any royalty or
* fee but returning back any change, improvement or addition in the
* form of source code, project image, documentation patches, etc.
*
* For commercial support on build Websocket enabled solutions
* contact us:
*
* Postal address:
* Advanced Software Production Line, S.L.
* Av. Juan Carlos I, Nº13, 2ºC
* Alcalá de Henares 28806 Madrid
* Spain
*
* Email address:
* [email protected] - http://www.aspl.es/nopoll
*/
/**
* \defgroup nopoll_conn noPoll Connection: functions required to create WebSocket client connections.
*/
/**
* \addtogroup nopoll_conn
* @{
*/
#include <nopoll_conn.h>
#include <nopoll_private.h>
#if defined(NOPOLL_OS_UNIX)
# include <netinet/tcp.h>
#endif
/**
* @brief Allows to enable/disable non-blocking/blocking behavior on
* the provided socket.
*
* @param socket The socket to be configured.
*
* @param enable nopoll_true to enable blocking I/O, otherwise use
* nopoll_false to enable non blocking I/O.
*
* @return nopoll_true if the operation was properly done, otherwise
* nopoll_false is returned.
*/
nopoll_bool nopoll_conn_set_sock_block (NOPOLL_SOCKET socket,
nopoll_bool enable)
{
#if defined(NOPOLL_OS_UNIX)
int flags;
#endif
if (enable) {
/* enable blocking mode */
#if defined(NOPOLL_OS_WIN32)
if (!nopoll_win32_blocking_enable (socket)) {
return nopoll_false;
}
#else
if ((flags = fcntl (socket, F_GETFL, 0)) < -1) {
return nopoll_false;
} /* end if */
flags &= ~O_NONBLOCK;
if (fcntl (socket, F_SETFL, flags) < -1) {
return nopoll_false;
} /* end if */
#endif
} else {
/* enable nonblocking mode */
#if defined(NOPOLL_OS_WIN32)
/* win32 case */
if (!nopoll_win32_nonblocking_enable (socket)) {
return nopoll_false;
}
#else
/* unix case */
if ((flags = fcntl (socket, F_GETFL, 0)) < -1) {
return nopoll_false;
}
flags |= O_NONBLOCK;
if (fcntl (socket, F_SETFL, flags) < -1) {
return nopoll_false;
}
#endif
} /* end if */
return nopoll_true;
}
/**
* @brief Allows to get current timeout set for \ref noPollConn
* connect operation.
*
* See also \ref nopoll_conn_connect_timeout.
*
* @return Current timeout configured. Returned value is measured in
* microseconds (1 second = 1000000 microseconds). If a null value is
* received, 0 is return and no timeout is implemented.
*/
long nopoll_conn_get_connect_timeout (noPollCtx * ctx)
{
/* check context recevied */
if (ctx == NULL) {
/* get the the default connect */
return (0);
} /* end if */
/* return current value */
return ctx->conn_connect_std_timeout;
}
/**
* @brief Allows to configure nopoll connect timeout.
*
* This function allows to set the TCP connect timeout used by \ref
* nopoll_conn_new.
*
* @param ctx The context where the operation will be performed.
*
* @param microseconds_to_wait Timeout value to be used. The value
* provided is measured in microseconds. Use 0 to restore the connect
* timeout to the default value.
*/
void nopoll_conn_connect_timeout (noPollCtx * ctx,
long microseconds_to_wait)
{
/* check reference received */
if (ctx == NULL)
return;
/* configure new value */
ctx->conn_connect_std_timeout = microseconds_to_wait;
return;
}
/**
* @brief Allows to configure tcp no delay flag (enable/disable Nagle
* algorithm).
*
* @param socket The socket to be configured.
*
* @param enable The value to be configured, nopoll_true to enable tcp no
* delay.
*
* @return nopoll_true if the operation is completed.
*/
nopoll_bool nopoll_conn_set_sock_tcp_nodelay (NOPOLL_SOCKET socket,
nopoll_bool enable)
{
/* local variables */
int result;
#if defined(NOPOLL_OS_WIN32)
BOOL flag = enable ? TRUE : FALSE;
result = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(BOOL));
#else
int flag = enable;
result = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof (flag));
#endif
if (result == NOPOLL_INVALID_SOCKET) {
return nopoll_false;
}
/* properly configured */
return nopoll_true;
} /* end */
/**
* @brief Allows to configure which network interface to bind to.
*
* @param socket The socket to be configured.
*
* @param options The options defining the interface value to be configured.
*
* @return nopoll_true if the operation is completed.
*/
nopoll_bool nopoll_conn_set_bind_interface (NOPOLL_SOCKET socket,
noPollConnOpts * options)
{
/* no local variable here please */
if ((NULL != options) && (NULL != options->_interface)) {
#if defined(NOPOLL_OS_WIN32) || defined(NOPOLL_OS_WIN64)
/* Windows still not supported: send us a patch! */
return nopoll_false;
#elif defined(__APPLE__) || defined(__FreeBSD__)
/* Mac/OSX: that supports */
/* bind to the interface */
return setsockopt (socket, SOL_SOCKET, IP_RECVIF,
options->_interface, strlen(options->_interface) ) == 0;
#else
/* Linux/Unix case: that supports SO_BINDTODEVICE */
/* bind to the interface */
return setsockopt (socket, SOL_SOCKET, SO_BINDTODEVICE,
options->_interface, strlen (options->_interface) ) == 0;
#endif
}
/* properly configured */
return nopoll_true;
} /* end */
NOPOLL_SOCKET __nopoll_conn_sock_connect_opts_internal (noPollCtx * ctx,
noPollTransport transport,
const char * host,
const char * port,
noPollConnOpts * options)
{
struct addrinfo hints, *res = NULL;
NOPOLL_SOCKET session = NOPOLL_INVALID_SOCKET;
/* clear hints structure */
memset (&hints, 0, sizeof(struct addrinfo));
switch (transport) {
case NOPOLL_TRANSPORT_IPV4:
/* configure hints */
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
/* resolve hosting name */
if (getaddrinfo (host, port, &hints, &res) != 0) {
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "unable to resolve host name %s, errno=%d", host, errno);
return -1;
} /* end if */
/* create the socket and check if it */
session = socket (AF_INET, SOCK_STREAM, 0);
break;
case NOPOLL_TRANSPORT_IPV6:
/* configure hints */
hints.ai_family = AF_INET6;
hints.ai_socktype = SOCK_STREAM;
/* resolve hosting name */
if (getaddrinfo (host, port, &hints, &res) != 0) {
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "unable to resolve host name %s, errno=%d", host, errno);
return -1;
} /* end if */
/* create the socket and check if it */
session = socket (AF_INET6, SOCK_STREAM, 0);
break;
} /* end switch */
if (session == NOPOLL_INVALID_SOCKET) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "unable to create socket");
/* relase address info */
freeaddrinfo (res);
return -1;
} /* end if */
/* disable nagle */
nopoll_conn_set_sock_tcp_nodelay (session, nopoll_true);
/* bind to specified interface */
if( nopoll_true != nopoll_conn_set_bind_interface (session, options) ) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "unable to bind to specified interface");
nopoll_close_socket (session);
/* relase address info */
freeaddrinfo (res);
return -1;
} /* end if */
/* set non blocking status */
nopoll_conn_set_sock_block (session, nopoll_false);
/* do a tcp connect */
if (connect (session, res->ai_addr, res->ai_addrlen) < 0) {
if(errno != NOPOLL_EINPROGRESS && errno != NOPOLL_EWOULDBLOCK && errno != NOPOLL_ENOTCONN) {
shutdown (session, SHUT_RDWR);
nopoll_close_socket (session);
nopoll_log (ctx, NOPOLL_LEVEL_WARNING, "unable to connect to remote host %s:%s errno=%d",
host, port, errno);
/* relase address info */
freeaddrinfo (res);
return -1;
} /* end if */
} /* end if */
/* relase address info */
freeaddrinfo (res);
/* return socket created */
return session;
}
/**
* @internal Allows to create a plain socket connection against the
* host and port provided.
*
* @param ctx The context where the connection happens.
*
* @param host The host server to connect to.
*
* @param port The port server to connect to.
*
* @param options The connection options to apply.
*
* @return A connected socket or -1 if it fails.
*/
NOPOLL_SOCKET nopoll_conn_sock_connect_opts (noPollCtx * ctx,
const char * host,
const char * port,
noPollConnOpts * options)
{
return __nopoll_conn_sock_connect_opts_internal (ctx, NOPOLL_TRANSPORT_IPV4, host, port, options);
}
/**
* @internal Allows to create a plain socket connection against the
* host and port provided.
*
* @param ctx The context where the connection happens.
*
* @param host The host server to connect to.
*
* @param port The port server to connect to.
*
* @return A connected socket or -1 if it fails.
*/
NOPOLL_SOCKET nopoll_conn_sock_connect (noPollCtx * ctx,
const char * host,
const char * port)
{
return nopoll_conn_sock_connect_opts (ctx, host, port, NULL);
}
/**
* @internal Function that builds the client init greetings that will
* be send to the server according to registered implementation.
*/
char * __nopoll_conn_get_client_init (noPollConn * conn, noPollConnOpts * opts)
{
/* build sec-websocket-key */
char key[50];
int key_size = 50;
char nonce[17];
/* get the nonce */
if (! nopoll_nonce (nonce, 16)) {
nopoll_log (conn->ctx, NOPOLL_LEVEL_CRITICAL, "Failed to get nonce, unable to produce Sec-WebSocket-Key.");
return NULL;
} /* end if */
/* now base 64 */
if (! nopoll_base64_encode (nonce, 16, key, &key_size)) {
nopoll_log (conn->ctx, NOPOLL_LEVEL_CRITICAL, "Unable to base 64 encode characters for Sec-WebSocket-Key");
return NULL;
}
nopoll_log (conn->ctx, NOPOLL_LEVEL_DEBUG, "Created Sec-WebSocket-Key nonce: %s", key);
/* create accept and store */
conn->handshake = nopoll_new (noPollHandShake, 1);
conn->handshake->expected_accept = nopoll_strdup (key);
/* send initial handshake */
return nopoll_strdup_printf ("GET %s HTTP/1.1"
"\r\nHost: %s"
"\r\nUpgrade: websocket"
"\r\nConnection: Upgrade"
"\r\nSec-WebSocket-Key: %s"
"\r\nSec-WebSocket-Version: %d"
"\r\nOrigin: %s"
"%s%s" /* Cookie */
"%s%s" /* protocol part */
"%s" /* extra arbitrary headers */
"\r\n\r\n",
conn->get_url,
conn->host_name,
/* sec-websocket-key */
key,
/* sec-websocket-version */
conn->ctx->protocol_version,
/* Origin */
conn->origin,
/* Cookie */
(opts && opts->cookie) ? "\r\nCookie: " : "",
(opts && opts->cookie) ? opts->cookie : "",
/* protocol part */
conn->protocols ? "\r\nSec-WebSocket-Protocol: " : "",
conn->protocols ? conn->protocols : "",
/* extra arbitrary headers */
(opts && opts->extra_headers) ? opts->extra_headers : "");
}
/**
* @internal Function that dumps all errors found on current ssl context.
*
* @return Always returns 0
*/
int nopoll_conn_log_ssl (noPollConn * conn)
{
#if defined(SHOW_DEBUG_LOG)
noPollCtx * ctx = conn->ctx;
#endif
char log_buffer [512];
unsigned long err;
int error_position;
int aux_position;
while ((err = ERR_get_error()) != 0) {
/* clear buffer */
memset (log_buffer, 0, 512);
/* dump error */
ERR_error_string_n (err, log_buffer, sizeof (log_buffer));
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "tls stack: err=%d, %s (find reason(code) at openssl/ssl.h)", err, log_buffer);
/* Check for recoverable errors:
* - openssl errstr 1409442E :: error:1409442E:SSL routines:SSL3_READ_BYTES:tlsv1 alert protocol version
*/
if (strstr (log_buffer, "1409442E"))
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "tls stack: err=%d, %s :: found TLS mismatch (peers running different TLS versions)", err, log_buffer);
/* find error code position */
error_position = 0;
while (log_buffer[error_position] != ':' && log_buffer[error_position] != 0 && error_position < 511)
error_position++;
error_position++;
aux_position = error_position;
while (log_buffer[aux_position] != 0) {
if (log_buffer[aux_position] == ':') {
log_buffer[aux_position] = 0;
break;
}
aux_position++;
} /* end while */
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, " details, run: openssl errstr %s", log_buffer + error_position);
}
recv (conn->session, log_buffer, 1, MSG_PEEK);
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, " noPoll id=%d, socket: %d (after testing errno: %d)",
conn->id, conn->session, errno);
return (0);
}
int __nopoll_conn_tls_handle_error (noPollConn * conn, int res, const char * label, nopoll_bool * needs_retry)
{
int ssl_err;
(*needs_retry) = nopoll_false;
/* get error returned */
ssl_err = SSL_get_error (conn->ssl, res);
switch (ssl_err) {
case SSL_ERROR_NONE:
/* no error, return the number of bytes read */
/* nopoll_log (conn->ctx, NOPOLL_LEVEL_DEBUG, "%s, ssl_err=%d, perfect, no error reported, bytes read=%d",
label, ssl_err, res); */
return res;
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_X509_LOOKUP:
nopoll_log (conn->ctx, NOPOLL_LEVEL_DEBUG, "%s, ssl_err=%d returned that isn't ready to read/write: you should retry",
label, ssl_err);
(*needs_retry) = nopoll_true;
return -2;
case SSL_ERROR_SYSCALL:
if(res < 0) { /* not EOF */
if(errno == NOPOLL_EINTR) {
nopoll_log (conn->ctx, NOPOLL_LEVEL_DEBUG, "%s interrupted by a signal: retrying", label);
/* report to retry */
return -2;
}
nopoll_log (conn->ctx, NOPOLL_LEVEL_WARNING, "SSL_read (SSL_ERROR_SYSCALL)");
return -1;
}
nopoll_log (conn->ctx, NOPOLL_LEVEL_CRITICAL, "SSL socket closed on %s (res=%d, ssl_err=%d, errno=%d)",
label, res, ssl_err, errno);
nopoll_conn_log_ssl (conn);
return res;
case SSL_ERROR_ZERO_RETURN: /* close_notify received */
nopoll_log (conn->ctx, NOPOLL_LEVEL_DEBUG, "SSL closed on %s", label);
return res;
case SSL_ERROR_SSL:
nopoll_log (conn->ctx, NOPOLL_LEVEL_WARNING, "%s function error (received SSL_ERROR_SSL) (res=%d, ssl_err=%d, errno=%d)",
label, res, ssl_err, errno);
nopoll_conn_log_ssl (conn);
return -1;
default:
/* nothing to handle */
break;
}
nopoll_log (conn->ctx, NOPOLL_LEVEL_WARNING, "%s/SSL_get_error returned %d", label, res);
return -1;
}
/**
* @internal Default connection receive until handshake is complete.
*/
int nopoll_conn_tls_receive (noPollConn * conn, char * buffer, int buffer_size)
{
int res;
nopoll_bool needs_retry;
/* call to read content */
res = SSL_read (conn->ssl, buffer, buffer_size);
/* nopoll_log (conn->ctx, NOPOLL_LEVEL_DEBUG, "SSL: received %d bytes..", res); */
/* call to handle error */
res = __nopoll_conn_tls_handle_error (conn, res, "SSL_read", &needs_retry);
/* nopoll_log (conn->ctx, NOPOLL_LEVEL_DEBUG, " SSL: after procesing error %d bytes..", res); */
if (res == -2) {
#if defined(NOPOLL_OS_UNIX)
errno = NOPOLL_EWOULDBLOCK;
#elif defined(NOPOLL_OS_WIN32)
WSASetLastError(NOPOLL_EWOULDBLOCK);
#endif
}
return res;
}
/**
* @internal Default connection send until handshake is complete.
*/
int nopoll_conn_tls_send (noPollConn * conn, char * buffer, int buffer_size)
{
int res;
nopoll_bool needs_retry;
/* call to read content */
res = SSL_write (conn->ssl, buffer, buffer_size);
nopoll_log (conn->ctx, NOPOLL_LEVEL_DEBUG, "SSL: sent %d bytes (requested: %d)..", res, buffer_size);
/* call to handle error */
res = __nopoll_conn_tls_handle_error (conn, res, "SSL_write", &needs_retry);
/* nopoll_log (conn->ctx, NOPOLL_LEVEL_DEBUG, " SSL: after processing error, sent %d bytes (requested: %d)..", res, buffer_size); */
if (res == -2) {
#if defined(NOPOLL_OS_UNIX)
errno = NOPOLL_EWOULDBLOCK;
#elif defined(NOPOLL_OS_WIN32)
WSASetLastError(NOPOLL_EWOULDBLOCK);
#endif
}
return res;
}
SSL_CTX * __nopoll_conn_get_ssl_context (noPollCtx * ctx, noPollConn * conn, noPollConnOpts * opts, nopoll_bool is_client)
{
/* call to user defined function if the context creator is defined */
if (ctx && ctx->context_creator)
return ctx->context_creator (ctx, conn, opts, is_client, ctx->context_creator_data);
if (opts == NULL) {
/* select a default mechanism according to what's
* available: ORDER IS IMPORTANT: make it select first
* strong methods over weak/old methods */
#if defined(NOPOLL_HAVE_TLS_FLEXIBLE_ENABLED)
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "choosing default tls-method=flexible conn-id=%d", conn->id);
/* flexible method */
return SSL_CTX_new (is_client ? TLS_client_method () : TLS_server_method ());
#elif defined(NOPOLL_HAVE_TLSv12_ENABLED) && OPENSSL_VERSION_NUMBER < 0x10100000L
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "choosing default tls-method=tlsv1.2 conn-id=%d", conn->id);
/* if not use TLSv1.2 */
return SSL_CTX_new (is_client ? TLSv1_2_client_method () : TLSv1_2_server_method ());
#elif defined(NOPOLL_HAVE_TLSv11_ENABLED) && OPENSSL_VERSION_NUMBER < 0x10100000L
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "choosing default tls-method=tlsv1.1 conn-id=%d", conn->id);
/* if not use TLSv1.1 */
return SSL_CTX_new (is_client ? TLSv1_1_client_method () : TLSv1_1_server_method ());
#elif defined(NOPOLL_HAVE_TLSv10_ENABLED) && OPENSSL_VERSION_NUMBER < 0x10100000L
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "choosing default tls-method=tlsv1.0 conn-id=%d", conn->id);
/* by default use TLSv1.0 */
return SSL_CTX_new (is_client ? TLSv1_client_method () : TLSv1_server_method ());
#elif defined(NOPOLL_HAVE_SSLv3_ENABLED) && OPENSSL_VERSION_NUMBER < 0x10100000L
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "choosing default tls-method=sslv3 conn-id=%d", conn->id);
/* if not use SSLv3 */
return SSL_CTX_new (is_client ? SSLv3_client_method () : SSLv3_server_method ());
#elif defined(NOPOLL_HAVE_SSLv23_ENABLED) && OPENSSL_VERSION_NUMBER < 0x10100000L
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "choosing default tls-method=sslv23 conn-id=%d", conn->id);
/* if not use SSLv23 */
return SSL_CTX_new (is_client ? SSLv23_client_method () : SSLv23_server_method ());
#else
/* no default method found */
return NULL;
#endif
} /* end if */
switch (opts->ssl_protocol) {
#if defined(NOPOLL_HAVE_TLS_FLEXIBLE_ENABLED)
case NOPOLL_METHOD_TLS_FLEXIBLE:
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "choosing tls-method=flexible conn-id=%d", conn->id);
return SSL_CTX_new (is_client ? TLS_client_method () : TLS_server_method ());
#endif
#if defined(NOPOLL_HAVE_TLSv10_ENABLED) && OPENSSL_VERSION_NUMBER < 0x10100000L
case NOPOLL_METHOD_TLSV1:
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "choosing tls-method=tlsv1.0 conn-id=%d", conn->id);
return SSL_CTX_new (is_client ? TLSv1_client_method () : TLSv1_server_method ());
#endif
#if defined(NOPOLL_HAVE_TLSv11_ENABLED) && OPENSSL_VERSION_NUMBER < 0x10100000L
case NOPOLL_METHOD_TLSV1_1:
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "choosing tls-method=tlsv1.1 conn-id=%d", conn->id);
return SSL_CTX_new (is_client ? TLSv1_1_client_method () : TLSv1_1_server_method ());
#endif
#if defined(NOPOLL_HAVE_TLSv12_ENABLED) && OPENSSL_VERSION_NUMBER < 0x10100000L
case NOPOLL_METHOD_TLSV1_2:
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "choosing tls-method=tlsv1.2 conn-id=%d", conn->id);
return SSL_CTX_new (is_client ? TLSv1_2_client_method () : TLSv1_2_server_method ());
#endif
#if defined(NOPOLL_HAVE_SSLv3_ENABLED) && OPENSSL_VERSION_NUMBER < 0x10100000L
case NOPOLL_METHOD_SSLV3:
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "choosing tls-method=sslv3 conn-id=%d", conn->id);
return SSL_CTX_new (is_client ? SSLv3_client_method () : SSLv3_server_method ());
#endif
#if defined(NOPOLL_HAVE_SSLv23_ENABLED) && OPENSSL_VERSION_NUMBER < 0x10100000L
case NOPOLL_METHOD_SSLV23:
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "choosing tls-method=sslv23 conn-id=%d", conn->id);
return SSL_CTX_new (is_client ? SSLv23_client_method () : SSLv23_server_method ());
#endif
default:
/* default case */
#if defined(NOPOLL_HAVE_TLS_FLEXIBLE_ENABLED)
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "choosing default tls-method=flexible conn-id=%d", conn->id);
return SSL_CTX_new (is_client ? TLS_client_method () : TLS_server_method ());
#else
return NULL;
#endif
}
#if defined(NOPOLL_HAVE_TLSv10_ENABLED) && OPENSSL_VERSION_NUMBER < 0x10100000L
/* reached this point, report default TLSv1 method */
return SSL_CTX_new (is_client ? TLSv1_client_method () : TLSv1_server_method ());
#else
return NULL;
#endif
}
noPollCtx * __nopoll_conn_ssl_ctx_debug = NULL;
int __nopoll_conn_ssl_verify_callback (int ok, X509_STORE_CTX * store) {
char data[256];
X509 * cert;
#if defined(SHOW_DEBUG_LOG)
int depth;
int err;
#endif
if (! ok) {
cert = X509_STORE_CTX_get_current_cert (store);
#if defined(SHOW_DEBUG_LOG)
depth = X509_STORE_CTX_get_error_depth (store);
err = X509_STORE_CTX_get_error (store);
#endif
nopoll_log (__nopoll_conn_ssl_ctx_debug, NOPOLL_LEVEL_CRITICAL, "CERTIFICATE: error=%d at depth: %d", err, depth);
X509_NAME_oneline (X509_get_issuer_name (cert), data, 256);
nopoll_log (__nopoll_conn_ssl_ctx_debug, NOPOLL_LEVEL_CRITICAL, "CERTIFICATE: issuer: %s", data);
X509_NAME_oneline (X509_get_subject_name (cert), data, 256);
nopoll_log (__nopoll_conn_ssl_ctx_debug, NOPOLL_LEVEL_CRITICAL, "CERTIFICATE: subject: %s", data);
nopoll_log (__nopoll_conn_ssl_ctx_debug, NOPOLL_LEVEL_CRITICAL, "CERTIFICATE: error %d:%s", err, X509_verify_cert_error_string (err));
}
return ok; /* return same value */
}
nopoll_bool __nopoll_conn_set_ssl_client_options (noPollCtx * ctx, noPollConn * conn, noPollConnOpts * options)
{
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "Checking to establish SSL options (%p)", options);
if (options && options->ca_certificate) {
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "Setting CA certificate: %s", options->ca_certificate);
if (SSL_CTX_load_verify_locations (conn->ssl_ctx, options->ca_certificate, NULL) != 1) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "Failed to configure CA certificate (%s), SSL_CTX_load_verify_locations () failed", options->ca_certificate);
return nopoll_false;
} /* end if */
} /* end if */
/* enable default verification paths */
/* printf ("conn = %p, conn->ssl_ctx = %p\n", conn, conn->ssl_ctx); */
if (SSL_CTX_set_default_verify_paths (conn->ssl_ctx) != 1) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "Unable to configure default verification paths, SSL_CTX_set_default_verify_paths () failed");
return nopoll_false;
} /* end if */
if (options && options->chain_certificate) {
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "Setting chain certificate: %s", options->chain_certificate);
if (SSL_CTX_use_certificate_chain_file (conn->ssl_ctx, options->chain_certificate) != 1) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "Failed to configure chain certificate (%s), SSL_CTX_use_certificate_chain_file () failed", options->chain_certificate);
return nopoll_false;
} /* end if */
} /* end if */
if (options && options->certificate) {
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "Setting certificate: %s", options->certificate);
if (SSL_CTX_use_certificate_chain_file (conn->ssl_ctx, options->certificate) != 1) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "Failed to configure client certificate (%s), SSL_CTX_use_certificate_file () failed", options->certificate);
return nopoll_false;
} /* end if */
} /* end if */
if (options && options->private_key) {
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "Setting private key: %s", options->private_key);
if (SSL_CTX_use_PrivateKey_file (conn->ssl_ctx, options->private_key, SSL_FILETYPE_PEM) != 1) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "Failed to configure private key (%s), SSL_CTX_use_PrivateKey_file () failed", options->private_key);
return nopoll_false;
} /* end if */
} /* end if */
if (options && options->private_key && options->certificate) {
if (!SSL_CTX_check_private_key (conn->ssl_ctx)) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "Certificate and private key do not matches, verification fails, SSL_CTX_check_private_key ()");
return nopoll_false;
} /* end if */
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "Certificate (%s) and private key (%s) matches", options->certificate, options->private_key);
} /* end if */
/* if no option and it is not disabled */
if (options == NULL || ! options->disable_ssl_verify) {
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "Enabling certificate peer verification");
/** really, really ugly hack to let
* __nopoll_conn_ssl_verify_callback to be able to get
* access to the context required to drop some logs */
__nopoll_conn_ssl_ctx_debug = ctx;
SSL_CTX_set_verify (conn->ssl_ctx, SSL_VERIFY_PEER, __nopoll_conn_ssl_verify_callback);
SSL_CTX_set_verify_depth (conn->ssl_ctx, 10);
} /* end if */
return nopoll_true;
}
/**
* @internal Internal implementation used to do a connect.
*/
noPollConn * __nopoll_conn_new_common (noPollCtx * ctx,
noPollConnOpts * options,
noPollTransport transport,
nopoll_bool enable_tls,
int socket,
const char * host_ip,
const char * host_port,
const char * host_name,
const char * get_url,
const char * protocols,
const char * origin)
{
noPollConn * conn;
NOPOLL_SOCKET session;
char * content;
int size;
int ssl_error;
X509 * server_cert;
int iterator;
long remaining_timeout;
if (! ctx || ! host_ip) {
/* release connection options */
__nopoll_conn_opts_release_if_needed (options);
return NULL;
} /* end if */
/* set default connection port */
if (host_port == NULL)
host_port = "80";
session = socket;
/* create socket connection in a non block manner */
if (session == NOPOLL_INVALID_SOCKET)
session = __nopoll_conn_sock_connect_opts_internal (ctx, transport, host_ip, host_port, options);
if (session == NOPOLL_INVALID_SOCKET) {
/* release connection options */
__nopoll_conn_opts_release_if_needed (options);
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "Failed to connect to remote host %s:%s", host_ip, host_port);
return NULL;
} /* end if */
/* create the connection */
conn = nopoll_new (noPollConn, 1);
if (conn == NULL) {
/* release connection options */
__nopoll_conn_opts_release_if_needed (options);
return NULL;
} /* end if */
conn->refs = 1;
/* create mutexes */
conn->ref_mutex = nopoll_mutex_create ();
conn->handshake_mutex = nopoll_mutex_create ();
/* register connection into context */
if (! nopoll_ctx_register_conn (ctx, conn)) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "Failed to register connection into the context, unable to create connection");
nopoll_free (conn);
/* release connection options */
__nopoll_conn_opts_release_if_needed (options);
return NULL;
}
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "Created noPoll conn-id=%d (ptr: %p, context: %p, socket: %d)",
conn->id, conn, ctx, session);
/* configure context */
conn->ctx = ctx;
conn->session = session;
conn->role = NOPOLL_ROLE_CLIENT;
/* record host and port */
conn->host = nopoll_strdup (host_ip);
conn->port = nopoll_strdup (host_port);
/* configure default handlers */
conn->receive = nopoll_conn_default_receive;
conn->send = nopoll_conn_default_send;
/* build host name */
if (host_name == NULL)
conn->host_name = nopoll_strdup (host_ip);
else
conn->host_name = nopoll_strdup (host_name);
/* build origin */
if (origin == NULL)
conn->origin = nopoll_strdup_printf ("http://%s", conn->host_name);
else
conn->origin = nopoll_strdup (origin);
/* get url */
if (get_url == NULL)
conn->get_url = nopoll_strdup ("/");
else
conn->get_url = nopoll_strdup (get_url);
/* protocols */
if (protocols != NULL)
conn->protocols = nopoll_strdup (protocols);
/* default to no close frame received */
conn->peer_close_status = 1006;
/* get client init payload */
content = __nopoll_conn_get_client_init (conn, options);
if (content == NULL) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "Failed to build client init message, unable to connect");
nopoll_conn_shutdown (conn);
/* release connection options */
__nopoll_conn_opts_release_if_needed (options);
return NULL;
} /* end if */
/* check for TLS support */
if (enable_tls) {
/* found TLS connection request, enable it */
conn->ssl_ctx = __nopoll_conn_get_ssl_context (ctx, conn, options, nopoll_true);
if (conn->ssl_ctx == NULL) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "Unable to enable TLS, internal __nopoll_conn_get_ssl_context (ctx=%p, conn=%p, options=%p, nopoll_true) failed",
ctx, conn, options);
goto fail_ssl_connection;
} /* end if */
/* check for client side SSL configuration */
if (! __nopoll_conn_set_ssl_client_options (ctx, conn, options)) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "Unable to configure additional SSL options, unable to continue, conn->ssl_ctx=%p, conn->ssl=%p",
conn->ssl_ctx, conn->ssl);
goto fail_ssl_connection;
} /* end if */
/* create context and check for result */
conn->ssl = SSL_new (conn->ssl_ctx);
if (conn->ssl_ctx == NULL || conn->ssl == NULL) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "Unable to create SSL context internal references are null (conn->ssl_ctx=%p, conn->ssl=%p)",
conn->ssl_ctx, conn->ssl);
fail_ssl_connection:
nopoll_free (content);
nopoll_conn_shutdown (conn);
/* release connection options */
__nopoll_conn_opts_release_if_needed (options);
return conn;
} /* end if */
/* set socket */
SSL_set_fd (conn->ssl, conn->session);
/* do the initial connect connect */
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "connecting to remote TLS site %s:%s", conn->host, conn->port);
iterator = 0;
while (SSL_connect (conn->ssl) <= 0) {
/* get ssl error */
ssl_error = SSL_get_error (conn->ssl, -1);
switch (ssl_error) {
case SSL_ERROR_WANT_READ:
nopoll_log (ctx, NOPOLL_LEVEL_WARNING, "still not prepared to continue because read wanted, conn-id=%d (%p, session: %d), errno=%d",
conn->id, conn, conn->session, errno);
break;
case SSL_ERROR_WANT_WRITE:
nopoll_log (ctx, NOPOLL_LEVEL_WARNING, "still not prepared to continue because write wanted, conn-id=%d (%p)",
conn->id, conn);
break;
case SSL_ERROR_SYSCALL:
/* Check ENOTCONN on SSL_connect error (only happening on windows). See:
* https://github.com/ASPLes/nopoll/pull/19
*/
if (errno == NOPOLL_ENOTCONN) {
nopoll_log (ctx, NOPOLL_LEVEL_DEBUG, "the socket is not yet connected, retrying, conn-id=%d (%p)",
conn->id, conn);
break;
}
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "syscall error while doing TLS handshake, ssl error (code:%d), conn-id: %d (%p), errno: %d, session: %d",
ssl_error, conn->id, conn, errno, conn->session);
nopoll_conn_log_ssl (conn);
nopoll_conn_shutdown (conn);
nopoll_free (content);
/* release connection options */
__nopoll_conn_opts_release_if_needed (options);
return conn;
default:
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "there was an error with the TLS negotiation, ssl error (code:%d) : %s",
ssl_error, ERR_error_string (ssl_error, NULL));
/* show log stack */
nopoll_conn_log_ssl (conn);
/* call to release connection */
nopoll_conn_shutdown (conn);
nopoll_free (content);
/* release connection options */
__nopoll_conn_opts_release_if_needed (options);
return conn;
} /* end switch */
/* try and limit max reconnect allowed */
iterator++;
if (iterator > 1000) {
nopoll_log (ctx, NOPOLL_LEVEL_CRITICAL, "Max retry calls=%d to SSL_connect reached, shutting down connection id=%d, errno=%d",
iterator, conn->id, errno);
nopoll_free (content);
/* release connection options */
__nopoll_conn_opts_release_if_needed (options);