-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve.c
More file actions
902 lines (824 loc) · 30.1 KB
/
serve.c
File metadata and controls
902 lines (824 loc) · 30.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
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
/*
* serve.c - Cross-platform static file HTTP server
* Compiles and runs on Windows, macOS, and Linux with no dependencies.
* Serves the current directory on a configurable port and opens the browser.
*
* Build:
* gcc -o serve serve.c (macOS / Linux)
* cl serve.c /Fe:serve.exe (Windows MSVC)
* gcc -o serve.exe serve.c -lws2_32 (Windows MinGW)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/stat.h>
/* ---- Platform Abstractions ---- */
#ifdef _WIN32
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#pragma comment(lib, "ws2_32.lib")
typedef SOCKET sock_t;
#define CLOSESOCKET closesocket
#define INVALID_SOCK INVALID_SOCKET
#define SOCKERR SOCKET_ERROR
static int platform_init(void) {
WSADATA wsa;
return WSAStartup(MAKEWORD(2, 2), &wsa);
}
static void platform_cleanup(void) { WSACleanup(); }
static void open_browser(int port) {
char cmd[256];
snprintf(cmd, sizeof(cmd), "start http://localhost:%d/manage.html", port);
system(cmd);
}
#define PATH_SEP '\\'
#define S_ISDIR(m) (((m) & _S_IFDIR) != 0)
#define S_ISREG(m) (((m) & _S_IFREG) != 0)
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
typedef int sock_t;
#define CLOSESOCKET close
#define INVALID_SOCK (-1)
#define SOCKERR (-1)
static int platform_init(void) { return 0; }
static void platform_cleanup(void) {}
static void open_browser(int port) {
char cmd[256];
#ifdef __APPLE__
snprintf(cmd, sizeof(cmd), "open http://localhost:%d/manage.html", port);
#else
snprintf(cmd, sizeof(cmd), "xdg-open http://localhost:%d/manage.html 2>/dev/null || "
"sensible-browser http://localhost:%d/manage.html 2>/dev/null || "
"echo 'Open http://localhost:%d/manage.html in your browser'",
port, port, port);
#endif
system(cmd);
}
#define PATH_SEP '/'
#endif
/* ---- Globals ---- */
static volatile int running = 1;
static sock_t server_sock = INVALID_SOCK;
static void handle_signal(int sig) {
(void)sig;
running = 0;
if (server_sock != INVALID_SOCK) {
CLOSESOCKET(server_sock);
server_sock = INVALID_SOCK;
}
}
/* ---- MIME Types ---- */
typedef struct {
const char *ext;
const char *mime;
} mime_entry;
static const mime_entry mime_table[] = {
{ ".html", "text/html; charset=utf-8" },
{ ".htm", "text/html; charset=utf-8" },
{ ".css", "text/css; charset=utf-8" },
{ ".js", "application/javascript; charset=utf-8" },
{ ".json", "application/json; charset=utf-8" },
{ ".png", "image/png" },
{ ".jpg", "image/jpeg" },
{ ".jpeg", "image/jpeg" },
{ ".gif", "image/gif" },
{ ".svg", "image/svg+xml" },
{ ".ico", "image/x-icon" },
{ ".txt", "text/plain; charset=utf-8" },
{ ".md", "text/plain; charset=utf-8" },
{ ".woff", "font/woff" },
{ ".woff2","font/woff2" },
{ ".ttf", "font/ttf" },
{ ".xml", "application/xml" },
{ NULL, NULL }
};
static const char *get_mime(const char *path) {
const char *dot = strrchr(path, '.');
if (dot) {
for (int i = 0; mime_table[i].ext; i++) {
if (strcmp(dot, mime_table[i].ext) == 0) {
return mime_table[i].mime;
}
}
}
return "application/octet-stream";
}
/* ---- Path Safety ---- */
static int path_is_safe(const char *path) {
/* Block directory traversal */
if (strstr(path, "..")) return 0;
if (path[0] == '/') path++;
if (path[0] == '\\') path++;
/* Block absolute Windows paths */
if (strlen(path) >= 2 && path[1] == ':') return 0;
return 1;
}
/* ---- Send Helpers ---- */
static void send_response(sock_t client, int status, const char *status_text,
const char *content_type, const char *body, long body_len) {
char header[1024];
int hlen = snprintf(header, sizeof(header),
"HTTP/1.1 %d %s\r\n"
"Content-Type: %s\r\n"
"Content-Length: %ld\r\n"
"Connection: close\r\n"
"Access-Control-Allow-Origin: *\r\n"
"\r\n",
status, status_text, content_type, body_len);
send(client, header, hlen, 0);
if (body && body_len > 0) {
long sent = 0;
while (sent < body_len) {
long chunk = body_len - sent;
if (chunk > 8192) chunk = 8192;
int n = send(client, body + sent, (int)chunk, 0);
if (n <= 0) break;
sent += n;
}
}
}
static void send_error(sock_t client, int status, const char *text) {
char body[256];
int blen = snprintf(body, sizeof(body),
"<html><body><h1>%d %s</h1></body></html>", status, text);
send_response(client, status, text, "text/html; charset=utf-8", body, blen);
}
static void send_file(sock_t client, const char *filepath) {
FILE *f = fopen(filepath, "rb");
if (!f) {
send_error(client, 404, "Not Found");
return;
}
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
char *buf = (char *)malloc(fsize);
if (!buf) {
fclose(f);
send_error(client, 500, "Internal Server Error");
return;
}
fread(buf, 1, fsize, f);
fclose(f);
const char *mime = get_mime(filepath);
send_response(client, 200, "OK", mime, buf, fsize);
free(buf);
}
/* ---- Request Handler ---- */
/* Read the full request body of a given Content-Length */
static char *read_request_body(sock_t client, const char *headers, int already_read, long *out_len) {
/* Find Content-Length */
const char *cl = strstr(headers, "Content-Length:");
if (!cl) cl = strstr(headers, "content-length:");
if (!cl) { *out_len = 0; return NULL; }
long content_length = atol(cl + 15);
if (content_length <= 0 || content_length > 10 * 1024 * 1024) { /* max 10MB */
*out_len = 0;
return NULL;
}
/* Find end of headers */
const char *body_start = strstr(headers, "\r\n\r\n");
if (!body_start) { *out_len = 0; return NULL; }
body_start += 4;
long header_len = (long)(body_start - headers);
long body_already = already_read - header_len;
if (body_already < 0) body_already = 0;
char *body = (char *)malloc(content_length + 1);
if (!body) { *out_len = 0; return NULL; }
/* Copy what we already have */
if (body_already > 0) {
if (body_already > content_length) body_already = content_length;
memcpy(body, body_start, body_already);
}
/* Read the rest */
long remaining = content_length - body_already;
long offset = body_already;
while (remaining > 0) {
int chunk = recv(client, body + offset, (int)remaining, 0);
if (chunk <= 0) break;
offset += chunk;
remaining -= chunk;
}
body[offset] = '\0';
*out_len = offset;
return body;
}
/* Handle POST /api/save - write JSON to crissy-data.json */
static void handle_api_save(sock_t client, const char *headers, int headers_len) {
long body_len = 0;
char *body = read_request_body(client, headers, headers_len, &body_len);
if (!body || body_len == 0) {
send_error(client, 400, "Bad Request");
if (body) free(body);
return;
}
FILE *f = fopen("crissy-data.json", "wb");
if (!f) {
const char *msg = "{\"error\":\"Failed to write crissy-data.json\"}";
send_response(client, 500, "Internal Server Error",
"application/json; charset=utf-8", msg, (long)strlen(msg));
free(body);
return;
}
fwrite(body, 1, body_len, f);
fclose(f);
free(body);
printf("Saved crissy-data.json (%ld bytes)\n", body_len);
const char *ok = "{\"ok\":true,\"message\":\"Saved crissy-data.json\"}";
send_response(client, 200, "OK", "application/json; charset=utf-8", ok, (long)strlen(ok));
}
/* Handle POST /api/build - run the Go build tool */
static void handle_api_build(sock_t client) {
int rc;
#ifdef _WIN32
/* Try portfolio-build.exe first, then go run */
struct stat st;
if (stat("portfolio-build.exe", &st) == 0) {
rc = system("portfolio-build.exe .");
} else if (stat("build.go", &st) == 0) {
rc = system("go run build.go .");
} else {
const char *msg = "{\"error\":\"No build tool found (portfolio-build.exe or build.go)\"}";
send_response(client, 500, "Internal Server Error",
"application/json; charset=utf-8", msg, (long)strlen(msg));
return;
}
#else
struct stat st;
if (stat("portfolio-build", &st) == 0) {
rc = system("./portfolio-build .");
} else if (stat("build.go", &st) == 0) {
rc = system("go run build.go .");
} else {
const char *msg = "{\"error\":\"No build tool found (portfolio-build or build.go)\"}";
send_response(client, 500, "Internal Server Error",
"application/json; charset=utf-8", msg, (long)strlen(msg));
return;
}
#endif
if (rc == 0) {
printf("Build completed successfully.\n");
const char *ok = "{\"ok\":true,\"message\":\"Build completed successfully\"}";
send_response(client, 200, "OK", "application/json; charset=utf-8", ok, (long)strlen(ok));
} else {
printf("Build failed with exit code %d.\n", rc);
const char *msg = "{\"error\":\"Build failed. Check terminal for details.\"}";
send_response(client, 500, "Internal Server Error",
"application/json; charset=utf-8", msg, (long)strlen(msg));
}
}
/* Handle GET /api/deploy-config - read deploy.conf */
static void handle_api_deploy_config_get(sock_t client) {
FILE *f = fopen("deploy.conf", "r");
if (!f) {
const char *empty = "{\"repo\":\"\",\"domain\":\"\"}";
send_response(client, 200, "OK", "application/json; charset=utf-8",
empty, (long)strlen(empty));
return;
}
char line[1024];
char repo[1024] = {0};
char domain[256] = {0};
while (fgets(line, sizeof(line), f)) {
int len = (int)strlen(line);
while (len > 0 && (line[len-1] == '\n' || line[len-1] == '\r' ||
line[len-1] == ' ')) line[--len] = '\0';
if (line[0] == '#' || line[0] == '\0') continue;
if (strncmp(line, "repo=", 5) == 0) {
strncpy(repo, line + 5, sizeof(repo) - 1);
} else if (strncmp(line, "domain=", 7) == 0) {
strncpy(domain, line + 7, sizeof(domain) - 1);
}
}
fclose(f);
char json[2048];
snprintf(json, sizeof(json), "{\"repo\":\"%s\",\"domain\":\"%s\"}", repo, domain);
send_response(client, 200, "OK", "application/json; charset=utf-8",
json, (long)strlen(json));
}
/* Handle POST /api/deploy-config - write deploy.conf */
static void handle_api_deploy_config_post(sock_t client, const char *headers, int headers_len) {
long body_len = 0;
char *body = read_request_body(client, headers, headers_len, &body_len);
if (!body || body_len == 0) {
send_error(client, 400, "Bad Request");
if (body) free(body);
return;
}
/* Simple JSON parse for {"repo":"...","domain":"..."} */
char repo[1024] = {0};
char domain[256] = {0};
char *rk = strstr(body, "\"repo\"");
if (rk) {
char *colon = strchr(rk + 6, ':');
if (colon) {
char *q1 = strchr(colon, '"');
if (q1) {
q1++;
char *q2 = strchr(q1, '"');
if (q2 && (q2 - q1) < (int)sizeof(repo)) {
memcpy(repo, q1, q2 - q1);
repo[q2 - q1] = '\0';
}
}
}
}
char *dk = strstr(body, "\"domain\"");
if (dk) {
char *colon = strchr(dk + 8, ':');
if (colon) {
char *q1 = strchr(colon, '"');
if (q1) {
q1++;
char *q2 = strchr(q1, '"');
if (q2 && (q2 - q1) < (int)sizeof(domain)) {
memcpy(domain, q1, q2 - q1);
domain[q2 - q1] = '\0';
}
}
}
}
free(body);
FILE *f = fopen("deploy.conf", "w");
if (!f) {
const char *msg = "{\"error\":\"Failed to write deploy.conf\"}";
send_response(client, 500, "Internal Server Error",
"application/json; charset=utf-8", msg, (long)strlen(msg));
return;
}
fprintf(f, "# deploy.conf - GitHub Pages deploy target\n");
fprintf(f, "repo=%s\n", repo);
if (domain[0]) {
fprintf(f, "domain=%s\n", domain);
}
fclose(f);
printf("Saved deploy.conf: repo=%s domain=%s\n", repo, domain);
const char *ok = "{\"ok\":true,\"message\":\"Deploy config saved\"}";
send_response(client, 200, "OK", "application/json; charset=utf-8",
ok, (long)strlen(ok));
}
/* Handle GET /api/deploy-check - inspect repo and list build files */
static void handle_api_deploy_check(sock_t client) {
/* Build JSON with: build files, remote repo files, remote CNAME */
char json[32768];
int pos = 0;
pos += snprintf(json + pos, sizeof(json) - pos, "{\"build\":[");
/* List build/ directory files */
struct stat st;
int has_build = (stat("build", &st) == 0);
if (has_build) {
#ifdef _WIN32
FILE *p = _popen("dir /B build\\ 2>nul", "r");
#else
FILE *p = popen("ls -1 build/ 2>/dev/null", "r");
#endif
if (p) {
char fname[512];
int first = 1;
while (fgets(fname, sizeof(fname), p)) {
int len = (int)strlen(fname);
while (len > 0 && (fname[len-1] == '\n' || fname[len-1] == '\r'))
fname[--len] = '\0';
if (len == 0) continue;
if (!first) pos += snprintf(json + pos, sizeof(json) - pos, ",");
pos += snprintf(json + pos, sizeof(json) - pos, "\"%s\"", fname);
first = 0;
}
#ifdef _WIN32
_pclose(p);
#else
pclose(p);
#endif
}
}
pos += snprintf(json + pos, sizeof(json) - pos, "],");
/* Read deploy.conf for repo URL */
char repo[1024] = {0};
char domain[256] = {0};
FILE *cf = fopen("deploy.conf", "r");
if (cf) {
char line[1024];
while (fgets(line, sizeof(line), cf)) {
int len = (int)strlen(line);
while (len > 0 && (line[len-1] == '\n' || line[len-1] == '\r' ||
line[len-1] == ' ')) line[--len] = '\0';
if (line[0] == '#' || line[0] == '\0') continue;
if (strncmp(line, "repo=", 5) == 0)
strncpy(repo, line + 5, sizeof(repo) - 1);
else if (strncmp(line, "domain=", 7) == 0)
strncpy(domain, line + 7, sizeof(domain) - 1);
}
fclose(cf);
}
/* Check remote repo */
pos += snprintf(json + pos, sizeof(json) - pos, "\"remote\":[");
char remote_cname[256] = {0};
int repo_exists = 0;
if (repo[0]) {
/* Use git ls-remote to check if repo exists, then ls-tree for file list */
char cmd[2048];
snprintf(cmd, sizeof(cmd),
"git ls-tree --name-only HEAD -r 2>/dev/null"
" || true");
/* Actually clone shallow to tmp to list files */
char tmpdir[1024];
#ifdef _WIN32
const char *tmp = getenv("TEMP");
if (!tmp) tmp = "C:\\Temp";
snprintf(tmpdir, sizeof(tmpdir), "%s\\deploy-check", tmp);
snprintf(cmd, sizeof(cmd), "rmdir /S /Q \"%s\" 2>nul", tmpdir);
#else
const char *tmp = getenv("TMPDIR");
if (!tmp) tmp = "/tmp";
snprintf(tmpdir, sizeof(tmpdir), "%s/deploy-check", tmp);
snprintf(cmd, sizeof(cmd), "rm -rf \"%s\"", tmpdir);
#endif
system(cmd);
snprintf(cmd, sizeof(cmd),
"git clone --depth 1 \"%s\" \"%s\" 2>/dev/null", repo, tmpdir);
int clone_rc = system(cmd);
if (clone_rc == 0) {
repo_exists = 1;
/* List files */
#ifdef _WIN32
snprintf(cmd, sizeof(cmd), "dir /B \"%s\\\" 2>nul", tmpdir);
FILE *p = _popen(cmd, "r");
#else
snprintf(cmd, sizeof(cmd),
"ls -1A \"%s\" 2>/dev/null | grep -v '^.git$'", tmpdir);
FILE *p = popen(cmd, "r");
#endif
if (p) {
char fname[512];
int first = 1;
while (fgets(fname, sizeof(fname), p)) {
int len = (int)strlen(fname);
while (len > 0 && (fname[len-1] == '\n' || fname[len-1] == '\r'))
fname[--len] = '\0';
if (len == 0 || strcmp(fname, ".git") == 0) continue;
if (!first) pos += snprintf(json + pos, sizeof(json) - pos, ",");
pos += snprintf(json + pos, sizeof(json) - pos, "\"%s\"", fname);
first = 0;
/* Check for CNAME */
if (strcmp(fname, "CNAME") == 0) {
char cpath[1024];
snprintf(cpath, sizeof(cpath), "%s%cCNAME", tmpdir,
#ifdef _WIN32
'\\'
#else
'/'
#endif
);
FILE *cnf = fopen(cpath, "r");
if (cnf) {
if (fgets(remote_cname, sizeof(remote_cname), cnf)) {
int cl = (int)strlen(remote_cname);
while (cl > 0 && (remote_cname[cl-1] == '\n' ||
remote_cname[cl-1] == '\r'))
remote_cname[--cl] = '\0';
}
fclose(cnf);
}
}
}
#ifdef _WIN32
_pclose(p);
#else
pclose(p);
#endif
}
/* Cleanup */
#ifdef _WIN32
snprintf(cmd, sizeof(cmd), "rmdir /S /Q \"%s\" 2>nul", tmpdir);
#else
snprintf(cmd, sizeof(cmd), "rm -rf \"%s\"", tmpdir);
#endif
system(cmd);
}
}
pos += snprintf(json + pos, sizeof(json) - pos, "],");
pos += snprintf(json + pos, sizeof(json) - pos,
"\"repoExists\":%s,", repo_exists ? "true" : "false");
pos += snprintf(json + pos, sizeof(json) - pos,
"\"remoteCname\":\"%s\",", remote_cname);
pos += snprintf(json + pos, sizeof(json) - pos,
"\"hasBuild\":%s}", has_build ? "true" : "false");
send_response(client, 200, "OK", "application/json; charset=utf-8",
json, (long)strlen(json));
}
/* Handle POST /api/deploy - run the deploy tool */
static void handle_api_deploy(sock_t client) {
int rc;
#ifdef _WIN32
struct stat st;
if (stat("deploy\\deploy.exe", &st) == 0) {
rc = system("deploy\\deploy.exe");
} else if (stat("deploy\\deploy.c", &st) == 0) {
const char *msg = "{\"error\":\"deploy.exe not compiled. Run: cd deploy && cl deploy.c /Fe:deploy.exe\"}";
send_response(client, 500, "Internal Server Error",
"application/json; charset=utf-8", msg, (long)strlen(msg));
return;
} else {
const char *msg = "{\"error\":\"No deploy tool found in deploy/ directory\"}";
send_response(client, 500, "Internal Server Error",
"application/json; charset=utf-8", msg, (long)strlen(msg));
return;
}
#else
struct stat st;
if (stat("deploy/deploy", &st) == 0) {
rc = system("./deploy/deploy");
} else if (stat("deploy/deploy.c", &st) == 0) {
const char *msg = "{\"error\":\"deploy binary not compiled. Run: cd deploy && cc -O2 -o deploy deploy.c\"}";
send_response(client, 500, "Internal Server Error",
"application/json; charset=utf-8", msg, (long)strlen(msg));
return;
} else {
const char *msg = "{\"error\":\"No deploy tool found in deploy/ directory\"}";
send_response(client, 500, "Internal Server Error",
"application/json; charset=utf-8", msg, (long)strlen(msg));
return;
}
#endif
if (rc == 0) {
printf("Deploy completed successfully.\n");
const char *ok = "{\"ok\":true,\"message\":\"Deploy completed successfully\"}";
send_response(client, 200, "OK", "application/json; charset=utf-8",
ok, (long)strlen(ok));
} else {
printf("Deploy failed with exit code %d.\n", rc);
const char *msg = "{\"error\":\"Deploy failed. Check terminal for details.\"}";
send_response(client, 500, "Internal Server Error",
"application/json; charset=utf-8", msg, (long)strlen(msg));
}
}
static void handle_request(sock_t client) {
/* Use a larger buffer for POST bodies */
char buf[65536];
int n = recv(client, buf, sizeof(buf) - 1, 0);
if (n <= 0) return;
buf[n] = '\0';
/* Parse request line */
char method[16] = {0};
char raw_path[1024] = {0};
sscanf(buf, "%15s %1023s", method, raw_path);
/* Strip query string */
char *qmark = strchr(raw_path, '?');
if (qmark) *qmark = '\0';
/* Handle POST endpoints */
if (strcmp(method, "POST") == 0) {
if (strcmp(raw_path, "/api/save") == 0) {
handle_api_save(client, buf, n);
return;
}
if (strcmp(raw_path, "/api/build") == 0) {
handle_api_build(client);
return;
}
if (strcmp(raw_path, "/api/deploy") == 0) {
handle_api_deploy(client);
return;
}
if (strcmp(raw_path, "/api/deploy-config") == 0) {
handle_api_deploy_config_post(client, buf, n);
return;
}
send_error(client, 404, "Not Found");
return;
}
/* Handle GET endpoints */
if (strcmp(method, "GET") == 0 && strcmp(raw_path, "/api/deploy-config") == 0) {
handle_api_deploy_config_get(client);
return;
}
if (strcmp(method, "GET") == 0 && strcmp(raw_path, "/api/deploy-check") == 0) {
handle_api_deploy_check(client);
return;
}
/* Only handle GET beyond this point */
if (strcmp(method, "GET") != 0) {
send_error(client, 405, "Method Not Allowed");
return;
}
/* URL decode (basic: handle %XX) */
char path[1024];
{
int pi = 0;
for (int i = 0; raw_path[i] && pi < (int)sizeof(path) - 1; i++) {
if (raw_path[i] == '%' && raw_path[i+1] && raw_path[i+2]) {
char hex[3] = { raw_path[i+1], raw_path[i+2], 0 };
path[pi++] = (char)strtol(hex, NULL, 16);
i += 2;
} else {
path[pi++] = raw_path[i];
}
}
path[pi] = '\0';
}
/* Safety check */
if (!path_is_safe(path)) {
send_error(client, 403, "Forbidden");
return;
}
/* Build local file path */
char filepath[2048];
const char *rel = path;
if (rel[0] == '/') rel++;
if (rel[0] == '\0') {
/* Root request -> serve manage.html */
snprintf(filepath, sizeof(filepath), "manage.html");
} else {
snprintf(filepath, sizeof(filepath), "%s", rel);
}
/* Convert slashes on Windows */
#ifdef _WIN32
for (int i = 0; filepath[i]; i++) {
if (filepath[i] == '/') filepath[i] = '\\';
}
#endif
/* Check if path is a directory, try index.html */
struct stat st;
if (stat(filepath, &st) == 0 && S_ISDIR(st.st_mode)) {
char idx[2048];
snprintf(idx, sizeof(idx), "%s%cindex.html", filepath, PATH_SEP);
if (stat(idx, &st) == 0 && S_ISREG(st.st_mode)) {
send_file(client, idx);
} else {
send_error(client, 403, "Forbidden");
}
return;
}
if (stat(filepath, &st) == 0 && S_ISREG(st.st_mode)) {
send_file(client, filepath);
} else {
send_error(client, 404, "Not Found");
}
}
/* ---- Main ---- */
int main(int argc, char *argv[]) {
int port = 9090;
if (argc > 1) {
port = atoi(argv[1]);
if (port <= 0 || port > 65535) {
fprintf(stderr, "Invalid port: %s\n", argv[1]);
return 1;
}
}
signal(SIGINT, handle_signal);
#ifndef _WIN32
signal(SIGPIPE, SIG_IGN);
#endif
if (platform_init() != 0) {
fprintf(stderr, "Failed to initialize networking.\n");
return 1;
}
server_sock = socket(AF_INET, SOCK_STREAM, 0);
if (server_sock == INVALID_SOCK) {
fprintf(stderr, "Failed to create socket.\n");
platform_cleanup();
return 1;
}
/* Allow port reuse */
int opt = 1;
#ifdef _WIN32
setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt));
#else
setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#endif
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons((unsigned short)port);
while (bind(server_sock, (struct sockaddr *)&addr, sizeof(addr)) == SOCKERR) {
fprintf(stderr, "\nPort %d is already in use.\n\n", port);
fprintf(stderr, " [k] Kill the process using port %d and retry\n", port);
fprintf(stderr, " [d] Choose a different port\n");
fprintf(stderr, " [q] Quit\n\n");
fprintf(stderr, "Choice: ");
fflush(stderr);
char choice[16];
if (!fgets(choice, sizeof(choice), stdin)) {
CLOSESOCKET(server_sock);
platform_cleanup();
return 1;
}
if (choice[0] == 'q' || choice[0] == 'Q') {
CLOSESOCKET(server_sock);
platform_cleanup();
return 0;
} else if (choice[0] == 'k' || choice[0] == 'K') {
/* Kill the process occupying the port */
char kill_cmd[256];
#ifdef _WIN32
snprintf(kill_cmd, sizeof(kill_cmd),
"for /f \"tokens=5\" %%%%a in ('netstat -aon ^| findstr :%d') do taskkill /F /PID %%%%a >nul 2>&1", port);
#elif defined(__APPLE__)
snprintf(kill_cmd, sizeof(kill_cmd),
"lsof -ti tcp:%d | xargs kill -9 2>/dev/null", port);
#else
snprintf(kill_cmd, sizeof(kill_cmd),
"fuser -k %d/tcp 2>/dev/null", port);
#endif
int ret = system(kill_cmd);
if (ret != 0) {
fprintf(stderr, "Could not kill process on port %d (may need sudo).\n", port);
} else {
fprintf(stderr, "Killed process on port %d. Retrying...\n", port);
}
/* Small delay to let the OS release the port */
#ifdef _WIN32
Sleep(500);
#else
usleep(500000);
#endif
/* Recreate socket since the old one may be in a bad state */
CLOSESOCKET(server_sock);
server_sock = socket(AF_INET, SOCK_STREAM, 0);
if (server_sock == INVALID_SOCK) {
fprintf(stderr, "Failed to create socket.\n");
platform_cleanup();
return 1;
}
#ifdef _WIN32
setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt));
#else
setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#endif
} else if (choice[0] == 'd' || choice[0] == 'D') {
fprintf(stderr, "Enter new port: ");
fflush(stderr);
char port_buf[16];
if (!fgets(port_buf, sizeof(port_buf), stdin)) {
CLOSESOCKET(server_sock);
platform_cleanup();
return 1;
}
int new_port = atoi(port_buf);
if (new_port <= 0 || new_port > 65535) {
fprintf(stderr, "Invalid port number.\n");
continue;
}
port = new_port;
addr.sin_port = htons((unsigned short)port);
/* Recreate socket for the new port */
CLOSESOCKET(server_sock);
server_sock = socket(AF_INET, SOCK_STREAM, 0);
if (server_sock == INVALID_SOCK) {
fprintf(stderr, "Failed to create socket.\n");
platform_cleanup();
return 1;
}
#ifdef _WIN32
setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt));
#else
setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#endif
} else {
fprintf(stderr, "Invalid choice. Enter k, d, or q.\n");
}
}
if (listen(server_sock, 16) == SOCKERR) {
fprintf(stderr, "Failed to listen.\n");
CLOSESOCKET(server_sock);
platform_cleanup();
return 1;
}
printf("Portfolio server running at http://localhost:%d/\n", port);
printf("Manager: http://localhost:%d/manage.html\n", port);
printf("Portfolio: http://localhost:%d/index.html\n", port);
printf("Press Ctrl+C to stop.\n\n");
open_browser(port);
while (running) {
struct sockaddr_in client_addr;
#ifdef _WIN32
int client_len = sizeof(client_addr);
#else
socklen_t client_len = sizeof(client_addr);
#endif
sock_t client = accept(server_sock, (struct sockaddr *)&client_addr, &client_len);
if (client == INVALID_SOCK) {
if (!running) break;
continue;
}
handle_request(client);
CLOSESOCKET(client);
}
printf("\nServer stopped.\n");
if (server_sock != INVALID_SOCK) {
CLOSESOCKET(server_sock);
}
platform_cleanup();
return 0;
}