-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkdown_server.c
More file actions
1907 lines (1825 loc) · 71.9 KB
/
markdown_server.c
File metadata and controls
1907 lines (1825 loc) · 71.9 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 <stdio.h> /* Standard I/O functions (printf, fopen, etc.) */
#include <stdlib.h> /* Standard library functions (malloc, free, etc.) */
#include <string.h> /* String manipulation functions */
#include <errno.h> /* For errno and error codes */
#include <signal.h> /* For signal handling (SIGINT) */
#include <stdbool.h> /* For bool type (C99+) */
#include <sys/stat.h> /* For stat() and file information */
#include <ctype.h> /* For character type functions (isalpha, isdigit, etc.) */
#include <stdint.h> /* For fixed-width integer types (uint16_t) */
// Platform-specific includes
#ifdef _WIN32
#include <winsock2.h> /* Windows socket API (must come before windows.h) */
#include <ws2tcpip.h> /* Windows socket extensions */
#include <direct.h> /* For _mkdir, _access */
#include <io.h> /* For _access on some compilers */
typedef SOCKET socket_t; /* Abstract socket type (UINT_PTR on Windows) */
typedef int socklen_t; /* Socket address length type */
// Note: ssize_t should be defined by MinGW headers now, removed manual typedef
#define CLOSE_SOCKET closesocket /* Abstraction for closing sockets */
// Rely on <sys/stat.h> for stat, S_ISREG, S_ISDIR
#define PATH_SEPARATOR '\\' /* Directory separator character */
#define MKDIR(path) _mkdir(path) /* Directory creation function */
#define F_OK 0 /* File existence test flag for access() */
#define access _access /* Map to Windows file access check */
#define strcasecmp _stricmp /* Map to Windows case-insensitive string compare */
// Link with -lws2_32 using compiler flag
#else // POSIX
#include <unistd.h> /* POSIX API (close, unlink, access, etc.) */
#include <sys/socket.h> /* POSIX socket API */
#include <netinet/in.h> /* Internet address structures */
#include <arpa/inet.h> /* inet_addr and related functions */
#include <fcntl.h> /* File control options */
#include <strings.h> /* For strcasecmp on POSIX */
typedef int socket_t; /* Abstract socket type (file descriptor on POSIX) */
#define INVALID_SOCKET (-1) /* Error value for socket creation */
#define SOCKET_ERROR (-1) /* Error return value for socket operations */
#define CLOSE_SOCKET close /* Abstraction for closing sockets */
#define PATH_SEPARATOR '/' /* Directory separator character */
#define MKDIR(path) mkdir(path, 0755) /* Directory creation with permissions */
#endif
// --- Constants ---
#define BUFFER_SIZE 4096 /* Size of buffer for reading HTTP requests */
#define MAX_CONNECTIONS 20 /* Maximum backlog of pending connections */
#define MAX_PATH_LEN 512 /* Maximum length of file paths */
#define DEFAULT_PORT 8080 /* Default HTTP port if not specified */
#define DEFAULT_IP "0.0.0.0" /* Default listening address (all interfaces) */
#define SERVER_VERSION "CMarkdownServ/0.7" /* Server identifier and version */
// --- Global Configuration ---
/**
* @brief Rendering mode enumeration
*
* Defines the two possible rendering modes for the server:
* - RENDER_FRONTEND: Client-side rendering with marked.js (default)
* - RENDER_BACKEND: Server-side rendering with internal markdown parser
*/
typedef enum
{
RENDER_FRONTEND, /* Client-side rendering using marked.js */
RENDER_BACKEND /* Server-side rendering using internal renderer */
} RenderMode;
/**
* @brief Global rendering mode (frontend or backend)
*
* Controls whether Markdown is rendered on the client side (RENDER_FRONTEND)
* using marked.js or on the server side (RENDER_BACKEND) using the internal
* renderer. Set via the --render command-line option.
*/
RenderMode G_render_mode = RENDER_FRONTEND;
/**
* @brief Base directory for serving files
*
* Root directory from which .md files are served. All relative paths
* requested by clients are resolved relative to this directory.
* Set via the --dir command-line option.
*/
const char *G_base_dir = ".";
/**
* @brief IP address to listen on
*
* The server binds to this IP address to listen for incoming connections.
* Default is "0.0.0.0" (all interfaces). Set via the --ip command-line option.
*/
const char *G_listen_ip_str = DEFAULT_IP;
/**
* @brief Port number to listen on
*
* The TCP port on which the server listens for incoming HTTP connections.
* Default is 8080. Set via the --port command-line option.
*/
uint16_t G_listen_port = DEFAULT_PORT;
/**
* @brief Verbosity level for logging
*
* Controls how much information is logged:
* 0 = quiet (errors only)
* 1 = info (basic operations)
* 2 = detail (more operational detail)
* 3 = debug (verbose diagnostic information)
* Set via -v, -vv, -vvv command-line options.
*/
int G_verbose_level = 0; // 0=quiet, 1=info, 2=detail, 3=debug
// --- Platform-specific Socket Format Specifier ---
#ifdef _WIN32
#define SOCKET_FMT "%llu" /* Format specifier for SOCKET on Windows (unsigned long long) */
#define SOCKET_CAST(s) ((unsigned long long)(s)) /* Cast SOCKET to unsigned long long for printing */
#else
#define SOCKET_FMT "%d" /* Format specifier for socket fd on POSIX (int) */
#define SOCKET_CAST(s) (s) /* No cast needed for POSIX sockets */
#endif
// --- Log Macros ---
#define LOG_INFO(...) \
do \
{ \
if (G_verbose_level >= 1) \
{ \
printf("[INFO] " __VA_ARGS__); \
fflush(stdout); \
} \
} while (0) /* Basic informational messages */
#define LOG_DETAIL(...) \
do \
{ \
if (G_verbose_level >= 2) \
{ \
printf("[DETAIL] " __VA_ARGS__); \
fflush(stdout); \
} \
} while (0) /* Detailed operational messages */
#define LOG_DEBUG(...) \
do \
{ \
if (G_verbose_level >= 3) \
{ \
printf("[DEBUG] " __VA_ARGS__); \
fflush(stdout); \
} \
} while (0) /* Low-level debug information */
#define LOG_ERROR(...) \
do \
{ \
fprintf(stderr, "[ERROR] " __VA_ARGS__); \
fflush(stderr); \
} while (0) /* Error messages (always print) */
// --- Embedded index.html (for Frontend Mode - Added Header) ---
/**
* @brief Embedded HTML content for frontend rendering mode
*
* Contains the complete HTML shell that is sent to clients in frontend mode.
* Includes CSS styles, JavaScript for fetching and rendering Markdown using
* marked.js, and the top navigation header with home link.
*/
const char *html_index_content =
"<!doctype html><html><head><meta charset=\"utf-8\"/><title>C Dynamic Markdown Server</title>"
"<style>"
"body{font-family:sans-serif;line-height:1.6;padding:20px;max-width:800px;margin:auto;padding-top:50px;position:relative;}" // Added padding-top and relative position
".top-header{position:absolute;top:10px;left:20px;font-size:0.9em;}" // Style for header
".top-header a{text-decoration:none;color:#007bff;}"
".top-header a:hover{text-decoration:underline;}"
"#content{border:1px solid #eee;padding:1em 2em;background-color:#f9f9f9;border-radius:5px;min-height:100px}"
".loading{font-style:italic;color:#888}"
".error-message{color:red;font-weight:bold}"
".status-code{font-family:monospace;background-color:#eee;padding:.1em .3em;border-radius:3px}"
"</style></head>"
"<body>"
"<div class=\"top-header\"><a href=\"/\">← Home</a></div>" // Added Header Link
"<div id=\"content\"><p class=loading>Loading content...</p></div>"
"<script src=\"https://cdn.jsdelivr.net/npm/marked/marked.min.js\"></script>"
"<script>const c=document.getElementById('content'),p=window.location.pathname;let m=(p==='/')?'/index.md':`${p.endsWith('/')?p.slice(0,-1):p}.md`;c.querySelector('.loading').textContent=`Loading content from ${m}...`;console.log(`Requesting Markdown: ${m}`);fetch(m).then(r=>{if(!r.ok)throw new Error(`HTTP error! Status: <span class=status-code>${r.status} ${r.statusText}</span> trying <span class=status-code>${m}</span>`);return r.text()}).then(t=>{marked.use({gfm:!0});c.innerHTML=marked.parse(t)}).catch(e=>{c.innerHTML=`<p class=error-message>Error loading/rendering:</p><p>${e.message}</p>`;console.error('Fetch/Render Error:',e)})</script>"
"</body></html>";
// --- Embedded SSR HTML Template (Added Header) ---
/**
* @brief HTML template for server-side rendering mode
*
* Template used to wrap rendered HTML content in backend mode.
* Contains a %s placeholder where the rendered HTML fragment is inserted.
* Includes CSS styles and the top navigation header with home link.
*/
const char *ssr_html_template =
"<!doctype html><html><head><meta charset=\"utf-8\"/><title>C Markdown Server (SSR)</title>"
"<style>"
"body{font-family:sans-serif;line-height:1.6;padding:20px;max-width:800px;margin:auto;padding-top:50px;position:relative;}" // Added padding-top and relative position
".top-header{position:absolute;top:10px;left:20px;font-size:0.9em;}" // Style for header
".top-header a{text-decoration:none;color:#007bff;}"
".top-header a:hover{text-decoration:underline;}"
"h1,h2,h3,h4,h5,h6{margin-top:1.5em;margin-bottom:.5em;border-bottom:1px solid #eee;padding-bottom:.2em}h1{border-bottom-width:2px}"
"p{margin-bottom:1em}"
"code{background-color:#f0f0f0;padding:.2em .4em;border-radius:3px;font-family:monospace}"
"pre{background-color:#f8f8f8;border:1px solid #ddd;padding:1em;overflow:auto;border-radius:4px}"
"pre code{background-color:transparent;padding:0;border-radius:0}"
"strong{font-weight:bold}em{font-style:italic}hr{border:0;border-top:1px solid #ccc;margin:2em 0}"
"ul,ol{padding-left:2em;margin-bottom:1em}li{margin-bottom:.3em}"
"</style></head>"
"<body>"
"<div class=\"top-header\"><a href=\"/\">← Home</a></div>" // Added Header Link
"%s" // Placeholder for the rendered HTML content
"</body></html>";
// --- Forward Declarations ---
void handle_connection(socket_t client_socket);
void send_response(socket_t sock, const char *status, const char *content_type, const char *body, long body_len);
void send_file_response(socket_t sock, const char *filename, const char *content_type);
void send_error_response(socket_t sock, int status_code, const char *status_message, const char *body_message);
bool file_exists_and_is_regular(const char *filename);
bool is_path_safe(const char *relative_path);
long get_file_size(const char *filename);
bool ensure_directory_exists(const char *filepath);
char *render_markdown_to_html(const char *markdown);
char *render_inline_markdown(const char *text);
char *safe_append(char *dest, size_t *dest_len, size_t *dest_cap, const char *src, size_t src_len);
char *escape_html(const char *text);
void print_usage(const char *prog_name);
void sigint_handler(int sig);
// --- Global Variables ---
/**
* @brief Flag controlling the main server loop
*
* When true, the server continues accepting connections.
* Set to false by the SIGINT handler to initiate graceful shutdown.
*/
volatile sig_atomic_t keep_running = 1;
// --- Signal Handler ---
/**
* @brief Handles SIGINT signal (Ctrl+C) to perform graceful server shutdown
*
* This function is registered with the signal handler and called when a SIGINT is
* received. It uses write() which is signal-safe (unlike printf) to inform the user
* and sets the global keep_running flag to 0 to terminate the main accept loop.
*
* @param sig The signal number (unused but required by signal handler signature)
*/
void sigint_handler(int sig)
{
(void)sig;
const char msg[] = "\nCaught SIGINT, shutting down...\n";
write(STDOUT_FILENO, msg, sizeof(msg) - 1); // Use write for better signal safety
keep_running = 0;
}
// --- Main Function ---
/**
* @brief Main entry point for the Markdown server
*
* Parses command-line arguments, initializes the server socket, and enters the main
* connection accept loop. Supports configuration of render mode (frontend/backend),
* base directory, IP address, port, and verbosity level. Sets up signal handling for
* graceful shutdown. Handles platform-specific socket initialization for both POSIX
* and Windows.
*
* @param argc Number of command-line arguments
* @param argv Array of command-line argument strings
* @return int Exit code (0 for success, non-zero for errors)
*/
int main(int argc, char *argv[])
{
// --- Parse Command Line Arguments ---
for (int i = 1; i < argc; ++i)
{
if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0)
{
print_usage(argv[0]);
return 0;
}
else if (strcmp(argv[i], "-v") == 0)
{
if (G_verbose_level < 3)
G_verbose_level = 1;
}
else if (strcmp(argv[i], "-vv") == 0)
{
if (G_verbose_level < 3)
G_verbose_level = 2;
}
else if (strcmp(argv[i], "-vvv") == 0)
{
G_verbose_level = 3;
}
else if (strcmp(argv[i], "--render") == 0 && i + 1 < argc)
{
i++;
if (strcmp(argv[i], "frontend") == 0)
G_render_mode = RENDER_FRONTEND;
else if (strcmp(argv[i], "backend") == 0)
G_render_mode = RENDER_BACKEND;
else
{
LOG_ERROR("Invalid value for --render: %s\n", argv[i]);
print_usage(argv[0]);
return 1;
}
}
else if (strcmp(argv[i], "--dir") == 0 && i + 1 < argc)
{
G_base_dir = argv[++i];
}
else if (strcmp(argv[i], "--ip") == 0 && i + 1 < argc)
{
G_listen_ip_str = argv[++i];
}
else if (strcmp(argv[i], "--port") == 0 && i + 1 < argc)
{
char *endptr;
long port_l = strtol(argv[++i], &endptr, 10);
if (*endptr != '\0' || port_l <= 0 || port_l > 65535)
{
LOG_ERROR("Invalid port number: %s\n", argv[i]);
return 1;
}
G_listen_port = (uint16_t)port_l;
}
else
{
LOG_ERROR("Unknown or incomplete argument: %s\n", argv[i]);
print_usage(argv[0]);
return 1;
}
}
// Validate Base Directory
struct stat dir_stat;
if (stat(G_base_dir, &dir_stat) != 0 || !S_ISDIR(dir_stat.st_mode))
{
LOG_ERROR("Invalid base directory '%s': %s\n", G_base_dir, strerror(errno));
return 1;
}
LOG_DEBUG("Base directory '%s' validated.\n", G_base_dir);
// Platform Init & Signal Handling
#ifdef _WIN32
WSADATA wsaData;
int wsa_res = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (wsa_res != 0)
{
LOG_ERROR("WSAStartup failed: %d\n", wsa_res);
return 1;
}
#endif
signal(SIGINT, sigint_handler);
// Socket Setup
socket_t server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == INVALID_SOCKET)
{
perror("[ERROR] Socket creation failed"); /* cleanup */
return 1;
}
LOG_DEBUG("Socket created (fd=" SOCKET_FMT ")\n", SOCKET_CAST(server_fd));
int opt = 1;
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt));
// Prepare Socket Address
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(G_listen_port);
#ifdef _WIN32
server_addr.sin_addr.s_addr = inet_addr(G_listen_ip_str); // Deprecated but simple for demo
if (server_addr.sin_addr.s_addr == INADDR_NONE)
{
LOG_ERROR("Invalid IP address format (inet_addr): %s\n", G_listen_ip_str);
CLOSE_SOCKET(server_fd);
WSACleanup();
return 1;
}
#else
if (inet_pton(AF_INET, G_listen_ip_str, &server_addr.sin_addr) <= 0)
{
LOG_ERROR("Invalid IP address format (inet_pton): %s\n", G_listen_ip_str);
CLOSE_SOCKET(server_fd);
return 1;
}
#endif
// Bind & Listen
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR)
{
perror("[ERROR] Socket bind failed");
fprintf(stderr, "[ERROR] Attempted to bind to %s:%u\n", G_listen_ip_str, G_listen_port);
CLOSE_SOCKET(server_fd); /* cleanup */
return 1;
}
if (listen(server_fd, MAX_CONNECTIONS) == SOCKET_ERROR)
{
perror("[ERROR] Listen failed");
CLOSE_SOCKET(server_fd); /* cleanup */
return 1;
}
printf("Server configuration:\n");
printf(" Render Mode: %s\n", (G_render_mode == RENDER_FRONTEND) ? "Frontend (Client-Side)" : "Backend (Server-Side)");
printf(" Base Dir: %s\n", G_base_dir);
printf(" Verbosity: %d\n", G_verbose_level);
printf("Server listening on http://%s:%u\n", G_listen_ip_str, G_listen_port);
// Accept Loop
while (keep_running)
{
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
socket_t client_socket = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len);
if (!keep_running)
{
if (client_socket != INVALID_SOCKET)
CLOSE_SOCKET(client_socket);
break;
}
if (client_socket == INVALID_SOCKET)
{
#ifdef _WIN32
if (WSAGetLastError() == WSAEINTR)
continue;
#else
if (errno == EINTR)
continue;
#endif
perror("[WARN] Accept failed");
continue;
}
LOG_INFO("Connection accepted (socket=" SOCKET_FMT ")\n", SOCKET_CAST(client_socket));
handle_connection(client_socket);
CLOSE_SOCKET(client_socket);
LOG_INFO("Connection closed (socket=" SOCKET_FMT ")\n", SOCKET_CAST(client_socket));
}
// Cleanup
printf("Shutting down server socket.\n");
CLOSE_SOCKET(server_fd);
#ifdef _WIN32
WSACleanup();
#endif
printf("Server shut down gracefully.\n");
return 0;
}
// --- Request Handler (Corrected Page Combination) ---
/**
* @brief Processes an individual client connection
*
* This function handles a client's HTTP request by:
* 1. Reading and parsing the request to extract the HTTP method and URI
* 2. Validating the request (only GET method is supported)
* 3. Normalizing and checking the safety of the requested path
* 4. Branching based on render mode (frontend or backend):
* - Frontend mode: Serves either raw .md files or the embedded HTML shell
* - Backend mode: Reads the .md file, renders it to HTML, and sends the complete page
* 5. Handling error cases and special cases (like missing index.md)
*
* @param client_socket Socket descriptor for the connected client
*/
void handle_connection(socket_t client_socket)
{
char buffer[BUFFER_SIZE];
memset(buffer, 0, BUFFER_SIZE);
ssize_t bytes_received = -1;
#ifdef _WIN32
bytes_received = recv(client_socket, buffer, BUFFER_SIZE - 1, 0);
#else
bytes_received = read(client_socket, buffer, BUFFER_SIZE - 1);
#endif
if (bytes_received <= 0)
{ /* Handle read error/disconnect */
return;
}
buffer[bytes_received] = '\0';
LOG_DETAIL("Received Request (%ld bytes) from socket " SOCKET_FMT ":\n---\n%s\n---\n", (long)bytes_received, SOCKET_CAST(client_socket), buffer);
char method[16], request_uri[MAX_PATH_LEN];
if (sscanf(buffer, "%15s %511s %*s", method, request_uri) < 2)
{
send_error_response(client_socket, 400, "BR", "Parse fail");
return;
}
if (strcmp(method, "GET") != 0)
{
send_error_response(client_socket, 501, "NI", "GET only");
return;
}
LOG_INFO("Request from " SOCKET_FMT ": %s %s\n", SOCKET_CAST(client_socket), method, request_uri);
// Path Processing
char *query_start = strchr(request_uri, '?');
if (query_start)
*query_start = '\0';
char normalized_req_path[MAX_PATH_LEN];
strncpy(normalized_req_path, request_uri, sizeof(normalized_req_path) - 1);
normalized_req_path[sizeof(normalized_req_path) - 1] = '\0';
for (char *p = normalized_req_path; *p; ++p)
{
if (*p == '/')
*p = PATH_SEPARATOR;
}
const char *relative_path = (normalized_req_path[0] == PATH_SEPARATOR) ? normalized_req_path + 1 : normalized_req_path;
if (strcmp(relative_path, "") == 0 || strcmp(relative_path, ".") == 0)
relative_path = "index";
LOG_DEBUG("Normalized relative path: '%s'\n", relative_path);
if (!is_path_safe(relative_path))
{
send_error_response(client_socket, 400, "BR", "Unsafe path");
return;
}
// Branch based on Render Mode
if (G_render_mode == RENDER_FRONTEND)
{
// --- Frontend Mode ---
bool serve_markdown_file = false;
char target_filepath[MAX_PATH_LEN + strlen(G_base_dir) + 5];
size_t req_len = strlen(relative_path);
if (req_len > 3 && strcasecmp(relative_path + req_len - 3, ".md") == 0)
{
serve_markdown_file = true;
snprintf(target_filepath, sizeof(target_filepath), "%s%c%s", G_base_dir, PATH_SEPARATOR, relative_path);
}
if (serve_markdown_file)
{
LOG_DETAIL("Frontend Mode: Serving raw MD file: %s\n", target_filepath);
if (!ensure_directory_exists(target_filepath))
{
send_error_response(client_socket, 500, "ISE", "Dir check error");
return;
}
if (file_exists_and_is_regular(target_filepath))
{
send_file_response(client_socket, target_filepath, "text/markdown; charset=utf-8");
}
else
{
char target_index_path[sizeof(target_filepath)];
snprintf(target_index_path, sizeof(target_index_path), "%s%cindex.md", G_base_dir, PATH_SEPARATOR);
if (strcmp(target_filepath, target_index_path) == 0 && errno == ENOENT)
{
const char *m = "# Welcome!\n\n`index.md` missing.";
send_response(client_socket, "200 OK", "text/md", m, strlen(m));
}
else
{
send_error_response(client_socket, 404, "NF", "MD not found.");
}
}
}
else
{
LOG_DETAIL("Frontend Mode: Serving embedded HTML shell for request '%s'\n", request_uri);
send_response(client_socket, "200 OK", "text/html", html_index_content, strlen(html_index_content));
}
}
else
{
// --- Backend Mode ---
char target_md_filepath[MAX_PATH_LEN + strlen(G_base_dir) + 5];
size_t rel_len = strlen(relative_path);
if (rel_len > 3 && strcasecmp(relative_path + rel_len - 3, ".md") == 0)
{
snprintf(target_md_filepath, sizeof(target_md_filepath), "%s%c%s", G_base_dir, PATH_SEPARATOR, relative_path);
}
else
{
snprintf(target_md_filepath, sizeof(target_md_filepath), "%s%c%s.md", G_base_dir, PATH_SEPARATOR, relative_path);
}
LOG_DETAIL("Backend Mode: Attempting to render: %s\n", target_md_filepath);
if (!ensure_directory_exists(target_md_filepath))
{
send_error_response(client_socket, 500, "ISE", "Dir check error");
return;
}
if (file_exists_and_is_regular(target_md_filepath))
{
long file_size = get_file_size(target_md_filepath);
if (file_size < 0)
{
send_error_response(client_socket, 500, "ISE", "Size check fail");
return;
}
char *md_content = NULL;
if (file_size > 0)
{
md_content = (char *)malloc(file_size + 1);
if (!md_content)
{
send_error_response(client_socket, 500, "ISE", "Mem fail");
return;
}
FILE *file = fopen(target_md_filepath, "rb");
if (!file)
{
free(md_content);
send_error_response(client_socket, 500, "ISE", "Open fail");
return;
}
if (fread(md_content, 1, file_size, file) != (size_t)file_size)
{
fclose(file);
free(md_content);
send_error_response(client_socket, 500, "ISE", "Read fail");
return;
}
fclose(file);
md_content[file_size] = '\0';
}
else
{
md_content = strdup("");
}
if (!md_content)
{
send_error_response(client_socket, 500, "ISE", "Content error");
return;
}
char *rendered_html_fragment = render_markdown_to_html(md_content);
free(md_content);
if (!rendered_html_fragment)
{
send_error_response(client_socket, 500, "ISE", "Render fail");
return;
}
// --- FIXED PAGE COMBINATION using snprintf ---
int required_size = snprintf(NULL, 0, ssr_html_template, rendered_html_fragment);
if (required_size < 0)
{
LOG_ERROR("snprintf size calculation failed\n");
free(rendered_html_fragment);
send_error_response(client_socket, 500, "ISE", "Page gen error (size calc)");
return;
}
size_t full_page_size = (size_t)required_size + 1; // +1 for null terminator
char *full_page = (char *)malloc(full_page_size);
if (!full_page)
{
LOG_ERROR("Malloc failed for full page (%zu bytes)\n", full_page_size);
free(rendered_html_fragment);
send_error_response(client_socket, 500, "ISE", "Page mem fail");
return;
}
int written_size = snprintf(full_page, full_page_size, ssr_html_template, rendered_html_fragment);
free(rendered_html_fragment); // Free fragment now
if (written_size < 0 || (size_t)written_size >= full_page_size)
{
LOG_ERROR("snprintf failed during page combination (written %d, size %zu)\n", written_size, full_page_size);
free(full_page);
send_error_response(client_socket, 500, "ISE", "Page gen error (combine)");
return;
}
// --- End of fix ---
LOG_DETAIL("Backend Mode: Sending rendered HTML page (%zu bytes)\n", strlen(full_page));
send_response(client_socket, "200 OK", "text/html; charset=utf-8", full_page, strlen(full_page));
free(full_page);
}
else
{ /* Handle 404 / default index.md message for backend */
int err = errno;
char target_index_path[sizeof(target_md_filepath)];
snprintf(target_index_path, sizeof(target_index_path), "%s%cindex.md", G_base_dir, PATH_SEPARATOR);
if (strcmp(target_md_filepath, target_index_path) == 0 && err == ENOENT)
{
const char *m = "# Welcome!\n\n`index.md` missing.";
char *r = render_markdown_to_html(m);
if (r)
{
// --- FIXED PAGE COMBINATION for default msg ---
int req_size_def = snprintf(NULL, 0, ssr_html_template, r);
if (req_size_def >= 0)
{
size_t fp_size = (size_t)req_size_def + 1;
char *fp = (char *)malloc(fp_size);
if (fp)
{
if (snprintf(fp, fp_size, ssr_html_template, r) > 0)
{
send_response(client_socket, "200 OK", "text/html", fp, strlen(fp));
}
else
{
LOG_ERROR("snprintf default combine failed\n");
}
free(fp);
}
else
{
LOG_ERROR("Malloc failed for default page\n");
}
}
else
{
LOG_ERROR("snprintf default size calc failed\n");
}
// --- End of fix ---
free(r);
}
else
{
send_error_response(client_socket, 500, "ISE", "Render fail");
}
}
else
{
send_error_response(client_socket, 404, "NF", "Page source not found.");
}
}
}
}
// --- Utility: Safe String Appending ---
/**
* @brief Safely appends a string to a dynamically allocated buffer
*
* This utility function handles dynamic memory allocation and growth for string
* building operations. If the destination buffer isn't large enough to accommodate
* the source string, it automatically reallocates with a larger capacity. This is
* particularly useful for the Markdown renderer which builds HTML incrementally.
*
* @param dest The destination buffer (may be reallocated if needed)
* @param dest_len Pointer to the current length of content in dest
* @param dest_cap Pointer to the current capacity of dest
* @param src Source string to append
* @param src_len Length of the source string
* @return char* Updated destination buffer pointer (may differ from input if reallocated)
* or NULL on allocation failure (original dest is freed in this case)
*/
char *safe_append(char *dest, size_t *dest_len, size_t *dest_cap, const char *src, size_t src_len)
{ /* ... as before ... */
if (*dest_len + src_len + 1 > *dest_cap)
{
size_t new_cap = (*dest_cap == 0) ? 256 : (*dest_cap * 2);
while (*dest_len + src_len + 1 > new_cap)
{
new_cap *= 2;
}
LOG_DEBUG("Reallocating buffer from %zu to %zu\n", *dest_cap, new_cap);
char *new_dest = (char *)realloc(dest, new_cap);
if (!new_dest)
{
LOG_ERROR("realloc failed in safe_append\n");
free(dest);
return NULL;
}
dest = new_dest;
*dest_cap = new_cap;
}
memcpy(dest + *dest_len, src, src_len);
*dest_len += src_len;
dest[*dest_len] = '\0';
return dest;
}
// --- Utility: HTML Escaping (Corrected) ---
/**
* @brief Escapes special HTML characters to prevent injection issues
*
* Converts characters that have special meaning in HTML to their corresponding
* entity references to ensure they display correctly and prevent injection attacks:
* - < becomes <
* - > becomes >
* - & becomes &
* - " becomes "
*
* Uses safe_append for dynamic memory management during conversion.
*
* @param text Input text to escape
* @return char* Newly allocated string containing the escaped content,
* or NULL on allocation failure
*/
char *escape_html(const char *text)
{
if (!text)
return NULL;
size_t text_len = strlen(text);
// Estimate capacity: start with text length, add potential padding for escapes
// Each escape adds 3-5 extra chars. Assume ~10% might be escaped on average?
size_t cap = text_len + (text_len / 10) + 32; // Add some base padding too
char *escaped = (char *)malloc(cap);
if (!escaped)
{
LOG_ERROR("Malloc failed in escape_html (initial size %zu)\n", cap);
return NULL;
}
escaped[0] = '\0';
size_t len = 0;
for (const char *p = text; *p; ++p)
{
const char *replacement = NULL;
size_t rep_len = 0;
// Use the correct HTML entity string literals
switch (*p)
{
case '<':
replacement = "<";
rep_len = 4;
break;
case '>':
replacement = ">";
rep_len = 4;
break;
case '&':
replacement = "&";
rep_len = 5;
break;
case '"':
replacement = """;
rep_len = 6;
break;
// Add ' for single quotes if needed, though less critical
// case '\'': replacement = "'"; rep_len = 6; break;
}
if (replacement)
{
// Append the HTML entity string
escaped = safe_append(escaped, &len, &cap, replacement, rep_len);
if (!escaped)
return NULL; // safe_append handles free on error
}
else
{
// Append the original character (no replacement needed)
escaped = safe_append(escaped, &len, &cap, p, 1);
if (!escaped)
return NULL;
}
}
// Optional: Shrink buffer to actual size if memory is critical
// char* final_escaped = realloc(escaped, len + 1);
// return final_escaped ? final_escaped : escaped; // Return original if realloc fails
return escaped;
}
// --- Inline Markdown Renderer (Corrected Code Span) ---
/**
* @brief Renders inline Markdown elements to HTML
*
* Processes inline Markdown syntax including:
* - Bold (**text** or __text__)
* - Italic (*text* or _text_)
* - Code spans (`code`)
* - Links ([text](url))
* - Escaped characters (backslash followed by a special character)
*
* Uses a character-by-character parsing approach with markers and state tracking.
* HTML-escapes content appropriately to prevent injection issues.
*
* @param text Input Markdown text to render
* @return char* Newly allocated string containing rendered HTML,
* or NULL on allocation failure
*/
char *render_inline_markdown(const char *text)
{
if (!text)
return NULL;
LOG_DEBUG("Rendering inline: '%.30s...'\n", text);
size_t text_len = strlen(text);
size_t html_cap = text_len + 256;
char *html = (char *)malloc(html_cap);
if (!html)
{
LOG_ERROR("Malloc failed in render_inline\n");
return NULL;
}
html[0] = '\0';
size_t html_len = 0;
const char *p = text;
const char *last_copy_pos = text;
while (*p)
{
const char *marker_pos = p;
char open_tag[64] = {0};
char close_tag[16] = {0};
const char *end_marker = NULL;
const char *content_start = NULL;
size_t content_len = 0;
bool found_inline = false;
bool escape_content = false;
// Escape Character
if (*p == '\\' && p[1] != '\0' && strchr("*_[]()`\\", p[1]))
{
if (marker_pos > last_copy_pos)
{
html = safe_append(html, &html_len, &html_cap, last_copy_pos, marker_pos - last_copy_pos);
if (!html)
return NULL;
}
html = safe_append(html, &html_len, &html_cap, p + 1, 1);
if (!html)
return NULL; // Append escaped char
p += 2;
last_copy_pos = p;
continue;
}
// Single Backtick Code Spans
else if (*p == '`')
{ // LOOK FOR SINGLE BACKTICK
end_marker = strchr(p + 1, '`'); // Find next single backtick
if (end_marker)
{
strcpy(open_tag, "<code>");
strcpy(close_tag, "</code>");
content_start = p + 1;
content_len = end_marker - content_start;
// Basic trim space inside `code`
while (content_len > 0 && isspace((unsigned char)*content_start))
{
content_start++;
content_len--;
}
while (content_len > 0 && isspace((unsigned char)*(content_start + content_len - 1)))
{
content_len--;
}
p = end_marker + 1; // Move past closing backtick
found_inline = true;
escape_content = true;
LOG_DEBUG("Found code span, len %zu\n", content_len);
} // else: no closing backtick found, treat as literal
}
// Bold/Italic
else if (strncmp(p, "**", 2) == 0 || strncmp(p, "__", 2) == 0)
{
char marker[3] = {*p, *p, '\0'};
end_marker = strstr(p + 2, marker);
if (end_marker && end_marker > p + 2)
{
strcpy(open_tag, "<strong>");
strcpy(close_tag, "</strong>");
content_start = p + 2;
content_len = end_marker - content_start;
p = end_marker + 2;
found_inline = true;
}
}
else if ((*p == '*' || *p == '_'))
{
char marker[2] = {*p, '\0'};
end_marker = strstr(p + 1, marker);
if (end_marker && end_marker > p + 1)
{
bool start_ok = (p == text || !isalnum((unsigned char)*(p - 1)));
bool end_ok = (end_marker[1] == '\0' || !isalnum((unsigned char)end_marker[1]));
bool no_internal_space = !isspace((unsigned char)*(p + 1)) && !isspace((unsigned char)*(end_marker - 1));
if (start_ok && end_ok && no_internal_space)
{
strcpy(open_tag, "<em>");
strcpy(close_tag, "</em>");
content_start = p + 1;
content_len = end_marker - content_start;
p = end_marker + 1;
found_inline = true;
}
}
}
// Links
else if (*p == '[')
{
const char *text_end = strchr(p + 1, ']');
if (text_end && text_end[1] == '(')
{
const char *url_start = text_end + 2;
const char *url_end = url_start;
int paren_level = 1;
while (*url_end)
{
if (*url_end == '(')
paren_level++;
else if (*url_end == ')')
{
if (--paren_level == 0)
break;
}
url_end++;
}
if (*url_end == ')')
{
content_start = p + 1;