-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpd.c
2120 lines (1843 loc) · 65.5 KB
/
httpd.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
/* J. David's webserver */
/* This is a simple webserver.
* Created November 1999 by J. David Blackstone.
* CSE 4344 (Network concepts), Prof. Zeigler
* University of Texas at Arlington
*/
/* This program compiles for Sparc Solaris 2.6.
* To compile for Linux:
* 1) Comment out the #include <pthread.h> line.
* 2) Comment out the line that defines the variable newthread.
* 3) Comment out the two lines that run pthread_create().
* 4) Uncomment the line that runs accept_request().
* 5) Remove -lsocket from the Makefile.
*/
/*
代码中除了用到 C 语言标准库的一些函数,也用到了一些与环境有关的函数(例如POSIX标准)
具体可以参读《The Linux Programming Interface》,以下简称《TLPI》,页码指示均为英文版
注释者: github: cbsheng
*/
// #ifndef __NXOS__
// #define __NXOS__
// #endif
#include <stdio.h>
#include <ctype.h>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <signal.h>
#include <errno.h>
#if defined(__UNIX__)
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <dirent.h>
#include <sys/fcntl.h>
#define sock_close(sock) close(sock)
#define IS_DIR(mode) S_ISDIR(mode)
#define IS_EXEC(mode) (((mode) & S_IXUSR) || ((mode) & S_IXGRP) || ((mode) & S_IXOTH))
/* config */
// 使用多线程处理请求,当需要大量服务时可以考虑开启,0/1
#define USE_MULTI_THREAD_REQUEST 1
#define USE_CMD_PORT 1
#define USE_AUTO_PORT 1
#define USE_PIPE_SIGNAL 1
#elif defined(__NXOS__)
#include <nxos.h>
#include <netsocket.h>
// net api wrapper
#define socket(domain, type, protocol) NET_Socket(domain, type, protocol)
#define sock_close(sock) NET_Close(sock)
#define bind(sock, addr, addrlen) NET_Bind(sock, addr, addrlen)
#define listen(sock, backlog) NET_Listen(sock, backlog)
#define accept(sock, addr, addrlen) NET_Accept(sock, addr, addrlen)
#define send(sock, buf, len, flags) NET_Send(sock, (void *)(buf), len, flags)
#define recv(sock, buf, len, flags) NET_Recv(sock, (void *)(buf), len, flags)
#define shutdown(sock, how) NET_Shutdown(sock, how)
#define IS_DIR(mode) NX_FILE_IS_DIR(mode)
#define IS_EXEC(mode) ((mode) & NX_FILE_MODE_EXEC)
/* config */
// 使用多线程处理请求,当需要大量服务时可以考虑开启,0/1
#define USE_MULTI_THREAD_REQUEST 0
#define USE_CMD_PORT 0
#define USE_AUTO_PORT 0
#define USE_PIPE_SIGNAL 0
#else
#error unknown os!
#endif
#if USE_CMD_PORT == 1
#include <getopt.h>
#endif
// 默认端口号
#define DEFAULT_PORT 8080
#if USE_MULTI_THREAD_REQUEST == 1
#if defined(__NXOS__)
// nothing
#elif defined(__UNIX__)
#include <pthread.h>
#endif
#endif
#define ISspace(x) isspace((int)(x))
#define SERVER_NAME "tinyhttpd/0.1.0"
#define SERVER_STRING "Server: "SERVER_NAME"\r\n"
void accept_request(int);
void bad_request(int);
#if defined(__UNIX__)
void cat(int, FILE *);
#elif defined(__NXOS__)
void cat(int, NX_Solt);
#endif
void cannot_execute(int);
void error_die(const char *);
void execute_cgi(int, const char *, const char *, const char *, char *header);
int get_line(int, char *, int);
void headers(int, const char *);
void not_found(int);
void serve_file(int, const char *);
int startup(unsigned short *);
void unimplemented(int);
/**
* 功能配置说明:
* browser_root:在浏览器访问时显示的目录
* webdav_root:在webdav客户端访问时显示的目录
* index_file:在浏览器访问目录时访问的默认首页文件
* enable_indexes:在浏览器访问目录时是否显示目录,如果配置1,则显示目录,不然则返回index_file对应的文件
*/
// 使能目录查看功能
int enable_indexes = 1;
#if defined(__UNIX__)
const char *showdir_cgi = "./cgi/showdir.cgi"; // showdir.py
#elif defined(__NXOS__)
const char *showdir_cgi = "/System/Applications/showdir.xapp";
#endif
// 浏览器服务目录,可修改为htdocs
char *browser_root = "webdav";
// webdav服务目录
char *webdav_root = "webdav";
char *icons_root = "icons";
// 默认浏览器索引文件
char *index_file = "index.html";
static unsigned short server_port = DEFAULT_PORT;
// 发送HTTP响应
void send_response(int client, const char *status, const char *content_type, const char *body) {
char header[1024];
sprintf(header,
"HTTP/1.1 %s\r\n"
"Content-Type: %s\r\n"
"Content-Length: %lu\r\n"
"Connection: close\r\n\r\n",
status, content_type, strlen(body));
send(client, header, strlen(header), 0);
send(client, body, strlen(body), 0);
}
// 检查请求头中是否有某个参数,并将结果保存到 buf 中
int get_header_value(const char *header, const char *param, char *buf, int buflen) {
char *param_str = strstr(header, param);
if (param_str) {
// 找到参数,解析其值
param_str += strlen(param);
char *value_start = strchr(param_str, ':');
if (value_start) {
value_start++; // 跳过冒号
while (*value_start == ' ') value_start++; // 跳过空格
char *value_end = strchr(value_start, '\n');
if (value_end) {
int value_len = value_end - value_start;
if (value_len < buflen) {
strncpy(buf, value_start, value_len);
buf[value_len] = '\0'; // 确保字符串结束符
return 0; // 成功
} else {
return -2; // 缓冲区溢出
}
}
}
}
return -1; // 未找到参数
}
#define BUFFER_SIZE 4096
int read_header(int client, char *buf, int len) {
int numchars;
char line[1024];
int total_read = 0;
// 读取请求头
while ((numchars = get_line(client, line, sizeof(line))) > 0) {
// 将读取的行累积到 buf 中
if (total_read + numchars < len) {
strcpy(buf + total_read, line);
total_read += numchars;
} else {
// 缓冲区溢出
return -1;
}
// 检查是否到达请求头结束(空行)
if (strcmp(line, "\n") == 0 || strcmp(line, "") == 0) {
break;
}
}
// 返回读取的请求头长度
return total_read;
}
int read_body(int client, char *buf, int len, int content_len) {
int numchars;
char line[1024];
int total_read = 0;
// 初始化缓冲区
memset(buf, 0, len);
// 读取请求头
while (content_len > 0 && (numchars = get_line(client, line, sizeof(line))) > 0) {
// 将读取的行累积到 buf 中
if (total_read + numchars < len) {
strcpy(buf + total_read, line);
total_read += numchars;
} else {
// 缓冲区溢出
return -1;
}
content_len -= total_read;
}
// 返回读取的请求头长度
return total_read;
}
void handle_put(int client, const char *filepath, char *header) {
printf("Method: PUT %s\n", filepath);
int numchars;
int content_length = -1;
char buf[1024];
// 获取header其他部分
char content_buf[16];
if (!get_header_value(header, "Content-Length", content_buf, sizeof(content_buf))) {
//如果不存在,那把这次 http 的请求后续的内容(head 和 body)全部读完并忽略
content_length = atoi(content_buf); //记录 body 的长度大小
}
//如果 http 请求的 header 没有指示 body 长度大小的参数,则报错返回
if (content_length == -1) {
bad_request(client);
return;
}
printf("Content-Length:%d\n", content_length);
FILE *file = fopen(filepath, "wb");
if (file == NULL) {
send_response(client, "500 Internal Server Error", "text/plain", "Failed to open file");
return;
}
while (content_length > 0 && (numchars = recv(client, buf, sizeof(buf) -1, 0)) > 0) {
buf[numchars] = '\0'; // Ensure null-terminated string
fwrite(buf, 1, numchars, file);
content_length -= numchars;
}
fclose(file);
send_response(client, "201 Created", "text/plain", "Success to creat file");
}
void format_time(time_t t, char *buf, size_t len) {
struct tm *tm_info;
// 使用 gmtime 或 localtime,这里我们使用 gmtime
tm_info = gmtime(&t);
if (tm_info == NULL) {
// 处理错误情况
snprintf(buf, len, "Invalid time");
return;
}
// 使用 strftime 格式化时间
if (strftime(buf, len, "%a, %d %b %Y %H:%M:%S GMT", tm_info) == 0) {
// 处理错误情况
snprintf(buf, len, "Failed to format time");
}
}
// 定义MIME类型映射表
typedef struct {
const char *extension;
const char *mime_type;
} MimeMap;
// 预定义一些常见的MIME类型
static const MimeMap mime_types[] = {
{".html", "text/html"},
{".txt", "text/plain"},
{".jpg", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".png", "image/png"},
{".gif", "image/gif"},
{".css", "text/css"},
{".js", "application/javascript"},
// 添加更多MIME类型映射...
{NULL, NULL} // 表结束标志
};
// 根据文件扩展名获取MIME类型
void get_mime_type_by_extension(const char *filename, char *buf, size_t buf_size) {
int i;
const char *ext = strrchr(filename, '.');
if (!ext) {
strncpy(buf, "application/octet-stream", buf_size); // 未知类型默认值
buf[buf_size - 1] = '\0'; // 确保字符串以 NULL 结尾
return;
}
for (i = 0; mime_types[i].extension != NULL; ++i) {
if (strcmp(ext, mime_types[i].extension) == 0) {
strncpy(buf, mime_types[i].mime_type, buf_size);
buf[buf_size - 1] = '\0'; // 确保字符串以 NULL 结尾
return;
}
}
strncpy(buf, "application/octet-stream", buf_size); // 未找到匹配的扩展名
buf[buf_size - 1] = '\0'; // 确保字符串以 NULL 结尾
}
// 根据目录路径获取MIME类型
void get_mime_type_for_directory(const char *path, char *buf, size_t buf_size) {
#if defined(__UNIX__)
struct stat statbuf;
if (stat(path, &statbuf) == 0 && IS_DIR(statbuf.st_mode)) {
#elif defined(__NXOS__)
NX_FileStatInfo statbuf;
if (NX_FileGetStatFromPath(path, &statbuf) == NX_EOK && NX_FILE_IS_DIR(statbuf.mode)) {
#endif
strncpy(buf, "httpd/unix-directory", buf_size); // 目录的MIME类型
buf[buf_size - 1] = '\0'; // 确保字符串以 NULL 结尾
}
}
// 根据文件路径获取MIME类型
void get_mime_type(const char *filepath, char *buf, size_t buf_size) {
char mime_type[256];
get_mime_type_for_directory(filepath, buf, buf_size);
if (strcmp(buf, "httpd/unix-directory") == 0) {
return; // 返回目录的MIME类型
}
get_mime_type_by_extension(filepath, mime_type, sizeof(mime_type));
strncpy(buf, mime_type, buf_size);
buf[buf_size - 1] = '\0'; // 确保字符串以 NULL 结尾
}
#if defined(__UNIX__)
int generate_propfind_response_body(struct stat *statbuf, char *xml_response, int response_len, int offset, const char *path) {
time_t st_mtim = statbuf->st_mtime;
time_t st_ctim = statbuf->st_ctime;
ino_t st_ino = statbuf->st_ino;
mode_t st_mode = statbuf->st_mode;
off_t st_size = statbuf->st_size;
#elif defined(__NXOS__)
int generate_propfind_response_body(NX_FileStatInfo *statbuf, char *xml_response, int response_len, int offset, const char *path) {
time_t st_mtim = statbuf->mtime;
time_t st_ctim = statbuf->ctime;
NX_U32 st_ino = 0; // unsupport
NX_U32 st_mode = statbuf->mode;
NX_Size st_size = statbuf->size;
#endif
// 添加资源类型、创建日期、最后修改日期、ETag等属性
char time_buffer[256];
format_time(st_mtim, time_buffer, sizeof(time_buffer));
offset += snprintf(xml_response + offset, response_len - offset,
"<D:response>\n"
"<D:href>%s</D:href>\n"
"<D:propstat>\n"
"<D:prop>\n",
(path)); // 跳过路径的第一个字符,通常是 /
// 检查是否是目录
if (IS_DIR(st_mode)) {
offset += snprintf(xml_response + offset, response_len - offset,
"<D:resourcetype><D:collection/></D:resourcetype>\n");
} else {
// 文件的resourcetype为空
offset += snprintf(xml_response + offset, response_len - offset, "<D:resourcetype/>\n");
}
offset += snprintf(xml_response + offset, response_len - offset,
"<D:creationdate>%s</D:creationdate>\n"
"<D:getlastmodified>%s</D:getlastmodified>\n"
"<D:getetag>\"%lx-%lx\"</D:getetag>\n",
ctime(&st_ctim), // 创建时间
time_buffer, // 最后修改时间
st_ino, // ETag第一部分:inode
(unsigned long)st_size); // ETag第二部分:文件大小
// 添加文件大小
offset += snprintf(xml_response + offset, response_len - offset,
"<D:getcontentlength>%ld</D:getcontentlength>\n",
(long)st_size);
// 添加锁支持
offset += snprintf(xml_response + offset, response_len - offset,
"<D:supportedlock>\n"
"<D:lockentry>\n"
"<D:lockscope><D:exclusive/></D:lockscope>\n"
"<D:locktype><D:write/></D:locktype>\n"
"</D:lockentry>\n"
"<D:lockentry>\n"
"<D:lockscope><D:shared/></D:lockscope>\n"
"<D:locktype><D:write/></D:locktype>\n"
"</D:lockentry>\n"
"</D:supportedlock>\n"
"<D:lockdiscovery/>\n");
// 添加内容类型
char mime_type[256];
get_mime_type(path, mime_type, sizeof(mime_type)); // 假设有一个函数来获取MIME类型
offset += snprintf(xml_response + offset, response_len - offset,
"<D:getcontenttype>%s</D:getcontenttype>\n",
mime_type);
// 结束prop和propstat元素
offset += snprintf(xml_response + offset, response_len - offset,
"</D:prop>\n"
"<D:status>HTTP/1.1 200 OK</D:status>\n"
"</D:propstat>\n"
"</D:response>\n");
return offset;
}
// 假设有一个函数来获取文件或目录的属性
int generate_propfind_response(char *xml_response, int response_len, const char *path, const char *url) {
int offset = 0;
#if defined(__UNIX__)
struct stat statbuf;
if (stat(path, &statbuf) == -1) {
return -1;
}
#elif defined(__NXOS__)
NX_FileStatInfo statbuf;
if (NX_FileGetStatFromPath(path, &statbuf) != NX_EOK) {
return -1;
}
#endif
// 添加响应头
offset += snprintf(xml_response, response_len,
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<D:multistatus xmlns:D=\"DAV:\">\n");
offset = generate_propfind_response_body(&statbuf, xml_response, response_len, offset, url);
// 结束multistatus元素
offset += snprintf(xml_response + offset, response_len,
"</D:multistatus>\n");
return offset;
}
#define PROP_CHUNK 2048
#define EXPAND_SIZE (PROP_CHUNK * 4)
#if defined(__UNIX__)
static int propfind_dir(int client, const char *filepath, const char *url)
{
DIR *dir;
struct dirent *entry;
char entry_path[1024];
char entry_url[1024];
char *response;
int response_len = EXPAND_SIZE;
int offset = 0;
struct stat statbuf;
dir = opendir(filepath);
if (dir == NULL) {
send_response(client, "500 Internal Server Error", "text/plain", "Failed to open directory");
return -1;
}
response = malloc(response_len);
if (!response) {
closedir(dir);
send_response(client, "500 Internal Server Error", "text/plain", "Failed to open directory");
return -1;
}
// 其他XML部分...
offset += sprintf(response, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:multistatus xmlns:D=\"DAV:\">\n");
while ((entry = readdir(dir)) != NULL) {
// 跳过 "." 和 ".."
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 构建完整的文件路径
memset(entry_path, 0, sizeof(entry_path));
if (filepath[strlen(filepath) - 1] == '/') {
snprintf(entry_path, sizeof(entry_path), "%s%s", filepath, entry->d_name);
} else {
snprintf(entry_path, sizeof(entry_path), "%s/%s", filepath, entry->d_name);
}
memset(entry_url, 0, sizeof(entry_url));
if (url[strlen(url) - 1] == '/') {
snprintf(entry_url, sizeof(entry_url), "%s%s", url, entry->d_name);
} else {
snprintf(entry_url, sizeof(entry_url), "%s/%s", url, entry->d_name);
}
if (stat(entry_path, &statbuf) == -1) {
closedir(dir);
free(response);
send_response(client, "500 Internal Server Error", "text/plain", "File not exist");
return -1;
}
// 获取文件状态
offset = generate_propfind_response_body(&statbuf, response, response_len, offset, entry_url);
// 扩展响应内存
if (offset + PROP_CHUNK > response_len) {
// printf("expand , response len %d, off %d\n", response_len, offset);
response = realloc(response, response_len + EXPAND_SIZE);
if (!response) {
closedir(dir);
free(response);
send_response(client, "500 Internal Server Error", "text/plain", "No enough memory");
return -1;
}
response_len += EXPAND_SIZE;
}
}
offset += sprintf(response + offset, "</D:multistatus>");
send_response(client, "207 Multi-Status", "application/xml", response);
free(response);
closedir(dir);
return offset;
}
#elif defined(__NXOS__)
static int propfind_dir(int client, const char *filepath, const char *url)
{
NX_Solt dir;
NX_Dirent entry;
char entry_path[1024];
char entry_url[1024];
char *response;
int response_len = EXPAND_SIZE;
int offset = 0;
NX_FileStatInfo statbuf;
dir = NX_DirOpen(filepath);
if (dir == NX_SOLT_INVALID_VALUE) {
send_response(client, "500 Internal Server Error", "text/plain", "Failed to open directory");
return -1;
}
response = malloc(response_len);
if (!response) {
NX_DirClose(dir);
send_response(client, "500 Internal Server Error", "text/plain", "Failed to open directory");
return -1;
}
// 其他XML部分...
offset += sprintf(response, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:multistatus xmlns:D=\"DAV:\">\n");
while ((NX_DirRead(dir, &entry)) == NX_EOK) {
// 跳过 "." 和 ".."
if (strcmp(entry.name, ".") == 0 || strcmp(entry.name, "..") == 0) {
continue;
}
// 构建完整的文件路径
memset(entry_path, 0, sizeof(entry_path));
if (filepath[strlen(filepath) - 1] == '/') {
snprintf(entry_path, sizeof(entry_path), "%s%s", filepath, entry.name);
} else {
snprintf(entry_path, sizeof(entry_path), "%s/%s", filepath, entry.name);
}
memset(entry_url, 0, sizeof(entry_url));
if (url[strlen(url) - 1] == '/') {
snprintf(entry_url, sizeof(entry_url), "%s%s", url, entry.name);
} else {
snprintf(entry_url, sizeof(entry_url), "%s/%s", url, entry.name);
}
if (NX_FileGetStatFromPath(entry_path, &statbuf) != NX_EOK) {
NX_DirClose(dir);
free(response);
send_response(client, "500 Internal Server Error", "text/plain", "File not exist");
return -1;
}
// 获取文件状态
offset = generate_propfind_response_body(&statbuf, response, response_len, offset, entry_url);
// 扩展响应内存
if (offset + PROP_CHUNK > response_len) {
// printf("expand , response len %d, off %d\n", response_len, offset);
response = realloc(response, response_len + EXPAND_SIZE);
if (!response) {
NX_DirClose(dir);
free(response);
send_response(client, "500 Internal Server Error", "text/plain", "No enough memory");
return -1;
}
response_len += EXPAND_SIZE;
}
}
offset += sprintf(response + offset, "</D:multistatus>");
send_response(client, "207 Multi-Status", "application/xml", response);
free(response);
NX_DirClose(dir);
return offset;
}
#endif
void handle_propfind(int client, const char *filepath, const char *url, char *header) {
#if defined(__UNIX__)
struct stat file_stat;
mode_t st_mode;
#elif defined(__NXOS__)
NX_FileStatInfo file_stat;
NX_U32 st_mode;
#endif
char response[PROP_CHUNK];
memset(response, 0, sizeof(response));
printf("Method: PROPFIND %s\n", filepath);
// 检查是否有长度参数,如果有就读取剩余的,没有就不读取。
char depth[16];
if (get_header_value(header, "Depth", depth, sizeof(depth))) {
strcpy(depth, "infinity"); // 默认"infinity"
}
//如果 http 请求的 header 没有指示 body 长度大小的参数,则报错返回
if (strcmp(depth, "infinity") == 0) {
printf("Depth:%s not support\n", depth);
snprintf(response, 1024, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<D:multistatus xmlns:D=\"DAV:\">\n"
" <D:response>\n"
" <D:href>%s</D:href>\n"
" <D:propstat>\n"
" <D:prop>\n"
" <D:resourcetype><D:collection/></D:resourcetype>\n"
" </D:prop>\n"
" <D:status>HTTP/1.1 403 Forbidden</D:status>\n"
" </D:propstat>\n"
" </D:response>\n"
" <D:error>\n"
" <D:cannot-modify-property />\n"
" </D:error>\n"
"</D:multistatus>\n", url);
send_response(client, "403 Forbidden", "application/xml; charset=\"utf-8\"", response);
return;
}
#if defined(__UNIX__)
if (stat(filepath, &file_stat) == -1) {
send_response(client, "404 Not Found", "text/plain", "File not found");
return;
}
st_mode = file_stat.st_mode;
#elif defined(__NXOS__)
if (NX_FileGetStatFromPath(filepath, &file_stat) != NX_EOK) {
send_response(client, "404 Not Found", "text/plain", "File not found");
return;
}
st_mode = file_stat.mode;
#endif
// 只有depth为1才返回目录,不然依然返回文件信息
if (IS_DIR(st_mode) && strcmp(depth, "1") == 0) {
if (propfind_dir(client, filepath, url) == -1)
return;
} else {
generate_propfind_response(response, sizeof(response), filepath, url);
send_response(client, "207 Multi-Status", "application/xml", response);
}
}
#if defined(__UNIX__)
// 递归删除目录及其所有内容
int remove_directory(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
char full_path[1024];
if ((dir = opendir(path)) == NULL) {
return -1; // 打开目录失败
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue; // 跳过 "." 和 ".."
}
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (stat(full_path, &statbuf) == -1) {
closedir(dir);
return -1; // 获取状态失败
}
if (IS_DIR(statbuf.st_mode)) {
// 递归删除子目录
if (remove_directory(full_path) == -1) {
closedir(dir);
return -1; // 子目录删除失败
}
} else {
// 删除文件
if (remove(full_path) == -1) {
closedir(dir);
return -1; // 文件删除失败
}
}
}
closedir(dir);
// 删除空目录
return rmdir(path);
}
void handle_delete(int client, const char *path) {
struct stat statbuf;
printf("Method: DELETE %s\n", path);
if (stat(path, &statbuf) == -1) {
// 文件或目录不存在
send_response(client, "404 Not Found", "text/plain", "File not found");
return;
}
if (IS_DIR(statbuf.st_mode)) {
// 删除目录
if (remove_directory(path) == -1) {
send_response(client, "500 Internal Server Error", "text/plain", "Remove directory failed");
return;
}
} else {
// 删除文件
if (remove(path) == -1) {
send_response(client, "500 Internal Server Error", "text/plain", "Remove file failed");
return;
}
}
// 删除成功
send_response(client, "204 No Content", "text/plain", "Success to delete resource");
}
#elif defined(__NXOS__)
// 递归删除目录及其所有内容
int remove_directory(const char *path) {
NX_Solt dir;
NX_Dirent entry;
NX_FileStatInfo statbuf;
char full_path[1024];
if ((dir = NX_DirOpen(path)) == NX_SOLT_INVALID_VALUE) {
return -1; // 打开目录失败
}
while ((NX_DirRead(dir, &entry)) == NX_EOK) {
if (strcmp(entry.name, ".") == 0 || strcmp(entry.name, "..") == 0) {
continue; // 跳过 "." 和 ".."
}
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry.name);
if (NX_FileGetStatFromPath(path, &statbuf) != NX_EOK) {
NX_DirClose(dir);
return -1; // 获取状态失败
}
if (IS_DIR(statbuf.mode)) {
// 递归删除子目录
if (remove_directory(full_path) == -1) {
NX_DirClose(dir);
return -1; // 子目录删除失败
}
} else {
// 删除文件
if (NX_FileDelete(full_path) == -1) {
NX_DirClose(dir);
return -1; // 文件删除失败
}
}
}
NX_DirClose(dir);
// 删除空目录
return NX_DirDelete(path);
}
void handle_delete(int client, const char *path) {
NX_FileStatInfo statbuf;
printf("Method: DELETE %s\n", path);
if (NX_FileGetStatFromPath(path, &statbuf) != NX_EOK) {
// 文件或目录不存在
send_response(client, "404 Not Found", "text/plain", "File not found");
return;
}
if (IS_DIR(statbuf.mode)) {
// 删除目录
if (remove_directory(path) == -1) {
send_response(client, "500 Internal Server Error", "text/plain", "Remove directory failed");
return;
}
} else {
// 删除文件
if (NX_FileDelete(path) == -1) {
send_response(client, "500 Internal Server Error", "text/plain", "Remove file failed");
return;
}
}
// 删除成功
send_response(client, "204 No Content", "text/plain", "Success to delete resource");
}
#endif
int handle_mkcol(int client, const char *path) {
printf("Method: MKCOL %s\n", path);
#if defined(__UNIX__)
// 尝试创建目录
if (mkdir(path, 0755) == -1) {
// 目录创建失败
if (errno == EEXIST) {
send_response(client, "405 Method Not Allowed", "text/plain", "The resource already exists.");
} else if (errno == EACCES || errno == EPERM) {
send_response(client, "403 Forbidden", "text/plain", "Permission denied.");
} else {
char *err_msg = strerror(errno);
send_response(client, "500 Internal Server Error", "text/plain", err_msg);
}
return -1;
}
#elif defined(__NXOS__)
NX_Error err = NX_DirCreate(path, 0755);
// 尝试创建目录
if (err != NX_EOK) {
// 目录创建失败
if (err == NX_ENORES) {
send_response(client, "405 Method Not Allowed", "text/plain", "The resource already exists.");
} else if (err == NX_EPERM || err == NX_EFAULT) {
send_response(client, "403 Forbidden", "text/plain", "Permission denied.");
} else {
char *err_msg = strerror(errno);
send_response(client, "500 Internal Server Error", "text/plain", err_msg);
}
return -1;
}
#endif
// 目录创建成功
send_response(client, "201 Created", "text/plain", "Collection created successfully.");
return 0;
}
#define PARM_MOVE_DEST "Destination:"
int is_remote_url(const char *dest) {
// Simple check to see if the destination starts with "http://" or "https://"
return strncmp(dest, "http://", 7) == 0 || strncmp(dest, "https://", 8) == 0;
}
char* extract_path_from_url(const char *url) {
// 找到主机名后的第一个 '/' 字符的位置
const char *start = strstr(url, "://");
if (start) {
start += 3; // 跳过 "://"
const char *host_end = strchr(start, '/');
if (host_end) {
// 返回主机名后的第一个 '/' 之后的部分,即路径
return (char *)host_end + 1;
}
}
return NULL; // 如果没有找到路径,返回 NULL
}
int parse_dest_path(const char *header, char *buf, int buflen) {
char dest[256] = {0};
if (get_header_value(header, "Destination", dest, sizeof(dest))) {
return -1;
}
char *path = is_remote_url(dest) ? extract_path_from_url(dest): dest;
if (!path)
return -1;
snprintf(buf, buflen, "%s/%s", webdav_root, path);
return 0;
}
int handle_move(int client, const char *path, char *header) {
printf("Method: MOVE %s\n", path);
/* 获取参数 */
char dest[256] = {0};
if (parse_dest_path(header, dest, sizeof(dest))) {
send_response(client, "400 Bad Request", "text/plain", "No file destination");
return -1;
}
// 检查目标文件是否已经存在
#if defined(__UNIX__)
if (access(dest, F_OK) == 0) {
#elif defined(__NXOS__)
if (NX_FileAccess(dest, NX_FILE_READ_OK) == NX_EOK) {
#endif
send_response(client, "409 Conflict", "text/plain", "File conflict");
return -1;
}
#if defined(__UNIX__)
if (rename(path, dest) == 0) {
#elif defined(__NXOS__)
if (NX_FileRename(path, dest) == NX_EOK) {
#endif
send_response(client, "200 OK", "text/plain", "Move file sucess");
} else {
send_response(client, "500 Internal Server Error", "text/plain", "Move file failed");
return -1;
}
return 0;
}
#if defined(__UNIX__)
static int copy_file(const char *src, const char *dest, mode_t mode) {
int src_fd = open(src, O_RDONLY);
if (src_fd == -1) {
return -1;
}
int dest_fd = open(dest, O_WRONLY | O_CREAT | O_TRUNC, mode);
if (dest_fd == -1) {
close(src_fd);
return -1;
}
char buffer[4096];
ssize_t bytes_read;
while ((bytes_read = read(src_fd, buffer, sizeof(buffer))) > 0) {
if (write(dest_fd, buffer, bytes_read) != bytes_read) {
close(src_fd);
close(dest_fd);
return -1;
}
}
if (bytes_read == -1) {
close(src_fd);
close(dest_fd);
return -1;
}
close(src_fd);
close(dest_fd);
return 0;
}
// 递归复制目录
int copy_directory(const char *src, const char *dest) {
DIR *dir;