-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_conn.cpp
More file actions
1178 lines (1032 loc) · 30.6 KB
/
http_conn.cpp
File metadata and controls
1178 lines (1032 loc) · 30.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "http_conn.h"
#include "util.h"
// 定义HTTP响应的一些状态信息
const char *ok_200_title = "OK";
const char *error_400_title = "Bad Request";
const char *error_400_form = "400:Your request has bad syntax or is inherently impossible to satisfy.\n";
const char *error_403_title = "Forbidden";
const char *error_403_form = "403:You do not have permission to get file from this server.\n";
const char *error_404_title = "Not Found";
const char *error_404_form = "404:The requested file was not found on this server.\n";
const char *error_500_title = "Internal Error";
const char *error_500_form = "500:There was an unusual problem serving the requested file.\n";
// 所有的客户数
int http_conn::m_epollfd = -1;
// 所有socket上的事件都被注册到同一个epoll内核事件中,所以设置成静态的
int http_conn::m_user_count = 0;
// 网站根目录
const std::string doc_root = "/home/zen/webserver/resources";
// 上传文件目录
const std::string http_conn::UPLOAD_DIR = "/home/zen/webserver/resources/uploads";
// 初始化连接
void http_conn::init(int sockfd, const sockaddr_in &addr)
{
m_sockfd = sockfd;
m_address = addr;
// 端口复用
int reuse = 1;
setsockopt(m_sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
// 添加到epoll对象中
addfd(m_epollfd, m_sockfd, true);
m_user_count++; // 总用户数+1
init();
}
void http_conn::init()
{
// 不再需要手动释放文件映射
m_file_address.reset();
bytes_to_send = 0;
bytes_have_send = 0;
m_check_state = CHECK_STATE_REQUESTLINE; // 初始化状态为解析请求首行
m_linger = false; // 默认不保持链接 Connection : keep-alive保持连接
m_start_line = 0;
m_checked_idx = 0;
m_read_idx = 0;
m_write_idx = 0;
m_method = GET; // 默认请求方式为GET
m_url.clear();
m_version.clear();
m_content_length = 0;
m_host.clear();
// 初始化文件上传相关成员
m_content_type.clear();
m_boundary.clear();
m_upload_file_name.clear();
m_is_upload_request = false;
bzero(m_read_buf, READ_BUFFER_SIZE);
bzero(m_write_buf, READ_BUFFER_SIZE);
m_real_file.clear();
}
// 关闭连接
void http_conn::close_conn()
{
if (m_sockfd != -1)
{
removefd(m_epollfd, m_sockfd);
m_sockfd = -1;
m_user_count--; // 用户数-1
// 智能指针会自动清理资源
m_file_address.reset();
}
}
// 循环读取客户数据,直到无数据可读或者对方关闭连接
bool http_conn::read()
{
if (m_read_idx >= READ_BUFFER_SIZE)
{
return false;
}
// 读取到的字节
int bytes_read = 0;
while (true)
{
// 从m_read_buf + m_read_idx索引开始保存数据,大小是READ_BUFFER_SIZE - m_read_idx
bytes_read = recv(m_sockfd, m_read_buf + m_read_idx, READ_BUFFER_SIZE - m_read_idx, 0);
if (bytes_read == -1)
{
if (errno == EAGAIN || errno == EWOULDBLOCK)
{
// 没有数据
break;
}
return false;
}
else if (bytes_read == 0)
{
// 对方关闭连接
return false;
}
m_read_idx += bytes_read;
}
printf("读取到了数据:%s\n", m_read_buf);
return true;
}
bool http_conn::write()
{
int temp = 0;
if (bytes_to_send == 0)
{
// 将要发送的字节为0,这一次响应结束。
modfd(m_epollfd, m_sockfd, EPOLLIN);
init();
return true;
}
while (1)
{
// 分散写
temp = writev(m_sockfd, m_iv, m_iv_count);
if (temp <= -1)
{
// 如果TCP写缓冲没有空间,则等待下一轮EPOLLOUT事件,虽然在此期间,
// 服务器无法立即接收到同一客户的下一个请求,但可以保证连接的完整性。
if (errno == EAGAIN)
{
modfd(m_epollfd, m_sockfd, EPOLLOUT);
return true;
}
// 智能指针会自动释放资源
m_file_address.reset();
return false;
}
bytes_to_send -= temp;
bytes_have_send += temp;
if (bytes_have_send >= m_iv[0].iov_len)
{
m_iv[0].iov_len = 0;
m_iv[1].iov_base = m_file_address.get() + (bytes_have_send - m_write_idx);
m_iv[1].iov_len = bytes_to_send;
}
else
{
m_iv[0].iov_base = m_write_buf + bytes_have_send;
m_iv[0].iov_len = m_iv[0].iov_len - temp;
}
if (bytes_to_send <= 0)
{
// 没有数据要发送了
m_file_address.reset();
modfd(m_epollfd, m_sockfd, EPOLLIN);
if (m_linger)
{
init();
return true;
}
else
{
return false;
}
}
}
}
// 由线程池中的工作线程调用,这是处理http请求的入口函数
void http_conn::process()
{
// 解析HTTP请求
HTTP_CODE read_ret = process_read();
if (read_ret == NO_REQUEST)
{
modfd(m_epollfd, m_sockfd, EPOLLIN);
return;
}
// 生成响应
bool write_ret = process_write(read_ret);
if (!write_ret)
{
close_conn();
}
modfd(m_epollfd, m_sockfd, EPOLLOUT);
}
// 主状态机,解析请求 - 使用正则表达式
http_conn::HTTP_CODE http_conn::process_read()
{
// 初始化缓冲区末尾,确保字符串正确终止
m_read_buf[m_read_idx] = '\0';
// 使用字符串视图存储完整的请求
std::string request(m_read_buf, m_read_idx);
// 检查是否包含完整的HTTP请求(至少包含\r\n\r\n)
if (request.find("\r\n\r\n") == std::string::npos)
{
return NO_REQUEST;
}
// 解析请求行
HTTP_CODE ret = parse_request_line(request);
if (ret == BAD_REQUEST)
{
return BAD_REQUEST;
}
// 解析请求头
ret = parse_headers(request);
if (ret == BAD_REQUEST)
{
return BAD_REQUEST;
}
// 如果是GET请求且没有请求体,直接处理请求
if (m_method == GET && m_content_length == 0)
{
return do_request();
}
// 处理POST请求或包含请求体的GET请求
if (m_content_length > 0)
{
// 检查是否接收到足够的数据
size_t header_end = request.find("\r\n\r\n");
if (header_end != std::string::npos &&
static_cast<size_t>(m_read_idx) < (static_cast<size_t>(m_content_length) + header_end + 4))
{
return NO_REQUEST; // 请求体数据不完整,继续读取
}
// 解析请求体
ret = parse_content(request);
if (ret == BAD_REQUEST)
{
return BAD_REQUEST;
}
// 请求体完整,处理请求
return do_request();
}
return NO_REQUEST;
}
// 解析HTTP请求行,获得请求方法、目标URL、HTTP版本
http_conn::HTTP_CODE http_conn::parse_request_line(const std::string &request)
{
// 正则表达式匹配HTTP请求行: 方法 URL HTTP版本
std::regex request_line_regex("^([A-Z]+)\\s+([^\\s]+)\\s+HTTP/([0-9]\\.[0-9])\\r\\n");
std::smatch matches;
if (!std::regex_search(request, matches, request_line_regex))
{
return BAD_REQUEST;
}
// 解析方法(支持GET和POST)
std::string method = matches[1];
if (method == "GET")
{
m_method = GET;
}
else if (method == "POST")
{
m_method = POST;
}
else
{
return BAD_REQUEST;
}
// 解析URL
std::string url = matches[2];
// 处理带有http://的URL
if (url.compare(0, 7, "http://") == 0)
{
size_t pos = url.find('/', 7);
if (pos != std::string::npos)
{
url = url.substr(pos);
}
else
{
return BAD_REQUEST;
}
}
// 处理URL,必须以/开头
if (url.empty() || url[0] != '/')
{
return BAD_REQUEST;
}
// 直接赋值给std::string成员变量
m_url = url;
// 解析HTTP版本(只支持HTTP/1.1)
std::string version = matches[3];
if (version != "1.1")
{
return BAD_REQUEST;
}
// 直接赋值给std::string成员变量
m_version = version;
return m_method == GET ? GET_REQUEST : NO_REQUEST;
}
// 解析HTTP请求的头部信息
http_conn::HTTP_CODE http_conn::parse_headers(const std::string &request)
{
// 找到请求行结束和头部开始的位置
size_t header_start = request.find("\r\n") + 2;
if (header_start >= request.length())
{
return BAD_REQUEST;
}
// 头部和正文的分界
size_t header_end = request.find("\r\n\r\n");
if (header_end == std::string::npos)
{
return NO_REQUEST;
}
// 截取头部部分
std::string headers = request.substr(header_start, header_end - header_start);
// 用正则表达式匹配各个头部字段
std::regex header_regex("([^:\\r\\n]+):\\s*([^\\r\\n]*)\\r\\n");
std::regex_iterator<std::string::iterator> it(headers.begin(), headers.end(), header_regex);
std::regex_iterator<std::string::iterator> end;
while (it != end)
{
std::string header_name = (*it)[1];
std::string header_value = (*it)[2];
// 处理Connection头部
if (header_name == "Connection")
{
if (header_value == "keep-alive")
{
m_linger = true;
}
}
// 处理Content-Length头部
else if (header_name == "Content-Length")
{
m_content_length = std::stoi(header_value);
}
// 处理Host头部
else if (header_name == "Host")
{
// 直接赋值给std::string成员变量
m_host = header_value;
}
// 处理Content-Type头部,用于文件上传
else if (header_name == "Content-Type")
{
m_content_type = header_value;
// 检查是否是multipart/form-data表单提交
if (m_content_type.find("multipart/form-data") != std::string::npos)
{
m_is_upload_request = true;
// 提取boundary值
size_t boundary_pos = m_content_type.find("boundary=");
if (boundary_pos != std::string::npos)
{
m_boundary = m_content_type.substr(boundary_pos + 9);
}
}
}
++it;
}
// 如果解析完头部后,且没有请求体,则认为是一个完整的GET请求
if (m_content_length == 0)
{
return GET_REQUEST;
}
return NO_REQUEST;
}
// 解析HTTP请求的消息体
http_conn::HTTP_CODE http_conn::parse_content(const std::string &request)
{
// 找到消息体开始的位置
size_t content_start = request.find("\r\n\r\n") + 4;
if (content_start == std::string::npos + 4 || content_start <= 4) // 如果没找到\r\n\r\n或位置不正确
{
return BAD_REQUEST;
}
// 检查消息体是否完整接收
if (request.length() - content_start >= (size_t)m_content_length)
{
// 提取请求体内容
std::string body = request.substr(content_start, m_content_length);
// 处理文件上传请求
if (m_is_upload_request && !m_boundary.empty())
{
return handle_file_upload(body);
}
// 处理文件删除请求
else if (m_url == "/delete")
{
printf("接收到删除文件请求: %s\n", body.c_str());
// 设置checked_idx位置,让do_request能正确解析请求体
m_checked_idx = content_start;
}
else
{
printf("接收到POST请求体: %s\n", body.c_str());
}
// 成功解析POST请求,返回GET_REQUEST表示一个完整的请求
return GET_REQUEST;
}
return NO_REQUEST;
}
// 处理文件上传请求
http_conn::HTTP_CODE http_conn::handle_file_upload(const std::string &request_body)
{
// 检查文件上传目录是否存在
struct stat dir_stat;
if (stat(UPLOAD_DIR.c_str(), &dir_stat) < 0 || !S_ISDIR(dir_stat.st_mode))
{
// 目录不存在,尝试创建
if (mkdir(UPLOAD_DIR.c_str(), 0755) < 0)
{
printf("创建上传目录失败: %s\n", strerror(errno));
return INTERNAL_ERROR;
}
}
// 解析多部分表单数据
std::map<std::string, std::string> form_data = parse_multipart_form_data(request_body);
// 检查是否找到上传的文件
if (form_data.find("file_content") != form_data.end() && !m_upload_file_name.empty())
{
// 保存上传的文件
bool save_result = save_uploaded_file(form_data["file_content"], m_upload_file_name);
if (!save_result)
{
printf("保存上传文件失败\n");
return INTERNAL_ERROR;
}
// 保存文件描述信息(如果有)
if (form_data.find("description") != form_data.end() && !form_data["description"].empty())
{
std::string desc_file_path = UPLOAD_DIR + "/.desc_" + m_upload_file_name;
FILE *fp = fopen(desc_file_path.c_str(), "w");
if (fp)
{
fprintf(fp, "%s", form_data["description"].c_str());
fclose(fp);
printf("保存文件描述成功: %s\n", desc_file_path.c_str());
}
}
printf("文件上传成功: %s\n", m_upload_file_name.c_str());
// 设置响应页面为上传成功页面
m_real_file = doc_root + "/post_response.html";
return FILE_REQUEST;
}
return BAD_REQUEST;
}
// 解析多部分表单数据
std::map<std::string, std::string> http_conn::parse_multipart_form_data(const std::string &request_body)
{
std::map<std::string, std::string> form_data;
// 如果boundary为空,则无法解析
if (m_boundary.empty())
{
return form_data;
}
// 添加--前缀以匹配分界线
std::string boundary = "--" + m_boundary;
std::string end_boundary = "--" + m_boundary + "--";
// 在表单数据中查找分界线
size_t pos = request_body.find(boundary);
while (pos != std::string::npos && request_body.compare(pos, end_boundary.length(), end_boundary) != 0)
{
// 寻找下一个分界线
size_t next_boundary = request_body.find(boundary, pos + boundary.length());
if (next_boundary == std::string::npos)
{
// 如果找不到下一个分界线,尝试查找结束分界线
next_boundary = request_body.find(end_boundary, pos + boundary.length());
if (next_boundary == std::string::npos)
{
// 如果结束分界线也找不到,退出循环
break;
}
}
// 提取当前部分(不包括分界线)
size_t part_start = pos + boundary.length();
// 跳过boundary后的\r\n
if (request_body.substr(part_start, 2) == "\r\n")
{
part_start += 2;
}
size_t part_end = next_boundary;
// 确保不会越界
if (part_start >= request_body.length() || part_start >= part_end)
{
pos = next_boundary;
continue;
}
std::string part = request_body.substr(part_start, part_end - part_start);
// 查找头部和内容的分隔符(空行,即\r\n\r\n)
size_t headers_end = part.find("\r\n\r\n");
if (headers_end != std::string::npos)
{
std::string headers = part.substr(0, headers_end);
std::string content = part.substr(headers_end + 4);
// 检查是否包含Content-Disposition头
if (headers.find("Content-Disposition:") != std::string::npos)
{
// 检查是否是文件字段
if (headers.find("filename=") != std::string::npos)
{
// 提取文件名
std::regex filename_regex("filename=\"([^\"]+)\"");
std::smatch matches;
if (std::regex_search(headers, matches, filename_regex))
{
m_upload_file_name = matches[1];
}
// 如果没找到文件名,返回一个默认名称
else
{
m_upload_file_name = "unknown_file";
}
// 如果文件内容是二进制,移除结尾的\r\n
if (!content.empty() && content.substr(content.length() - 2) == "\r\n")
{
content = content.substr(0, content.length() - 2);
}
// 保存文件内容
form_data["file_content"] = content;
}
else
{
// 普通表单字段,提取字段名和值
// 从Content-Disposition头中提取文件名
std::regex field_regex("name=\"([^\"]+)\"");
std::smatch matches;
if (std::regex_search(headers, matches, field_regex))
{
std::string field_name = matches[1];
// 移除结尾的\r\n
if (!content.empty() && content.substr(content.length() - 2) == "\r\n")
{
content = content.substr(0, content.length() - 2);
}
form_data[field_name] = content;
}
}
}
}
// 移动到下一个部分
pos = next_boundary;
}
return form_data;
}
// 保存上传的文件
bool http_conn::save_uploaded_file(const std::string &file_content, const std::string &file_name)
{
// 构造完整的文件路径
std::string file_path = UPLOAD_DIR + "/" + file_name;
// 打开文件准备写入
FILE *fp = fopen(file_path.c_str(), "wb");
if (!fp)
{
printf("无法创建文件: %s\n", file_path.c_str());
return false;
}
// 写入文件内容
size_t written = fwrite(file_content.c_str(), 1, file_content.length(), fp);
fclose(fp);
// 检查是否写入成功
if (written != file_content.length())
{
printf("写入文件失败: %s\n", file_path.c_str());
return false;
}
return true;
}
// 当得到一个完整、正确的HTTP请求时,我们就分析目标文件的属性
http_conn::HTTP_CODE http_conn::do_request()
{
// 构造请求文件路径
m_real_file = doc_root + m_url;
// 对于根目录"/",自动定向到index.html
if (m_url == "/")
{
m_real_file = doc_root + "/index.html";
}
// 处理上传文件夹的请求
if (m_url.compare(0, 9, "/uploads/") == 0)
{
std::string filename = m_url.substr(8); // 去掉/uploads前缀,保留/
m_real_file = UPLOAD_DIR + filename;
}
// 对于POST请求,可以根据URL路径和请求体内容做特殊处理
if (m_method == POST)
{
printf("处理POST请求: %s\n", m_url.c_str());
// 处理上传请求
if (m_url == "/upload" && m_is_upload_request)
{
// 上传处理已经在parse_content阶段的handle_file_upload中完成
// 这里设置响应页面
m_real_file = doc_root + "/post_response.html";
}
// 处理文件删除请求
else if (m_url == "/delete")
{
printf("处理文件删除请求\n");
// 从请求体中提取文件名
std::string request_body(m_read_buf + m_checked_idx, m_content_length);
// 解析表单数据 - application/x-www-form-urlencoded 格式
std::string filename;
size_t pos = request_body.find("filename=");
if (pos != std::string::npos)
{
pos += 9; // 跳过"filename="
size_t end_pos = request_body.find("&", pos);
if (end_pos == std::string::npos)
{
end_pos = request_body.length();
}
filename = request_body.substr(pos, end_pos - pos);
// 处理URL编码
for (size_t i = 0; i < filename.length(); ++i)
{
if (filename[i] == '+')
{
filename[i] = ' ';
}
else if (filename[i] == '%' && i + 2 < filename.length())
{
int hex_val = 0;
sscanf(filename.substr(i + 1, 2).c_str(), "%x", &hex_val);
filename.replace(i, 3, 1, static_cast<char>(hex_val));
}
}
}
printf("尝试删除文件: %s\n", filename.c_str());
// 如果有文件名,尝试删除文件
if (!filename.empty())
{
std::string file_path = UPLOAD_DIR + "/" + filename;
// 检查文件是否存在并且是常规文件
struct stat file_stat;
if (stat(file_path.c_str(), &file_stat) == 0 && S_ISREG(file_stat.st_mode))
{
// 尝试删除文件
if (unlink(file_path.c_str()) == 0)
{
printf("文件 %s 成功删除\n", filename.c_str());
}
else
{
printf("文件 %s 删除失败: %s\n", filename.c_str(), strerror(errno));
}
}
else
{
printf("文件 %s 不存在或不是普通文件\n", filename.c_str());
}
}
// 设置删除响应页面
m_real_file = doc_root + "/delete_response.html";
}
else
{
// 其他POST请求,返回固定的POST响应页面
m_real_file = doc_root + "/post_response.html";
}
// 如果特定响应页面不存在,使用默认页面
if (stat(m_real_file.c_str(), &m_file_stat) < 0)
{
m_real_file = doc_root + "/index.html";
}
}
// 获取文件状态信息
if (stat(m_real_file.c_str(), &m_file_stat) < 0)
{
return NO_RESOURCE;
}
// 判断访问权限
if (!(m_file_stat.st_mode & S_IROTH))
{
return FORBIDDEN_REQUEST;
}
// 判断是否是目录
if (S_ISDIR(m_file_stat.st_mode))
{
return BAD_REQUEST;
}
// 特殊处理index.html,动态插入文件列表
if (m_real_file == doc_root + "/index.html")
{
// 读取原始index.html内容
int fd = open(m_real_file.c_str(), O_RDONLY);
if (fd < 0)
{
return NO_RESOURCE;
}
// 分配内存保存文件内容
char *file_content = new char[m_file_stat.st_size + 1];
int bytes_read = ::read(fd, file_content, m_file_stat.st_size);
close(fd);
if (bytes_read < 0)
{
delete[] file_content;
return NO_RESOURCE;
}
file_content[bytes_read] = '\0';
std::string html_content(file_content);
delete[] file_content;
// 查找文件列表占位符
size_t file_list_pos = html_content.find("<div class=\"file-list\">");
if (file_list_pos != std::string::npos)
{
// 找到文件列表的标题后面的位置
size_t content_pos = html_content.find("<p>", file_list_pos);
if (content_pos != std::string::npos)
{
// 找到段落结束的位置
size_t end_pos = html_content.find("</p>", content_pos);
if (end_pos != std::string::npos)
{
// 替换占位符内容为实际文件列表
std::string file_list = generate_file_list_html();
html_content.replace(content_pos, end_pos + 4 - content_pos, file_list);
// 创建临时文件存储修改后的内容
char temp_path[128];
sprintf(temp_path, "/tmp/index_%d.html", m_sockfd);
int temp_fd = open(temp_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (temp_fd > 0)
{
::write(temp_fd, html_content.c_str(), html_content.length());
close(temp_fd);
// 替换m_real_file为临时文件
m_real_file = temp_path;
// 更新文件状态
stat(m_real_file.c_str(), &m_file_stat);
}
}
}
}
}
// 以只读方式打开文件
int fd = open(m_real_file.c_str(), O_RDONLY);
if (fd < 0)
{
return NO_RESOURCE;
}
// 先清除之前的映射
m_file_address.reset();
// 创建内存映射
char *addr = (char *)mmap(0, m_file_stat.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
close(fd);
if (addr == MAP_FAILED)
{
return INTERNAL_ERROR;
}
// 使用自定义删除器的智能指针
m_file_address = std::shared_ptr<char>(addr, [this](char *p)
{
if (p != nullptr && p != MAP_FAILED) {
munmap(p, m_file_stat.st_size);
} });
return FILE_REQUEST;
}
// 生成文件列表HTML
std::string http_conn::generate_file_list_html()
{
std::string file_list_html = "";
// 打开uploads目录
DIR *dir = opendir(UPLOAD_DIR.c_str());
if (dir == NULL)
{
return "<p>无法访问上传目录。</p>";
}
// 存储文件列表
std::vector<std::string> files;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL)
{
// 跳过.和..目录以及隐藏文件
if (entry->d_name[0] == '.')
{
continue;
}
// 构建完整路径
std::string full_path = UPLOAD_DIR + "/" + entry->d_name;
// 检查是否是普通文件
struct stat file_stat;
if (stat(full_path.c_str(), &file_stat) == 0 && S_ISREG(file_stat.st_mode))
{
files.push_back(entry->d_name);
}
}
closedir(dir);
// 如果没有文件,显示相应信息
if (files.empty())
{
return "<p>目前没有文件,请到表单页面上传文件。</p>";
}
// 按字母顺序排序文件
std::sort(files.begin(), files.end());
// 构建文件列表HTML
file_list_html = "<ul class=\"files\">\n";
for (const auto &file : files)
{
// 获取文件描述信息
std::string desc_file_path = UPLOAD_DIR + "/.desc_" + file;
std::string description = "";
FILE *fp = fopen(desc_file_path.c_str(), "r");
if (fp)
{
char desc_buf[1024] = {0};
if (fgets(desc_buf, sizeof(desc_buf), fp))
{
description = desc_buf;
}
fclose(fp);
}
// 文件大小信息
std::string full_path = UPLOAD_DIR + "/" + file;
struct stat file_stat;
stat(full_path.c_str(), &file_stat);
// 计算可读的文件大小
std::string size_str;
if (file_stat.st_size < 1024)
{
size_str = std::to_string(file_stat.st_size) + " B";
}
else if (file_stat.st_size < 1024 * 1024)
{
size_str = std::to_string(file_stat.st_size / 1024) + " KB";
}
else
{
size_str = std::to_string(file_stat.st_size / (1024 * 1024)) + " MB";
}
// 添加文件链接、大小、描述和删除按钮
file_list_html += " <li>\n";
file_list_html += " <div>\n";
file_list_html += " <a href=\"/uploads/" + file + "\">" + file + "</a>\n";
file_list_html += " <span class=\"file-size\">" + size_str + "</span>\n";
if (!description.empty())
{
file_list_html += " <div class=\"file-desc\">" + description + "</div>\n";
}
file_list_html += " </div>\n";
file_list_html += " <div class=\"file-actions\">\n";
file_list_html += " <form action=\"/delete\" method=\"POST\">\n";
file_list_html += " <input type=\"hidden\" name=\"filename\" value=\"" + file + "\">\n";
file_list_html += " <button type=\"submit\" class=\"delete-btn\">删除</button>\n";
file_list_html += " </form>\n";
file_list_html += " </div>\n";
file_list_html += " </li>\n";
}
file_list_html += "</ul>\n";
return file_list_html;
}
// 往写缓冲中写入待发送的数据
bool http_conn::add_status_line(int status, const char *title)
{
return add_response("%s %d %s\r\n", "HTTP/1.1", status, title);
}
void http_conn::add_headers(int content_len)
{
add_content_length(content_len);
add_content_type();
add_linger();
add_blank_line();
}
bool http_conn::add_content_length(int content_len)
{
return add_response("Content-Length: %d\r\n", content_len);
}
bool http_conn::add_content_type()
{
// 获取文件扩展名
size_t dot_pos = m_real_file.find_last_of('.');
std::string content_type = "text/html";
bool add_disposition = false;
std::string filename = "";
// 提取文件名,用于Content-Disposition头
if (m_url.compare(0, 9, "/uploads/") == 0)
{
size_t last_slash = m_url.find_last_of('/');
if (last_slash != std::string::npos)
{
filename = m_url.substr(last_slash + 1);