forked from disconnect/apache-websocket
-
Notifications
You must be signed in to change notification settings - Fork 4
/
mod_websocket.c
1918 lines (1658 loc) · 66.3 KB
/
mod_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
/*
* Copyright 2010-2012 self.disconnect
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file has been modified from its original upstream version. It is
* forked from commit cfaef071 of the (now abandoned) repository at
*
* https://github.com/disconnect/apache-websocket
*/
/* _ _ _ _
* _ __ ___ ___ __| | __ __ _ | |__ ___ ___ ___ | | __ _ _| |_ mod_websocket
* | '_ ` _ \ / _ \ / _` | \ \ /\ / / _ \ '_ \/ __// _ \ / __\| |/ / _ \_ _| Apache Interface to WebSocket
* | | | | | | (_) | (_| | \ V V / __/ |_) )__ \ (_) | (___| ( __/| |__
* |_| |_| |_|\___/ \__,_|___\_/\_/ \___|_,__/|___/\___/ \___/|_|\_\___| \__/
* |_____|
* mod_websocket.c
* Apache API inteface structures
*/
#include "apr_base64.h"
#include "apr_lib.h"
#include "apr_queue.h"
#include "apr_sha1.h"
#include "apr_strings.h"
#include "apr_thread_cond.h"
#include "httpd.h"
#include "http_config.h"
#include "http_log.h"
#include "http_protocol.h"
#include "util_varbuf.h"
#include "websocket_plugin.h"
#include "validate_utf8.h"
#define CORE_PRIVATE
#include "http_core.h"
#include "http_connection.h"
#if !defined(APR_ARRAY_IDX)
#define APR_ARRAY_IDX(ary,i,type) (((type *)(ary)->elts)[i])
#endif
#if !defined(APR_ARRAY_PUSH)
#define APR_ARRAY_PUSH(ary,type) (*((type *)apr_array_push(ary)))
#endif
module AP_MODULE_DECLARE_DATA websocket_module;
#ifdef APLOG_USE_MODULE /* only in Apache 2.4 */
APLOG_USE_MODULE(websocket);
#endif
#ifndef APLOG_TRACE1 /* not defined in Apache 2.2 */
#define APLOG_TRACE1 APLOG_DEBUG
#endif
typedef struct
{
char *location;
apr_dso_handle_t *res_handle;
WebSocketPlugin *plugin;
apr_int64_t message_limit;
int allow_reserved; /* whether to allow reserved status codes */
int origin_check; /* how to check the Origin during a handshake */
apr_hash_t *trusted_origins; /* allowlist for ORIGIN_CHECK_TRUSTED */
} websocket_config_rec;
/* Possible config values for websocket_config_rec->origin_check */
#define ORIGIN_CHECK_OFF 0 /* No checks whatsoever */
#define ORIGIN_CHECK_SAME 1 /* Origin must match that of the request target */
#define ORIGIN_CHECK_TRUSTED 2 /* Origin must be on the WebSocketTrustedOrigin list */
#define BLOCK_DATA_SIZE 4096
#define QUEUE_CAPACITY 16
#define DATA_FRAMING_MASK 0
#define DATA_FRAMING_START 1
#define DATA_FRAMING_PAYLOAD_LENGTH 2
#define DATA_FRAMING_PAYLOAD_LENGTH_EXT 3
#define DATA_FRAMING_EXTENSION_DATA 4
#define DATA_FRAMING_APPLICATION_DATA 5
#define FRAME_GET_FIN(BYTE) (((BYTE) >> 7) & 0x01)
#define FRAME_GET_RSV1(BYTE) (((BYTE) >> 6) & 0x01)
#define FRAME_GET_RSV2(BYTE) (((BYTE) >> 5) & 0x01)
#define FRAME_GET_RSV3(BYTE) (((BYTE) >> 4) & 0x01)
#define FRAME_GET_OPCODE(BYTE) ( (BYTE) & 0x0F)
#define FRAME_GET_MASK(BYTE) (((BYTE) >> 7) & 0x01)
#define FRAME_GET_PAYLOAD_LEN(BYTE) ( (BYTE) & 0x7F)
#define FRAME_SET_FIN(BYTE) (((BYTE) & 0x01) << 7)
#define FRAME_SET_OPCODE(BYTE) ((BYTE) & 0x0F)
#define FRAME_SET_MASK(BYTE) (((BYTE) & 0x01) << 7)
#define FRAME_SET_LENGTH(X64, IDX) (unsigned char)(((X64) >> ((IDX)*8)) & 0xFF)
#define OPCODE_CONTINUATION 0x0
#define OPCODE_TEXT 0x1
#define OPCODE_BINARY 0x2
#define OPCODE_CLOSE 0x8
#define OPCODE_PING 0x9
#define OPCODE_PONG 0xA
#define WEBSOCKET_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
#define WEBSOCKET_GUID_LEN 36
#define STATUS_CODE_OK 1000
#define STATUS_CODE_GOING_AWAY 1001
#define STATUS_CODE_PROTOCOL_ERROR 1002
#define STATUS_CODE_RESERVED 1004 /* Protocol 8: frame too large */
#define STATUS_CODE_INVALID_UTF8 1007
#define STATUS_CODE_POLICY_VIOLATION 1008
#define STATUS_CODE_MESSAGE_TOO_LARGE 1009
#define STATUS_CODE_INTERNAL_ERROR 1011
/* The supported WebSocket protocol versions. */
static int supported_versions[] = { 13, 8, 7 };
static int supported_versions_len = sizeof(supported_versions) /
sizeof(supported_versions[0]);
/*
* Configuration
*/
static void *mod_websocket_create_dir_config(apr_pool_t *p, char *path)
{
websocket_config_rec *conf = NULL;
if (path != NULL) {
conf = apr_pcalloc(p, sizeof(websocket_config_rec));
if (conf != NULL) {
conf->location = apr_pstrdup(p, path);
conf->message_limit = 32 * 1024 * 1024;
conf->origin_check = ORIGIN_CHECK_SAME;
conf->trusted_origins = apr_hash_make(p);
}
}
return (void *)conf;
}
static apr_status_t mod_websocket_cleanup_config(void *data)
{
if (data != NULL) {
websocket_config_rec *conf = (websocket_config_rec *)data;
if (conf != NULL) {
if ((conf->plugin != NULL) && (conf->plugin->destroy != NULL)) {
conf->plugin->destroy(conf->plugin);
}
conf->plugin = NULL;
if (conf->res_handle != NULL) {
apr_dso_unload(conf->res_handle);
conf->res_handle = NULL;
}
}
}
return APR_SUCCESS;
}
static const char *mod_websocket_conf_allow_reserved(cmd_parms *cmd,
void *confv, int on)
{
websocket_config_rec *conf = (websocket_config_rec *)confv;
if (conf != NULL) {
conf->allow_reserved = on;
}
return NULL;
}
static const char *mod_websocket_conf_handler(cmd_parms *cmd, void *confv,
const char *path,
const char *name)
{
websocket_config_rec *conf = (websocket_config_rec *)confv;
apr_dso_handle_t *res_handle = NULL;
apr_dso_handle_sym_t sym;
WebSocketPlugin *plugin;
const char *errmsg = NULL;
if (!conf || !path || !name) {
return "Invalid parameters for WebSocketHandler";
}
if (apr_dso_load(&res_handle, ap_server_root_relative(cmd->pool, path),
cmd->pool) != APR_SUCCESS) {
char err[256];
return apr_pstrcat(cmd->pool, "Could not load WebSocketHandler ", path,
": ", apr_dso_error(res_handle, err, sizeof(err)),
NULL);
}
if ((apr_dso_sym(&sym, res_handle, name) != APR_SUCCESS) || !sym) {
apr_dso_unload(res_handle);
return apr_psprintf(cmd->pool, "Could not find initialization function "
"\"%s\" for WebSocketHandler %s", name, path);
}
/* Get the plugin struct from the module and sanity-check. */
plugin = ((WS_Init) sym) ();
if (!plugin) {
errmsg = "returned NULL";
}
else if (plugin->version != WEBSOCKET_PLUGIN_VERSION_0) {
errmsg = apr_psprintf(cmd->pool, "unsupported plugin version %u",
plugin->version);
}
else if (plugin->size < sizeof(WebSocketPlugin)) {
errmsg = "invalid plugin size; check plugin version and compiler";
}
else if (!plugin->on_message) {
errmsg = "on_message handler is NULL";
}
if (errmsg) {
apr_dso_unload(res_handle);
return apr_pstrcat(cmd->pool, "Invalid response from WebSocketHandler "
"initialization function ", name, " (", errmsg, ")",
NULL);
}
conf->res_handle = res_handle;
conf->plugin = plugin;
apr_pool_cleanup_register(cmd->pool, conf, mod_websocket_cleanup_config,
apr_pool_cleanup_null);
return NULL;
}
static const char *mod_websocket_conf_origin_check(cmd_parms *cmd, void *confv,
const char *mode)
{
websocket_config_rec *conf = (websocket_config_rec *)confv;
if (conf) {
if (!strcasecmp(mode, "Off")) {
conf->origin_check = ORIGIN_CHECK_OFF;
} else if (!strcasecmp(mode, "Same")) {
conf->origin_check = ORIGIN_CHECK_SAME;
} else if (!strcasecmp(mode, "Trusted")) {
conf->origin_check = ORIGIN_CHECK_TRUSTED;
} else {
return "WebSocketOriginCheck must be Off, Same, or Trusted";
}
}
return NULL;
}
static const char *mod_websocket_conf_add_origin(cmd_parms *cmd, void *confv,
const char *arg)
{
websocket_config_rec *conf = (websocket_config_rec *)confv;
if (conf) {
const char *origin = apr_pstrdup(cmd->pool, arg);
apr_hash_set(conf->trusted_origins, origin, APR_HASH_KEY_STRING,
origin);
ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, cmd->server,
"added Origin '%s' to the Trusted list for %s",
origin, (cmd->path ? cmd->path : "null"));
}
return NULL;
}
static const char *mod_websocket_conf_max_message_size(cmd_parms *cmd,
void *confv,
const char *size)
{
websocket_config_rec *conf = (websocket_config_rec *)confv;
char *response;
/* Warn about the name change from MaxMessageSize, if appropriate. */
if (cmd->cmd->name[0] == 'M') {
ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, cmd->server,
"The MaxMessageSize directive (%s:%d) is deprecated; use "
"WebSocketMaxMessageSize instead",
cmd->directive->filename, cmd->directive->line_num);
}
if ((conf != NULL) && (size != NULL)) {
apr_int64_t message_limit = apr_atoi64(size);
if (message_limit > 0) {
if (message_limit > APR_SIZE_MAX) {
/*
* Since we pass messages as a single contiguous buffer to the
* plugin, they can't exceed the max size_t.
*
* FIXME: a streaming API could allow plugins to get around this
* restriction.
*/
response = apr_psprintf(cmd->pool,
"Max message size is too large for your"
" system (reduce to %"APR_SIZE_T_FMT")",
APR_SIZE_MAX);
} else {
conf->message_limit = message_limit;
response = NULL;
}
}
else {
response = "Invalid maximum message size";
}
}
else {
response = "Invalid parameter";
}
return response;
}
/*
* Functions available to plugins.
*/
typedef struct _WebSocketState
{
request_rec *r;
apr_bucket_brigade *obb;
apr_os_thread_t main_thread;
apr_thread_mutex_t *mutex;
apr_thread_cond_t *cond;
apr_array_header_t *protocols;
int closing;
apr_int64_t protocol_version;
apr_pollset_t *pollset;
apr_queue_t *queue;
} WebSocketState;
static request_rec *CALLBACK mod_websocket_request(const WebSocketServer *server)
{
if ((server != NULL) && (server->state != NULL)) {
return server->state->r;
}
return NULL;
}
static const char *CALLBACK mod_websocket_header_get(const WebSocketServer *server,
const char *key)
{
if ((server != NULL) && (key != NULL)) {
WebSocketState *state = server->state;
if ((state != NULL) && (state->r != NULL)) {
return apr_table_get(state->r->headers_in, key);
}
}
return NULL;
}
static void CALLBACK mod_websocket_header_set(const WebSocketServer *server,
const char *key,
const char *value)
{
if ((server != NULL) && (key != NULL) && (value != NULL)) {
WebSocketState *state = server->state;
if ((state != NULL) && (state->r != NULL)) {
apr_table_setn(state->r->headers_out,
apr_pstrdup(state->r->pool, key),
apr_pstrdup(state->r->pool, value));
}
}
}
static size_t CALLBACK mod_websocket_protocol_count(const WebSocketServer *server)
{
size_t count = 0;
if ((server != NULL) && (server->state != NULL) &&
(server->state->protocols != NULL) &&
!apr_is_empty_array(server->state->protocols)) {
count = (size_t) server->state->protocols->nelts;
}
return count;
}
static const char *CALLBACK mod_websocket_protocol_index(const WebSocketServer *server,
const size_t index)
{
if ((index >= 0) && (index < mod_websocket_protocol_count(server))) {
return APR_ARRAY_IDX(server->state->protocols, index, char *);
}
return NULL;
}
static void CALLBACK mod_websocket_protocol_set(const WebSocketServer *server,
const char *protocol)
{
if ((server != NULL) && (protocol != NULL)) {
WebSocketState *state = server->state;
if ((state != NULL) && (state->r != NULL)) {
apr_table_setn(state->r->headers_out, "Sec-WebSocket-Protocol",
apr_pstrdup(state->r->pool, protocol));
}
}
}
/*
* Sends data to the WebSocket connection using the given server state. The
* server state must be locked upon entering this function. buffer_size is
* assumed to be within the limits defined by the WebSocket protocol (i.e. fits
* in 63 bits).
*/
static size_t mod_websocket_send_internal(WebSocketState *state,
const int type,
const unsigned char *buffer,
const size_t buffer_size)
{
apr_uint64_t payload_length =
(apr_uint64_t) ((buffer != NULL) ? buffer_size : 0);
size_t written = 0;
if ((state->r != NULL) && (state->obb != NULL) && !state->closing) {
unsigned char header[32];
ap_filter_t *of = state->r->connection->output_filters;
apr_size_t pos = 0;
unsigned char opcode;
switch (type) {
case MESSAGE_TYPE_TEXT:
opcode = OPCODE_TEXT;
break;
case MESSAGE_TYPE_BINARY:
opcode = OPCODE_BINARY;
break;
case MESSAGE_TYPE_PING:
opcode = OPCODE_PING;
break;
case MESSAGE_TYPE_PONG:
opcode = OPCODE_PONG;
break;
case MESSAGE_TYPE_CLOSE:
default:
state->closing = 1;
opcode = OPCODE_CLOSE;
break;
}
header[pos++] = FRAME_SET_FIN(1) | FRAME_SET_OPCODE(opcode);
if (payload_length < 126) {
header[pos++] =
FRAME_SET_MASK(0) | FRAME_SET_LENGTH(payload_length, 0);
}
else {
if (payload_length < 65536) {
header[pos++] = FRAME_SET_MASK(0) | 126;
}
else {
header[pos++] = FRAME_SET_MASK(0) | 127;
header[pos++] = FRAME_SET_LENGTH(payload_length, 7);
header[pos++] = FRAME_SET_LENGTH(payload_length, 6);
header[pos++] = FRAME_SET_LENGTH(payload_length, 5);
header[pos++] = FRAME_SET_LENGTH(payload_length, 4);
header[pos++] = FRAME_SET_LENGTH(payload_length, 3);
header[pos++] = FRAME_SET_LENGTH(payload_length, 2);
}
header[pos++] = FRAME_SET_LENGTH(payload_length, 1);
header[pos++] = FRAME_SET_LENGTH(payload_length, 0);
}
ap_fwrite(of, state->obb, (const char *)header, pos); /* Header */
if (payload_length > 0) {
if (ap_fwrite(of, state->obb,
(const char *)buffer,
buffer_size) == APR_SUCCESS) { /* Payload Data */
written = buffer_size;
}
}
if (ap_fflush(of, state->obb) != APR_SUCCESS) {
written = 0;
}
}
return written;
}
typedef struct
{
int type;
const unsigned char * buffer;
size_t buffer_size;
int done;
size_t written;
} WebSocketMessageData;
/*
* Sends a buffer of data via the WebSocket. Returns the number of bytes that
* are actually written.
*
* If this function is called from a different thread than the one running the
* main framing loop, the message will be queued and the calling thread will
* block until the data is written by the main thread.
*/
static size_t CALLBACK mod_websocket_plugin_send(const WebSocketServer *server,
const int type,
const unsigned char *buffer,
const size_t buffer_size)
{
size_t written = 0;
/* Deal with size more that 63 bits - FIXME */
/* FIXME - if sending a zero-length message, the API cannot distinguish
* between success and failure */
if ((server != NULL) && (server->state != NULL)) {
WebSocketState *state = server->state;
apr_thread_mutex_lock(state->mutex);
if (apr_os_thread_equal(apr_os_thread_current(), state->main_thread)) {
/* This is the main thread. It's safe to write messages directly. */
written = mod_websocket_send_internal(state, type, buffer, buffer_size);
}
else if ((state->pollset != NULL) && (state->queue != NULL) &&
!state->closing) {
/* Dispatch this message to the main thread. */
apr_status_t rv;
WebSocketMessageData msg = { 0 };
/* Populate the message data. */
msg.type = type;
msg.buffer = buffer;
msg.buffer_size = buffer_size;
/* Queue the message. */
do {
rv = apr_queue_push(state->queue, &msg);
} while (APR_STATUS_IS_EINTR(rv));
if (rv != APR_SUCCESS) {
/* Couldn't push the message onto the queue. */
goto send_unlock;
}
/* Interrupt the pollset. */
rv = apr_pollset_wakeup(state->pollset);
if (rv != APR_SUCCESS) {
/*
* Couldn't wake up poll...? We can't return zero since we've
* already pushed the message, and it might actually be sent...
*/
/* TODO: log. */
}
/* Wait for the message to be written. */
while (!msg.done && !state->closing) {
apr_thread_cond_wait(state->cond, state->mutex);
}
if (msg.done) {
written = msg.written;
}
}
send_unlock:
apr_thread_mutex_unlock(state->mutex);
}
return written;
}
static void CALLBACK mod_websocket_plugin_close(const WebSocketServer *
server)
{
if (server != NULL) {
/* Send closing handshake */
mod_websocket_plugin_send(server, MESSAGE_TYPE_CLOSE, NULL, 0);
}
}
/*
* Read a buffer of data from the input stream.
*/
static apr_status_t mod_websocket_read_nonblock(request_rec *r,
apr_bucket_brigade *bb,
char *buffer,
apr_size_t *bufsiz)
{
apr_status_t rv;
if ((rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
APR_NONBLOCK_READ, *bufsiz)) == APR_SUCCESS) {
rv = apr_brigade_flatten(bb, buffer, bufsiz);
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, rv, r,
"read %ld bytes from brigade", (long) *bufsiz);
apr_brigade_cleanup(bb);
}
if ((rv == APR_SUCCESS) && (*bufsiz == 0)) {
/*
* For some reason, nonblocking reads can return APR_SUCCESS even when
* there was nothing actually read. Treat this as an EAGAIN.
*/
rv = APR_EAGAIN;
}
return rv;
}
/*
* Base64-encode the SHA-1 hash of the client-supplied key with the WebSocket
* GUID appended to it.
*/
static void mod_websocket_handshake(request_rec *r, const char *key)
{
apr_byte_t response[32];
apr_byte_t digest[APR_SHA1_DIGESTSIZE];
apr_sha1_ctx_t context;
int len;
apr_sha1_init(&context);
apr_sha1_update(&context, key, strlen(key));
apr_sha1_update(&context, WEBSOCKET_GUID, WEBSOCKET_GUID_LEN);
apr_sha1_final(digest, &context);
len = apr_base64_encode_binary((char *)response, digest, sizeof(digest));
response[len] = '\0';
apr_table_setn(r->headers_out, "Sec-WebSocket-Accept",
apr_pstrdup(r->pool, (const char *)response));
}
/*
* Compatibility wrapper for ap_parse_token_list_strict(), which doesn't exist
* until Apache 2.4.17. We remove the skip_invalid flag since we never ignore
* invalid separators, and we assume the tokens array is always preinitialized.
*/
static const char* parse_token_list_strict(apr_pool_t *p, const char *tok,
apr_array_header_t *tokens)
{
#if AP_MODULE_MAGIC_AT_LEAST(20120211,51)
return ap_parse_token_list_strict(p, tok, &tokens,
0 /* don't ignore invalid separators */);
#else
/*
* ap_get_token() allows a bunch of stuff we don't want, so we have to
* perform more validity checks.
*/
while (*tok) {
const char *token;
token = ap_get_token(p, &tok, 0);
/*
* Check that the token is valid before putting it into the array. Empty
* tokens are fine (we must accept them per RFC 7230); we'll just skip
* them.
*/
if (token && *token) {
const char *c;
for (c = token; *c; ++c) {
/*
* This is the T_HTTP_TOKEN_STOP check from gen_test_char.
* Disallow control characters and separators in tokens.
*/
if (apr_iscntrl(*c) || strchr(" \t()<>@,;:\\\"/[]?={}", *c)) {
return apr_psprintf(p, "Encountered illegal separator "
"'\\x%.2x'", (unsigned int) *c);
}
}
*((const char **) apr_array_push(tokens)) = token;
}
/*
* ap_get_token() breaks tokens on whitespace, semicolons, and commas.
* Make sure that we only get commas after a token.
*/
if (*tok == ',') {
++tok;
} else if (*tok) {
return apr_psprintf(p, "Encountered illegal separator '\\x%.2x'",
(unsigned int) *tok);
}
}
return NULL;
#endif
}
/*
* The client-supplied WebSocket protocol entry consists of a list of
* client-side supported protocols. Parse the list, and populate an array with
* those protocol names.
*/
static apr_status_t parse_protocol(request_rec *r,
apr_array_header_t *protocols)
{
const char *sec_websocket_protocol;
const char *error;
sec_websocket_protocol = apr_table_get(r->headers_in,
"Sec-WebSocket-Protocol");
if (!sec_websocket_protocol) {
/* A missing header means we have no requested subprotocols. */
return APR_SUCCESS;
}
error = parse_token_list_strict(r->pool, sec_websocket_protocol, protocols);
if (!error && apr_is_empty_array(protocols)) {
/* Sec-WebSocket-Protocol must contain at least one valid token. */
error = "Header contains no subprotocols";
}
if (error) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, APR_SUCCESS, r,
"Client sent invalid Sec-WebSocket-Protocol: %s", error);
return APR_EINVAL;
}
return APR_SUCCESS;
}
/*
* Parses the protocol version from a Sec-WebSocket-Version header. Returns -1
* if the version is invalid or prohibited by the RFC.
*/
static apr_int64_t parse_protocol_version(const char *version)
{
size_t len;
apr_int64_t result;
if (!version) {
return -1;
}
len = strlen(version);
/*
* We perform our checks up front because apr_atoi64() is rather permissive
* in what it allows.
*
* The rules:
* - No empty strings.
* - All characters must be digits 0-9.
* - No leading zeroes ("0" is okay, but not "013").
* - Only values 0-255 are allowed.
*/
if ((len < 1) || !apr_isdigit(version[0]) ||
((len > 1) && (!apr_isdigit(version[1]) || (version[0] == '0'))) ||
((len > 2) && !apr_isdigit(version[2])) ||
(len > 3)) {
return -1;
}
result = apr_atoi64(version);
if (result < 0 || result > 255) {
return -1;
}
return result;
}
/* Checks whether a string is a valid Sec-WebSocket-Key. */
static int is_valid_key(const char *key)
{
/*
* The key has to be a Base64-encoded value that decodes to 16 bytes long.
* That means a valid encoded value is exactly 24 bytes long, with one of
* the values 'A', 'Q', 'g', or 'w' for the final encoded character, and two
* bytes of padding ("==") at the end.
*/
static const char * const base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const char * const final_chars = "AQgw";
if (!key) {
return 0;
}
return ((strlen(key) == 24) &&
(strspn(key, base64_chars) == 22) &&
(strspn(key + 21, final_chars) == 1) &&
(key[22] == '=') && (key[23] == '='));
}
/*
* Checks whether or not a parsed protocol version is supported by this module.
*/
static int is_supported_version(apr_int64_t version)
{
int i;
for (i = 0; i < supported_versions_len; ++i) {
if (version == supported_versions[i]) {
return 1;
}
}
return 0;
}
/*
* Creates a Sec-WebSocket-Version header value containing the supported
* protocol versions.
*/
static const char *make_supported_version_header(apr_pool_t *pool)
{
apr_array_header_t *versions = apr_array_make(pool, supported_versions_len,
sizeof(const char*));
int i;
/* Convert our supported versions to strings. */
for (i = 0; i < supported_versions_len; ++i) {
const char **new = (const char **) apr_array_push(versions);
*new = apr_itoa(pool, supported_versions[i]);
}
/* Concatenate the version strings into a single header value. */
return apr_array_pstrcat(pool, versions, ',');
}
typedef struct _WebSocketFrameData
{
struct ap_varbuf message_buf;
unsigned char fin;
unsigned char opcode;
unsigned int utf8_state;
apr_int64_t message_length; /* length of the current message so far */
} WebSocketFrameData;
/* Variables that need to persist across calls to mod_websocket_handle_incoming */
typedef struct
{
int framing_state;
int closing; /* should the connection be closed due to incoming data? */
unsigned short status_code;
/* XXX fin and opcode appear to be duplicated with frame; can they be removed? */
unsigned char fin;
unsigned char opcode;
WebSocketFrameData control_frame;
WebSocketFrameData message_frame;
WebSocketFrameData *frame;
apr_int64_t payload_length; /* length of the current frame */
apr_int64_t mask_offset;
apr_int64_t extension_bytes_remaining;
int payload_length_bytes_remaining;
int masking;
int mask_index;
unsigned char mask[4];
} WebSocketReadState;
/*
* Returns 1 if the given status code is prohibited from being sent by an
* endpoint.
*/
static int is_prohibited_status_code(unsigned short status)
{
return (
/* 0-999 are not used. */
(status < STATUS_CODE_OK) ||
/* These three codes are reserved for client-side use. */
(status == 1005) ||
(status == 1006) ||
(status == 1015) ||
/* The spec only defines up to 4999. Be conservative and reject. */
(status >= 5000)
);
}
/*
* Returns 1 if the given status code is currently marked reserved/unassigned by
* the RFC and the close code registry, but it is not explicitly prohibited from
* being sent by an endpoint.
*/
static int is_reserved_status_code(unsigned short status)
{
return (
/* Reserved -- old code from protocol version 8 */
(status == STATUS_CODE_RESERVED) ||
/* Unassigned. */
(status == 1014) ||
((status >= 1016) && (status < 3000))
);
}
/*
* Checks the reason buffer for a Close frame and verifies that the status code
* (contained in the first two bytes) is not prohibited by RFC 6455.
*
* The reject_reserved parameter controls whether reserved/unassigned codes are
* rejected.
*/
static int is_valid_status_code(const unsigned char *buffer, size_t buffer_size,
int reject_reserved)
{
unsigned short status;
if (buffer_size < 2) {
/* There is no status code; consider it valid. */
return 1;
}
/* The status code is in the first two bytes of the reason buffer. */
status = buffer[0] << 8;
status |= buffer[1];
return !is_prohibited_status_code(status) &&
!(reject_reserved && is_reserved_status_code(status));
}
/*
* Constructs a serialized Origin string for the request URI. See RFC 6454.
*/
static const char *construct_request_origin(request_rec *r)
{
const char *hostname = r->hostname;
apr_port_t port = ap_get_server_port(r);
if (ap_strchr_c(hostname, ':')) {
/* IPv6 hostnames need to be bracketed. */
hostname = apr_pstrcat(r->pool, "[", hostname, "]", NULL);
}
return apr_pstrcat(r->pool, ap_http_scheme(r), "://", hostname,
(ap_is_default_port(port, r) ?
NULL : apr_psprintf(r->pool, ":%d", port)),
NULL);
}
/*
* Checks the origin of the incoming handshake and determines whether it's one
* we trust.
*/
static int is_trusted_origin(request_rec *r, websocket_config_rec *conf,
apr_int64_t version) {
const char *request_origin;
const char *origin;
int mode = conf->origin_check;
if (mode == ORIGIN_CHECK_OFF) {
/* No checks; trust everything. */
return 1;
}
/*
* Versions 8 (HyBi draft 12) and 13 use the Origin header; protocol 7 uses
* Sec-WebSocket-Origin.
*/
origin = apr_table_get(r->headers_in, (version < 8) ? "Sec-WebSocket-Origin"
: "Origin");
if (!origin) {
/*
* A request without an Origin is not made on behalf of a user by a
* user-agent, so we don't need to apply same-origin protection.
*/
return 1;
}
if (mode == ORIGIN_CHECK_SAME) {
/*
* The origin of the request and the Origin sent by the user-agent must
* match exactly.
*/
request_origin = construct_request_origin(r);
if (!request_origin) {
return 0;
}
if (strcmp(origin, request_origin)) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, APR_SUCCESS, r,
"Origin header '%s' sent by user-agent does not match "
"request origin '%s'; rejecting WebSocket upgrade",
origin, request_origin);
return 0;
}
return 1;
} else if (mode == ORIGIN_CHECK_TRUSTED) {
/*
* See if the Origin is in our allowlist.
*/
void *val = apr_hash_get(conf->trusted_origins, origin,
APR_HASH_KEY_STRING);