forked from vurtun/lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.h
2017 lines (1803 loc) · 69 KB
/
web.h
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
/*
web.h - BSD LICENSE - Andreas Fredriksson
ABOUT:
This is a web server intended for debugging tools inside a
program with a continously running main loop. It's intended to be used when
all you need is something tiny and performance isn't a key concern.
NOTE: this is a single header port of Andreas Fredriksson
Webby(https://github.com/deplinenoise/webby).
Features
- Single header library to be easy to embed into your code.
- No dynamic memory allocations -- server memory is completely fixed
- No threading, all I/O and serving happens on the calling thread
- Supports socket keep-alives
- Supports the 100-Continue scheme for file uploading
- Basic support for WebSockets is available.
Because request/response I/O is synchronous on the calling thread, performance
will suffer when you are serving data. For the use-cases wby is intended for,
this is fine. You can still run wby in a background thread at your
discretion if this is a problem.
DEFINES:
WBY_IMPLEMENTATION
Generates the implementation of the library into the included file.
If not provided the library is in header only mode and can be included
in other headers or source files without problems. But only ONE file
should hold the implementation.
WBY_STATIC
The generated implementation will stay private inside implementation
file and all internal symbols and functions will only be visible inside
that file.
WBY_ASSERT
WBY_USE_ASSERT
If you define WBY_USE_ASSERT without defining ASSERT web.h
will use assert.h and asssert(). Otherwise it will use your assert
method. If you do not define WBY_USE_ASSERT no additional checks
will be added. This is the only C standard library function used
by web.
WBY_UINT_PTR
If your compiler is C99 you do not need to define this.
Otherwise, web will try default assignments for them
and validate them at compile time. If they are incorrect, you will
get compile errors and will need to define them yourself.
You can define this to 'size_t' if you use the standard library,
otherwise it needs to be able to hold the maximum addressable memory
space. If you do not define this it will default to unsigned long.
LICENSE: (BSD)
Copyright (c) 2016, Andreas Fredriksson, Micha Mettke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
CONTRIBUTORS:
Andreas Fredriksson (implementation)
Micha Mettke (single header conversion)
USAGE:
Request handling
When you configure the server, you give it a function pointer to your
dispatcher. The dispatcher is called by wby when a request has been fully
read into memory and is ready for processing. The socket the request came in on
has then been switched to blocking mode, and you're free to read any request
data using `wby_read()` (if present, check `content_length`) and then write
your response.
There are two ways to generate a response; explicit size or chunked.
When you know the size of the data
When you know in advance how big the response is going to be, you should pass
that size in bytes to `wby_response_begin()` (it will be sent as the
Content-Length header). You then call `wby_write()` to push that data out, and
finally `wby_response_end()` to finalize the response and prepare the socket
for a new request.
When the response size is dynamic
Sometimes you want to generate an arbitrary amount of text in the response, and
you don't know how much that will be. Rather than buffering everything in RAM,
you can use chunked encoding. First call `wby_response_begin()` as normal, but
pass it -1 for the content length. This triggers sending the
`Transfer-Encoding: chunked` header. You then call `wby_write()` as desired
until the response is complete. When you're done, call `wby_response_end()` to finish up.
EXAMPLES:
for a actual working example please look inside tests/wby_test.c */
#if 0
/* request and websocket handling callback */
static int dispatch(struct wby_con *connection, void *pArg);
static int websocket_connect(struct wby_con *conn, void *pArg);
static void websocket_connected(struct wby_con *con, void *pArg);
static int websocket_frame(struct wby_con *conn, const struct wby_frame *frame, void *pArg);
static void websocket_closed(struct wby_con *connection, void *pArg);
int main(int argc, const char * argv[])
{
/* setup config */
struct wby_config config;
memset(config, 0, sizeof(config));
config.address = "127.0.0.1";
config.port = 8888;
config.connection_max = 8;
config.request_buffer_size = 2048;
config.io_buffer_size = 8192;
config.dispatch = dispatch;
config.ws_connect = websocket_connect;
config.ws_connected = websocket_connected;
config.ws_frame = websocket_frame;
config.ws_closed = websocket_closed;
/* compute and allocate needed memory and start server */
struct wby_server server;
size_t needed_memory;
wby_server_init(&server, &config, &needed_memory);
void *memory = calloc(needed_memory, 1);
wby_server_start(&server, memory);
while (1) {
wby_server_update(&server);
}
wby_server_stop(&server);
free(memory);
}
#endif
/* ===============================================================
*
* HEADER
*
* =============================================================== */
#ifndef WBY_H_
#define WBY_H_
#ifdef __cplusplus
extern "C" {
#endif
#ifdef WBY_STATIC
#define WBY_API static
#else
#define WBY_API extern
#endif
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 19901L)
#include <stdint.h>
#ifndef WBY_UINT_PTR
#define WBY_UINT_PTR uintptr_t
#endif
#else
#ifndef WBY_UINT_PTR
#if defined(__i386__) || (!defined(_WIN64) && defined(_WIN32))
#define WBY_UINT_PTR unsigned long
#else
#define WBY_UINT_PTR unsigned long long
#endif
#endif
#endif
typedef unsigned char wby_byte;
typedef WBY_UINT_PTR wby_size;
typedef WBY_UINT_PTR wby_ptr;
#define WBY_OK (0)
#define WBY_FLAG(x) (1 << (x))
#ifndef WBY_MAX_HEADERS
#define WBY_MAX_HEADERS 64
#endif
struct wby_header {
const char *name;
const char *value;
};
/* A HTTP request. */
struct wby_request {
const char *method;
/* The method of the request, e.g. "GET", "POST" and so on */
const char *uri;
/* The URI that was used. */
const char *http_version;
/* The used HTTP version */
const char *query_params;
/* The query parameters passed in the URL, or NULL if none were passed. */
int content_length;
/* The number of bytes of request body that are available via WebbyRead() */
int header_count;
/* The number of headers */
struct wby_header headers[WBY_MAX_HEADERS];
/* Request headers */
};
/* Connection state, as published to the serving callback. */
struct wby_con {
struct wby_request request;
/* The request being served. Read-only. */
void *user_data;
/* User data. Read-write. wby doesn't care about this. */
};
struct wby_frame {
wby_byte flags;
wby_byte opcode;
wby_byte header_size;
wby_byte padding_;
wby_byte mask_key[4];
int payload_length;
};
enum wby_websock_flags {
WBY_WSF_FIN = WBY_FLAG(0),
WBY_WSF_MASKED = WBY_FLAG(1)
};
enum wby_websock_operation {
WBY_WSOP_CONTINUATION = 0,
WBY_WSOP_TEXT_FRAME = 1,
WBY_WSOP_BINARY_FRAME = 2,
WBY_WSOP_CLOSE = 8,
WBY_WSOP_PING = 9,
WBY_WSOP_PONG = 10
};
/* Configuration data required for starting a server. */
typedef void(*wby_log_f)(const char *msg);
struct wby_config {
void *userdata;
/* userdata which will be passed */
const char *address;
/* The bind address. Must be a textual IP address. */
unsigned short port;
/* The port to listen to. */
unsigned int connection_max;
/* Maximum number of simultaneous connections. */
wby_size request_buffer_size;
/* The size of the request buffer. This must be big enough to contain all
* headers and the request line sent by the client. 2-4k is a good size for
* this buffer. */
wby_size io_buffer_size;
/* The size of the I/O buffer, used when writing the reponse. 4k is a good
* choice for this buffer.*/
wby_log_f log;
/* Optional callback function that receives debug log text (without newlines). */
int(*dispatch)(struct wby_con *con, void *userdata);
/* Request dispatcher function. This function is called when the request
* structure is ready.
* If you decide to handle the request, call wby_response_begin(),
* wby_write() and wby_response_end() and then return 0. Otherwise, return a
* non-zero value to have Webby send back a 404 response. */
int(*ws_connect)(struct wby_con*, void *userdata);
/*WebSocket connection dispatcher. Called when an incoming request wants to
* update to a WebSocket connection.
* Return 0 to allow the connection.
* Return 1 to ignore the connection.*/
void (*ws_connected)(struct wby_con*, void *userdata);
/* Called when a WebSocket connection has been established.*/
void (*ws_closed)(struct wby_con*, void *userdata);
/*Called when a WebSocket connection has been closed.*/
int (*ws_frame)(struct wby_con*, const struct wby_frame *frame, void *userdata);
/*Called when a WebSocket data frame is incoming.
* Call wby_read() to read the payload data.
* Return non-zero to close the connection.*/
};
struct wby_connection;
struct wby_server {
struct wby_config config;
/* server configuration */
wby_size memory_size;
/* minimum required memory */
wby_ptr socket;
/* server socket */
wby_size con_count;
/* number of active connection */
struct wby_connection *con;
/* connections */
#ifdef _WIN32
int windows_socket_initialized;
/* whether WSAStartup had to be called on Windows */
#endif
};
WBY_API void wby_init(struct wby_server*, const struct wby_config*,
wby_size *needed_memory);
/* this function clears the server and calculates the needed memory to run
Input:
- filled server configuration data to calculate the needed memory
Output:
- needed memory for the server to run
*/
WBY_API int wby_start(struct wby_server*, void *memory);
/* this function starts running the server in the specificed memory space. Size
* must be at least big enough as determined in the wby_server_init().
Input:
- allocated memory space to create the server into
*/
WBY_API void wby_update(struct wby_server*);
/* updates the server by being called frequenctly (at least once a frame) */
WBY_API void wby_stop(struct wby_server*);
/* stops and shutdown the server */
WBY_API int wby_response_begin(struct wby_con*, int status_code, int content_length,
const struct wby_header headers[], int header_count);
/* this function begins a response
Input:
- HTTP status code to send. (Normally 200).
- size in bytes you intend to write, or -1 for chunked encoding
- array of HTTP headers to transmit (can be NULL of header_count == 0)
- number of headers in the array
Output:
- returns 0 on success, non-zero on error.
*/
WBY_API void wby_response_end(struct wby_con*);
/* this function finishes a response. When you're done wirting the response
* body, call this function. this makes sure chunked encoding is terminated
* correctly and that the connection is setup for reuse. */
WBY_API int wby_read(struct wby_con*, void *ptr, wby_size len);
/* this function reads data from the request body. Only read what the client
* has priovided (via content_length) parameter, or you will end up blocking
* forever.
Input:
- pointer to a memory block that will be filled
- size of the memory block to fill
*/
WBY_API int wby_write(struct wby_con*, const void *ptr, wby_size len);
/* this function writes a response data to the connection. If you're not using
* chunked encoding, be careful not to send more than the specified content
* length. You can call this function multiple times as long as the total
* number of bytes matches up with the content length.
Input:
- pointer to a memory block that will be send
- size of the memory block to send
*/
WBY_API int wby_frame_begin(struct wby_con*, int opcode);
/* this function begins an outgoing websocket frame */
WBY_API int wby_frame_end(struct wby_con*);
/* this function finishes an outgoing websocket frame */
WBY_API int wby_find_query_var(const char *buf, const char *name, char *dst, wby_size dst_len);
/* this function is a helper function to lookup a query parameter given a URL
* encoded string. Returns the size of the returned data, or -1 if the query
* var wasn't found. */
WBY_API const char* wby_find_header(struct wby_con*, const char *name);
/* this convenience function to find a header in a request. Returns the value
* of the specified header, or NULL if its was not present. */
#ifdef __cplusplus
}
#endif
#endif /* WBY_H_ */
/* ===============================================================
*
* IMPLEMENTATION
*
* ===============================================================*/
#ifdef WBY_IMPLEMENTATION
typedef int wby__check_ptr_size[(sizeof(void*) == sizeof(WBY_UINT_PTR)) ? 1 : -1];
#define WBY_LEN(a) (sizeof(a)/sizeof((a)[0]))
#define WBY_UNUSED(a) ((void)(a))
#ifdef WBY_USE_ASSERT
#ifndef WBY_ASSERT
#include <assert.h>
#define WBY_ASSERT(expr) assert(expr)
#endif
#else
#define WBY_ASSERT(expr)
#endif
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#define WBY_SOCK(s) ((wby_socket)(s))
#define WBY_INTERN static
#define WBY_GLOBAL static
#define WBY_STORAGE static
/* ===============================================================
* UTIL
* ===============================================================*/
struct wby_buffer {
wby_size used;
/* current buffer size */
wby_size max;
/* buffer capacity */
wby_byte *data;
/* pointer inside a global buffer */
};
WBY_INTERN void
wby_dbg(wby_log_f log, const char *fmt, ...)
{
char buffer[1024];
va_list args;
if (!log) return;
va_start(args, fmt);
vsnprintf(buffer, sizeof buffer, fmt, args);
va_end(args);
buffer[(sizeof buffer)-1] = '\0';
log(buffer);
}
WBY_INTERN int
wb_peek_request_size(const wby_byte *buf, int len)
{
int i;
int max = len - 3;
for (i = 0; i < max; ++i) {
if ('\r' != buf[i + 0]) 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;
}
WBY_INTERN char*
wby_skipws(char *p)
{
for (;;) {
char ch = *p;
if (' ' == ch || '\t' == ch) ++p;
else break;
}
return p;
}
#define WBY_TOK_SKIPWS WBY_FLAG(0)
WBY_INTERN int
wby_tok_inplace(char *buf, const char* separator, char *tokens[], int max, int flags)
{
char *b = buf;
char *e = buf;
int token_count = 0;
int separator_len = (int)strlen(separator);
while (token_count < max) {
if (flags & WBY_TOK_SKIPWS)
b = wby_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;
}
WBY_INTERN wby_size
wby_make_websocket_header(wby_byte buffer[10], wby_byte opcode,
int payload_len, int fin)
{
buffer[0] = (wby_byte)((fin ? 0x80 : 0x00) | opcode);
if (payload_len < 126) {
buffer[1] = (wby_byte)(payload_len & 0x7f);
return 2;
} else if (payload_len < 65536) {
buffer[1] = 126;
buffer[2] = (wby_byte)(payload_len >> 8);
buffer[3] = (wby_byte)payload_len;
return 4;
} else {
buffer[1] = 127;
/* Ignore high 32-bits. I didn't want to require 64-bit types and typdef hell in the API. */
buffer[2] = buffer[3] = buffer[4] = buffer[5] = 0;
buffer[6] = (wby_byte)(payload_len >> 24);
buffer[7] = (wby_byte)(payload_len >> 16);
buffer[8] = (wby_byte)(payload_len >> 8);
buffer[9] = (wby_byte)payload_len;
return 10;
}
}
WBY_INTERN int
wby_read_buffered_data(int *data_left, struct wby_buffer* buffer,
char **dest_ptr, wby_size *dest_len)
{
int offset, read_size;
int left = *data_left;
int len;
if (left == 0)
return 0;
len = (int) *dest_len;
offset = (int)buffer->used - left;
read_size = (len > left) ? left : len;
memcpy(*dest_ptr, buffer->data + offset, (wby_size)read_size);
(*dest_ptr) += read_size;
(*dest_len) -= (wby_size) read_size;
(*data_left) -= read_size;
return read_size;
}
/* ---------------------------------------------------------------
* SOCKET
* ---------------------------------------------------------------*/
#ifdef _WIN32
#include <winsock2.h>
#pragma comment(lib, "Ws2_32.lib")
typedef SOCKET wby_socket;
typedef int wby_socklen;
typedef char wby_sockopt;
#if defined(__GNUC__)
#define WBY_ALIGN(x) __attribute__((aligned(x)))
#else
#define WBY_ALIGN(x) __declspec(align(x))
#endif
#define WBY_INVALID_SOCKET INVALID_SOCKET
#define snprintf _snprintf
WBY_INTERN int
wby_socket_error(void)
{
return WSAGetLastError();
}
#if !defined(__GNUC__)
WBY_INTERN int
strcasecmp(const char *a, const char *b)
{
return _stricmp(a, b);
}
WBY_INTERN int
strncasecmp(const char *a, const char *b, wby_size len)
{
return _strnicmp(a, b, len);
}
#endif
WBY_INTERN int
wby_socket_set_blocking(wby_socket socket, int blocking)
{
u_long val = !blocking;
return ioctlsocket(socket, FIONBIO, &val);
}
WBY_INTERN int
wby_socket_is_valid(wby_socket socket)
{
return (INVALID_SOCKET != socket);
}
WBY_INTERN void
wby_socket_close(wby_socket socket)
{
closesocket(socket);
}
WBY_INTERN int
wby_socket_is_blocking_error(int error)
{
return WSAEWOULDBLOCK == error;
}
#else /* UNIX */
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <strings.h>
typedef int wby_socket;
typedef socklen_t wby_socklen;
typedef int wby_sockopt;
#define WBY_ALIGN(x) __attribute__((aligned(x)))
#define WBY_INVALID_SOCKET (-1)
WBY_INTERN int
wby_socket_error(void)
{
return errno;
}
WBY_INTERN int
wby_socket_is_valid(wby_socket socket)
{
return (socket > 0);
}
WBY_INTERN void
wby_socket_close(wby_socket socket)
{
close(socket);
}
WBY_INTERN int
wby_socket_is_blocking_error(int error)
{
return (EAGAIN == error);
}
WBY_INTERN int
wby_socket_set_blocking(wby_socket socket, int blocking)
{
int flags = fcntl(socket, F_GETFL, 0);
if (flags < 0) return flags;
flags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
return fcntl(socket, F_SETFL, flags);
}
#endif
WBY_INTERN int
wby_socket_config_incoming(wby_socket socket)
{
wby_sockopt off = 0;
int err;
if ((err = wby_socket_set_blocking(socket, 0)) != WBY_OK) return err;
setsockopt(socket, SOL_SOCKET, SO_LINGER, (const char*) &off, sizeof(int));
return 0;
}
WBY_INTERN int
wby_socket_send(wby_socket socket, const wby_byte *buffer, int size)
{
while (size > 0) {
long err = send(socket, (const char*)buffer, (wby_size)size, 0);
if (err <= 0) return 1;
buffer += err;
size -= (int)err;
}
return 0;
}
/* Read as much as possible without blocking while there is buffer space. */
enum {WBY_FILL_OK, WBY_FILL_ERROR, WBY_FILL_FULL};
WBY_INTERN int
wby_socket_recv(wby_socket socket, struct wby_buffer *buf, wby_log_f log)
{
long err;
int buf_left;
for (;;) {
buf_left = (int)buf->max - (int)buf->used;
wby_dbg(log, "buffer space left = %d", buf_left);
if (buf_left == 0)
return WBY_FILL_FULL;
/* Read what we can into the current buffer space. */
err = recv(socket, (char*)buf->data + buf->used, (wby_size)buf_left, 0);
if (err < 0) {
int sock_err = wby_socket_error();
if (wby_socket_is_blocking_error(sock_err)) {
return WBY_FILL_OK;
} else {
/* Read error. Give up. */
wby_dbg(log, "read error %d - connection dead", sock_err);
return WBY_FILL_ERROR;
}
} else if (err == 0) {
/* The peer has closed the connection. */
wby_dbg(log, "peer has closed the connection");
return WBY_FILL_ERROR;
} else buf->used += (wby_size)err;
}
}
WBY_INTERN int
wby_socket_flush(wby_socket socket, struct wby_buffer *buf)
{
if (buf->used > 0){
if (wby_socket_send(socket, buf->data, (int)buf->used) != WBY_OK)
return 1;
}
buf->used = 0;
return 0;
}
/* ---------------------------------------------------------------
* URL
* ---------------------------------------------------------------*/
/* 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.
*/
WBY_INTERN wby_size
wby_url_decode(const char *src, wby_size src_len, char *dst, wby_size dst_len,
int is_form_url_encoded)
{
int a, b;
wby_size i, j;
#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 wby_byte*)(src + i + 1)) &&
isxdigit(*(const wby_byte*)(src + i + 2)))
{
a = tolower(*(const wby_byte*)(src + i + 1));
b = tolower(*(const wby_byte*)(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 */
WBY_API int
wby_find_query_var(const char *buf, const char *name, char *dst, wby_size dst_len)
{
const char *p, *e, *s;
wby_size name_len;
int len;
wby_size 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] == '=' &&
strncasecmp(name, p, name_len) == 0)
{
/* Point p to variable value */
p += name_len + 1;
/* Point s to the end of the value */
s = (const char *) memchr(p, '&', (wby_size)(e - p));
if (s == NULL) s = e;
WBY_ASSERT(s >= p);
/* Decode variable into destination buffer */
if ((wby_size) (s - p) < dst_len)
len = (int)wby_url_decode(p, (wby_size)(s - p), dst, dst_len, 1);
break;
}
}
return len;
}
/* ---------------------------------------------------------------
* BASE64
* ---------------------------------------------------------------*/
#define WBY_BASE64_QUADS_BEFORE_LINEBREAK 19
WBY_INTERN wby_size
wby_base64_bufsize(wby_size input_size)
{
wby_size triplets = (input_size + 2) / 3;
wby_size base_size = 4 * triplets;
wby_size line_breaks = 2 * (triplets / WBY_BASE64_QUADS_BEFORE_LINEBREAK);
wby_size null_termination = 1;
return base_size + line_breaks + null_termination;
}
WBY_INTERN int
wby_base64_encode(char* output, wby_size output_size,
const wby_byte *input, wby_size input_size)
{
wby_size i = 0;
int line_out = 0;
WBY_STORAGE const char enc[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/=";
if (output_size < wby_base64_bufsize(input_size))
return 1;
while (i < input_size) {
unsigned int idx_0, idx_1, idx_2, idx_3;
unsigned int i0;
i0 = (unsigned int)(input[i]) << 16; i++;
i0 |= (unsigned int)(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 == WBY_BASE64_QUADS_BEFORE_LINEBREAK) {
*output++ = '\r';
*output++ = '\n';
}
}
*output = '\0';
return 0;
}
/* ---------------------------------------------------------------
* SHA1
* ---------------------------------------------------------------*/
struct wby_sha1 {
unsigned int state[5];
unsigned int msg_size[2];
wby_size buf_used;
wby_byte buffer[64];
};
WBY_INTERN unsigned int
wby_sha1_rol(unsigned int value, unsigned int bits)
{
return ((value) << bits) | (value >> (32 - bits));
}
WBY_INTERN void
wby_sha1_hash_block(unsigned int state[5], const wby_byte *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] = wby_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 = wby_sha1_rol(a, 5) + (func) + e + (constant) + w[i]; \
e = d; d = c; c = wby_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;
}
WBY_INTERN void
wby_sha1_init(struct wby_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;
}
WBY_INTERN void
wby_sha1_update(struct wby_sha1 *s, const void *data_, wby_size size)
{
const char *data = (const char*)data_;
unsigned int size_lo;
unsigned int size_lo_orig;
wby_size remain = size;
while (remain > 0) {
wby_size buf_space = sizeof(s->buffer) - s->buf_used;
wby_size 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)) {
wby_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;
}
WBY_INTERN void
wby_sha1_final(wby_byte digest[20], struct wby_sha1 *s)
{
wby_byte zero = 0x00;
wby_byte one_bit = 0x80;
wby_byte 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] = (wby_byte)(word >> ((3 - (i & 3)) * 8));
}
/* Set trailing one-bit */
wby_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)
wby_sha1_update(s, &zero, 1);
/* Write size in bits as last 64-bits */
wby_sha1_update(s, count_data, 8);
/* Make sure we actually finalized our last block */
WBY_ASSERT(s->buf_used == 0);
/* Generate digest */
for (i = 0; i < 20; ++i) {
unsigned int word = s->state[i >> 2];
wby_byte byte = (wby_byte) ((word >> ((3 - (i & 3)) * 8)) & 0xff);
digest[i] = byte;
}
}
/* ---------------------------------------------------------------
* CONNECTION
* ---------------------------------------------------------------*/
#define WBY_WEBSOCKET_VERSION "13"
WBY_GLOBAL const char wby_continue_header[] = "HTTP/1.1 100 Continue\r\n\r\n";
WBY_GLOBAL const wby_size wby_continue_header_len = sizeof(wby_continue_header) - 1;
WBY_GLOBAL const char wby_websocket_guid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
WBY_GLOBAL const wby_size wby_websocket_guid_len = sizeof(wby_websocket_guid) - 1;
WBY_GLOBAL const wby_byte wby_websocket_pong[] = { 0x80, WBY_WSOP_PONG, 0x00 };
WBY_GLOBAL const struct wby_header wby_plain_text_headers[]={{"Content-Type","text/plain"}};
enum wby_connection_flags {
WBY_CON_FLAG_ALIVE = WBY_FLAG(0),
WBY_CON_FLAG_FRESH_CONNECTION = WBY_FLAG(1),
WBY_CON_FLAG_CLOSE_AFTER_RESPONSE = WBY_FLAG(2),
WBY_CON_FLAG_CHUNKED_RESPONSE = WBY_FLAG(3),
WBY_CON_FLAG_WEBSOCKET = WBY_FLAG(4)
};
enum wby_connection_state {
WBY_CON_STATE_REQUEST,
WBY_CON_STATE_SEND_CONTINUE,
WBY_CON_STATE_SERVE,
WBY_CON_STATE_WEBSOCKET
};
struct wby_connection {
struct wby_con public_data;
unsigned short flags;
unsigned short state;
wby_ptr socket;
wby_log_f log;