forked from allinurl/goaccess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.c
3006 lines (2543 loc) · 79.9 KB
/
websocket.c
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
/**
* websocket.c -- An rfc6455-complaint Web Socket Server
* _______ _______ __ __
* / ____/ | / / ___/____ _____/ /_____ / /_
* / / __ | | /| / /\__ \/ __ \/ ___/ //_/ _ \/ __/
* / /_/ / | |/ |/ /___/ / /_/ / /__/ ,< / __/ /_
* \____/ |__/|__//____/\____/\___/_/|_|\___/\__/
*
* The MIT License (MIT)
* Copyright (c) 2009-2023 Gerardo Orellana <hello @ goaccess.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.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdarg.h>
#include <stddef.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include "websocket.h"
#include "base64.h"
#include "error.h"
#include "gslist.h"
#include "sha1.h"
#include "xmalloc.h"
/* *INDENT-OFF* */
/* UTF-8 Decoder */
/* Copyright (c) 2008-2009 Bjoern Hoehrmann <[email protected]>
* See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details. */
#define UTF8_VALID 0
#define UTF8_INVAL 1
static const uint8_t utf8d[] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 00..1f */
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 20..3f */
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 40..5f */
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 60..7f */
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, /* 80..9f */
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, /* a0..bf */
8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, /* c0..df */
0xa,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x4,0x3,0x3, /* e0..ef */
0xb,0x6,0x6,0x6,0x5,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8, /* f0..ff */
0x0,0x1,0x2,0x3,0x5,0x8,0x7,0x1,0x1,0x1,0x4,0x6,0x1,0x1,0x1,0x1, /* s0..s0 */
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1, /* s1..s2 */
1,2,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1, /* s3..s4 */
1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,3,1,1,1,1,1,1, /* s5..s6 */
1,3,1,1,1,1,1,3,1,3,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* s7..s8 */
};
/* *INDENT-ON* */
static struct pollfd *fdstate = NULL;
static nfds_t nfdstate = 0;
static WSConfig wsconfig = { 0 };
static void handle_read_close (int *conn, WSClient * client, WSServer * server);
static void handle_reads (int *conn, WSServer * server);
static void handle_writes (int *conn, WSServer * server);
#ifdef HAVE_LIBSSL
static int shutdown_ssl (WSClient * client);
#endif
/* Determine if the given string is valid UTF-8.
*
* The state after the by has been processed is returned. */
static uint32_t
verify_utf8 (uint32_t *state, const char *str, int len) {
int i;
uint32_t type;
for (i = 0; i < len; ++i) {
type = utf8d[(uint8_t) str[i]];
*state = utf8d[256 + (*state) * 16 + type];
if (*state == UTF8_INVAL)
break;
}
return *state;
}
/* Decode a character maintaining state and a byte, and returns the
* state achieved after processing the byte.
*
* The state after the by has been processed is returned. */
static uint32_t
utf8_decode (uint32_t *state, uint32_t *p, uint32_t b) {
uint32_t type = utf8d[(uint8_t) b];
*p = (*state != UTF8_VALID) ? (b & 0x3fu) | (*p << 6) : (0xff >> type) & (b);
*state = utf8d[256 + *state * 16 + type];
return *state;
}
/* Replace malformed sequences with a substitute character.
*
* On success, it replaces the whole sequence and return a malloc'd buffer. */
static char *
sanitize_utf8 (const char *str, int len) {
char *buf = NULL;
uint32_t state = UTF8_VALID, prev = UTF8_VALID, cp = 0;
int i = 0, j = 0, k = 0, l = 0;
buf = xcalloc (len + 1, sizeof (char));
for (; i < len; prev = state, ++i) {
switch (utf8_decode (&state, &cp, (unsigned char) str[i])) {
case UTF8_INVAL:
/* replace the whole sequence */
if (k) {
for (l = i - k; l < i; ++l)
buf[j++] = '?';
} else {
buf[j++] = '?';
}
state = UTF8_VALID;
if (prev != UTF8_VALID)
i--;
k = 0;
break;
case UTF8_VALID:
/* fill i - k valid continuation bytes */
if (k)
for (l = i - k; l < i; ++l)
buf[j++] = str[l];
buf[j++] = str[i];
k = 0;
break;
default:
/* UTF8_VALID + continuation bytes */
k++;
break;
}
}
return buf;
}
/* find a pollfd structure based on fd
* this should only be called by set_pollfd and unset_pollfd
* because the position in memory may change */
static struct pollfd *
get_pollfd (int fd) {
struct pollfd *pfd, *efd = fdstate + nfdstate;
for (pfd = fdstate; pfd < efd; pfd++) {
if (pfd->fd == fd)
return pfd;
}
return NULL;
}
/* set flags for an existing pollfd structure based on fd,
* otherwise malloc a new one */
static void
set_pollfd (int fd, short flags) {
struct pollfd *pfd;
if (fd == -1)
FATAL ("Cannot poll an invalid fd");
pfd = get_pollfd (fd);
if (pfd == NULL) {
struct pollfd *newstate = xrealloc (fdstate, sizeof (*pfd) * (nfdstate + 1));
fdstate = newstate;
pfd = fdstate + nfdstate++;
pfd->fd = fd;
}
pfd->events = flags;
pfd->revents = 0;
}
/* free a pollfd structure based on fd */
static void
unset_pollfd (int fd) {
struct pollfd *pfd = get_pollfd (fd), *efd;
struct pollfd *newstate;
if (pfd == NULL)
return;
nfdstate--;
/* avoid undefined behaviour with realloc with a size of zero */
if (nfdstate == 0) {
free (fdstate);
fdstate = NULL;
return;
}
efd = fdstate + nfdstate;
if (pfd != efd)
memmove (pfd, pfd + 1, (char *) efd - (char *) pfd);
/* realloc could fail, but that's ok, we don't mind. */
newstate = realloc (fdstate, sizeof (*pfd) * nfdstate);
if (newstate != NULL)
fdstate = newstate;
}
/* Allocate memory for a websocket server */
static WSServer *
new_wsserver (void) {
WSServer *server = xcalloc (1, sizeof (WSServer));
return server;
}
/* Allocate memory for a websocket client */
static WSClient *
new_wsclient (void) {
WSClient *client = xcalloc (1, sizeof (WSClient));
client->status = WS_OK;
return client;
}
/* Allocate memory for a websocket header */
static WSHeaders *
new_wsheader (void) {
WSHeaders *headers = xcalloc (1, sizeof (WSHeaders));
memset (headers->buf, 0, sizeof (headers->buf));
headers->reading = 1;
return headers;
}
/* Allocate memory for a websocket frame */
static WSFrame *
new_wsframe (void) {
WSFrame *frame = xcalloc (1, sizeof (WSFrame));
memset (frame->buf, 0, sizeof (frame->buf));
frame->reading = 1;
return frame;
}
/* Allocate memory for a websocket message */
static WSMessage *
new_wsmessage (void) {
WSMessage *msg = xcalloc (1, sizeof (WSMessage));
return msg;
}
/* Allocate memory for a websocket pipeout */
static WSPipeOut *
new_wspipeout (void) {
WSPipeOut *pipeout = xcalloc (1, sizeof (WSPipeOut));
pipeout->fd = -1;
return pipeout;
}
/* Allocate memory for a websocket pipein */
static WSPipeIn *
new_wspipein (void) {
WSPipeIn *pipein = xcalloc (1, sizeof (WSPipeIn));
pipein->fd = -1;
return pipein;
}
/* Escapes the special characters, e.g., '\n', '\r', '\t', '\'
* in the string source by inserting a '\' before them.
*
* On error NULL is returned.
* On success the escaped string is returned */
static char *
escape_http_request (const char *src) {
char *dest, *q;
const unsigned char *p;
if (src == NULL || *src == '\0')
return NULL;
p = (const unsigned char *) src;
q = dest = xmalloc (strlen (src) * 4 + 1);
while (*p) {
switch (*p) {
case '\\':
*q++ = '\\';
*q++ = '\\';
break;
case '\n':
*q++ = '\\';
*q++ = 'n';
break;
case '\r':
*q++ = '\\';
*q++ = 'r';
break;
case '\t':
*q++ = '\\';
*q++ = 't';
break;
case '"':
*q++ = '\\';
*q++ = '"';
break;
default:
if ((*p < ' ') || (*p >= 0177)) {
/* not ASCII */
} else {
*q++ = *p;
}
break;
}
p++;
}
*q = 0;
return dest;
}
/* Make a string uppercase.
*
* On error the original string is returned.
* On success, the uppercased string is returned. */
static char *
strtoupper (char *str) {
char *p = str;
if (str == NULL || *str == '\0')
return str;
while (*p != '\0') {
*p = toupper ((int) *p);
p++;
}
return str;
}
/* Chop n characters from the beginning of the supplied buffer.
*
* The new length of the string is returned. */
static size_t
chop_nchars (char *str, size_t n, size_t len) {
if (n == 0 || str == 0)
return 0;
if (n > len)
n = len;
memmove (str, str + n, len - n);
return (len - n);
}
/* Match a client given a socket id and an item from the list.
*
* On match, 1 is returned, else 0. */
static int
ws_find_client_sock_in_list (void *data, void *needle) {
WSClient *client = data;
return client->listener == (*(int *) needle);
}
/* Find a client given a socket id.
*
* On success, an instance of a GSLList node is returned, else NULL. */
static GSLList *
ws_get_list_node_from_list (int listener, GSLList **colist) {
GSLList *match = NULL;
/* Find the client data for the socket in use */
if (!(match = list_find (*colist, ws_find_client_sock_in_list, &listener)))
return NULL;
return match;
}
/* Find a client given a socket id.
*
* On success, an instance of a WSClient is returned, else NULL. */
static WSClient *
ws_get_client_from_list (int listener, GSLList **colist) {
GSLList *match = NULL;
/* Find the client data for the socket in use */
if (!(match = list_find (*colist, ws_find_client_sock_in_list, &listener)))
return NULL;
return (WSClient *) match->data;
}
/* Free a frame structure and its data for the given client. */
static void
ws_free_frame (WSClient *client) {
if (client->frame)
free (client->frame);
client->frame = NULL;
}
/* Free a message structure and its data for the given client. */
static void
ws_free_message (WSClient *client) {
if (client->message && client->message->payload)
free (client->message->payload);
if (client->message)
free (client->message);
client->message = NULL;
}
/* Free all HTTP handshake headers data for the given client. */
static void
ws_free_header_fields (WSHeaders *headers) {
if (headers->connection)
free (headers->connection);
if (headers->host)
free (headers->host);
if (headers->agent)
free (headers->agent);
if (headers->method)
free (headers->method);
if (headers->origin)
free (headers->origin);
if (headers->path)
free (headers->path);
if (headers->protocol)
free (headers->protocol);
if (headers->upgrade)
free (headers->upgrade);
if (headers->ws_accept)
free (headers->ws_accept);
if (headers->ws_key)
free (headers->ws_key);
if (headers->ws_protocol)
free (headers->ws_protocol);
if (headers->ws_resp)
free (headers->ws_resp);
if (headers->ws_sock_ver)
free (headers->ws_sock_ver);
if (headers->referer)
free (headers->referer);
}
/* A wrapper to close a socket. */
static void
ws_close (int listener) {
unset_pollfd (listener);
close (listener);
}
/* Clear the client's sent queue and its data. */
static void
ws_clear_queue (WSClient *client) {
WSQueue **queue = &client->sockqueue;
if (!(*queue))
return;
if ((*queue)->queued)
free ((*queue)->queued);
(*queue)->queued = NULL;
(*queue)->qlen = 0;
free ((*queue));
(*queue) = NULL;
/* done sending the whole queue, stop throttling */
client->status &= ~WS_THROTTLING;
/* done sending, close connection if set to close */
if ((client->status & WS_CLOSE) && (client->status & WS_SENDING))
client->status = WS_CLOSE;
}
/* Free all HTTP handshake headers and structure. */
static void
ws_clear_handshake_headers (WSHeaders *headers) {
ws_free_header_fields (headers);
free (headers);
}
/* Remove the given client from the list. */
static void
ws_remove_client_from_list (WSClient *client, WSServer *server) {
GSLList *node = NULL;
if (!(node = ws_get_list_node_from_list (client->listener, &server->colist)))
return;
if (client->headers)
ws_clear_handshake_headers (client->headers);
list_remove_node (&server->colist, node);
}
#if HAVE_LIBSSL
/* Attempt to send the TLS/SSL "close notify" shutdown and and removes
* the SSL structure pointed to by ssl and frees up the allocated
* memory. */
static void
ws_shutdown_dangling_clients (WSClient *client) {
shutdown_ssl (client);
SSL_free (client->ssl);
client->ssl = NULL;
}
/* Attempt to remove the SSL_CTX object pointed to by ctx and frees up
* the allocated memory and cleans some more generally used TLS/SSL
* memory. */
static void
ws_ssl_cleanup (WSServer *server) {
if (!wsconfig.use_ssl)
return;
if (server->ctx)
SSL_CTX_free (server->ctx);
CRYPTO_cleanup_all_ex_data ();
CRYPTO_set_id_callback (NULL);
CRYPTO_set_locking_callback (NULL);
ERR_free_strings ();
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ERR_remove_state (0);
#endif
EVP_cleanup ();
}
#endif
/* Remove all clients that are still hanging out. */
static int
ws_remove_dangling_clients (void *value, void *user_data) {
WSClient *client = value;
(void) (user_data);
if (client == NULL)
return 1;
if (client->headers)
ws_clear_handshake_headers (client->headers);
if (client->sockqueue)
ws_clear_queue (client);
#ifdef HAVE_LIBSSL
if (client->ssl)
ws_shutdown_dangling_clients (client);
#endif
return 0;
}
/* Do some housekeeping on the named pipe data packet. */
static void
ws_clear_fifo_packet (WSPacket *packet) {
if (!packet)
return;
if (packet->data)
free (packet->data);
free (packet);
}
/* Do some housekeeping on the named pipe. */
static void
ws_clear_pipein (WSPipeIn *pipein) {
WSPacket **packet = &pipein->packet;
if (!pipein)
return;
if (pipein->fd != -1)
ws_close (pipein->fd);
ws_clear_fifo_packet (*packet);
free (pipein);
if (wsconfig.pipein && access (wsconfig.pipein, F_OK) != -1)
unlink (wsconfig.pipein);
}
/* Do some housekeeping on the named pipe. */
static void
ws_clear_pipeout (WSPipeOut *pipeout) {
if (!pipeout)
return;
if (pipeout->fd != -1)
ws_close (pipeout->fd);
free (pipeout);
if (wsconfig.pipeout && access (wsconfig.pipeout, F_OK) != -1)
unlink (wsconfig.pipeout);
}
/* Stop the server and do some cleaning. */
void
ws_stop (WSServer *server) {
WSPipeIn **pipein = &server->pipein;
WSPipeOut **pipeout = &server->pipeout;
ws_clear_pipein (*pipein);
ws_clear_pipeout (*pipeout);
/* close access log (if any) */
if (wsconfig.accesslog)
access_log_close ();
/* remove dangling clients */
if (list_count (server->colist) > 0)
list_foreach (server->colist, ws_remove_dangling_clients, NULL);
if (server->colist)
list_remove_nodes (server->colist);
#ifdef HAVE_LIBSSL
ws_ssl_cleanup (server);
#endif
free (server);
free (fdstate);
fdstate = NULL;
}
/* Set the connection status for the given client and return the given
* bytes.
*
* The given number of bytes are returned. */
static int
ws_set_status (WSClient *client, WSStatus status, int bytes) {
client->status = status;
return bytes;
}
/* Append the source string to destination and reallocates and
* updating the destination buffer appropriately. */
static void
ws_append_str (char **dest, const char *src) {
size_t curlen = strlen (*dest);
size_t srclen = strlen (src);
size_t newlen = curlen + srclen;
char *str = xrealloc (*dest, newlen + 1);
memcpy (str + curlen, src, srclen + 1);
*dest = str;
}
#if HAVE_LIBSSL
/* Create a new SSL_CTX object as framework to establish TLS/SSL
* enabled connections.
*
* On error 1 is returned.
* On success, SSL_CTX object is malloc'd and 0 is returned.
*/
static int
initialize_ssl_ctx (WSServer *server) {
int ret = 1;
SSL_CTX *ctx = NULL;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
SSL_library_init ();
SSL_load_error_strings ();
#endif
/* Ciphers and message digests */
OpenSSL_add_ssl_algorithms ();
/* ssl context */
#if OPENSSL_VERSION_NUMBER < 0x10100000L
if (!(ctx = SSL_CTX_new (SSLv23_server_method ())))
#else
if (!(ctx = SSL_CTX_new (TLS_server_method ())))
#endif
goto out;
/* set certificate */
if (!SSL_CTX_use_certificate_file (ctx, wsconfig.sslcert, SSL_FILETYPE_PEM))
goto out;
/* ssl private key */
if (!SSL_CTX_use_PrivateKey_file (ctx, wsconfig.sslkey, SSL_FILETYPE_PEM))
goto out;
if (!SSL_CTX_check_private_key (ctx))
goto out;
/* since we queued up the send data, a retry won't be the same buffer,
* thus we need the following flags */
SSL_CTX_set_mode (ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);
server->ctx = ctx;
ret = 0;
out:
if (ret) {
SSL_CTX_free (ctx);
LOG (("Error: %s\n", ERR_error_string (ERR_get_error (), NULL)));
}
return ret;
}
/* Log result code for TLS/SSL I/O operation */
static void
log_return_message (int ret, int err, const char *fn) {
unsigned long e;
switch (err) {
case SSL_ERROR_NONE:
LOG (("SSL: %s -> SSL_ERROR_NONE\n", fn));
LOG (("SSL: TLS/SSL I/O operation completed\n"));
break;
case SSL_ERROR_WANT_READ:
LOG (("SSL: %s -> SSL_ERROR_WANT_READ\n", fn));
LOG (("SSL: incomplete, data available for reading\n"));
break;
case SSL_ERROR_WANT_WRITE:
LOG (("SSL: %s -> SSL_ERROR_WANT_WRITE\n", fn));
LOG (("SSL: incomplete, data available for writing\n"));
break;
case SSL_ERROR_ZERO_RETURN:
LOG (("SSL: %s -> SSL_ERROR_ZERO_RETURN\n", fn));
LOG (("SSL: TLS/SSL connection has been closed\n"));
break;
case SSL_ERROR_WANT_X509_LOOKUP:
LOG (("SSL: %s -> SSL_ERROR_WANT_X509_LOOKUP\n", fn));
break;
case SSL_ERROR_SYSCALL:
LOG (("SSL: %s -> SSL_ERROR_SYSCALL\n", fn));
e = ERR_get_error ();
if (e > 0)
LOG (("SSL: %s -> %s\n", fn, ERR_error_string (e, NULL)));
/* call was not successful because a fatal error occurred either at the
* protocol level or a connection failure occurred. */
if (ret != 0) {
LOG (("SSL bogus handshake interrupt: %s\n", strerror (errno)));
break;
}
/* call not yet finished. */
LOG (("SSL: handshake interrupted, got EOF\n"));
if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
LOG (("SSL: %s -> not yet finished %s\n", fn, strerror (errno)));
break;
default:
LOG (("SSL: %s -> failed fatal error code: %d\n", fn, err));
LOG (("SSL: %s\n", ERR_error_string (ERR_get_error (), NULL)));
break;
}
}
/* Shut down the client's TLS/SSL connection
*
* On fatal error, 1 is returned.
* If data still needs to be read/written, -1 is returned.
* On success, the TLS/SSL connection is closed and 0 is returned */
static int
shutdown_ssl (WSClient *client) {
int ret = -1, err = 0;
/* all good */
if ((ret = SSL_shutdown (client->ssl)) > 0)
return ws_set_status (client, WS_CLOSE, 0);
err = SSL_get_error (client->ssl, ret);
log_return_message (ret, err, "SSL_shutdown");
switch (err) {
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
client->sslstatus = WS_TLS_SHUTTING;
break;
case SSL_ERROR_SYSCALL:
if (ret == 0) {
LOG (("SSL: SSL_shutdown, connection unexpectedly closed by peer.\n"));
/* The shutdown is not yet finished. */
if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
client->sslstatus = WS_TLS_SHUTTING;
break;
}
LOG (("SSL: SSL_shutdown, probably unrecoverable, forcing close.\n"));
/* FALLTHRU */
case SSL_ERROR_ZERO_RETURN:
case SSL_ERROR_WANT_X509_LOOKUP:
default:
return ws_set_status (client, WS_ERR | WS_CLOSE, 1);
}
return ret;
}
/* Wait for a TLS/SSL client to initiate a TLS/SSL handshake
*
* On fatal error, the connection is shut down.
* If data still needs to be read/written, -1 is returned.
* On success, the TLS/SSL connection is completed and 0 is returned */
static int
accept_ssl (WSClient *client) {
int ret = -1, err = 0;
/* all good on TLS handshake */
if ((ret = SSL_accept (client->ssl)) > 0) {
client->sslstatus &= ~WS_TLS_ACCEPTING;
return 0;
}
err = SSL_get_error (client->ssl, ret);
log_return_message (ret, err, "SSL_accept");
switch (err) {
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
client->sslstatus = WS_TLS_ACCEPTING;
break;
case SSL_ERROR_SYSCALL:
/* Wait for more activity else bail out, for instance if the socket is closed
* during the handshake. */
if (ret < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) {
client->sslstatus = WS_TLS_ACCEPTING;
break;
}
/* The peer notified that it is shutting down through a SSL "close_notify" so
* we shutdown too */
/* FALLTHRU */
case SSL_ERROR_ZERO_RETURN:
case SSL_ERROR_WANT_X509_LOOKUP:
default:
client->sslstatus &= ~WS_TLS_ACCEPTING;
return ws_set_status (client, WS_ERR | WS_CLOSE, 1);
}
return ret;
}
/* Create a new SSL structure for a connection and perform handshake */
static void
handle_accept_ssl (WSClient *client, WSServer *server) {
/* attempt to create SSL connection if we don't have one yet */
if (!client->ssl) {
if (!(client->ssl = SSL_new (server->ctx))) {
LOG (("SSL: SSL_new, new SSL structure failed.\n"));
return;
}
if (!SSL_set_fd (client->ssl, client->listener)) {
LOG (("SSL: unable to set file descriptor\n"));
return;
}
}
/* attempt to initiate the TLS/SSL handshake */
if (accept_ssl (client) == 0) {
LOG (("SSL Accepted: %d %s\n", client->listener, client->remote_ip));
}
}
/* Given the current status of the SSL buffer, perform that action.
*
* On error or if no SSL pending status, 1 is returned.
* On success, the TLS/SSL pending action is called and 0 is returned */
static int
handle_ssl_pending_rw (int *conn, WSServer *server, WSClient *client) {
if (!wsconfig.use_ssl)
return 1;
/* trying to write but still waiting for a successful SSL_accept */
if (client->sslstatus & WS_TLS_ACCEPTING) {
handle_accept_ssl (client, server);
return 0;
}
/* trying to read but still waiting for a successful SSL_read */
if (client->sslstatus & WS_TLS_READING) {
handle_reads (conn, server);
return 0;
}
/* trying to write but still waiting for a successful SSL_write */
if (client->sslstatus & WS_TLS_WRITING) {
handle_writes (conn, server);
return 0;
}
/* trying to write but still waiting for a successful SSL_shutdown */
if (client->sslstatus & WS_TLS_SHUTTING) {
if (shutdown_ssl (client) == 0)
handle_read_close (conn, client, server);
return 0;
}
return 1;
}
/* Write bytes to a TLS/SSL connection for a given client.
*
* On error or if no write is performed <=0 is returned.
* On success, the number of bytes actually written to the TLS/SSL
* connection are returned */
static int
send_ssl_buffer (WSClient *client, const char *buffer, int len) {
int bytes = 0, err = 0;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ERR_clear_error ();
#endif
if ((bytes = SSL_write (client->ssl, buffer, len)) > 0)
return bytes;
err = SSL_get_error (client->ssl, bytes);
log_return_message (bytes, err, "SSL_write");
switch (err) {
case SSL_ERROR_WANT_WRITE:
break;
case SSL_ERROR_WANT_READ:
client->sslstatus = WS_TLS_WRITING;
break;
case SSL_ERROR_SYSCALL:
if ((bytes < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)))
break;
/* The connection was shut down cleanly */
/* FALLTHRU */
case SSL_ERROR_ZERO_RETURN:
case SSL_ERROR_WANT_X509_LOOKUP:
default:
return ws_set_status (client, WS_ERR | WS_CLOSE, -1);
}
return bytes;
}
/* Read data from the given client's socket and set a connection
* status given the output of recv().
*
* On error, -1 is returned and the connection status is set.
* On success, the number of bytes read is returned. */
static int
read_ssl_socket (WSClient *client, char *buffer, int size) {
int bytes = 0, done = 0, err = 0;
do {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ERR_clear_error ();
#endif
done = 0;
if ((bytes = SSL_read (client->ssl, buffer, size)) > 0)
break;
err = SSL_get_error (client->ssl, bytes);
log_return_message (bytes, err, "SSL_read");
switch (err) {
case SSL_ERROR_WANT_WRITE:
client->sslstatus = WS_TLS_READING;
done = 1;
break;
case SSL_ERROR_WANT_READ:
done = 1;
break;
case SSL_ERROR_SYSCALL:
if ((bytes < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)))
break;
/* FALLTHRU */
case SSL_ERROR_ZERO_RETURN:
case SSL_ERROR_WANT_X509_LOOKUP:
default:
return ws_set_status (client, WS_ERR | WS_CLOSE, -1);
}
} while (SSL_pending (client->ssl) && !done);
return bytes;
}
#endif
/* Get sockaddr, either IPv4 or IPv6 */
static void *
ws_get_raddr (struct sockaddr *sa) {
if (sa->sa_family == AF_INET)
return &(((struct sockaddr_in *) (void *) sa)->sin_addr);
return &(((struct sockaddr_in6 *) (void *) sa)->sin6_addr);
}
/* Set the given file descriptor as NON BLOCKING. */