-
Notifications
You must be signed in to change notification settings - Fork 14
/
yhs.c
4581 lines (3690 loc) · 131 KB
/
yhs.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
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NONSTDC_NO_DEPRECATE
#include "yhs.h"
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//
// yhs - yocto HTTP server
// -----------------------
//
// `yocto' is (at the time of writing) the smallest SI prefix. It is
// very small.
//
// `yocto' refers to the server's feature set, not the size of the code.
// Though there's not THAT much to trawl through.
//
// THIS IS NOT FOR PRODUCTION USE. It's designed for use during development.
//
// yhs was written by Tom Seddon <[email protected]>.
//
// yhs is in the public domain.
//
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// Mac/iThing portajunk
#ifdef __APPLE__
#include <errno.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <ifaddrs.h>
#include <dirent.h>
#include <arpa/inet.h>
#define STRICMP(X,Y) (strcasecmp((X),(Y)))
#define STRNICMP(X,Y,N) (strncasecmp((X),(Y),(N)))
#define CLOSESOCKET(X) (close(X))
#define ALLOCA(X) (alloca(X))
typedef int SOCKET;
#define INVALID_SOCKET (-1)
#define DEBUG_BREAK() (assert(0))
#endif
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// Windows portajunk
#ifdef WIN32
#define _CRTDBG_MAP_ALLOC
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <WS2tcpip.h>
#include <windows.h>
#include <malloc.h>
#include <crtdbg.h>
typedef unsigned __int64 uint64_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int8 uint8_t;
#define STRICMP(X,Y) (_stricmp((X),(Y)))
#define STRNICMP(X,Y,N) (strnicmp((X),(Y),(N)))
#define CLOSESOCKET(X) (closesocket(X))
#define ALLOCA(X) (_alloca(X))
typedef int socklen_t;
#ifdef _MSC_VER
#pragma warning(error:4020)// too many actual parameters
#pragma warning(disable:4204)// nonstandard extension used : non-constant
// aggregate initializer (think this is part of C99
// now)
#endif//_MSC_VER
#define DEBUG_BREAK() (__debugbreak())
#endif
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
#include <limits.h>
#include <ctype.h>
#include <assert.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
#ifndef NDEBUG
#define ENABLE_UNIT_TESTS 1
#define YHS_ASSERT(X) ((X)?(void)0:(DEBUG_BREAK(),(void)0))
#else
#define YHS_ASSERT(X) ((void)0)
#endif//NDEBUG
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//
// Notes
// -----
//
// - Only one response is serviced at once. No multithreading, no funny
// business.
//
// - The connection is not reused. No need for Content-Length; just send
// whatever, the connection is closed afterwards, and the browser gets
// the picture.
//
// - I avoided implementing things I didn't absolutely have to...
//
// - Tested on the following browsers:
//
// - Safari 5 (Mac OS X)
//
// - Opera 10 (Mac OS X/Windows)
//
// - Firefox 3.5 (Windows)
//
// - Internet Explorer 6 (Windows)
//
// TODO
// ----
//
// - The PNG writing is pretty basic. It could be ten times smarter, and
// it would still be dumb as rocks.
//
// - Handle "Transfer-Encoding: chunked"? Does anything send this? At the
// very least, send some kind of error if a chunked request is received.
//
// - Send "Connection: close" as part of the response? Doesn't seem to
// bother any of the tested browsers, and it's not like they won't find
// out as the connection will get closed anyway...
//
// - Accept absolute URLs in the GET request?
//
// DONE
// ----
//
// - Support HEAD. Should be easy enough. Could be made transparent to the
// request handler by discarding the response data.
//
// - Probably want some way of deferring responses, so they can be
// serviced later during the main update loop. (Would just put the
// response on a list, and leave the socket open, so it can be referred
// to later.)
//
// - Make sure this is valid C++, or port back to C89.
//
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// Tweakables.
enum
{
// Maximum size of request, in chars, as sent (i.e. excluding trailing
// 0)
MAX_REQUEST_SIZE=8192,
// `backlog' argument for listening socket.
LISTEN_SOCKET_BACKLOG=10,
// Maximum length of format string expansion when using yhs_text*
MAX_TEXT_LEN=8192,
// Size of write buffer.
WRITE_BUF_SIZE=1000,
// Max size of server name
MAX_SERVER_NAME_SIZE=64,
// Max length of a path for the file serving component
MAX_PATH_SIZE=1000,
// Timeout, in seconds, to use when selecting sockets that are
// expected to definitely have incoming data.
EXPECTED_DATA_TIMEOUT=10,
};
// Memory allocation wrappers.
#define MALLOC(SIZE) (malloc(SIZE))
#define FREE(PTR) (free(PTR))
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static void print_message(FILE *f,const char *fmt,...)
{
va_list v;
va_start(v,fmt);
vfprintf(f,fmt,v);
va_end(v);
#ifdef _WIN32
{
char buf[1000];
va_start(v,fmt);
_vsnprintf(buf,sizeof buf,fmt,v);
buf[sizeof buf-1]=0;
va_end(v);
OutputDebugStringA(buf);
}
#endif
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static char *yhs_strdup(const char *str)
{
size_t n;
char *s;
assert(str);
n=strlen(str)+1;
s=(char *)MALLOC(n);
if(s)
memcpy(s,str,n);
return s;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// from http://nothings.org/stb.h
static void stb__sha1(const uint8_t *chunk, uint32_t h[5])
{
int i;
uint32_t a,b,c,d,e;
uint32_t w[80];
for (i=0; i < 16; ++i)
w[i]=(chunk[i*4+0]<<24)|(chunk[i*4+1]<<16)|(chunk[i*4+2]<<8)|(chunk[i*4+3]<<0);
for (i=16; i < 80; ++i) {
uint32_t t;
t = w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16];
w[i] = (t + t) | (t >> 31);
}
a = h[0];
b = h[1];
c = h[2];
d = h[3];
e = h[4];
#define STB__SHA1(k,f) \
{ \
uint32_t temp = (a << 5) + (a >> 27) + (f) + e + (k) + w[i]; \
e = d; \
d = c; \
c = (b << 30) + (b >> 2); \
b = a; \
a = temp; \
}
i=0;
for (; i < 20; ++i) STB__SHA1(0x5a827999, d ^ (b & (c ^ d)) );
for (; i < 40; ++i) STB__SHA1(0x6ed9eba1, b ^ c ^ d );
for (; i < 60; ++i) STB__SHA1(0x8f1bbcdc, (b & c) + (d & (b ^ c)) );
for (; i < 80; ++i) STB__SHA1(0xca62c1d6, b ^ c ^ d );
#undef STB__SHA1
h[0] += a;
h[1] += b;
h[2] += c;
h[3] += d;
h[4] += e;
}
void yhs_sha1(unsigned char output[20], const void *buffer_a,unsigned len)
{
unsigned char final_block[128];
uint32_t end_start, final_len, j;
int i;
const uint8_t *buffer=(const uint8_t *)buffer_a;
uint32_t h[5];
h[0] = 0x67452301;
h[1] = 0xefcdab89;
h[2] = 0x98badcfe;
h[3] = 0x10325476;
h[4] = 0xc3d2e1f0;
// we need to write padding to the last one or two
// blocks, so build those first into 'final_block'
// we have to write one special byte, plus the 8-byte length
// compute the block where the data runs out
end_start = len & ~63;
// compute the earliest we can encode the length
if (((len+9) & ~63) == end_start) {
// it all fits in one block, so fill a second-to-last block
end_start -= 64;
}
final_len = end_start + 128;
// now we need to copy the data in
assert(end_start + 128 >= len+9);
assert(end_start < len || len < 64-9);
j = 0;
if (end_start > len)
j = (uint32_t) - (int) end_start;
for (; end_start + j < len; ++j)
final_block[j] = buffer[end_start + j];
final_block[j++] = 0x80;
while (j < 128-5) // 5 byte length, so write 4 extra padding bytes
final_block[j++] = 0;
// big-endian size
final_block[j++] = (uint8_t)(len >> 29);
final_block[j++] = (uint8_t)(len >> 21);
final_block[j++] = (uint8_t)(len >> 13);
final_block[j++] = (uint8_t)(len >> 5);
final_block[j++] = (uint8_t)(len << 3);
assert(j == 128 && end_start + j == final_len);
for (j=0; j < final_len; j += 64) { // 512-bit chunks
if (j+64 >= end_start+64)
stb__sha1(&final_block[j - end_start], h);
else
stb__sha1(&buffer[j], h);
}
for (i=0; i < 5; ++i) {
output[i*4 + 0] = (uint8_t)(h[i] >> 24);
output[i*4 + 1] = (uint8_t)(h[i] >> 16);
output[i*4 + 2] = (uint8_t)(h[i] >> 8);
output[i*4 + 3] = (uint8_t)(h[i] >> 0);
}
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
enum HandlerFlags
{
HF_TOC=1,
};
struct yhsHandler
{
struct yhsHandler *next,*prev;
unsigned flags;
unsigned valid_methods;
char *res_path;
size_t res_path_len;
char *description;
yhsResPathHandlerFn handler_fn;
void *context;
};
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
struct PNGData
{
// Dimensions of image and bytes/pixel.
int w,h,bypp;
// Coords of next pixel to be written.
int x,y;
// Chunk CRC so far.
uint32_t chunk_crc;
// Adler sums for the Zlib encoding.
uint32_t adler32_s1,adler32_s2;
};
typedef struct PNGData PNGData;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
enum yhsResponseFlags
{
RF_DEFERRED=1,
RF_OWN_HEADER_DATA=2,
RF_HEAD=4,
};
enum yhsResponseType
{
RT_NONE_SET,
RT_DEFER,
// TEXT and IMAGE are distinguished for asserting purposes.
RT_TEXT,
RT_IMAGE,
RT_WEBSOCKET,
};
typedef enum yhsResponseType yhsResponseType;
enum {
MAX_WEBSOCKET_HEADER_SIZE=14,
SEC_WEBSOCKET_KEY_LEN=22,
SEC_WEBSOCKET_ACCEPT_LEN=28,
};
enum yhsResponseState
{
RS_NONE,
RS_HEADER,
RS_DATA,
};
typedef enum yhsResponseState yhsResponseState;
enum WebSocketState
{
WSS_NONE,
WSS_OPEN,
WSS_CLOSING,
WSS_CLOSED,
};
typedef enum WebSocketState WebSocketState;
enum WebSocketRecvState
{
WSRS_NONE,
WSRS_RECV,
WSRS_NEXT_FRAGMENT,
WSRS_DONE,
};
typedef enum WebSocketRecvState WebSocketRecvState;
enum WebSocketSendState
{
WSSS_NONE,
WSSS_SEND,
};
typedef enum WebSocketSendState WebSocketSendState;
enum WebSocketOpcode
{
// Data frames
WSO_CONTINUATION=0,
WSO_TEXT=1,
WSO_BINARY=2,
// Control frames
WSO_CLOSE=8,
WSO_PING=9,
WSO_PONG=10,
};
typedef enum WebSocketOpcode WebSocketOpcode;
struct WebSocketFrameHeader
{
uint8_t fin;
uint8_t opcode;
uint8_t mask;
int len;
uint8_t masking_key[4];
};
typedef struct WebSocketFrameHeader WebSocketFrameHeader;
struct KeyValuePair
{
const char *key;
const char *value;
};
typedef struct KeyValuePair KeyValuePair;
// SCHEME://HOST/PATH;PARAMS?QUERY#FRAGMENT
// \____/ \__/\___/ \____/ \___/ \______/
struct FormData
{
size_t num_controls;
KeyValuePair *controls;
char *controls_data_buffer;
};
typedef struct FormData FormData;
struct HeaderData
{
char *data;
size_t data_size;
size_t method_pos;
size_t path_pos;
size_t first_field_pos;
};
typedef struct HeaderData HeaderData;
typedef void (*WriteBufferFlushFn)(yhsRequest *);
struct WriteBufferData
{
char data[WRITE_BUF_SIZE];
size_t data_size;
WriteBufferFlushFn flush_fn;
};
typedef struct WriteBufferData WriteBufferData;
struct WebSocketRecvData
{
// websocket recv
WebSocketRecvState state;
int is_text;
int is_fragmented;
int offset;
int utf8_count;
int utf8_left;
uint32_t utf8_char;
WebSocketFrameHeader fh;
};
typedef struct WebSocketRecvData WebSocketRecvData;
struct WebSocketSendData
{
// websocket send
WebSocketSendState state;
WebSocketOpcode opcode;
int fin;
};
typedef struct WebSocketSendData WebSocketSendData;
struct WebSocketData
{
WebSocketState state;
char accept_str[SEC_WEBSOCKET_ACCEPT_LEN+1];
WebSocketSendData send;
WebSocketRecvData recv;
};
typedef struct WebSocketData WebSocketData;
struct yhsRequest
{
yhsRequest *next_deferred,*prev_deferred;
yhsRequest *next_deferred_in_chain;
unsigned flags;
yhsServer *server;
const yhsHandler *handler;
SOCKET sock;
yhsResponseType type;
yhsResponseState state;
yhsMethod method;
PNGData png;
FormData form;
HeaderData hdr;
WriteBufferData wbuf;
WebSocketData ws;
};
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
struct LogData
{
yhsBool enabled[YHS_LOG_ENDVALUE];
yhsLogFn fn;
void *context;
};
typedef struct LogData LogData;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
enum ServerState
{
SS_NONE,
SS_RUNNING,
SS_ERROR,
};
typedef enum ServerState ServerState;
struct yhsServer
{
// port to open on
int port;
//
ServerState state;
// socket that listens for incoming connections.
SOCKET listen_sock;
// doubly-linked. terminator has NULL handler_fn.
yhsHandler handlers;
// singly-linked.
yhsRequest *first_deferred;
LogData log;
// server name
char name[MAX_SERVER_NAME_SIZE];
};
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
#define SERVER_DEBUG(SERVER_PTR,...) (SERVER_MESSAGE((SERVER_PTR),DEBUG,__VA_ARGS__))
#define SERVER_INFO(SERVER_PTR,...) (SERVER_MESSAGE((SERVER_PTR),INFO,__VA_ARGS__))
#define SERVER_ERROR(SERVER_PTR,...) (SERVER_MESSAGE((SERVER_PTR),ERROR,__VA_ARGS__))
#define SERVER_MESSAGE(SERVER_PTR,CAT,...) ((SERVER_PTR)->log.enabled[YHS_LOG_##CAT]?do_log(&(SERVER_PTR)->log,YHS_LOG_##CAT,__VA_ARGS__):(void)0)
static void do_log(LogData *log,yhsLogCategory cat,const char *fmt,...)
{
char tmp[1000];
va_list v;
if(!log->enabled[cat])
return;
if(!log->fn)
return;
va_start(v,fmt);
vsnprintf(tmp,sizeof tmp,fmt,v);
tmp[sizeof tmp-1]=0;
va_end(v);
(*log->fn)(cat,tmp,log->context);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//#define YHS_ERROR(LOG_PTR,MSG) (yhs_err((LOG_PTR),__FILE__,__FUNCTION__,__LINE__,(MSG)),(void)0)
static void yhs_err(yhsServer *server,const char *file,const char *function,int line,const char *msg)
{
SERVER_ERROR(server,"YHS: Error:\n");
SERVER_ERROR(server," %s(%d): %s: %s\n",file,line,function,msg);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
#define SERVER_SOCKET_ERROR(SERVER_PTR,MSG) (yhs_socket_err((SERVER_PTR),__FILE__,__FUNCTION__,__LINE__,(MSG)),(void)0)
static void yhs_socket_err(yhsServer *server,const char *file,const char *function,int line,const char *msg)
{
#ifdef WIN32
int err=WSAGetLastError();
#else
int err=errno;
#endif
yhs_err(server,file,function,line,msg);
#ifdef WIN32
{
char msg[1000];
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,0,err,0,msg,sizeof msg,0);
while(strlen(msg)>=0&&isspace(msg[strlen(msg)-1]))
msg[strlen(msg)-1]=0;
SERVER_ERROR(server," %d - %s\n",err,msg);
}
#else
SERVER_ERROR(server," %d - %s\n",err,strerror(err));
#endif
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// static void hex_dump(const void *data,size_t data_size)
// {
// size_t i;
//
// for(i=0;i<data_size+16;i+=16)
// {
// size_t j;
// const uint8_t *line=(const uint8_t *)data+i;
//
// printf("%08lX:",i);
//
// for(j=0;j<16;++j)
// {
// if(i+j<data_size)
// printf(" %02X",line[j]);
// else
// printf(" **");
// }
//
// printf(" ");
//
// for(j=0;j<16;++j)
// {
// if(i+j<data_size)
// printf("%c",isprint(line[j])?line[j]:'.');
// else
// printf(" ");
// }
//
// printf("\n");
// }
// }
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static yhsBool create_listen_socket(yhsServer *server)
{
int good=0;
const int reuse_addr=1;
struct sockaddr_in listen_addr;
SOCKET sock=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sock<0)
{
SERVER_ERROR(server,"Create listen socket.");
goto done;
}
if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(const char *)&reuse_addr,sizeof reuse_addr)<0)
{
SERVER_ERROR(server,"Set REUSEADDR.");
goto done;
}
// Bind
memset(&listen_addr,0,sizeof listen_addr);
listen_addr.sin_family=AF_INET;
listen_addr.sin_addr.s_addr=htonl(INADDR_ANY);
assert(server->port>=0&&server->port<65536);
listen_addr.sin_port=htons((u_short)server->port);
if(bind(sock,(struct sockaddr *)&listen_addr,sizeof(listen_addr))<0)
{
SERVER_ERROR(server,"Bind listen socket.");
goto done;
}
// Listen
if(listen(sock,LISTEN_SOCKET_BACKLOG)<0)
{
SERVER_ERROR(server,"Set listen socket to listen mode.");
goto done;
}
good=1;
done:
if(!good)
{
CLOSESOCKET(sock);
sock=INVALID_SOCKET;
}
server->listen_sock=sock;
return sock;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static void print_likely_urls(yhsServer *server)
{
SERVER_INFO(server,"YHS: Likely URLs for this system are:\n");
SERVER_INFO(server,"\n");
#ifdef WIN32
{
char computer_name[500];
DWORD computer_name_size=sizeof computer_name;
if(!GetComputerNameExA(ComputerNameDnsHostname,computer_name,&computer_name_size))
SERVER_INFO(server,"YHS: Failed to get computer name.\n");
else
{
SERVER_INFO(server," http://%s",computer_name);
if(server->port!=80)
SERVER_INFO(server,":%d",server->port);
SERVER_INFO(server,"/\n");
}
}
#else
{
struct ifaddrs *interfaces;
if(getifaddrs(&interfaces)<0)
{
SERVER_INFO(server,"Get network interfaces.");
return;
}
for(struct ifaddrs *ifa=interfaces;ifa;ifa=ifa->ifa_next)
{
if(ifa->ifa_addr->sa_family==AF_INET)
{
struct sockaddr_in *addr_in=(struct sockaddr_in *)ifa->ifa_addr;
uint32_t addr=ntohl(addr_in->sin_addr.s_addr);
if(addr==0x7F000001)
continue;//don't bother printing localhost.
SERVER_INFO(server," http://%d.%d.%d.%d",(addr>>24)&0xFF,(addr>>16)&0xFF,(addr>>8)&0xFF,(addr>>0)&0xFF);
if(server->port!=80)
SERVER_INFO(server,":%d",server->port);
SERVER_INFO(server,"/\n");
}
}
freeifaddrs(interfaces);
interfaces=NULL;
SERVER_INFO(server,"\n");
}
#endif
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static void default_log_callback(yhsLogCategory category,const char *message,void *context)
{
FILE *f;
(void)context;
if(category==YHS_LOG_ERROR)
f=stderr;
else
f=stdout;
fputs(message,f);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
yhsServer *yhs_new_server(int port)
{
yhsServer *server=(yhsServer *)MALLOC(sizeof *server);
if(!server)
return NULL;
memset(server,0,sizeof *server);
server->handlers.next=&server->handlers;
server->handlers.prev=&server->handlers;
server->listen_sock=INVALID_SOCKET;
server->port=port;
yhs_set_server_log_enabled(server,YHS_LOG_ERROR,1);
yhs_set_server_log_callback(server,&default_log_callback,0);
yhs_set_server_name(server,"yhs");
return server;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
void yhs_set_server_name(yhsServer *server,const char *name)
{
strncpy(server->name,name,sizeof server->name);
server->name[sizeof server->name-1]=0;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
void yhs_delete_server(yhsServer *server)
{
yhsHandler *h;
if(!server)
return;
h=server->handlers.next;
while(h->handler_fn)
{
yhsHandler *next=h->next;
FREE(h->description);
FREE(h->res_path);
FREE(h);
h=next;
}
if(server->listen_sock!=INVALID_SOCKET)
CLOSESOCKET(server->listen_sock);
FREE(server);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static int select_socket(SOCKET sock,int num_seconds,int *is_readable,int *is_writeable)
{
struct timeval timeout;
fd_set read_fds,write_fds;
int nfds=0;
timeout.tv_sec=num_seconds;
timeout.tv_usec=0;
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4127)
#endif
if(is_readable)
{
FD_ZERO(&read_fds);
FD_SET(sock,&read_fds);
}
if(is_writeable)
{
FD_ZERO(&write_fds);
FD_SET(sock,&write_fds);
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#ifndef WIN32
nfds=sock+1;
#endif//WIN32
if(select(nfds,is_readable?&read_fds:0,is_writeable?&write_fds:0,NULL,&timeout)<0)
return 0;
if(is_readable)
*is_readable=FD_ISSET(sock,&read_fds);
if(is_writeable)
*is_writeable=FD_ISSET(sock,&write_fds);
return 1;
}
// Accepts request and stores header. *data_size is set to total data read,
// maybe including part of the payload; *request_size points just after the
// \r\n\r\n that terminates the request header.
static int accept_request(yhsServer *server,SOCKET *accepted_sock)