-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathW_http_server_C3U.c
1759 lines (1575 loc) · 44.5 KB
/
W_http_server_C3U.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
/*
* all question please send to [email protected] (or tell me directly in QQ)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <Winsock2.h>
#pragma comment(lib,"Ws2_32.lib")
#pragma warning(disable:4996)
//#define RECORD_IN_FILE 0 //宏定义后启用记录文件,否则仅显示于控制台
#define DEFAULT_PORT 80u //监听端口
#define MAX_CONNECT_NUMBER 10u //最大连接数
#define RECORD_FILE_NAME "HTTP_record.txt" //默认记录文件
#define HTTP_VERSION "HTTP/1.1" //默认HTTP版本 : 1.0=原始版 1.1=保持TCP连接,多HTTP复用TCP
#define ROOT_PATH "E:/winc/web_sinse2022/w_desktop/" //根目录
#define IP_PROTOCOL_IPv4_6 AF_INET //默认未定义既IPv4,定义生效既IPv6
#define REQUEST_BUF_SIZE_UNIT 4096u //make request缓冲区单元大小(初始化不能小于一单元大小,每次扩容一单元)
#define REQUEST_RECV_BUF_SIZE_UNIT 4096u //request接收缓冲区最小单位容量 (初始化也必须大于改大小,否则被强制扩容至该大小)
#define REQUEST_BUF_BASELINE_SIZE 512u //make request检测时小于这个大小就马上扩容
#define REQUEST_HTTP_VERSION " HTTP/1.0\r\n" //请求http版本 必须以 " HTTP/x.x\r\n"形式
#define REQUEST_RECV_SIZE_PER_TIME 1024u //request每次接收大小
#define RECV_BUFFER_SIZE 4096u //TCP首次接收缓冲区大小
#define RECV_MAX_CONTENT_LENGTH 2097152u //接收正文最大大小 2MB (2*1024*1024)
#define MAXLEN_HTTP_METHOD 7u //最大方法长度 6,+1
#define MAXLEN_HTTP_URL 2049u //最大URL长度 1024,+1
#define MAXLEN_HTTP_VERSION 9u //最大方法长度 8,+1 如 -HTTP/1.1-
#define RESPOND_CHUNK_ENCODING_THRESHOLD 102400u //返回内容超过此阈值则采用chunk编码以节省内存空间(实测回应时间会延长很多) 单位Byte
#define MAX_HTTP_HEADER_PAGE_NUM 3u //最多 3*10 个HTTP标头
#define MAX_COOKIE_PAGE 3u // 最多cookie数量:3*10 个
#define MAX_UNIT_PER_PAGE_IN_CHAIN 10u //链表每页10个
#define MAX_THREAD_LOG_ID 30000 //到达这个数后归零线程id
#define record_down(content) if(record_file){fwrite(content, sizeof(char), strlen(content), record_file);}else{printf("文件已关闭,记录失败:|%s|\n",content);} //记录到文件
#ifdef RECORD_IN_FILE
#define print_and_record(content) printf(content);record_down(content) //打印并记录
#else
#define print_and_record(content) printf(content) //打印并记录
#endif
//unsingned int typedef
typedef unsigned short u2;//2byte
typedef unsigned int u4;//4byte
typedef unsigned long long u8;//8byte
//传参用句柄与套接字组合结构体
struct param_u2_and_socket
{
u2 thread_id;
SOCKET client_socket;
};
//字典单元 结构体
struct dict_ele
{
char* name;
char* value;
};
//10单位 字典 链表 定义变量后一定要初始化len与next置零
struct dict_chain_10u
{
struct dict_ele eles[MAX_UNIT_PER_PAGE_IN_CHAIN];
u2 len;
struct dict_chain_10u* next;
};
u2 thread_total_num = 0;//HTTP连接处理线程总数
u8 thread_id_cycle = 0;//循环id池
HANDLE server_loop_handle = 0;//核心服务线程句柄
FILE* record_file = 0;// 记录与主页 文件指针
u2 cleanup = 0;//是否需要清除(WSA clean up)
struct dict_chain_10u request_headers,response_headers;//通用请求与回答标头
u2 root_path_len = 0;//根目录字符串长度
u8 index_len = 0;//index.html文件长
char* index_content = 0;//index.html文件内容
/*
* @brief 16转10进制
* @param c 要转换的字符(数字)
* @return 转换后的值,-1则为错误
*/
int hex2dec(char c)
{
if ('0' <= c && c <= '9')
{
return c - '0';
}
else if ('a' <= c && c <= 'f')
{
return c - 'a' + 10;
}
else if ('A' <= c && c <= 'F')
{
return c - 'A' + 10;
}
else
{
return -1;
}
}
/*
* @brief UTF8转ANSI
* @param str 输入的字符串
* @param result 返回解码后的字符串
*/
UTF8toANSI(const char* str, char* result)
{
int textlen;
wchar_t* turn;
textlen = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
turn = (wchar_t*)calloc((textlen + 1), sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, str, -1, turn, textlen);
textlen = WideCharToMultiByte(CP_ACP, 0, turn, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_ACP, 0, turn, -1, result, textlen, NULL, NULL);
free(turn);
return ;
}
/*
* @brief ANSI转UTF8
* @param str 输入的字符串
* @param result 返回解码后的字符串
*/
ANSItoUTF8(const char* str,char* result)
{
int textlen;
wchar_t* turn;
textlen = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0);
turn = (wchar_t*)calloc((textlen + 1) , sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, str, -1, turn, textlen);
textlen = WideCharToMultiByte(CP_UTF8, 0, turn, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_UTF8, 0, turn, -1, result, textlen, NULL, NULL);
free(turn);
return ;
}
/*
* @brief 在记录文件中记录当前时间(没有换行)
* @ param scription 记录的内容
*/
void inline print_and_record_with_time(const char* scription)
{
time_t now_t = time(0);
struct tm* now_tm = localtime(&now_t);
char now_str[32];
memset(now_str, 0, 32);
strftime(now_str, 32, "%Y-%m-%d %H:%M:%S:\t", now_tm);
u4 time_str_len = strlen(now_str);
u8 scription_len = strlen(scription);
char* output_cont = (char*)malloc(time_str_len + scription_len + 1);
memcpy(output_cont, now_str, time_str_len);
memcpy(output_cont + time_str_len, scription, scription_len + 1);
print_and_record(output_cont);
free(output_cont);
}
/*
* @brief HTTP状态码转名称
* @param state_code 状态码
* @return 返回对应名称
*/
const char* state_code_2_name(u2 state_code)
{
switch (state_code)
{
case 100:
return "Continue";
break;
case 101:
return "Switching Protocols";
break;
case 200:
return "OK";
break;
case 201:
return "Created";
break;
case 202:
return "Accepted";
break;
case 203:
return "Non-Authoritative Information";
break;
case 204:
return "No Content";
break;
case 205:
return "Reset Content";
break;
case 206:
return "Partial Content";
break;
case 300:
return "Multiple Choices";
break;
case 301:
return "Moved Permanently";
break;
case 302:
return "Found";
break;
case 303:
return "See Other";
break;
case 304:
return "Not Modified";
break;
case 305:
return "Use Proxy";
break;
case 307:
return "Temporary Redirect";
break;
case 400:
return "Bad Request";
break;
case 401:
return "Unauthorized";
break;
case 402:
return "Payment Required";
break;
case 403:
return "Forbidden";
break;
case 404:
return "Not Found";
break;
case 405:
return "Method Not Allowed";
break;
case 406:
return "Not Acceptable";
break;
case 407:
return "Proxy Authentication Required";
break;
case 408:
return "Request Time-out";
break;
case 409:
return "Conflict";
break;
case 410:
return "Gone";
break;
case 411:
return "Length Required";
break;
case 412:
return "Precondition Failed";
break;
case 413:
return "Request Entity Too Large";
break;
case 414:
return "Request-URI Too Large";
break;
case 415:
return "Unsupported Media Type";
break;
case 416:
return "Requested range not satisfiable";
break;
case 417:
return "Expectation Failed";
break;
case 500:
return "Internal Server Error";
break;
case 501:
return "Not Implemented";
break;
case 502:
return "Bad Gateway";
break;
case 503:
return "Service Unavailable";
break;
case 504:
return "Gateway Time-out";
break;
case 505:
return "HTTP Version not supported";
break;
default:
break;
}
}
/*
* @brief 文件后缀名转为HTTP协议Content-type(MIME)
* @param suffix 文件后缀名(不带.)
* @return 返回MIME
*/
const char* file_suffix_2_MIME(const char* suffix)
{
if (suffix == 0)
{
return "text/plain";
}
else if (memcmp(suffix, "html", 4) == 0)
{
return "text/html";
}
else if (memcmp(suffix, "icon", 4) == 0)
{
return "image/x-icon";
}
else if (memcmp(suffix, "docx", 4) == 0)
{
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
else if (memcmp(suffix, "xlsx", 4) == 0)
{
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
else if (memcmp(suffix, "pptx", 4) == 0)
{
return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
}
else if (memcmp(suffix, "zip", 3) == 0 || memcmp(suffix, "7z", 2) == 0)
{
return "application/zip";
}
else if (memcmp(suffix, "rar", 3) == 0)
{
return "application/rar";
}
else if (memcmp(suffix, "pdf", 3) == 0)
{
return "application/pdf";
}
else if (memcmp(suffix, "gif", 3) == 0)
{
return "image/gif";
}
else if (memcmp(suffix, "jpg", 3) == 0 || memcmp(suffix, "jpeg", 4) == 0)
{
return "image/jpeg";
}
else if (memcmp(suffix, "png", 3) == 0)
{
return "image/png";
}
else if (memcmp(suffix, "bmp", 3) == 0)
{
return "image/bmp";
}
else if (memcmp(suffix, "js", 2) == 0)
{
if (memcmp(suffix, "json", 4) == 0)
{
return "application/json";
}
else
{
return "text/javascript";
}
}
else if (memcmp(suffix, "css", 3) == 0)
{
return "text/css";
}
else if (memcmp(suffix, "mp3", 3) == 0)
{
return "audio/mpeg";
}
else if (memcmp(suffix, "mp4", 3) == 0)
{
return "video/mp4";
}
else
{
return "text/plain";
}
return "text/plain";
}
/*
* @brief 在字典链表中增加一个元素(表满则顺延到下一表或创建下一表)
* @param target 目标表
* @param ele_name 创建的元素名称
* @param ele_value 创建的元素值
*/
void dict_chain_apeend_ele(struct dict_chain_10u* target, const char* ele_name, const char* ele_value)
{
struct dict_chain_10u* handling = target;
while (handling->len == MAX_UNIT_PER_PAGE_IN_CHAIN)
{
if (handling->next==0)
handling->next = (struct dict_chain_10u*)calloc(1u, sizeof(struct dict_chain_10u));
handling = handling->next;
}
u8 len_buf = strlen(ele_name)+1;
handling->eles[handling->len].name = (char*)malloc(len_buf * sizeof(char));
memcpy(handling->eles[handling->len].name, ele_name, len_buf);
len_buf = strlen(ele_value) + 1;
handling->eles[handling->len].value = (char*)malloc(len_buf * sizeof(char));
memcpy(handling->eles[handling->len].value, ele_value, len_buf);
handling->len++;
}
/*
* @brief 释放字典链表结构体全链(链首只清空不释放)
* @param on_free 需要释放的字典链表 链头 指针
*
*/
void dict_chain_free(struct dict_chain_10u* on_free)
{
struct dict_chain_10u* freeing = on_free;
u2 chead = 1;
while (freeing->len--)
{
free(freeing->eles[freeing->len].name);
free(freeing->eles[freeing->len].value);
if (freeing->len==0)
{
if (freeing->next)
{
if (chead)
{
freeing = freeing->next;
chead = 0;
}
else
{
struct dict_chain_10u* fbuf = freeing;
freeing = freeing->next;
free(fbuf);
}
}
}
}
if (chead == 0)
{
free(freeing);
}
}
/*
* @brief 制作请求包
* @param[in,out] buf_pointer 指向结果字符串的指针的指针
* @param[in] buf_init_size 小于REQUEST_BUF_SIZE_UNIT自动补为该值
* @param[in] method 请求方法
* @param[in] url 统一资源定位符
* @param[in] url_len url长度
* @param[in] headers 自定义标头
* @param[in] content 报文内容
* @param[in] cont_len 内容长度
* @param[in] content_type 内容类型
* @return 返回buf_pointer 指向的指针的内容的长度
*/
u8 HTTP_make_request(char** buf_pointer, const u8 buf_init_size, const char* const method, const char* const url, const u8 url_len, struct dict_chain_10u* headers, const char* const content, const u8 cont_len, const char* content_type)
{
//init
u8 mpos = 0, add_size = 0, rlen = buf_init_size > REQUEST_BUF_SIZE_UNIT ? buf_init_size : REQUEST_BUF_SIZE_UNIT;
char* mbuf = (char*)malloc(rlen);
if (!mbuf)
{
printf("make_request 崩溃: malloc 无法分配要求的内存 request size:%d", rlen);
}
*buf_pointer = mbuf;
// method
if (memcmp(method, "GET", 3) == 0)
{
memcpy(mbuf, "GET /", 5);
mpos = 5;
}
else if (memcmp(method, "POST", 4) == 0)
{
memcpy(mbuf, "POST /", 6);
mpos = 6;
}
else
{
printf("make request unsopported HTTP method:%s", method);
return 0u;
}
// url
memcpy(mbuf + mpos, url, url_len);
mpos += url_len;
// version
memcpy(mbuf + mpos, REQUEST_HTTP_VERSION, 11);
mpos += 11;
if (rlen - mpos < REQUEST_BUF_BASELINE_SIZE)
{
rlen += REQUEST_BUF_SIZE_UNIT;
mbuf = (char*)realloc(mbuf, rlen);
}
//通用标头 public header
struct dict_chain_10u* on_make = &request_headers;
for (u2 num0 = 0; num0 < MAX_UNIT_PER_PAGE_IN_CHAIN * MAX_HTTP_HEADER_PAGE_NUM; num0++)
{
u2 opt = num0 % MAX_UNIT_PER_PAGE_IN_CHAIN;
if (opt == 0)
{
if (num0)
{
if (on_make->next == 0)
break;
else
on_make = on_make->next;
}
}
if (opt == on_make->len)
break;
add_size = strlen(on_make->eles[num0].name);
memcpy(mbuf + mpos, on_make->eles[num0].name, add_size);
mpos += add_size;
memcpy(mbuf + mpos, ": ", 2);
mpos += 2;
add_size = strlen(on_make->eles[num0].value);
memcpy(mbuf + mpos, on_make->eles[num0].value, add_size);
mpos += add_size;
memcpy(mbuf + mpos, "\r\n", 2);
mpos += 2;
}
if (rlen - mpos < REQUEST_BUF_BASELINE_SIZE)
{
rlen += REQUEST_BUF_SIZE_UNIT;
mbuf = (char*)realloc(mbuf, rlen);
}
//指定标头 private header
if (headers)
{
on_make = headers;
for (u2 num0 = 0; num0 < MAX_UNIT_PER_PAGE_IN_CHAIN * MAX_HTTP_HEADER_PAGE_NUM; num0++)
{
u2 opt = num0 % MAX_UNIT_PER_PAGE_IN_CHAIN;
if (opt == 0)
{
if (num0)
{
if (on_make->next == 0)
break;
else
on_make = on_make->next;
}
}
if (opt == on_make->len)
break;
add_size = strlen(on_make->eles[num0].name);
memcpy(mbuf + mpos, on_make->eles[num0].name, add_size);
mpos += add_size;
memcpy(mbuf + mpos, ": ", 2);
mpos += 2;
add_size = strlen(on_make->eles[num0].value);
memcpy(mbuf + mpos, on_make->eles[num0].value, add_size);
mpos += add_size;
memcpy(mbuf + mpos, "\r\n", 2);
mpos += 2;
}
}
if (rlen - mpos < REQUEST_BUF_BASELINE_SIZE)
{
rlen += REQUEST_BUF_SIZE_UNIT;
mbuf = (char*)realloc(mbuf, rlen);
}
//内容
if (content && cont_len && content_type)
{
//正文类型header
memcpy(mbuf + mpos, "Content-Type: ", 14);
mpos += 14;
add_size = strlen(content_type);
memcpy(mbuf + mpos, content_type, add_size);
mpos += add_size;
memcpy(mbuf + mpos, "\r\n", 2);
mpos += 2;
//正文长header
char len_str[32];
memset(len_str, 0, 32);
itoa(cont_len, len_str, 10);
memcpy(mbuf + mpos, "Content-Length: ", 16);
mpos += 16;
add_size = strlen(len_str);
memcpy(mbuf + mpos, len_str, add_size);
mpos += add_size;
memcpy(mbuf + mpos, "\r\n\r\n", 4);
mpos += 4;
//正文体
if (rlen < mpos + cont_len)
{
mbuf = (char*)realloc(mbuf, mpos + cont_len + 32u);
}
memcpy(mbuf + mpos, content, cont_len);
mpos += cont_len;
}
else
{
memcpy(mbuf + mpos, "\r\n", 2);
mpos += 2;
}
return mpos;
}
/*
* @brief 请求单个资源
* @param[in] rhost 主机 www.baidu.com / 123.456.789.1
* @param[in] rmessage 发送的报文(含方法标头内容从头到尾)
* @param[in] rmessage_len rmessage长度
* @param[out] rrecv_buf_pointer 接收缓冲区的指针的指针(指向一个未分配内存的char指针)
* @param[in] rrecv_init_buf_len 首次接收缓冲区大小
* @return 共接收的长度
*/
u8 HTTP_request(const char* const rhost, const char* const rmessage, const u8 rmessage_len, char** rrecv_buf_pointer, const u8 rrecv_init_buf_len)
{
//----------------------
// Declare and initialize variables.
int iResult;
u8 total_len = 0;
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
//-----------------------
//获取ip地址
struct addrinfo server_setting, * result;
memset(&server_setting, 0, sizeof(server_setting));
server_setting.ai_family = AF_INET;
server_setting.ai_socktype = SOCK_STREAM;
iResult = getaddrinfo(rhost, "80", &server_setting, &result);
if (iResult)
{
printf("get addr info err : getaddrinfo return code : %d err code = %d\n", iResult, WSAGetLastError());
return 0;
}
SOCKET ConnectSocket = INVALID_SOCKET;
//----------------------
// Create a SOCKET for connecting to server
ConnectSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
return 0;
}
//----------------------
// Connect to server.
iResult = connect(ConnectSocket, result->ai_addr, result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("connect failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
return 0;
}
//----------------------
// Send an initial buffer
iResult = send(ConnectSocket, rmessage, rmessage_len, 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
return 0;
}
// shutdown the connection since no more data will be sent
//iResult = shutdown(ConnectSocket, SD_SEND);
//if (iResult == SOCKET_ERROR) {
// printf("shutdown failed with error: %d\n", WSAGetLastError());
// closesocket(ConnectSocket);
//
// return 0;
//}
u8 recv_buf_len = rrecv_init_buf_len > REQUEST_RECV_BUF_SIZE_UNIT ? rrecv_init_buf_len : REQUEST_RECV_BUF_SIZE_UNIT;
char* recv_buf = (char*)malloc(recv_buf_len);
// Receive until the peer closes the connection
int recv_time_out = 5000;
setsockopt(ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&recv_time_out, sizeof(int));
u8 recv_ret = 1;
while (recv_ret)
{
recv_ret = recv(ConnectSocket, recv_buf + total_len, REQUEST_RECV_SIZE_PER_TIME, 0);
if (recv_ret == SOCKET_ERROR)
{
printf("recv接收错误,错误码:%d ,rhost:|%s|\n", WSAGetLastError(), rhost);
closesocket(ConnectSocket);
return 0;
}
total_len += recv_ret;
if (total_len + REQUEST_RECV_SIZE_PER_TIME > recv_buf_len)
{
recv_buf_len += REQUEST_RECV_BUF_SIZE_UNIT;
recv_buf = (char*)realloc(recv_buf, recv_buf_len);
if (recv_buf == 0)
{
printf("realloc failed !");
return 0;
}
}
}
*rrecv_buf_pointer = recv_buf;
// close the socket
iResult = closesocket(ConnectSocket);
if (iResult == SOCKET_ERROR) {
printf("close failed with error: %d\n", WSAGetLastError());
return 0;
}
return total_len;
}
/*
* @brief 发送HTTP回答,函数正常完成内部不做closesocket操作
* @param client 客户端套接字
* @param state_code HTTP状态码
* @param headers 在通用header (全局变量 response_headers) 上增加,(0则为空)
* @param content 报文正文内容 (长度与内容任一为0则此俩参数无效,不发送正文体与正文长header)
* @param content_len 报文正文内容长度
* @param content_type 报文正文内容类型(0则为空)
*/
void HTTP_respond(const SOCKET client, const u2 state_code, struct dict_chain_10u * headers, const char* const content, const u8 content_len, const char* const content_type)
{
//头信息栏
char send_buf[128],trans_buf[16];
memset(send_buf, 0, 128);
memset(trans_buf, 0, 16);
memcpy(send_buf, HTTP_VERSION, 8);
send_buf[8] = ' ';
itoa(state_code, trans_buf, 10);
memcpy(send_buf + 9, trans_buf, 4);
send_buf[12] = ' ';
const char* state_name = state_code_2_name(state_code);
u4 state_len = strlen(state_name);
memcpy(send_buf + 13, state_name, state_len);
memcpy(send_buf + state_len + 13, "\r\n", 2);
send(client, send_buf, state_len + 15, 0);
//通用标头
struct dict_chain_10u* on_send = &response_headers;
for (u2 num0 = 0; num0 < MAX_UNIT_PER_PAGE_IN_CHAIN * MAX_HTTP_HEADER_PAGE_NUM; num0++)
{
u2 opt = num0 % MAX_UNIT_PER_PAGE_IN_CHAIN;
if (opt == 0)
{
if (num0)
{
if (on_send->next == 0)
break;
else
on_send = on_send->next;
}
}
if (opt == on_send->len)
break;
send(client, on_send->eles[num0].name, strlen(on_send->eles[num0].name), 0);
send(client, ": ", 2, 0);
send(client, on_send->eles[num0].value, strlen(on_send->eles[num0].value), 0);
send(client, "\r\n", 2, 0);
}
//指定标头
if (headers)
{
on_send = headers;
for (u2 num0 = 0; num0 < MAX_UNIT_PER_PAGE_IN_CHAIN * MAX_HTTP_HEADER_PAGE_NUM; num0++)
{
u2 opt = num0 % MAX_UNIT_PER_PAGE_IN_CHAIN;
if (opt == 0)
{
if (num0)
{
if (on_send->next == 0)
break;
else
on_send = on_send->next;
}
}
if (opt == on_send->len)
break;
send(client, on_send->eles[num0].name, strlen(on_send->eles[num0].name), 0);
send(client, ": ", 2, 0);
send(client, on_send->eles[num0].value, strlen(on_send->eles[num0].value), 0);
send(client, "\r\n", 2, 0);
}
}
//正文类型header
if (content_type)
{
send(client, "Content-Type: ", 14, 0);
send(client, content_type, strlen(content_type), 0);
send(client, "\r\n", 2, 0);
}
//内容
if (content && content_len)
{
//正文长header
char len_str[32];
memset(len_str, 0, 32);
itoa(content_len, len_str, 10);
send(client, "Content-Length: ", 16, 0);
send(client, len_str, strlen(len_str), 0);
send(client, "\r\n\r\n", 4, 0);
//正文体
send(client, content, content_len, 0);
}
else
{
send(client, "\r\n", 2, 0);
}
}
u2 CRA_state = 0;//CRA页面所需值
/*
* @brief 主要的自定义区域,提供请求的解析数据,要求做出返回
* @param client 用户端套接字
* @param method 请求方法
* @param url 请求统一资源定位符
* @param path 请求路径
* @param query 表单
* @param fragment 定位符
* @param version HTTP版本
* @param headers 标头
* @param content 正文内容
* @param cont_len 正文内容长度
* @return 返回赋值 keep_alive,决定是否保持连接 1:保持 0: 关闭
*/
u2 reply_client(SOCKET client, const char* method, const char* url, const char* path, const char* query, const char* fragment,const char* version, const struct dict_chain_10u* headers, const char* content, u8 cont_len)
{
u2 keep_alive = 1;
//回应客户端
if (memcmp(method, "GET", 3) == 0)
{
if (memcmp(path, "index.html", 10) == 0)
{
HTTP_respond(client, 200, 0, index_content, index_len, "text/html");
}
else if (memcmp(path, "example/e.txt", 13) == 0)
{
HTTP_respond(client, 200, 0, "hello world", 11, "text/plain");
}
else//通用情况
{
u4 path_len = strlen(path);
char* request_path = (char*)malloc(root_path_len + path_len + 1, sizeof(char));
if (!request_path)
{
printf("reply_client get commnon condition : malloc failed");
}
memcpy(request_path, ROOT_PATH, root_path_len);
memcpy(request_path + root_path_len, path, path_len + 1);
request_path[root_path_len + path_len] = 0;
FILE* request_file = 0;
errno_t fo_code = fopen_s(&request_file, request_path, "rb");
free(request_path);
if (fo_code)
{
printf("文件访问错误: fopen_s path: |%s| error code: |%d| \n", path, fo_code);
HTTP_respond(client, 404, 0, 0, 0, 0);
}
else
{
fseek(request_file, 0, SEEK_END);
u8 req_flen = ftell(request_file);
fseek(request_file, 0, SEEK_SET);
if (req_flen)
{
u4 point_pos = 0;
char* file_suffix = 0;
for (u4 num = 0; num < path_len; num++)
if (path[num] == '.')
point_pos = num;
if (point_pos < path_len)
{
u2 path_rest_len = path_len - point_pos + 1;
file_suffix = (char*)malloc(path_rest_len);
memcpy(file_suffix, path + point_pos + 1, path_rest_len);
}
//内容类型content-type
char* cont_type = file_suffix_2_MIME(file_suffix);
free(file_suffix);
//自定义header
struct dict_chain_10u temporary_header = { .len = 0, .next = 0 };
struct dict_chain_10u* header_m = 0;
if (memcmp(path, "favicon.ico", 11) == 0 || memcmp(path, "maoyuna.png", 11) == 0 || memcmp(path, "dbp.png", 7) == 0)
{
header_m = &temporary_header;
dict_chain_apeend_ele(header_m, "Cache-Control", "max-age=2592000");
}
//选择传输方式
if (req_flen > RESPOND_CHUNK_ENCODING_THRESHOLD)
{
char chunk_buf[RESPOND_CHUNK_ENCODING_THRESHOLD+2];
header_m = &temporary_header;
dict_chain_apeend_ele(header_m, "Transfer-Encoding", "chunked");
HTTP_respond(client, 200, header_m, 0, 0, cont_type);//内容必须置零,否则会制作并发送内容长header
char chunk_size[64];
while (feof(request_file) == 0)
{
//循环发送直到末尾发0
u8 read_len = fread(chunk_buf, sizeof(char), RESPOND_CHUNK_ENCODING_THRESHOLD, request_file);
memset(chunk_size, 0, 64);
itoa(read_len, chunk_size, 16);
u2 size_len = strlen(chunk_size);
memcpy(chunk_size + size_len, "\r\n", 2);
memcpy(chunk_buf + read_len, "\r\n", 2);
send(client, chunk_size, size_len + 2, 0);
send(client, chunk_buf, read_len + 2, 0);
}
send(client, "0\r\n\r\n", 5, 0);
}
else
{
char* req_cont = (char*)malloc(req_flen * sizeof(char));
fread(req_cont, sizeof(char), req_flen, request_file);
HTTP_respond(client, 200, header_m, req_cont, req_flen, cont_type);
free(req_cont);
}
if (header_m)
dict_chain_free(header_m);
}
else
{
HTTP_respond(client, 204, 0, 0, 0, 0);
}
fclose(request_file);
}
}
}
else if (memcmp(method, "POST", 4) == 0)
{
if (memcmp(path, "example/e.txt",13) == 0)
{
HTTP_respond(client, 200, 0, "hello world", 11, "text/plain");
}
else if (memcmp(path, "echo", 4) == 0)
{
HTTP_respond(client, 200, 0, content, cont_len, "text/plain");