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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
|
#include "web.h"
#include "mytime.h"
#include <assert.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <microhttpd.h>
#include <sqlite3.h>
#include <cjson/cJSON.h>
#include <fcntl.h>
#define PAGE "<html><head><title>libmicrohttpd demo</title>"\
"</head><body>libmicrohttpd demo</body></html>"
static void sqliteError(void *pArg, int iErrCode, const char *zMsg) {
// @CLEANUP: We should stuff these somewhere, but for now just print it
fprintf(stderr, "(%d) %s\n", iErrCode, zMsg);
}
static int generate_secret(char *out) {
unsigned char bytes[16];
int fd = open("/dev/urandom", O_RDONLY);
if (fd < 0) return -1;
ssize_t n = read(fd, bytes, 16);
close(fd);
if (n != 16) return -1;
static const char hex[] = "0123456789abcdef";
for (int i = 0; i < 16; i++) {
out[i*2] = hex[(bytes[i] >> 4) & 0x0f];
out[i*2+1] = hex[bytes[i] & 0x0f];
}
out[32] = '\0';
return 0;
}
void prepare_database(struct App *app) {
// @CLEANUP: Move this to main? doesn't belong here at least
sqlite3_config(SQLITE_CONFIG_LOG, sqliteError, NULL);
sqlite3_config(SQLITE_CONFIG_URI, 1);
int err;
printf("Running migrations against %s\n", app->dbname);
sqlite3 *conn;
if((err = sqlite3_open(app->dbname, &conn)) != SQLITE_OK) {
fprintf(stderr, "(%d) %s\n", err, sqlite3_errmsg(conn));
abort();
}
sqlite3_db_config(conn, SQLITE_DBCONFIG_ENABLE_FKEY, 1, NULL);
if(sqlite3_exec(conn, "CREATE TABLE IF NOT EXISTS migration (id INTEGER PRIMARY KEY NOT NULL)", NULL, NULL, NULL) != SQLITE_OK) {
abort();
}
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(conn, "SELECT MAX(id) FROM migration", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
uint64_t maxVersion = 0;
while((err = sqlite3_step(stmt)) == SQLITE_ROW) {
maxVersion = sqlite3_column_int64(stmt, 0);
}
if(err != SQLITE_DONE) {
abort();
}
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
if(maxVersion < 1) {
char *prog =
"BEGIN TRANSACTION;"
"CREATE TABLE backups ("
"id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
"client TEXT NOT NULL, "
"status TEXT NOT NULL, "
"started TEXT NOT NULL, "
"completed TEXT "
") STRICT";
if(sqlite3_exec(conn, prog, NULL, NULL, NULL) != SQLITE_OK) {
abort();
}
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(conn, "INSERT INTO migration (id) VALUES (?1)", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_int64(stmt, 1, 1) != SQLITE_OK) {
abort();
}
if(sqlite3_step(stmt) != SQLITE_DONE) {
abort();
}
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
if(sqlite3_exec(conn, "COMMIT TRANSACTION", NULL, NULL, NULL) != SQLITE_OK) {
abort();
}
}
if(maxVersion < 2) {
char *prog =
"BEGIN TRANSACTION;"
"CREATE TABLE clients ("
"id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
"name TEXT NOT NULL "
") STRICT;"
"INSERT INTO clients(name) "
"SELECT b.client "
"FROM backups b "
"GROUP BY b.client;"
"CREATE TABLE backups_next ("
"id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
"client INTEGER NOT NULL, "
"status TEXT NOT NULL, "
"started TEXT NOT NULL, "
"completed TEXT ,"
"FOREIGN KEY(client) REFERENCES clients(id)"
") STRICT;"
"INSERT INTO backups_next(id, client, status, started, completed) "
"SELECT b.id, c.id, b.status, b.started, b.completed "
"FROM backups b "
"JOIN clients c ON b.client = c.name;"
"DROP TABLE backups;"
"ALTER TABLE backups_next RENAME TO backups;";
if(sqlite3_exec(conn, prog, NULL, NULL, NULL) != SQLITE_OK) {
abort();
}
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(conn, "INSERT INTO migration (id) VALUES (?1)", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_int64(stmt, 1, 2) != SQLITE_OK) {
abort();
}
if(sqlite3_step(stmt) != SQLITE_DONE) {
abort();
}
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
if(sqlite3_exec(conn, "COMMIT TRANSACTION", NULL, NULL, NULL) != SQLITE_OK) {
abort();
}
}
if(maxVersion < 3) {
char *prog =
"BEGIN TRANSACTION;"
"CREATE UNIQUE INDEX clients_name ON clients(name)";
if(sqlite3_exec(conn, prog, NULL, NULL, NULL) != SQLITE_OK) {
abort();
}
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(conn, "INSERT INTO migration (id) VALUES (?1)", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_int64(stmt, 1, 3) != SQLITE_OK) {
abort();
}
if(sqlite3_step(stmt) != SQLITE_DONE) {
abort();
}
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
if(sqlite3_exec(conn, "COMMIT TRANSACTION", NULL, NULL, NULL) != SQLITE_OK) {
abort();
}
}
if(maxVersion < 4) {
char *prog =
"BEGIN TRANSACTION;"
"ALTER TABLE clients ADD COLUMN secret TEXT NOT NULL DEFAULT ''";
if(sqlite3_exec(conn, prog, NULL, NULL, NULL) != SQLITE_OK) {
abort();
}
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(conn, "INSERT INTO migration (id) VALUES (?1)", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_int64(stmt, 1, 4) != SQLITE_OK) {
abort();
}
if(sqlite3_step(stmt) != SQLITE_DONE) {
abort();
}
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
if(sqlite3_exec(conn, "COMMIT TRANSACTION", NULL, NULL, NULL) != SQLITE_OK) {
abort();
}
}
}
enum ReportEvent {
REV_BEGIN,
REV_FINISH,
};
// @CLEANUP: This should live somewhere else, but I don't have a spot for it yet.
// Returns 0 on success, -1 on error, -2 on secret mismatch
int submit_report(struct App *app, char *client, char *secret, enum ReportEvent event) {
sqlite3 *conn;
int err;
if((err = sqlite3_open(app->dbname, &conn)) != SQLITE_OK) {
abort();
}
struct timespec now = get_current_time();
int64_t clientId;
{
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(conn, "SELECT id, secret FROM clients WHERE name = ?1", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_text(stmt, 1, client, -1, SQLITE_STATIC) != SQLITE_OK) {
abort();
}
if(sqlite3_step(stmt) != SQLITE_ROW) {
abort();
}
if(sqlite3_column_type(stmt, 0) == SQLITE_NULL) {
abort();
}
clientId = sqlite3_column_int64(stmt, 0);
const char *stored_secret = (const char *)sqlite3_column_text(stmt, 1);
if(stored_secret == NULL || strcmp(stored_secret, secret) != 0) {
sqlite3_finalize(stmt);
sqlite3_close(conn);
return -2;
}
if(sqlite3_step(stmt) != SQLITE_DONE) {
abort();
}
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
}
switch(event) {
case REV_BEGIN: {
sqlite3_stmt *stmt;
// Mark any existing RUNNING backup as INTERRUPTED
if(sqlite3_prepare_v2(conn, "UPDATE backups SET status = 'INTERRUPTED', completed = datetime(?1, 'unixepoch', 'subsec') WHERE client = ?2 AND status = 'RUNNING'", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_double(stmt, 1, TIME_AS_FLOAT(now)) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_int64(stmt, 2, clientId) != SQLITE_OK) {
abort();
}
if(sqlite3_step(stmt) != SQLITE_DONE) {
abort();
}
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
stmt = NULL;
// Insert the new backup
if(sqlite3_prepare_v2(conn, "INSERT INTO backups (client, status, started) VALUES (?1, ?2, datetime(?3, 'unixepoch', 'subsec'))", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_int64(stmt, 1, clientId) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_text(stmt, 2, "RUNNING", -1, SQLITE_STATIC) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_double(stmt, 3, TIME_AS_FLOAT(now)) != SQLITE_OK) {
abort();
}
if(sqlite3_step(stmt) != SQLITE_DONE) {
abort();
}
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
break;
}
case REV_FINISH: {
uint64_t backupId;
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(conn, "SELECT id FROM backups WHERE client = ?1 AND status = 'RUNNING'", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_int64(stmt, 1, clientId) != SQLITE_OK) {
abort();
}
if(sqlite3_step(stmt) != SQLITE_ROW) {
abort();
}
if(sqlite3_column_type(stmt, 0) == SQLITE_NULL) {
abort();
}
backupId = sqlite3_column_int64(stmt, 0);
if(sqlite3_step(stmt) != SQLITE_DONE) {
abort();
}
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
stmt = NULL;
if(sqlite3_prepare_v2(conn, "UPDATE backups SET status = ?1, completed = datetime(?2, 'unixepoch', 'subsec') WHERE id = ?3", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_text(stmt, 1, "FINISHED", -1, SQLITE_STATIC) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_double(stmt, 2, TIME_AS_FLOAT(now)) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_int64(stmt, 3, backupId) != SQLITE_OK) {
abort();
}
if(sqlite3_step(stmt) != SQLITE_DONE) {
abort();
}
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
break;
}
}
if(sqlite3_close(conn) != SQLITE_OK) {
abort();
}
return 0;
}
int create_client(struct Request *req, char *name, struct CreateClientResult *result) {
sqlite3 *conn;
int err;
if((err = sqlite3_open(req->server->app->dbname, &conn)) != SQLITE_OK) {
abort();
}
if(generate_secret(result->secret) != 0) {
abort();
}
{
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(conn, "INSERT INTO clients (name, secret) VALUES (?1, ?2)", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_text(stmt, 1, name, -1, SQLITE_STATIC) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_text(stmt, 2, result->secret, -1, SQLITE_STATIC) != SQLITE_OK) {
abort();
}
if(sqlite3_step(stmt) != SQLITE_DONE) {
abort();
}
result->id = sqlite3_last_insert_rowid(conn);
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
}
if(sqlite3_close(conn) != SQLITE_OK) {
abort();
}
return 0;
}
int delete_client(struct Request *req, int64_t client_id) {
sqlite3 *conn;
if(sqlite3_open(req->server->app->dbname, &conn) != SQLITE_OK) {
abort();
}
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(conn, "DELETE FROM clients WHERE id = ?1", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_int64(stmt, 1, client_id) != SQLITE_OK) {
abort();
}
if(sqlite3_step(stmt) != SQLITE_DONE) {
abort();
}
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
if(sqlite3_close(conn) != SQLITE_OK) {
abort();
}
return 0;
}
int list_clients(struct Request *req, struct ListClientResult *result) {
sqlite3 *conn;
int err;
if((err = sqlite3_open(req->server->app->dbname, &conn)) != SQLITE_OK) {
abort();
}
{
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(conn, "SELECT c.id, c.name, c.secret FROM clients c WHERE c.id > ?1 ORDER BY c.id ASC LIMIT ?2", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_int64(stmt, 1, -1) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_int64(stmt, 2, 16) != SQLITE_OK) {
abort();
}
int ret;
int index = 0;
while((ret = sqlite3_step(stmt)) == SQLITE_ROW) {
assert(index < 16);
if(sqlite3_column_type(stmt, 0) == SQLITE_NULL) {
abort();
}
int64_t clientId = sqlite3_column_int64(stmt, 0);
const uint8_t *name = sqlite3_column_text(stmt, 1);
const uint8_t *secret = sqlite3_column_text(stmt, 2);
result->clients[index].id = clientId;
strncpy(result->clients[index].name, (char*)name, CLIENT_NAME_MAX);
strncpy(result->clients[index].secret, (char*)secret, CLIENT_SECRET_LEN);
index++;
}
if(ret != SQLITE_DONE) {
abort();
}
result->clients_len = index;
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
}
if(sqlite3_close(conn) != SQLITE_OK) {
abort();
}
return 0;
}
int get_client_with_backups(struct Request *req, int64_t client_id, struct GetClientResult *result) {
sqlite3 *conn;
int err;
if((err = sqlite3_open(req->server->app->dbname, &conn)) != SQLITE_OK) {
abort();
}
result->found = 0;
// Query 1: Get client info
{
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(conn, "SELECT id, name, secret FROM clients WHERE id = ?1", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_int64(stmt, 1, client_id) != SQLITE_OK) {
abort();
}
int ret = sqlite3_step(stmt);
if(ret == SQLITE_ROW) {
result->found = 1;
result->id = sqlite3_column_int64(stmt, 0);
const uint8_t *name = sqlite3_column_text(stmt, 1);
const uint8_t *secret = sqlite3_column_text(stmt, 2);
strncpy(result->name, (char*)name, CLIENT_NAME_MAX);
strncpy(result->secret, (char*)secret, CLIENT_SECRET_LEN);
} else if(ret != SQLITE_DONE) {
abort();
}
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
}
if(!result->found) {
if(sqlite3_close(conn) != SQLITE_OK) {
abort();
}
return 0;
}
// Query 2: Get backups for this client
{
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(conn, "SELECT id, status, started, completed FROM backups WHERE client = ?1 ORDER BY started DESC LIMIT 50", -1, &stmt, NULL) != SQLITE_OK) {
abort();
}
if(sqlite3_bind_int64(stmt, 1, client_id) != SQLITE_OK) {
abort();
}
int ret;
int index = 0;
while((ret = sqlite3_step(stmt)) == SQLITE_ROW) {
if(index >= MAX_BACKUPS_DISPLAY) break;
result->backups[index].id = sqlite3_column_int64(stmt, 0);
const uint8_t *status = sqlite3_column_text(stmt, 1);
const uint8_t *started = sqlite3_column_text(stmt, 2);
const uint8_t *completed = sqlite3_column_text(stmt, 3);
strncpy(result->backups[index].status, status ? (char*)status : "", BACKUP_STATUS_MAX);
strncpy(result->backups[index].started, started ? (char*)started : "", BACKUP_DATETIME_MAX);
strncpy(result->backups[index].completed, completed ? (char*)completed : "", BACKUP_DATETIME_MAX);
index++;
}
if(ret != SQLITE_DONE && ret != SQLITE_ROW) {
abort();
}
result->backups_len = index;
if(sqlite3_finalize(stmt) != SQLITE_OK) {
abort();
}
}
if(sqlite3_close(conn) != SQLITE_OK) {
abort();
}
return 0;
}
static char *render_clients_page(struct Request *request, size_t *out_len) {
int ret;
struct ListClientResult *result = malloc(sizeof(struct ListClientResult) + sizeof(struct ListClientResultClient) * 16);
ret = list_clients(request, result);
if(ret != 0) {
free(result);
return NULL;
}
char *buf = NULL;
size_t buf_len = 0;
FILE *f = open_memstream(&buf, &buf_len);
if (!f) {
free(result);
return NULL;
}
fprintf(f,
"<!DOCTYPE html>\n"
"<html>\n"
"<head>\n"
" <title>Clients</title>\n"
"</head>\n"
"<body>\n"
" <h1>Clients</h1>\n"
" <table border=\"1\">\n"
" <tr><th>Name</th><th>Secret</th><th>Actions</th></tr>\n");
for (int i = 0; i < result->clients_len; i++) {
fprintf(f,
" <tr>\n"
" <td><a href=\"/client/%ld\">%s</a></td>\n"
" <td>%s</td>\n"
" <td>\n"
" <form method=\"POST\" action=\"/clients/delete\" style=\"display:inline\">\n"
" <input type=\"hidden\" name=\"client_id\" value=\"%ld\">\n"
" <button type=\"submit\">Delete</button>\n"
" </form>\n"
" </td>\n"
" </tr>\n",
result->clients[i].id,
result->clients[i].name,
result->clients[i].secret,
result->clients[i].id
);
}
fprintf(f,
" </table>\n"
" <h2>Add New Client</h2>\n"
" <form method=\"POST\" action=\"/clients\">\n"
" <input type=\"text\" name=\"name\" maxlength=\"31\" placeholder=\"Client name\" required>\n"
" <button type=\"submit\">Add Client</button>\n"
" </form>\n"
"</body>\n"
"</html>\n");
fclose(f);
*out_len = buf_len;
free(result);
return buf;
}
static char *render_client_detail_page(struct Request *request, int64_t client_id, size_t *out_len) {
struct GetClientResult *result = malloc(sizeof(struct GetClientResult) + sizeof(struct BackupRecord) * MAX_BACKUPS_DISPLAY);
int ret = get_client_with_backups(request, client_id, result);
if(ret != 0) {
free(result);
return NULL;
}
if(!result->found) {
free(result);
return NULL;
}
char *buf = NULL;
size_t buf_len = 0;
FILE *f = open_memstream(&buf, &buf_len);
if (!f) {
free(result);
return NULL;
}
fprintf(f,
"<!DOCTYPE html>\n"
"<html>\n"
"<head>\n"
" <title>Client: %s</title>\n"
"</head>\n"
"<body>\n"
" <p><a href=\"/clients\">Clients</a> > %s</p>\n"
" <h1>Client: %s</h1>\n"
" <h2>Details</h2>\n"
" <table border=\"1\">\n"
" <tr><th>ID</th><td>%ld</td></tr>\n"
" <tr><th>Name</th><td>%s</td></tr>\n"
" <tr><th>Secret</th><td>%s</td></tr>\n"
" </table>\n",
result->name,
result->name,
result->name,
result->id,
result->name,
result->secret
);
fprintf(f,
" <h2>Submit Report</h2>\n"
" <p>Use this curl command to submit a backup report:</p>\n"
" <pre>curl -X POST http://%s/api/report \\\n"
" -H \"Content-Type: application/json\" \\\n"
" -d '{\"client\": \"%s\", \"secret\": \"%s\", \"event\": \"begin_backup\"}'</pre>\n"
" <p>Replace <code>begin_backup</code> with <code>end_backup</code> to mark completion.</p>\n",
request->host ? request->host : "localhost",
result->name,
result->secret
);
fprintf(f, " <h2>Backup History</h2>\n");
if(result->backups_len == 0) {
fprintf(f, " <p>No backups recorded.</p>\n");
} else {
fprintf(f,
" <table border=\"1\">\n"
" <tr><th>ID</th><th>Status</th><th>Started</th><th>Completed</th></tr>\n");
for (int i = 0; i < result->backups_len; i++) {
fprintf(f,
" <tr>\n"
" <td>%ld</td>\n"
" <td>%s</td>\n"
" <td>%s</td>\n"
" <td>%s</td>\n"
" </tr>\n",
result->backups[i].id,
result->backups[i].status,
result->backups[i].started,
result->backups[i].completed[0] ? result->backups[i].completed : "-"
);
}
fprintf(f, " </table>\n");
}
fprintf(f,
"</body>\n"
"</html>\n");
fclose(f);
*out_len = buf_len;
free(result);
return buf;
}
static enum MHD_Result create_post_collector(struct PostCollector *c) {
c->data = malloc(512);
c->size = 0;
c->capacity = 512;
return MHD_YES;
}
static enum MHD_Result collect_post(struct PostCollector *c, const char *data, size_t *data_len) {
size_t newSize = c->size + *data_len;
if(newSize > c->capacity) {
while(newSize > c->capacity) c->capacity *= 2;
c->data = realloc(c->data, c->capacity);
}
memcpy(c->data + c->size, data, *data_len);
c->size = newSize;
return MHD_YES;
}
static enum MHD_Result destroy_post_collector(struct PostCollector *c) {
if(c->capacity != 0) {
free(c->data);
c->capacity = 0;
}
return MHD_YES;
}
static enum MHD_Result
form_iterator(void *cls,
enum MHD_ValueKind kind,
const char *key,
const char *filename,
const char *content_type,
const char *transfer_encoding,
const char *data,
uint64_t off,
size_t size)
{
struct Request *request = cls;
if (strcmp(key, "name") == 0 && off + size < CLIENT_NAME_MAX) {
memcpy(request->form.name + off, data, size);
request->form.name[off + size] = '\0';
request->form.name_set = 1;
} else if (strcmp(key, "client_id") == 0 && off == 0) {
char buf[32] = {0};
size_t copy_size = size < 31 ? size : 31;
memcpy(buf, data, copy_size);
request->form.client_id = strtoll(buf, NULL, 10);
request->form.client_id_set = 1;
}
return MHD_YES;
}
static enum MHD_Result handler(
void *cls,
struct MHD_Connection *connection,
const char *url,
const char *method,
const char *version,
const char *upload_data,
size_t *upload_data_size,
void **ptr
) {
struct Server *server = cls;
int ret;
// For the first call where con_cls points at NULL we have to create the
// connection state
struct Request *request = *ptr;
if (request == NULL) {
request = calloc(1, sizeof(struct Request));
if(request == NULL) {
return MHD_NO;
}
*ptr = request;
request->server = server;
request->host = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "Host");
if(strcmp(method, "POST") == 0) {
if(strcmp(url, "/clients") == 0 || strcmp(url, "/clients/delete") == 0) {
request->post_proc = MHD_create_post_processor(
connection, 1024, &form_iterator, request);
if (request->post_proc == NULL) {
free(request);
return MHD_NO;
}
} else {
create_post_collector(&request->pp);
}
}
return MHD_YES;
}
if(strcmp(method, "POST") == 0) {
if (request->post_proc != NULL) {
if (*upload_data_size != 0) {
MHD_post_process(request->post_proc, upload_data, *upload_data_size);
*upload_data_size = 0;
return MHD_YES;
}
} else {
collect_post(&request->pp, upload_data, upload_data_size);
if (*upload_data_size != 0) {
*upload_data_size = 0;
return MHD_YES;
}
}
if(strcmp(url, "/clients") == 0) {
MHD_destroy_post_processor(request->post_proc);
request->post_proc = NULL;
if (!request->form.name_set || request->form.name[0] == '\0') {
return MHD_NO;
}
struct CreateClientResult result;
ret = create_client(request, request->form.name, &result);
if(ret != 0) return MHD_NO;
// Post-Redirect-Get: redirect back to GET /clients
struct MHD_Response *response = MHD_create_response_from_buffer(
0, "", MHD_RESPMEM_PERSISTENT);
ret = MHD_add_response_header(response, "Location", "/clients");
if(ret != MHD_YES) return ret;
ret = MHD_queue_response(connection, MHD_HTTP_SEE_OTHER, response);
MHD_destroy_response(response);
return ret;
} else if(strcmp(url, "/clients/delete") == 0) {
MHD_destroy_post_processor(request->post_proc);
request->post_proc = NULL;
if (!request->form.client_id_set || request->form.client_id <= 0) {
return MHD_NO;
}
ret = delete_client(request, request->form.client_id);
if(ret != 0) return MHD_NO;
struct MHD_Response *response = MHD_create_response_from_buffer(
0, "", MHD_RESPMEM_PERSISTENT);
ret = MHD_add_response_header(response, "Location", "/clients");
if(ret != MHD_YES) return ret;
ret = MHD_queue_response(connection, MHD_HTTP_SEE_OTHER, response);
MHD_destroy_response(response);
return ret;
} else if(strcmp(url, "/api/report") == 0) {
cJSON *rootJson = cJSON_ParseWithLength(request->pp.data, request->pp.size);
cJSON *clientJson = cJSON_GetObjectItemCaseSensitive(rootJson, "client");
if(!cJSON_IsString(clientJson) || clientJson->valuestring == NULL) {
abort();
}
cJSON *secretJson = cJSON_GetObjectItemCaseSensitive(rootJson, "secret");
if(!cJSON_IsString(secretJson) || secretJson->valuestring == NULL) {
abort();
}
cJSON *eventJson = cJSON_GetObjectItemCaseSensitive(rootJson, "event");
if(!cJSON_IsString(eventJson) || eventJson->valuestring == NULL) {
abort();
}
enum ReportEvent event;
if(strcmp(eventJson->valuestring, "begin_backup") == 0) {
event = REV_BEGIN;
} else if(strcmp(eventJson->valuestring, "end_backup") == 0) {
event = REV_FINISH;
} else {
abort();
}
ret = submit_report(server->app, clientJson->valuestring, secretJson->valuestring, event);
if(ret == -2) {
cJSON_Delete(rootJson);
destroy_post_collector(&request->pp);
struct MHD_Response *response = MHD_create_response_from_buffer(
0,
"",
MHD_RESPMEM_PERSISTENT
);
ret = MHD_add_response_header(response, "Content-Type", "application/json");
if(ret != MHD_YES) return ret;
ret = MHD_queue_response(
connection,
MHD_HTTP_UNAUTHORIZED,
response
);
MHD_destroy_response(response);
return ret;
}
if(ret != 0) {
// Should actually return an error page, but this will do for now
return MHD_NO;
}
cJSON_Delete(rootJson);
// We've taken in all the data, now we can use it
destroy_post_collector(&request->pp);
struct MHD_Response *response = MHD_create_response_from_buffer(
0,
"",
MHD_RESPMEM_PERSISTENT
);
ret = MHD_add_response_header(response, "Content-Type", "application/json");
if(ret != MHD_YES) return ret;
ret = MHD_queue_response(
connection,
MHD_HTTP_NO_CONTENT,
response
);
MHD_destroy_response(response);
return ret;
} else if(strcmp(url, "/api/client") == 0) {
cJSON *rootJson = cJSON_ParseWithLength(request->pp.data, request->pp.size);
cJSON *nameJson = cJSON_GetObjectItemCaseSensitive(rootJson, "name");
if(!cJSON_IsString(nameJson) || nameJson->valuestring == NULL) {
abort();
}
struct CreateClientResult result;
ret = create_client(request, nameJson->valuestring, &result);
if(ret != 0) {
// Should actually return an error page, but this will do for now
return MHD_NO;
}
cJSON_Delete(rootJson);
// We've taken in all the data, now we can use it
destroy_post_collector(&request->pp);
char *buf = malloc(1024);
size_t buf_len = snprintf(buf, 1024, "{ \"id\": \"%ld\", \"secret\": \"%s\" }", result.id, result.secret);
if(buf_len >= 1024) {
abort();
}
struct MHD_Response *response = MHD_create_response_from_buffer(
buf_len,
buf,
MHD_RESPMEM_MUST_FREE
);
ret = MHD_add_response_header(response, "Content-Type", "application/json");
if(ret != MHD_YES) return ret;
ret = MHD_queue_response(
connection,
MHD_HTTP_OK,
response
);
MHD_destroy_response(response);
return ret;
} else {
// Not found
destroy_post_collector(&request->pp);
struct MHD_Response *response = MHD_create_response_from_buffer(
0,
"",
MHD_RESPMEM_PERSISTENT
);
ret = MHD_add_response_header(response, "Content-Type", "application/json");
if(ret != MHD_YES) return ret;
ret = MHD_queue_response(
connection,
MHD_HTTP_NOT_FOUND,
response
);
MHD_destroy_response(response);
return ret;
}
} else if (strcmp(method, "GET") == 0) {
if (*upload_data_size != 0) return MHD_NO;
if(strcmp(url, "/clients") == 0) {
size_t html_len;
char *html = render_clients_page(request, &html_len);
if (!html) {
return MHD_NO;
}
struct MHD_Response *response = MHD_create_response_from_buffer(
html_len,
html,
MHD_RESPMEM_MUST_FREE
);
ret = MHD_add_response_header(response, "Content-Type", "text/html");
if(ret != MHD_YES) return ret;
ret = MHD_queue_response(
connection,
MHD_HTTP_OK,
response
);
MHD_destroy_response(response);
return ret;
} else if (strncmp(url, "/client/", 8) == 0) {
int64_t client_id;
if (sscanf(url + 8, "%ld", &client_id) != 1 || client_id <= 0) {
// Bad Request
struct MHD_Response *response = MHD_create_response_from_buffer(
0, "", MHD_RESPMEM_PERSISTENT);
ret = MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, response);
MHD_destroy_response(response);
return ret;
}
size_t html_len;
char *html = render_client_detail_page(request, client_id, &html_len);
if (!html) {
// Not Found
struct MHD_Response *response = MHD_create_response_from_buffer(
0, "", MHD_RESPMEM_PERSISTENT);
ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);
MHD_destroy_response(response);
return ret;
}
struct MHD_Response *response = MHD_create_response_from_buffer(
html_len,
html,
MHD_RESPMEM_MUST_FREE
);
ret = MHD_add_response_header(response, "Content-Type", "text/html");
if(ret != MHD_YES) return ret;
ret = MHD_queue_response(
connection,
MHD_HTTP_OK,
response
);
MHD_destroy_response(response);
return ret;
} else {
struct MHD_Response *response = MHD_create_response_from_buffer(
strlen(server->page),
(void *)server->page,
MHD_RESPMEM_PERSISTENT
);
ret = MHD_queue_response(
connection,
MHD_HTTP_OK,
response
);
MHD_destroy_response(response);
return ret;
}
}
return MHD_NO;
}
static void request_completed_callback (
void *cls,
struct MHD_Connection *connection,
void **con_cls,
enum MHD_RequestTerminationCode toe
) {
struct Request *request = *con_cls;
if (request->post_proc != NULL) {
MHD_destroy_post_processor(request->post_proc);
}
destroy_post_collector(&request->pp);
free(request);
}
static struct MHD_Daemon *d = NULL;
int web_begin(struct Server *server, int port) {
assert(d == NULL);
server->page = PAGE;
d = MHD_start_daemon(
MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DUAL_STACK,
port,
NULL, NULL,
&handler, server,
MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL,
MHD_OPTION_END
);
if (d == NULL) return 1;
return 0;
}
int web_join(struct Server *server) {
assert(d != NULL);
MHD_stop_daemon(d);
d = NULL;
return 0;
}
|