-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathmain.c
More file actions
418 lines (353 loc) · 11.1 KB
/
main.c
File metadata and controls
418 lines (353 loc) · 11.1 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
#include "httpd.h"
#include "templates.h"
#include <sys/stat.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <dirent.h>
#define CHUNK_SIZE 1024 // read 1024 bytes at a time
// Public directory settings
#define PUBLIC_DIR "./public"
#define INDEX_HTML "/index.html"
#define NOT_FOUND_HTML "/404.html"
#ifndef TESTING
int main(int c, char **v) {
char *port = c == 1 ? "8000" : v[1];
serve_forever(port);
return 0;
}
#endif
// Validate path to prevent directory traversal attacks
int is_path_safe(const char *path, const char *base_dir) {
char real_path[PATH_MAX];
char real_base[PATH_MAX];
// Get canonical paths
if (realpath(base_dir, real_base) == NULL) {
return 0;
}
// For non-existent files, check the directory part
char temp_path[PATH_MAX];
snprintf(temp_path, sizeof(temp_path), "%s", path);
// Check if path exists, if not try to resolve its parent
if (realpath(temp_path, real_path) == NULL) {
// Path doesn't exist, check if it would be inside base_dir
// by checking if the path starts with ../ or is absolute
if (path[0] == '/' || strstr(path, "../") != NULL) {
return 0;
}
// Additional check: construct the full path and verify it starts with base
snprintf(real_path, sizeof(real_path), "%s", temp_path);
}
// Verify the resolved path is within base directory
size_t base_len = strlen(real_base);
if (strncmp(real_path, real_base, base_len) != 0) {
return 0;
}
// Ensure the path is either exactly the base or starts with base/
if (real_path[base_len] != '\0' && real_path[base_len] != '/') {
return 0;
}
return 1;
}
int file_exists(const char *file_name) {
struct stat buffer;
int exists;
exists = (stat(file_name, &buffer) == 0);
return exists;
}
int is_directory(const char *path) {
struct stat statbuf;
if (stat(path, &statbuf) != 0)
return 0;
return S_ISDIR(statbuf.st_mode);
}
int read_file(const char *file_name) {
char buf[CHUNK_SIZE];
FILE *file;
size_t nread;
int err = 1;
file = fopen(file_name, "r");
if (file) {
while ((nread = fread(buf, 1, sizeof buf, file)) > 0)
fwrite(buf, 1, nread, stdout);
err = ferror(file);
fclose(file);
}
return err;
}
// Build path in public directory with safety check
int build_public_path(char *dest, size_t dest_size, const char *relative_path) {
int result = snprintf(dest, dest_size, "%s%s", PUBLIC_DIR, relative_path);
if (result < 0 || result >= dest_size) {
return -1; // Path too long
}
return 0;
}
// Format file size in human-readable format
void format_size(off_t size, char *buf, size_t buf_size) {
if (size < 1024) {
snprintf(buf, buf_size, "%lld B", (long long)size);
} else if (size < 1024 * 1024) {
snprintf(buf, buf_size, "%.1f KB", size / 1024.0);
} else if (size < 1024 * 1024 * 1024) {
snprintf(buf, buf_size, "%.1f MB", size / (1024.0 * 1024.0));
} else {
snprintf(buf, buf_size, "%.1f GB", size / (1024.0 * 1024.0 * 1024.0));
}
}
// Serve directory listing
void serve_directory_listing(const char *dir_path, const char *uri_path) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
char full_path[512];
char size_str[32];
char time_str[64];
dir = opendir(dir_path);
if (!dir) {
HTTP_404;
printf("Cannot open directory\n");
return;
}
HTTP_200;
// HTML header
printf(DIR_LISTING_HTML_HEAD, uri_path, uri_path);
// Table header
printf("%s", DIR_LISTING_TABLE_HEAD);
// Parent directory link
if (strcmp(uri_path, "/") != 0) {
printf("%s", DIR_LISTING_PARENT_ROW);
}
// Read directory entries
while ((entry = readdir(dir)) != NULL) {
// Skip hidden files and . ..
if (entry->d_name[0] == '.') continue;
// Build full path
snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, entry->d_name);
// Get file stats
if (stat(full_path, &file_stat) != 0) continue;
// Format modification time
struct tm *tm_info = localtime(&file_stat.st_mtime);
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tm_info);
// Check if directory
int is_dir = S_ISDIR(file_stat.st_mode);
// Format size
if (is_dir) {
snprintf(size_str, sizeof(size_str), "-");
} else {
format_size(file_stat.st_size, size_str, sizeof(size_str));
}
// Build URI for the file
const char *trailing_slash = (uri_path[strlen(uri_path) - 1] == '/') ? "" : "/";
const char *dir_slash = is_dir ? "/" : "";
// Table row
printf("<tr>");
printf("<td><a href=\"%s%s%s%s\" class=\"%s\">%s%s</a></td>",
uri_path, trailing_slash, entry->d_name, dir_slash,
is_dir ? "dir" : "",
entry->d_name, dir_slash);
printf("<td class=\"date\">%s</td>", time_str);
printf("<td class=\"size\">%s</td>", size_str);
printf("</tr>\n");
}
printf("%s", DIR_LISTING_HTML_FOOTER);
closedir(dir);
}
// Serve static file from public directory
void serve_static_file(const char *relative_path) {
char file_path[256];
if (build_public_path(file_path, sizeof(file_path), relative_path) < 0) {
HTTP_500;
printf("Internal error\n");
return;
}
// Validate path to prevent directory traversal
if (!is_path_safe(file_path, PUBLIC_DIR)) {
HTTP_404;
printf("Access denied\n");
return;
}
if (file_exists(file_path)) {
HTTP_200;
read_file(file_path);
} else {
HTTP_404;
// Try to serve 404 page
if (build_public_path(file_path, sizeof(file_path), NOT_FOUND_HTML) == 0 &&
file_exists(file_path)) {
read_file(file_path);
} else {
printf("File not found\n");
}
}
}
void route() {
ROUTE_START()
GET("/") {
char index_html[256];
if (build_public_path(index_html, sizeof(index_html), INDEX_HTML) == 0 &&
file_exists(index_html)) {
HTTP_200;
read_file(index_html);
} else {
HTTP_200;
printf("Hello! You are using %s\n\n", request_header("User-Agent"));
}
}
GET("/test") {
HTTP_200;
printf("===========================================\n");
printf(" Pico HTTP Server - System Info\n");
printf("===========================================\n\n");
// Current date and time
time_t now = time(NULL);
struct tm *tm_info = localtime(&now);
char time_buffer[80];
strftime(time_buffer, sizeof(time_buffer), "%Y-%m-%d %H:%M:%S %Z", tm_info);
printf("Current Date/Time: %s\n", time_buffer);
// Server uptime
extern time_t server_start_time;
double uptime = difftime(now, server_start_time);
int uptime_hours = (int)(uptime / 3600);
int uptime_minutes = (int)((uptime - uptime_hours * 3600) / 60);
int uptime_seconds = (int)(uptime - uptime_hours * 3600 - uptime_minutes * 60);
printf("Server Uptime: %02d:%02d:%02d\n", uptime_hours, uptime_minutes, uptime_seconds);
// Operating System information
struct utsname sys_info;
if (uname(&sys_info) == 0) {
printf("Operating System: %s\n", sys_info.sysname);
printf("OS Release: %s\n", sys_info.release);
printf("OS Version: %s\n", sys_info.version);
printf("Machine Architecture: %s\n", sys_info.machine);
printf("Hostname: %s\n", sys_info.nodename);
}
// Compiler information
#ifdef __GNUC__
printf("Compiler: GCC %d.%d.%d\n", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
#elif defined(__clang__)
printf("Compiler: Clang %s\n", __clang_version__);
#else
printf("Compiler: Unknown\n");
#endif
printf("Compiled on: %s %s\n", __DATE__, __TIME__);
// C Standard
#if defined(__STDC_VERSION__)
#if __STDC_VERSION__ >= 201710L
printf("C Standard: C18\n");
#elif __STDC_VERSION__ >= 201112L
printf("C Standard: C11\n");
#elif __STDC_VERSION__ >= 199901L
printf("C Standard: C99\n");
#else
printf("C Standard: C90\n");
#endif
#else
printf("C Standard: Pre-C99\n");
#endif
// Process information
printf("Process ID (PID): %d\n", getpid());
printf("Parent PID (PPID): %d\n", getppid());
// Server configuration
extern int *clients;
printf("Max Connections: 1000\n");
printf("Buffer Size: 65535 bytes\n");
printf("\n===========================================\n");
printf(" Request Headers\n");
printf("===========================================\n\n");
header_t *h = request_headers();
while (h->name) {
printf("%s: %s\n", h->name, h->value);
h++;
}
printf("\n===========================================\n");
}
POST("/") {
HTTP_201;
printf("Wow, seems that you POSTed %d bytes.\n", payload_size);
printf("Fetch the data using `payload` variable.\n");
if (payload_size > 0) {
printf("Request body: ");
// Use fputs to avoid format string vulnerabilities
fwrite(payload, 1, payload_size, stdout);
}
}
HEAD("/") {
// HEAD is like GET but returns only headers, no body
char index_html[256];
if (build_public_path(index_html, sizeof(index_html), INDEX_HTML) == 0 &&
file_exists(index_html)) {
HTTP_200;
// No body sent for HEAD requests
} else {
HTTP_200;
// No body sent for HEAD requests
}
}
HEAD("/test") {
// Return headers only, useful for checking if endpoint exists
HTTP_200;
// No body sent for HEAD requests
}
HEAD(uri) {
// Check if static file exists without sending content
char file_name[256];
if (build_public_path(file_name, sizeof(file_name), uri) == 0 &&
is_path_safe(file_name, PUBLIC_DIR) &&
file_exists(file_name)) {
HTTP_200;
// No body sent for HEAD requests
} else {
HTTP_404;
// No body sent for HEAD requests
}
}
GET(uri) {
char file_path[256];
// Build full path
if (build_public_path(file_path, sizeof(file_path), uri) < 0) {
HTTP_500;
printf("Internal error\n");
return;
}
// Validate path to prevent directory traversal
if (!is_path_safe(file_path, PUBLIC_DIR)) {
HTTP_404;
printf("Access denied\n");
return;
}
// Check if path exists
if (!file_exists(file_path)) {
HTTP_404;
// Try to serve 404 page
char not_found_path[256];
if (build_public_path(not_found_path, sizeof(not_found_path), NOT_FOUND_HTML) == 0 &&
file_exists(not_found_path)) {
read_file(not_found_path);
} else {
printf("File not found\n");
}
return;
}
// Check if it's a directory
if (is_directory(file_path)) {
// Try to serve index.html from directory
char index_path[512];
snprintf(index_path, sizeof(index_path), "%s/index.html", file_path);
if (file_exists(index_path)) {
// Serve index.html
HTTP_200;
read_file(index_path);
} else {
// Show directory listing
serve_directory_listing(file_path, uri);
}
} else {
// It's a regular file
HTTP_200;
read_file(file_path);
}
}
ROUTE_END()
}