forked from deplinenoise/webby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webby.c
1726 lines (1424 loc) · 43.4 KB
/
webby.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
#include "webby.h"
/* Copyright (c) 2012, Andreas Fredriksson < dep at defmacro dot se > */
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <ctype.h>
#if defined(__PS3__)
#include "webby_ps3.h"
#elif defined(__XBOX__)
#include "webby_xbox.h"
#elif defined(_WIN32)
#include "webby_win32.h"
#else
#include "webby_unix.h"
#endif
#define WB_WEBSOCKET_VERSION "13"
#define WB_ALIGN_ARB(x, a) (((x) + ((a)-1)) & ~((a)-1))
#define WB_ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
static const char continue_header[] = "HTTP/1.1 100 Continue\r\n\r\n";
static const size_t continue_header_len = sizeof(continue_header) - 1;
static const char websocket_guid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
static const size_t websocket_guid_len = sizeof(websocket_guid) - 1;
static const unsigned char websocket_pong[] = { 0x80, WEBBY_WS_OP_PONG, 0x00 };
static const struct WebbyHeader plain_text_headers[] =
{
{ "Content-Type", "text/plain" },
};
#ifdef _MSC_VER
/* MSVC keeps complaining about constant conditionals inside the FD_SET() macro. */
#pragma warning(disable: 4127)
#endif
struct WebbyConnection;
struct WebbyRequest;
enum
{
WB_ALIVE = 1 << 0,
WB_FRESH_CONNECTION = 1 << 1,
WB_CLOSE_AFTER_RESPONSE = 1 << 2,
WB_CHUNKED_RESPONSE = 1 << 3,
WB_WEBSOCKET = 1 << 4
};
enum
{
WBC_REQUEST,
WBC_SEND_CONTINUE,
WBC_SERVE,
WBC_WEBSOCKET
};
struct WebbyBuffer
{
int used;
int max;
unsigned char* data;
};
struct WebbyConnectionPrv
{
struct WebbyConnection public_data;
unsigned short flags;
unsigned short state; /* WBC_xxx */
webby_socket_t socket;
struct WebbyBuffer header_buf;
struct WebbyBuffer io_buf;
int header_body_left;
int io_data_left;
int continue_data_left;
int body_bytes_read;
struct WebbyServer* server;
struct WebbyWsFrame ws_frame;
unsigned char ws_opcode;
int blocking_count; /* number of times blocking has been requested */
};
struct WebbyServer
{
struct WebbyServerConfig config;
size_t memory_size;
webby_socket_t socket;
int connection_count;
struct WebbyConnectionPrv connections[1];
};
static void dbg(struct WebbyServer *srv, const char *fmt, ...)
{
char buffer[1024];
va_list args;
if (srv->config.flags & WEBBY_SERVER_LOG_DEBUG)
{
va_start(args, fmt);
vsnprintf(buffer, sizeof buffer, fmt, args);
va_end(args);
buffer[(sizeof buffer)-1] = '\0';
(*srv->config.log)(buffer);
}
}
static int make_connection_blocking(struct WebbyConnectionPrv *conn)
{
if (0 == conn->blocking_count)
{
if (0 != wb_set_blocking(conn->socket, 1))
{
dbg(conn->server, "failed to switch connection to blocking");
conn->flags &= ~WB_ALIVE;
return -1;
}
}
++conn->blocking_count;
return 0;
}
static int make_connection_nonblocking(struct WebbyConnectionPrv *conn)
{
int count = conn->blocking_count;
if (1 == count)
{
if (0 != wb_set_blocking(conn->socket, 0))
{
dbg(conn->server, "failed to switch connection to non-blocking");
conn->flags &= ~WB_ALIVE;
return -1;
}
}
conn->blocking_count = count - 1;
return 0;
}
/* URL-decode input buffer into destination buffer.
* 0-terminate the destination buffer. Return the length of decoded data.
* form-url-encoded data differs from URI encoding in a way that it
* uses '+' as character for space, see RFC 1866 section 8.2.1
* http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
*
* This bit of code was taken from mongoose.
*/
static size_t url_decode(const char *src, size_t src_len, char *dst, size_t dst_len, int is_form_url_encoded)
{
size_t i, j;
int a, b;
#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
if (src[i] == '%' &&
isxdigit(* (const unsigned char *) (src + i + 1)) &&
isxdigit(* (const unsigned char *) (src + i + 2))) {
a = tolower(* (const unsigned char *) (src + i + 1));
b = tolower(* (const unsigned char *) (src + i + 2));
dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
i += 2;
} else if (is_form_url_encoded && src[i] == '+') {
dst[j] = ' ';
} else {
dst[j] = src[i];
}
}
#undef HEXTOI
dst[j] = '\0'; /* Null-terminate the destination */
return j;
}
/* Pulled from mongoose */
int WebbyFindQueryVar(const char *buf, const char *name, char *dst, size_t dst_len)
{
const char *p, *e, *s;
size_t name_len;
int len;
size_t buf_len = strlen(buf);
name_len = strlen(name);
e = buf + buf_len;
len = -1;
dst[0] = '\0';
// buf is "var1=val1&var2=val2...". Find variable first
for (p = buf; p != NULL && p + name_len < e; p++)
{
if ((p == buf || p[-1] == '&') && p[name_len] == '=' && 0 == strncasecmp(name, p, name_len))
{
// Point p to variable value
p += name_len + 1;
// Point s to the end of the value
s = (const char *) memchr(p, '&', (size_t)(e - p));
if (s == NULL) {
s = e;
}
assert(s >= p);
// Decode variable into destination buffer
if ((size_t) (s - p) < dst_len)
{
len = (int) url_decode(p, (size_t)(s - p), dst, dst_len, 1);
}
break;
}
}
return len;
}
enum
{
BASE64_QUADS_BEFORE_LINEBREAK = 19
};
static size_t base64_bufsize(size_t input_size)
{
size_t triplets = (input_size + 2) / 3;
size_t base_size = 4 * triplets;
size_t line_breaks = 2 * (triplets / BASE64_QUADS_BEFORE_LINEBREAK);
size_t null_termination = 1;
return base_size + line_breaks + null_termination;
}
static int base64_encode(char* output, size_t output_size, const unsigned char *input, size_t input_size)
{
static const char enc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
size_t i = 0;
int line_out = 0;
if (output_size < base64_bufsize(input_size))
return 1;
while (i < input_size)
{
unsigned int idx_0, idx_1, idx_2, idx_3;
unsigned int i0;
i0 = (input[i]) << 16; i++;
i0 |= (i < input_size ? input[i] : 0) << 8; i++;
i0 |= (i < input_size ? input[i] : 0); i++;
idx_0 = (i0 & 0xfc0000) >> 18; i0 <<= 6;
idx_1 = (i0 & 0xfc0000) >> 18; i0 <<= 6;
idx_2 = (i0 & 0xfc0000) >> 18; i0 <<= 6;
idx_3 = (i0 & 0xfc0000) >> 18;
if (i - 1 > input_size)
idx_2 = 64;
if (i > input_size)
idx_3 = 64;
*output++ = enc[idx_0];
*output++ = enc[idx_1];
*output++ = enc[idx_2];
*output++ = enc[idx_3];
if (++line_out == BASE64_QUADS_BEFORE_LINEBREAK) {
*output++ = '\r';
*output++ = '\n';
}
}
*output = '\0';
return 0;
}
static unsigned int sha1_rol(unsigned int value, unsigned int bits)
{
return ((value) << bits) | (value >> (32 - bits));
}
struct sha1 {
unsigned int state[5];
unsigned int msg_size[2];
size_t buf_used;
unsigned char buffer[64];
};
static void sha1_hash_block(unsigned int state[5], const unsigned char *block)
{
int i;
unsigned int a, b, c, d, e;
unsigned int w[80];
/* Prepare message schedule */
for (i = 0; i < 16; ++i)
w[i] =
(((unsigned int)block[(i*4)+0]) << 24) |
(((unsigned int)block[(i*4)+1]) << 16) |
(((unsigned int)block[(i*4)+2]) << 8) |
(((unsigned int)block[(i*4)+3]) << 0);
for (i = 16; i < 80; ++i)
w[i] = sha1_rol(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1);
/* Initialize working variables */
a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4];
/* This is the core loop for each 20-word span. */
#define SHA1_LOOP(start, end, func, constant) \
for (i = (start); i < (end); ++i) \
{ \
unsigned int t = sha1_rol(a, 5) + (func) + e + (constant) + w[i]; \
e = d; d = c; c = sha1_rol(b, 30); b = a; a = t; \
}
SHA1_LOOP( 0, 20, ((b & c) ^ (~b & d)), 0x5a827999)
SHA1_LOOP(20, 40, (b ^ c ^ d), 0x6ed9eba1)
SHA1_LOOP(40, 60, ((b & c) ^ (b & d) ^ (c & d)), 0x8f1bbcdc)
SHA1_LOOP(60, 80, (b ^ c ^ d), 0xca62c1d6)
#undef SHA1_LOOP
/* Update state */
state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e;
}
static void sha1_init(struct sha1 *s)
{
s->state[0] = 0x67452301;
s->state[1] = 0xefcdab89;
s->state[2] = 0x98badcfe;
s->state[3] = 0x10325476;
s->state[4] = 0xc3d2e1f0;
s->msg_size[0] = 0;
s->msg_size[1] = 0;
s->buf_used = 0;
}
static void sha1_update(struct sha1 *s, const void *data_, size_t size)
{
const char *data = (const char*) data_;
unsigned int size_lo;
unsigned int size_lo_orig;
size_t remain = size;
while (remain > 0)
{
size_t buf_space = (sizeof s->buffer) - s->buf_used;
size_t copy_size = remain < buf_space ? remain : buf_space;
memcpy(s->buffer + s->buf_used, data, copy_size);
s->buf_used += copy_size;
data += copy_size;
remain -= copy_size;
if (s->buf_used == sizeof s->buffer)
{
sha1_hash_block(s->state, s->buffer);
s->buf_used = 0;
}
}
size_lo = size_lo_orig = s->msg_size[1];
size_lo += (unsigned int) (size * 8);
if (size_lo < size_lo_orig)
s->msg_size[0] += 1;
s->msg_size[1] = size_lo;
}
static void sha1_final(unsigned char digest[20], struct sha1 *s)
{
unsigned char zero = 0x00;
unsigned char one_bit = 0x80;
unsigned char count_data[8];
int i;
/* Generate size data in bit endian format */
for (i = 0; i < 8; ++i)
{
unsigned int word = s->msg_size[i >> 2];
count_data[i] = (unsigned char) (word >> ((3 - (i & 3)) * 8));
}
/* Set trailing one-bit */
sha1_update(s, &one_bit, 1);
/* Emit null padding to to make room for 64 bits of size info in the last 512 bit block */
while (s->buf_used != 56)
sha1_update(s, &zero, 1);
/* Write size in bits as last 64-bits */
sha1_update(s, count_data, 8);
/* Make sure we actually finalized our last block */
assert(0 == s->buf_used);
/* Generate digest */
for (i = 0; i < 20; ++i)
{
unsigned int word = s->state[i >> 2];
unsigned char byte = (unsigned char) ((word >> ((3 - (i & 3)) * 8)) & 0xff);
digest[i] = byte;
}
}
static int discard_incoming_data(struct WebbyConnection* conn, int count)
{
while (count > 0)
{
char buffer[1024];
int read_size = count > sizeof buffer ? sizeof buffer : count;
if (0 != WebbyRead(conn, buffer, (size_t) read_size))
return -1;
count -= read_size;
}
return 0;
}
const char *WebbyFindHeader(struct WebbyConnection *conn, const char *name)
{
int i, count;
for (i = 0, count = conn->request.header_count; i < count; ++i)
{
if (0 == strcasecmp(conn->request.headers[i].name, name))
{
return conn->request.headers[i].value;
}
}
return NULL;
}
int
WebbyServerMemoryNeeded(const struct WebbyServerConfig *config)
{
return
WB_ALIGN_ARB(sizeof(struct WebbyServer), 16) +
WB_ALIGN_ARB((config->connection_max - 1) * sizeof(struct WebbyConnection), 16) +
config->connection_max * config->request_buffer_size +
config->connection_max * config->io_buffer_size;
}
struct WebbyServer*
WebbyServerInit(struct WebbyServerConfig *config, void *memory, size_t memory_size)
{
int i;
struct WebbyServer *server = (struct WebbyServer*) memory;
unsigned char *buffer = (unsigned char*) memory;
memset(buffer, 0, memory_size);
server->config = *config;
server->memory_size = memory_size;
server->socket = WB_INVALID_SOCKET;
buffer += WB_ALIGN_ARB(sizeof(struct WebbyServer) + sizeof(struct WebbyConnection) * (config->connection_max - 1), 16);
for (i = 0; i < config->connection_max; ++i)
{
server->connections[i].server = server;
server->connections[i].header_buf.data = buffer;
buffer += config->request_buffer_size;
server->connections[i].io_buf.data = buffer;
buffer += config->io_buffer_size;
}
assert((size_t)(buffer - (unsigned char*) memory) <= memory_size);
server->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
dbg(server, "Server socket = %d", (int) server->socket);
if (!wb_valid_socket(server->socket))
{
dbg(server, "failed to initialized server socket: %d", wb_socket_error());
goto error;
}
{
int on = 1;
int off = 0;
setsockopt(server->socket, SOL_SOCKET, SO_REUSEADDR, (const char*) &on, sizeof(int));
setsockopt(server->socket, SOL_SOCKET, SO_LINGER, (const char*) &off, sizeof(int));
}
#ifdef __APPLE__
/* Don't generate SIGPIPE when writing to dead socket, we check all writes. */
signal(SIGPIPE, SIG_IGN);
#endif
if (0 != wb_set_blocking(server->socket, 0))
{
goto error;
}
{
struct sockaddr_in bind_addr;
dbg(server, "binding to %s:%d", config->bind_address, config->listening_port);
memset(&bind_addr, 0, sizeof bind_addr); // use 0.0.0.0
bind_addr.sin_family = AF_INET;
bind_addr.sin_addr.s_addr = inet_addr(config->bind_address);
bind_addr.sin_port = htons((unsigned short) config->listening_port);
if (0 != bind(server->socket, (struct sockaddr*) &bind_addr, sizeof bind_addr))
{
dbg(server, "bind() failed: %d", wb_socket_error());
goto error;
}
}
if (0 != listen(server->socket, SOMAXCONN))
{
dbg(server, "listen() failed: %d", wb_socket_error());
wb_close_socket(server->socket);
goto error;
}
dbg(server, "server initialized");
return server;
error:
if (wb_valid_socket(server->socket))
{
wb_close_socket(server->socket);
}
return NULL;
}
void WebbyServerShutdown(struct WebbyServer *srv)
{
int i;
wb_close_socket(srv->socket);
for (i = 0; i < srv->connection_count; ++i)
{
wb_close_socket(srv->connections[i].socket);
}
memset(srv, 0, srv->memory_size);
}
static int wb_config_incoming_socket(webby_socket_t socket)
{
int err;
if (0 != (err = wb_set_blocking(socket, 0)))
{
return err;
}
{
int off = 0;
setsockopt(socket, SOL_SOCKET, SO_LINGER, (const char*) &off, sizeof(int));
}
return 0;
}
static void reset_connection(struct WebbyServer *srv, struct WebbyConnectionPrv *conn)
{
conn->header_buf.used = 0;
conn->header_buf.max = srv->config.request_buffer_size;
conn->io_buf.used = 0;
conn->io_buf.max = srv->config.io_buffer_size;
conn->header_body_left = 0;
conn->io_data_left = 0;
conn->continue_data_left = 0;
conn->body_bytes_read = 0;
conn->state = WBC_REQUEST;
conn->public_data.user_data = NULL;
conn->blocking_count = 0;
}
static int wb_on_incoming(struct WebbyServer *srv)
{
int connection_index;
char WB_ALIGN(8) client_addr[64];
struct WebbyConnectionPrv* connection;
webby_socklen_t client_addr_len = sizeof client_addr;
webby_socket_t fd;
/* Make sure we have space for a new connection */
connection_index = srv->connection_count;
if (connection_index == srv->config.connection_max)
{
dbg(srv, "out of connection slots");
return 1;
}
/* Accept the incoming connection. */
fd = accept(srv->socket, (struct sockaddr*) &client_addr[0], &client_addr_len);
if (!wb_valid_socket(fd))
{
int err = wb_socket_error();
if (!wb_is_blocking_error(err))
dbg(srv, "accept() failed: %d", err);
return 1;
}
connection = &srv->connections[connection_index];
reset_connection(srv, connection);
connection->flags = WB_FRESH_CONNECTION;
srv->connection_count = connection_index + 1;
/* Configure socket */
if (0 != wb_config_incoming_socket(fd))
{
wb_close_socket(fd);
return 1;
}
/* OK, keep this connection */
dbg(srv, "tagging connection %d as alive", connection_index);
connection->flags |= WB_ALIVE;
connection->socket = fd;
return 0;
}
static int wb_peek_request_size(const unsigned char *buf, int len)
{
int i;
int max = len - 3;
for (i = 0; i < max; ++i)
{
if ('\r' != buf[i])
continue;
if ('\n' != buf[i + 1])
continue;
if ('\r' != buf[i + 2])
continue;
if ('\n' != buf[i + 3])
continue;
/* OK; we have CRLFCRLF which indicates the end of the header section */
return i + 4;
}
return -1;
}
static char* skipws(char *p)
{
for (;;)
{
char ch = *p;
if (' ' == ch || '\t' == ch)
++p;
else
break;
}
return p;
}
enum
{
WB_TOK_SKIPWS = 1 << 0
};
static int tok_inplace(char *buf, const char* separator, char *tokens[], int max, int flags)
{
int token_count = 0;
char *b = buf;
char *e = buf;
int separator_len = (int) strlen(separator);
while (token_count < max)
{
if (flags & WB_TOK_SKIPWS)
{
b = skipws(b);
}
if (NULL != (e = strstr(b, separator)))
{
int len = (int) (e - b);
if (len > 0)
{
tokens[token_count++] = b;
}
*e = '\0';
b = e + separator_len;
}
else
{
tokens[token_count++] = b;
break;
}
}
return token_count;
}
static void wb_close_client(struct WebbyServer *srv, struct WebbyConnectionPrv* connection)
{
(void) srv;
if (connection->flags & WB_ALIVE)
{
wb_close_socket(connection->socket);
connection->socket = WB_INVALID_SOCKET;
}
connection->flags = 0;
}
static int send_fully(webby_socket_t socket, const unsigned char *buffer, int size)
{
while (size > 0)
{
int err;
send_fully_retry:
err = send(socket, (const char*) buffer, size, 0);
if(err == -1)
{
if(wb_is_blocking_error(errno))
{
wb_sleep(1);
goto send_fully_retry;
}
}
if (err <= 0)
return 1;
buffer += err;
size -= err;
}
return 0;
}
static int wb_setup_request(struct WebbyServer *srv, struct WebbyConnectionPrv *connection, int request_size)
{
char* lines[WEBBY_MAX_HEADERS + 2];
int line_count;
char* tok[16];
char* query_params;
int tok_count;
int i;
int header_count;
char *buf = (char*) connection->header_buf.data;
struct WebbyRequest *req = &connection->public_data.request;
/* Null-terminate the request envelope by overwriting the last CRLF with 00LF */
buf[request_size - 2] = '\0';
/* Split header into lines */
line_count = tok_inplace(buf, "\r\n", lines, WB_ARRAY_SIZE(lines), 0);
header_count = line_count - 2;
if (line_count < 1 || header_count > WB_ARRAY_SIZE(req->headers))
return 1;
/* Parse request line */
tok_count = tok_inplace(lines[0], " ", tok, WB_ARRAY_SIZE(tok), 0);
if (3 != tok_count)
return 1;
req->method = tok[0];
req->uri = tok[1];
req->http_version = tok[2];
req->content_length = 0;
/* See if there are any query parameters */
if (NULL != (query_params = (char*) strchr(req->uri, '?')))
{
req->query_params = query_params + 1;
*query_params = '\0';
}
else
req->query_params = NULL;
/* Decode the URI in place */
{
size_t uri_len = strlen(req->uri);
url_decode(req->uri, uri_len, (char*) req->uri, uri_len + 1, /* url encoded: */ 1);
}
/* Parse headers */
for (i = 0; i < header_count; ++i)
{
tok_count = tok_inplace(lines[i + 1], ":", tok, 2, WB_TOK_SKIPWS);
if (tok_count != 2)
{
return 1;
}
req->headers[i].name = tok[0];
req->headers[i].value = tok[1];
if (0 == strcasecmp("content-length", tok[0]))
{
req->content_length = strtoul(tok[1], NULL, 10);
dbg(srv, "request has body; content length is %d", req->content_length);
}
else if (0 == strcasecmp("transfer-encoding", tok[0]))
{
dbg(srv, "cowardly refusing to handle Transfer-Encoding: %s", tok[1]);
return 1;
}
}
req->header_count = header_count;
return 0;
}
enum
{
WB_FILL_OK,
WB_FILL_ERROR,
WB_FILL_FULL
};
/* Read as much as possible without blocking while there is buffer space. */
static int wb_fill_buffer(struct WebbyServer *srv, struct WebbyBuffer *buf, webby_socket_t socket)
{
int err;
int buf_left;
for (;;)
{
buf_left = buf->max - buf->used;
dbg(srv, "buffer space left = %d", buf_left);
if (0 == buf_left)
{
return WB_FILL_FULL;
}
/* Read what we can into the current buffer space. */
err = recv(socket, (char*) buf->data + buf->used, buf_left, 0);
if (err < 0)
{
int sock_err = wb_socket_error();
if (wb_is_blocking_error(sock_err))
{
return WB_FILL_OK;
}
else
{
/* Read error. Give up. */
dbg(srv, "read error %d - connection dead", sock_err);
return WB_FILL_ERROR;
}
}
else if (err == 0)
{
/* The peer has closed the connection. */
dbg(srv, "peer has closed the connection");
return WB_FILL_ERROR;
}
else
{
buf->used += err;
}
}
}
static int is_websocket_request(struct WebbyConnection* conn)
{
const char *hdr;
if (NULL == (hdr = WebbyFindHeader(conn, "Connection")))
return 0;
if (0 != strcasecmp(hdr, "Upgrade"))
return 0;
if (NULL == (hdr = WebbyFindHeader(conn, "Upgrade")))
return 0;
if (0 != strcasecmp(hdr, "websocket"))
return 0;
return 1;
}
static int send_websocket_upgrade(struct WebbyServer *srv, struct WebbyConnectionPrv* connection)
{
const char *hdr;
struct sha1 sha;
unsigned char digest[20];
char output_digest[64];
struct WebbyHeader headers[3];
struct WebbyConnection *conn = &connection->public_data;
if (0 == (srv->config.flags & WEBBY_SERVER_WEBSOCKETS))
{
dbg(srv, "websockets not enabled in server config");
return 1;
}
if (NULL == (hdr = WebbyFindHeader(conn, "Sec-WebSocket-Version")))
{
dbg(srv, "Sec-WebSocket-Version header not present");
return 1;
}
if (0 != strcmp(hdr, WB_WEBSOCKET_VERSION))
{
dbg(srv, "WebSocket version %s not supported (we only do %s)", hdr, WB_WEBSOCKET_VERSION);
return 1;
}
if (NULL == (hdr = WebbyFindHeader(conn, "Sec-WebSocket-Key")))
{
dbg(srv, "Sec-WebSocket-Key header not present");
return 1;
}
/* Compute SHA1 hash of Sec-Websocket-Key + the websocket guid as required by
* the RFC.
*
* This handshake is bullshit. It adds zero security. Just forces me to drag
* in SHA1 and create a base64 encoder.
*/
sha1_init(&sha);
sha1_update(&sha, hdr, (int) strlen(hdr));
sha1_update(&sha, websocket_guid, websocket_guid_len);
sha1_final(&digest[0], &sha);
if (0 != base64_encode(output_digest, sizeof output_digest, &digest[0], sizeof digest))
return 1;
headers[0].name = "Upgrade";
headers[0].value = "websocket";
headers[1].name = "Connection";
headers[1].value = "Upgrade";
headers[2].name = "Sec-WebSocket-Accept";
headers[2].value = output_digest;
WebbyBeginResponse(&connection->public_data, 101, 0, headers, WB_ARRAY_SIZE(headers));
WebbyEndResponse(&connection->public_data);
return 0;
}
static int scan_websocket_frame(const struct WebbyBuffer *buf, struct WebbyWsFrame *frame)
{
unsigned char flags = 0;
unsigned int len = 0;
unsigned int opcode = 0;
unsigned char* data = buf->data;
unsigned char* data_max = data + buf->used;
int i;
int len_bytes = 0;
int mask_bytes = 0;
unsigned char header0, header1;
if (buf->used < 2)
return -1;
header0 = *data++;
header1 = *data++;
if (header0 & 0x80)
{
flags |= WEBBY_WSF_FIN;
}
if (header1 & 0x80)
{
flags |= WEBBY_WSF_MASKED;
mask_bytes = 4;
}