-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket_server_runtime.c
More file actions
1630 lines (1318 loc) · 47.7 KB
/
Copy pathwebsocket_server_runtime.c
File metadata and controls
1630 lines (1318 loc) · 47.7 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
/*
* Copyright (c) 2026 Aleksandr Cherednikov
* Licensed under the MIT License. See LICENSE for details.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_websocket.h"
#include "php_websocket_compat.h"
#include "Zend/zend_exceptions.h"
#include "Zend/zend_smart_str.h"
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#define WEBSOCKET_LISTEN_BACKLOG 1024
#define WEBSOCKET_ACCEPT_BATCH_LIMIT 1024
#define WEBSOCKET_LOOP_TIMEOUT_USEC 100000
#define WEBSOCKET_READ_CHUNK_SIZE 4096
typedef enum _websocket_server_frame_status {
WEBSOCKET_SERVER_FRAME_INCOMPLETE = 0,
WEBSOCKET_SERVER_FRAME_OK = 1,
WEBSOCKET_SERVER_FRAME_PROTOCOL_ERROR = 2,
WEBSOCKET_SERVER_FRAME_MESSAGE_TOO_BIG = 3,
WEBSOCKET_SERVER_FRAME_INVALID_PAYLOAD = 4,
} websocket_server_frame_status;
typedef struct _websocket_server_frame {
uint8_t opcode;
bool final;
size_t bytes_consumed;
zend_string *payload;
} websocket_server_frame;
static bool websocket_server_close_with_code(websocket_connection_object *connection_obj, zend_long code, const char *reason);
static bool websocket_server_send_bytes(int fd, const char *buffer, size_t len);
static uint64_t websocket_server_handshake_timeout_usec(websocket_server_object *intern);
static uint64_t websocket_server_idle_timeout_usec(websocket_server_object *intern);
static uint64_t websocket_server_ping_interval_usec(websocket_server_object *intern);
static uint64_t websocket_server_pong_timeout_usec(websocket_server_object *intern);
static const char websocket_bad_request_response[] =
"HTTP/1.1 400 Bad Request\r\n"
"Connection: close\r\n"
"Content-Length: 0\r\n"
"\r\n";
static const char websocket_service_unavailable_response[] =
"HTTP/1.1 503 Service Unavailable\r\n"
"Connection: close\r\n"
"Content-Length: 0\r\n"
"\r\n";
static const char websocket_forbidden_response[] =
"HTTP/1.1 403 Forbidden\r\n"
"Connection: close\r\n"
"Content-Length: 0\r\n"
"\r\n";
static uint64_t websocket_server_now_usec(void)
{
#ifdef CLOCK_MONOTONIC
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
return ((uint64_t) ts.tv_sec * 1000000u) + ((uint64_t) ts.tv_nsec / 1000u);
}
#endif
{
struct timeval tv;
if (gettimeofday(&tv, NULL) == 0) {
return ((uint64_t) tv.tv_sec * 1000000u) + (uint64_t) tv.tv_usec;
}
}
return 0;
}
static void websocket_server_close_fd(const int fd)
{
if (fd >= 0) {
while (close(fd) < 0 && errno == EINTR) {
}
}
}
static int websocket_server_set_nonblocking(const int fd)
{
const int flags = fcntl(fd, F_GETFL, 0);
if (flags < 0) {
return FAILURE;
}
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
return FAILURE;
}
return SUCCESS;
}
static bool websocket_server_call_handler(zval *handler, uint32_t param_count, zval *params)
{
zval retval;
if (Z_ISUNDEF_P(handler)) {
return true;
}
ZVAL_UNDEF(&retval);
if (call_user_function(EG(function_table), NULL, handler, &retval, param_count, params) == FAILURE) {
zend_throw_error(NULL, "Failed to call WebSocket server handler");
return false;
}
if (!Z_ISUNDEF(retval)) {
zval_ptr_dtor(&retval);
}
return !EG(exception);
}
static bool websocket_server_call_open_handler(websocket_server_object *intern, zval *connection, bool *close_requested)
{
zval retval;
zval params[1];
zval *call_params = NULL;
uint32_t param_count = 0;
*close_requested = false;
if (Z_ISUNDEF(intern->on_open)) {
return true;
}
if (connection) {
ZVAL_COPY_VALUE(¶ms[0], connection);
call_params = params;
param_count = 1;
}
ZVAL_UNDEF(&retval);
if (intern->on_open_cache_initialized) {
websocket_call_known_fcc(&intern->on_open_cache, &retval, param_count, call_params);
} else if (call_user_function(EG(function_table), NULL, &intern->on_open, &retval, param_count, call_params) == FAILURE) {
zend_throw_error(NULL, "Failed to call WebSocket server handler");
return false;
}
if (!Z_ISUNDEF(retval)) {
*close_requested = Z_TYPE(retval) == IS_FALSE;
zval_ptr_dtor(&retval);
}
return !EG(exception);
}
static const char *websocket_http_reason_phrase(const zend_long status)
{
switch (status) {
case 200:
return "OK";
case 400:
return "Bad Request";
case 401:
return "Unauthorized";
case 403:
return "Forbidden";
case 404:
return "Not Found";
case 429:
return "Too Many Requests";
case 500:
return "Internal Server Error";
case 503:
return "Service Unavailable";
default:
return "Rejected";
}
}
static bool websocket_server_send_handshake_response(const int fd, zval *response)
{
zval *status_zv;
zval *headers_zv;
zval *body_zv;
zend_long status;
zend_string *body;
zend_string *name;
zval *value;
bool has_connection = false;
bool has_content_length = false;
smart_str buffer = {0};
bool ok;
status_zv = zend_read_property(websocket_handshake_response_ce, Z_OBJ_P(response), "status", strlen("status"), 0, NULL);
headers_zv = zend_read_property(websocket_handshake_response_ce, Z_OBJ_P(response), "headers", strlen("headers"), 0, NULL);
body_zv = zend_read_property(websocket_handshake_response_ce, Z_OBJ_P(response), "body", strlen("body"), 0, NULL);
status = zval_get_long(status_zv);
body = zval_get_string(body_zv);
smart_str_append_printf(&buffer, "HTTP/1.1 %ld %s\r\n", (long) status, websocket_http_reason_phrase(status));
if (Z_TYPE_P(headers_zv) == IS_ARRAY) {
ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(headers_zv), name, value) {
if (!name || Z_TYPE_P(value) != IS_STRING) {
continue;
}
if (zend_string_equals_literal_ci(name, "Connection")) {
has_connection = true;
} else if (zend_string_equals_literal_ci(name, "Content-Length")) {
has_content_length = true;
}
smart_str_append(&buffer, name);
smart_str_appendl(&buffer, ": ", 2);
smart_str_append(&buffer, Z_STR_P(value));
smart_str_appendl(&buffer, "\r\n", 2);
} ZEND_HASH_FOREACH_END();
}
if (!has_connection) {
smart_str_appendl(&buffer, "Connection: close\r\n", strlen("Connection: close\r\n"));
}
if (!has_content_length) {
smart_str_append_printf(&buffer, "Content-Length: %zu\r\n", ZSTR_LEN(body));
}
smart_str_appendl(&buffer, "\r\n", 2);
smart_str_append(&buffer, body);
smart_str_0(&buffer);
ok = buffer.s && websocket_server_send_bytes(fd, ZSTR_VAL(buffer.s), ZSTR_LEN(buffer.s));
if (buffer.s) {
smart_str_free(&buffer);
}
zend_string_release(body);
return ok;
}
static zend_string *websocket_server_lower_header_name(const char *name, const size_t name_len)
{
zend_string *header = zend_string_init(name, name_len, false);
zend_string *lower = zend_string_tolower(header);
zend_string_release(header);
return lower;
}
static void websocket_server_add_request_header(zval *headers, const char *name, const size_t name_len, const char *value, const size_t value_len)
{
zend_string *lower_name = websocket_server_lower_header_name(name, name_len);
zval *existing = zend_hash_find(Z_ARRVAL_P(headers), lower_name);
zval header_value;
if (existing && Z_TYPE_P(existing) == IS_STRING) {
zend_string *joined = strpprintf(0, "%s, %.*s", Z_STRVAL_P(existing), (int) value_len, value);
ZVAL_STR(&header_value, joined);
zend_hash_update(Z_ARRVAL_P(headers), lower_name, &header_value);
} else {
ZVAL_STRINGL(&header_value, value, value_len);
zend_hash_update(Z_ARRVAL_P(headers), lower_name, &header_value);
}
zend_string_release(lower_name);
}
static void websocket_server_http_trim(const char **value, size_t *len)
{
while (*len > 0 && ((*value)[0] == ' ' || (*value)[0] == '\t')) {
(*value)++;
(*len)--;
}
while (*len > 0 && ((*value)[*len - 1] == ' ' || (*value)[*len - 1] == '\t')) {
(*len)--;
}
}
static bool websocket_server_create_request(zval *request, const char *buffer, const size_t bytes_consumed)
{
const char *header_end = buffer + bytes_consumed - 4;
const char *request_line_end = memchr(buffer, '\r', bytes_consumed);
const char *method_end;
const char *target_start;
const char *target_end;
const char *line;
zval headers;
if (!request_line_end || request_line_end + 1 >= buffer + bytes_consumed || request_line_end[1] != '\n') {
return false;
}
method_end = memchr(buffer, ' ', (size_t) (request_line_end - buffer));
if (!method_end) {
return false;
}
target_start = method_end + 1;
target_end = memchr(target_start, ' ', (size_t) (request_line_end - target_start));
if (!target_end) {
return false;
}
object_init_ex(request, websocket_request_ce);
zend_update_property_stringl(websocket_request_ce, Z_OBJ_P(request), "method", strlen("method"), buffer, (size_t) (method_end - buffer));
zend_update_property_stringl(websocket_request_ce, Z_OBJ_P(request), "target", strlen("target"), target_start, (size_t) (target_end - target_start));
array_init(&headers);
line = request_line_end + 2;
while (line < header_end) {
const char *line_end = memchr(line, '\r', (size_t) (header_end - line) + 1);
const char *colon;
const char *name;
const char *value;
size_t line_len;
size_t name_len;
size_t value_len;
if (!line_end || line_end + 1 >= buffer + bytes_consumed || line_end[1] != '\n') {
zval_ptr_dtor(&headers);
zval_ptr_dtor(request);
ZVAL_UNDEF(request);
return false;
}
line_len = (size_t) (line_end - line);
if (line_len == 0) {
break;
}
colon = memchr(line, ':', line_len);
if (!colon) {
zval_ptr_dtor(&headers);
zval_ptr_dtor(request);
ZVAL_UNDEF(request);
return false;
}
name = line;
name_len = (size_t) (colon - line);
value = colon + 1;
value_len = line_len - name_len - 1;
websocket_server_http_trim(&name, &name_len);
websocket_server_http_trim(&value, &value_len);
websocket_server_add_request_header(&headers, name, name_len, value, value_len);
line = line_end + 2;
}
zend_update_property(websocket_request_ce, Z_OBJ_P(request), "headers", strlen("headers"), &headers);
zval_ptr_dtor(&headers);
return true;
}
static bool websocket_server_handle_handshake_exception(websocket_connection_object *connection_obj, bool *accepted)
{
zend_object *exception = EG(exception);
zval exception_zv;
zval *response;
if (!exception || !instanceof_function(exception->ce, websocket_handshake_exception_ce)) {
return false;
}
GC_ADDREF(exception);
zend_clear_exception();
ZVAL_OBJ(&exception_zv, exception);
response = zend_read_property(websocket_handshake_exception_ce, Z_OBJ(exception_zv), "response", strlen("response"), 0, NULL);
if (Z_TYPE_P(response) == IS_OBJECT && instanceof_function(Z_OBJCE_P(response), websocket_handshake_response_ce)) {
(void) websocket_server_send_handshake_response(connection_obj->fd, response);
} else {
(void) websocket_server_send_bytes(connection_obj->fd, websocket_forbidden_response, sizeof(websocket_forbidden_response) - 1);
}
connection_obj->open = false;
*accepted = false;
zval_ptr_dtor(&exception_zv);
return true;
}
static bool websocket_server_call_handshake_handler(websocket_server_object *intern, zval *request, websocket_connection_object *connection_obj, bool *accepted)
{
zval retval;
zval params[1];
*accepted = true;
if (Z_ISUNDEF(intern->on_handshake)) {
return true;
}
ZVAL_COPY(¶ms[0], request);
ZVAL_UNDEF(&retval);
if (call_user_function(EG(function_table), NULL, &intern->on_handshake, &retval, 1, params) == FAILURE) {
zval_ptr_dtor(¶ms[0]);
zend_throw_error(NULL, "Failed to call WebSocket server handshake handler");
return false;
}
zval_ptr_dtor(¶ms[0]);
if (EG(exception)) {
if (websocket_server_handle_handshake_exception(connection_obj, accepted)) {
if (!Z_ISUNDEF(retval)) {
zval_ptr_dtor(&retval);
}
return true;
}
if (!Z_ISUNDEF(retval)) {
zval_ptr_dtor(&retval);
}
return false;
}
if (!Z_ISUNDEF(retval) && Z_TYPE(retval) != IS_NULL) {
zend_type_error("WebSocket handshake handler must return void, %s returned", websocket_zval_value_name(&retval));
zval_ptr_dtor(&retval);
return false;
}
if (!Z_ISUNDEF(retval)) {
zval_ptr_dtor(&retval);
}
return true;
}
static int websocket_server_create_listener(websocket_server_object *intern)
{
struct addrinfo hints;
struct addrinfo *addresses = NULL;
struct addrinfo *address;
char port[16];
int listener_fd = -1;
int last_errno = 0;
int error;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
snprintf(port, sizeof(port), "%ld", (long) intern->port);
error = getaddrinfo(ZSTR_VAL(intern->host), port, &hints, &addresses);
if (error != 0) {
zend_throw_error(NULL, "Cannot resolve WebSocket listen address %s:%ld: %s", ZSTR_VAL(intern->host), (long) intern->port, gai_strerror(error));
return -1;
}
for (address = addresses; address != NULL; address = address->ai_next) {
const int reuse = 1;
listener_fd = socket(address->ai_family, address->ai_socktype, address->ai_protocol);
if (listener_fd < 0) {
last_errno = errno;
continue;
}
(void) setsockopt(listener_fd, SOL_SOCKET, SO_REUSEADDR, (const void *) &reuse, sizeof(reuse));
if (websocket_server_set_nonblocking(listener_fd) == FAILURE) {
last_errno = errno;
websocket_server_close_fd(listener_fd);
listener_fd = -1;
continue;
}
if (bind(listener_fd, address->ai_addr, address->ai_addrlen) < 0) {
last_errno = errno;
websocket_server_close_fd(listener_fd);
listener_fd = -1;
continue;
}
if (listen(listener_fd, WEBSOCKET_LISTEN_BACKLOG) < 0) {
last_errno = errno;
websocket_server_close_fd(listener_fd);
listener_fd = -1;
continue;
}
break;
}
freeaddrinfo(addresses);
if (listener_fd < 0) {
zend_throw_error(NULL, "Cannot listen on %s:%ld: %s", ZSTR_VAL(intern->host), (long) intern->port, strerror(last_errno ? last_errno : errno));
}
return listener_fd;
}
static bool websocket_server_ensure_connection_capacity(websocket_server_object *intern)
{
if (intern->connection_count < intern->connection_capacity) {
return true;
}
if (intern->connection_capacity == 0) {
intern->connection_capacity = 8;
} else {
intern->connection_capacity *= 2;
}
intern->connections = erealloc(intern->connections, sizeof(zval) * intern->connection_capacity);
return true;
}
static bool websocket_server_close_connection_at(websocket_server_object *intern, size_t index, bool notify)
{
zval connection;
websocket_connection_object *connection_obj;
bool ok = true;
ZVAL_COPY_VALUE(&connection, &intern->connections[index]);
if (index + 1 < intern->connection_count) {
memmove(&intern->connections[index], &intern->connections[index + 1], sizeof(zval) * (intern->connection_count - index - 1));
}
intern->connection_count--;
connection_obj = Z_WEBSOCKET_CONNECTION_P(&connection);
connection_obj->open = false;
if (WEBSOCKET_G(driver) && connection_obj->fd >= 0) {
WEBSOCKET_G(driver)->unwatch(connection_obj->fd);
}
if (notify && connection_obj->upgraded && !connection_obj->close_notified && !Z_ISUNDEF(intern->on_close)) {
zval params[1];
connection_obj->close_notified = true;
ZVAL_COPY_VALUE(¶ms[0], &connection);
ok = websocket_server_call_handler(&intern->on_close, 1, params);
}
websocket_connection_close_socket(connection_obj);
zval_ptr_dtor(&connection);
return ok;
}
static bool websocket_server_purge_closed_connections(websocket_server_object *intern)
{
size_t i = 0;
while (i < intern->connection_count) {
websocket_connection_object *connection_obj = Z_WEBSOCKET_CONNECTION_P(&intern->connections[i]);
if (!connection_obj->open) {
if (!websocket_server_close_connection_at(intern, i, true)) {
return false;
}
continue;
}
i++;
}
return true;
}
static bool websocket_server_close_all_connections(websocket_server_object *intern, bool notify)
{
while (intern->connection_count > 0) {
if (!websocket_server_close_connection_at(intern, intern->connection_count - 1, notify)) {
return false;
}
}
return true;
}
static bool websocket_server_notify_connection_closed(websocket_server_object *intern, zval *connection, websocket_connection_object *connection_obj)
{
zval params[1];
bool ok;
if (!connection_obj->upgraded || connection_obj->close_notified || Z_ISUNDEF(intern->on_close)) {
return true;
}
connection_obj->close_notified = true;
ZVAL_COPY_VALUE(¶ms[0], connection);
ok = websocket_server_call_handler(&intern->on_close, 1, params);
return ok;
}
static bool websocket_server_connection_expired(websocket_server_object *intern, websocket_connection_object *connection_obj, const uint64_t now_usec)
{
uint64_t last_activity_usec;
uint64_t timeout_usec;
if (now_usec == 0) {
return false;
}
last_activity_usec = connection_obj->last_activity_usec ? connection_obj->last_activity_usec : connection_obj->accepted_at_usec;
if (last_activity_usec == 0 || now_usec < last_activity_usec) {
return false;
}
if (!connection_obj->upgraded) {
timeout_usec = websocket_server_handshake_timeout_usec(intern);
} else {
timeout_usec = websocket_server_idle_timeout_usec(intern);
}
return timeout_usec > 0 && now_usec - last_activity_usec >= timeout_usec;
}
static void websocket_server_close_expired_connection(websocket_connection_object *connection_obj)
{
if (connection_obj->upgraded) {
(void) websocket_server_close_with_code(connection_obj, WEBSOCKET_CLOSE_NORMAL, "idle timeout");
return;
}
websocket_connection_close_socket(connection_obj);
}
static void websocket_server_create_connection_zval(websocket_server_object *intern, zval *connection)
{
if (!Z_ISUNDEF(intern->reusable_connection)) {
ZVAL_COPY_VALUE(connection, &intern->reusable_connection);
ZVAL_UNDEF(&intern->reusable_connection);
return;
}
ZVAL_OBJ(connection, websocket_connection_ce->create_object(websocket_connection_ce));
}
static bool websocket_connection_ensure_read_capacity(websocket_connection_object *connection_obj, const size_t append_len, const size_t limit)
{
size_t needed;
size_t capacity;
if (append_len > limit || connection_obj->read_buffer_len > limit - append_len) {
return false;
}
needed = connection_obj->read_buffer_len + append_len;
if (needed <= connection_obj->read_buffer_capacity) {
return true;
}
capacity = connection_obj->read_buffer_capacity > 0 ? connection_obj->read_buffer_capacity : 1024;
while (capacity < needed) {
capacity *= 2;
}
if (capacity > limit) {
capacity = limit;
}
if (connection_obj->read_buffer) {
connection_obj->read_buffer = erealloc(connection_obj->read_buffer, capacity);
} else {
connection_obj->read_buffer = emalloc(capacity);
}
connection_obj->read_buffer_capacity = capacity;
return true;
}
static bool websocket_server_send_bytes(const int fd, const char *buffer, const size_t len)
{
size_t sent = 0;
while (sent < len) {
ssize_t written;
#ifdef MSG_NOSIGNAL
written = send(fd, buffer + sent, len - sent, MSG_NOSIGNAL);
#else
written = send(fd, buffer + sent, len - sent, 0);
#endif
if (written > 0) {
sent += (size_t) written;
continue;
}
if (written < 0 && errno == EINTR) {
continue;
}
return false;
}
return true;
}
static void websocket_connection_discard_read_bytes(websocket_connection_object *connection_obj, const size_t bytes)
{
if (bytes >= connection_obj->read_buffer_len) {
connection_obj->read_buffer_len = 0;
return;
}
memmove(connection_obj->read_buffer, connection_obj->read_buffer + bytes, connection_obj->read_buffer_len - bytes);
connection_obj->read_buffer_len -= bytes;
}
static size_t websocket_server_positive_option(websocket_server_object *intern, const char *name, const size_t name_len, const size_t fallback)
{
zval *value;
zval rv;
zend_long option_value;
if (Z_TYPE(intern->options) == IS_ARRAY) {
value = zend_hash_str_find(Z_ARRVAL(intern->options), name, name_len);
if (!value) {
return fallback;
}
} else if (Z_TYPE(intern->options) == IS_OBJECT && instanceof_function(Z_OBJCE(intern->options), websocket_server_options_ce)) {
value = zend_read_property(websocket_server_options_ce, Z_OBJ(intern->options), name, name_len, 0, &rv);
} else {
return fallback;
}
option_value = zval_get_long(value);
if (option_value <= 0) {
return fallback;
}
return (size_t) option_value;
}
static size_t websocket_server_nonnegative_option(websocket_server_object *intern, const char *name, const size_t name_len, const size_t fallback)
{
zval *value;
zval rv;
zend_long option_value;
if (Z_TYPE(intern->options) == IS_ARRAY) {
value = zend_hash_str_find(Z_ARRVAL(intern->options), name, name_len);
if (!value) {
return fallback;
}
} else if (Z_TYPE(intern->options) == IS_OBJECT && instanceof_function(Z_OBJCE(intern->options), websocket_server_options_ce)) {
value = zend_read_property(websocket_server_options_ce, Z_OBJ(intern->options), name, name_len, 0, &rv);
} else {
return fallback;
}
option_value = zval_get_long(value);
if (option_value < 0) {
return fallback;
}
return (size_t) option_value;
}
static size_t websocket_server_max_message_size(websocket_server_object *intern)
{
return websocket_server_positive_option(intern, "maxMessageSize", strlen("maxMessageSize"), WEBSOCKET_DEFAULT_MAX_MESSAGE_SIZE);
}
static size_t websocket_server_max_queued_bytes(websocket_server_object *intern)
{
return websocket_server_positive_option(intern, "maxQueuedBytes", strlen("maxQueuedBytes"), WEBSOCKET_DEFAULT_MAX_QUEUED_BYTES);
}
static size_t websocket_server_max_connections(websocket_server_object *intern)
{
return websocket_server_positive_option(intern, "maxConnections", strlen("maxConnections"), WEBSOCKET_DEFAULT_MAX_CONNECTIONS);
}
static uint64_t websocket_server_handshake_timeout_usec(websocket_server_object *intern)
{
return (uint64_t) websocket_server_positive_option(intern, "handshakeTimeoutMs", strlen("handshakeTimeoutMs"), WEBSOCKET_DEFAULT_HANDSHAKE_TIMEOUT_MS) * 1000u;
}
static uint64_t websocket_server_idle_timeout_usec(websocket_server_object *intern)
{
return (uint64_t) websocket_server_positive_option(intern, "idleTimeoutMs", strlen("idleTimeoutMs"), WEBSOCKET_DEFAULT_IDLE_TIMEOUT_MS) * 1000u;
}
static uint64_t websocket_server_ping_interval_usec(websocket_server_object *intern)
{
return (uint64_t) websocket_server_nonnegative_option(intern, "pingIntervalMs", strlen("pingIntervalMs"), WEBSOCKET_DEFAULT_PING_INTERVAL_MS) * 1000u;
}
static uint64_t websocket_server_pong_timeout_usec(websocket_server_object *intern)
{
return (uint64_t) websocket_server_positive_option(intern, "pongTimeoutMs", strlen("pongTimeoutMs"), WEBSOCKET_DEFAULT_PONG_TIMEOUT_MS) * 1000u;
}
static bool websocket_server_close_with_code(websocket_connection_object *connection_obj, const zend_long code, const char *reason)
{
zend_string *reason_string;
bool ok;
reason_string = reason ? zend_string_init(reason, strlen(reason), false) : zend_string_init("", 0, false);
ok = websocket_connection_send_close_frame(connection_obj, code, reason_string);
zend_string_release(reason_string);
if (ok) {
websocket_connection_close_after_write(connection_obj);
} else {
websocket_connection_close_socket(connection_obj);
ok = true;
}
return ok;
}
static bool websocket_server_process_heartbeat(websocket_server_object *intern, websocket_connection_object *connection_obj, const uint64_t now_usec)
{
const uint64_t ping_interval_usec = websocket_server_ping_interval_usec(intern);
const uint64_t last_activity_usec = connection_obj->last_activity_usec ? connection_obj->last_activity_usec : connection_obj->accepted_at_usec;
zend_string *payload;
bool ok;
if (ping_interval_usec == 0 || now_usec == 0 || !connection_obj->open || !connection_obj->upgraded || connection_obj->close_after_write) {
return true;
}
if (connection_obj->awaiting_pong) {
const uint64_t pong_timeout_usec = websocket_server_pong_timeout_usec(intern);
if (connection_obj->last_ping_usec > 0 && now_usec >= connection_obj->last_ping_usec && now_usec - connection_obj->last_ping_usec >= pong_timeout_usec) {
return websocket_server_close_with_code(connection_obj, WEBSOCKET_CLOSE_NORMAL, "pong timeout");
}
return true;
}
if (last_activity_usec == 0 || now_usec < last_activity_usec || now_usec - last_activity_usec < ping_interval_usec) {
return true;
}
payload = zend_string_init("", 0, false);
ok = websocket_connection_send_frame(connection_obj, payload, WEBSOCKET_OPCODE_PING);
zend_string_release(payload);
if (!ok) {
return websocket_server_close_with_code(connection_obj, WEBSOCKET_CLOSE_NORMAL, "heartbeat failed");
}
connection_obj->awaiting_pong = true;
connection_obj->last_ping_usec = now_usec;
return true;
}
static zend_always_inline void websocket_server_mask_payload(unsigned char *dst, const unsigned char *src, const size_t len, const uint8_t mask[4])
{
size_t i;
for (i = 0; i < len; i++) {
dst[i] = src[i] ^ mask[i & 3];
}
}
static websocket_server_frame_status websocket_server_parse_frame(websocket_connection_object *connection_obj, const size_t max_message_size, websocket_server_frame *frame)
{
const unsigned char *in = (const unsigned char *) connection_obj->read_buffer;
const size_t len = connection_obj->read_buffer_len;
size_t pos = 2;
uint8_t b0;
uint8_t b1;
uint64_t payload_len;
uint8_t mask[4];
size_t i;
memset(frame, 0, sizeof(*frame));
if (len < 2) {
return WEBSOCKET_SERVER_FRAME_INCOMPLETE;
}
b0 = in[0];
b1 = in[1];
frame->final = (b0 & 0x80) != 0;
frame->opcode = b0 & 0x0f;
payload_len = b1 & 0x7f;
if ((b0 & 0x70) != 0 || (b1 & 0x80) == 0) {
return WEBSOCKET_SERVER_FRAME_PROTOCOL_ERROR;
}
if (!websocket_protocol_opcode_is_valid(frame->opcode)) {
return WEBSOCKET_SERVER_FRAME_PROTOCOL_ERROR;
}
if (payload_len == 126) {
if (len < 4) {
return WEBSOCKET_SERVER_FRAME_INCOMPLETE;
}
payload_len = ((uint64_t) in[2] << 8) | in[3];
if (payload_len < 126) {
return WEBSOCKET_SERVER_FRAME_PROTOCOL_ERROR;
}
pos = 4;
} else if (payload_len == 127) {
if (len < 10) {
return WEBSOCKET_SERVER_FRAME_INCOMPLETE;
}
if ((in[2] & 0x80) != 0) {
return WEBSOCKET_SERVER_FRAME_PROTOCOL_ERROR;
}
payload_len = 0;
for (i = 0; i < 8; i++) {
payload_len = (payload_len << 8) | in[2 + i];
}
if (payload_len <= 0xffff) {
return WEBSOCKET_SERVER_FRAME_PROTOCOL_ERROR;
}
pos = 10;
}
if (websocket_protocol_opcode_is_control(frame->opcode) && (!frame->final || payload_len > 125)) {
return WEBSOCKET_SERVER_FRAME_PROTOCOL_ERROR;
}
if (!websocket_protocol_opcode_is_control(frame->opcode) && payload_len > max_message_size) {
return WEBSOCKET_SERVER_FRAME_MESSAGE_TOO_BIG;
}
if (payload_len > SIZE_MAX || payload_len > SIZE_MAX - pos || len < pos + 4) {
return WEBSOCKET_SERVER_FRAME_INCOMPLETE;
}
memcpy(mask, in + pos, sizeof(mask));
pos += 4;
if (payload_len > SIZE_MAX - pos || len < pos + (size_t) payload_len) {
return WEBSOCKET_SERVER_FRAME_INCOMPLETE;
}
if (frame->opcode == WEBSOCKET_OPCODE_CLOSE) {
if (payload_len == 1) {
return WEBSOCKET_SERVER_FRAME_PROTOCOL_ERROR;
}
if (payload_len >= 2) {
const zend_long close_code = ((zend_long) (in[pos] ^ mask[0]) << 8) | (zend_long) (in[pos + 1] ^ mask[1]);
if (!websocket_protocol_close_code_is_valid(close_code)) {
return WEBSOCKET_SERVER_FRAME_PROTOCOL_ERROR;
}
}
}
frame->payload = zend_string_alloc((size_t) payload_len, false);
websocket_server_mask_payload((unsigned char *) ZSTR_VAL(frame->payload), in + pos, (size_t) payload_len, mask);
ZSTR_VAL(frame->payload)[payload_len] = '\0';
frame->bytes_consumed = pos + (size_t) payload_len;
if (frame->opcode == WEBSOCKET_OPCODE_CLOSE && payload_len >= 2 && !websocket_protocol_is_valid_utf8(ZSTR_VAL(frame->payload) + 2, (size_t) payload_len - 2)) {
zend_string_release(frame->payload);
frame->payload = NULL;
return WEBSOCKET_SERVER_FRAME_INVALID_PAYLOAD;
}
return WEBSOCKET_SERVER_FRAME_OK;
}
static bool websocket_server_call_message_handler(websocket_server_object *intern, zval *connection, zend_string *payload, const uint8_t opcode)
{
zval params[3];
zval retval;
zend_object *type_case;
bool ok;
if (Z_ISUNDEF(intern->on_message)) {
return true;
}
type_case = websocket_protocol_message_type_from_opcode(opcode);
if (!type_case) {
return true;
}
ZVAL_COPY(¶ms[0], connection);
ZVAL_STR_COPY(¶ms[1], payload);
ZVAL_OBJ_COPY(¶ms[2], type_case);
ZVAL_UNDEF(&retval);
ok = call_user_function(EG(function_table), NULL, &intern->on_message, &retval, 3, params) != FAILURE;
zval_ptr_dtor(¶ms[0]);
zval_ptr_dtor(¶ms[1]);
zval_ptr_dtor(¶ms[2]);
if (!ok) {