Repository navigation
Expand file tree
/
Copy pathserver.cpp
More file actions
1919 lines (1683 loc) · 73.2 KB
/
Copy pathserver.cpp
File metadata and controls
1919 lines (1683 loc) · 73.2 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
/************************************************************************
FAUST Architecture File
Copyright (C) 2017 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************
************************************************************************/
#include <fcntl.h>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstring>
#include <ctime>
#include <cctype>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <random>
#include <regex>
#include <set>
#include <sstream>
#include <string>
#include <vector>
// libmicrohttpd
#include <microhttpd.h>
// libcryptopp
#include <openssl/sha.h>
// libarchive
#include <archive.h>
#include <archive_entry.h>
#include "content.hh"
#include "faustOptions.hh"
#include "process.hh"
#include "htmlPages.hh"
#include "match.hh"
#include "server.hh"
#include "utilities.hh"
// to use command line tools
#include <stdlib.h>
// Avoid using namespace std for better code clarity
namespace fs = std::filesystem;
extern int gVerbosity;
/*
* Various responses to GET requests
*/
extern bool gAnyOrigin; // when true adds Access-Control-Allow-Origin to http answers
#define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN "Access-Control-Allow-Origin"
// SECURITY: Protect faust against stack overflow and resource exhaustion: 8 MB of stack
// (the default can be much larger on Linux) and 30 seconds of CPU time
static const ProcessLimits kFaustLimits = {8 * 1024 * 1024, 30};
// dot can be legitimately slow: a generous CPU time and no stack limit
static const ProcessLimits kDotLimits = {0, 180};
// SECURITY: Maximum size of an uploaded file, before any decompression (the content of an
// archive is limited to 500 KB when extracted)
static const size_t kMaxUploadSize = 1024 * 1024;
/*
* Generates an SHA-1 key for Faust file or archive.
*/
/*
* The uploaded file is stored under a name chosen by the server: only its
* extension comes from the client. The client's name is kept for the DSP file
* compiled in sourcecode/, since it names the generated applications.
*/
static fs::path uploaded_file_path(const connection_info_struct* con_info)
{
return fs::path(con_info->tmppath) /
("upload" + fs::path(con_info->filename).extension().string());
}
static std::string generate_sha1(connection_info_struct* con_info)
{
return generateFileSHA1(uploaded_file_path(con_info));
}
/*
* SECURITY: A foreign function names a header that the generated C++ code
* includes. A .lib file of the upload named that way would be compiled as C++
* code, so the generated code may only include headers of the system or of
* Faust: an included path must be relative, without "..", and name no file of
* sourcecode/. Faust copies strings into the generated code without letting
* them add lines, so every #include line comes from an include directive.
*/
static bool includes_only_system_headers(const fs::path& generated_file,
const fs::path& sourcecode_path)
{
std::ifstream generated(generated_file);
std::string line;
while (std::getline(generated, line)) {
size_t hash = line.find_first_not_of(" \t");
if (hash == std::string::npos || line[hash] != '#') {
continue;
}
size_t keyword = line.find_first_not_of(" \t", hash + 1);
if (keyword == std::string::npos || line.compare(keyword, 7, "include") != 0) {
continue;
}
size_t open = line.find_first_not_of(" \t", keyword + 7);
if (open == std::string::npos || (line[open] != '<' && line[open] != '"')) {
return false;
}
size_t close = line.find(line[open] == '<' ? '>' : '"', open + 1);
if (close == std::string::npos) {
return false;
}
fs::path header = line.substr(open + 1, close - open - 1);
if (header.empty() || !header.is_relative()) {
return false;
}
for (const fs::path& component : header) {
if (component == "..") {
return false;
}
}
std::error_code error;
if (fs::exists(sourcecode_path / header, error)) {
return false;
}
}
return true;
}
/*
* Validates that a Faust file or archive is sane and returns 0 for success
* or 1 for failure. If the evaluation fails, the appropriate error message
* is set. More info on the con_info structure is in server.hh.
* Create the session directory <sha>/ with the following structure:
* sessions/<sha>/
* sourcecode/
* <filename>.dsp
* ...other content if from zip
* user_code.dsp (a copy of sourcecode/<filename>.dsp)
* generated.cpp (the generated C++ code)
* errors.log (any errors that occurred during compilation)
* svg/ (the resulting svg blockdiagrams)
* targets/ (platform/architecture specific compilation directories)
* <platform>/<architecture>/
* Makefile
* <filename>.dsp (copied from sourcecode/)
* ...other source files
*
* the compilation command is :
* cd sourcecode/
* && cp <filename>.dsp ../user_code.dsp
* && faust <filename>.dsp -o ../generated.cpp -svg 2> ../errors.log";
*
* if no compilation errors where produced then errors.log is empty
* in this case we can move sourcecode/<filename>-svg/ to svg/
* and available :
* <sha>/user_code.dsp
* <sha>/generated.cpp
* <sha>/svg/process.svg
* <sha>/errors.log (empty)
*
* if some compilation errors where produced then errors.log is not empty and are only available :
* <sha>/user_code.dsp
* <sha>/errors.log
*
*/
static int validate_faust(connection_info_struct* con_info)
{
fs::path filename = fs::path(con_info->filename);
fs::path uploaded_file = uploaded_file_path(con_info);
if (gVerbosity >= 1) {
std::cerr << "\nENTER validate_faust for file: " << uploaded_file << std::endl;
}
// Generate SHA1 for session directory
std::string sha1 = generate_sha1(con_info);
fs::path session_path = fs::path(con_info->directory) / fs::path(sha1);
fs::path sourcecode_path = session_path / "sourcecode";
if (gVerbosity >= 1) {
std::cerr << "Session creation for: " << sha1 << std::endl;
}
// Create session structure
if (!fs::is_directory(session_path)) {
try {
fs::create_directories(sourcecode_path);
} catch (const fs::filesystem_error& e) {
std::cerr << "Error: can't create directory " << sourcecode_path << ": "
<< e.code().message() << std::endl;
con_info->answerstring = completebuterrorpage;
return 1;
}
std::string main_dsp_filename;
// Handle file upload: simple DSP file or archive
if (!fs::is_regular_file(uploaded_file)) {
con_info->answerstring = completebuterrorpage;
if (gVerbosity >= 1) {
std::cerr << "EXIT validate_faust: not regular file: " << uploaded_file
<< std::endl;
}
return 1;
}
if (filename.extension() == ".dsp") {
// Simple DSP file: copy to sourcecode/ with original name
main_dsp_filename = filename.filename().string();
fs::copy_file(uploaded_file, sourcecode_path / main_dsp_filename);
if (gVerbosity >= 1) {
std::cerr << "Copied DSP file: " << main_dsp_filename << std::endl;
}
} else {
// Archive: extract to sourcecode/ and find main DSP file
struct archive* archive;
struct archive_entry* entry;
std::vector<std::string> dsp_files;
archive = archive_read_new();
archive_read_support_filter_all(archive);
archive_read_support_format_all(archive);
int status = archive_read_open_filename(archive, uploaded_file.string().c_str(), 10240);
if (status != ARCHIVE_OK) {
con_info->answerstring = completebutdecompressionproblem;
archive_read_free(archive);
return 1;
}
// Extract all files with multiple protections against zip bombs
const size_t MAX_EXTRACTED_SIZE = 5 * 102400; // 500KB limit
const size_t MAX_ENTRIES = 100; // 100 files max
const auto MAX_EXTRACTION_TIME = std::chrono::seconds(5); // 5 seconds max
size_t total_extracted = 0;
size_t entry_count = 0;
auto start_time = std::chrono::steady_clock::now();
bool size_limit_exceeded = false;
bool time_limit_exceeded = false;
bool entries_limit_exceeded = false;
while (archive_read_next_header(archive, &entry) == ARCHIVE_OK) {
// Check time limit
auto current_time = std::chrono::steady_clock::now();
if (current_time - start_time > MAX_EXTRACTION_TIME) {
if (gVerbosity >= 1) {
std::cerr << "Extraction time limit exceeded - stopping after "
<< entry_count << " entries" << std::endl;
}
time_limit_exceeded = true;
break;
}
// Check entries limit
if (++entry_count > MAX_ENTRIES) {
if (gVerbosity >= 1) {
std::cerr << "Too many entries - stopping at " << MAX_ENTRIES << " files"
<< std::endl;
}
entries_limit_exceeded = true;
break;
}
fs::path entry_path = fs::path(archive_entry_pathname(entry));
// SECURITY: An entry must stay inside sourcecode/ and be a plain file or a
// directory: its path is joined to sourcecode/, and a link would redirect the
// entries that follow it
bool inside_sourcecode = entry_path.is_relative();
for (const fs::path& component : entry_path) {
inside_sourcecode = inside_sourcecode && component != "..";
}
const auto entry_type = archive_entry_filetype(entry);
const bool plain_entry =
(entry_type == AE_IFREG || entry_type == AE_IFDIR) &&
archive_entry_hardlink(entry) == nullptr;
if (!inside_sourcecode || !plain_entry) {
if (gVerbosity >= 1) {
std::cerr << "SECURITY: Silently removing unsafe entry from ZIP: "
<< entry_path << std::endl;
}
entry_count--; // Don't count removed files
continue;
}
// SECURITY: Skip files with unsafe names (silent removal)
std::string entry_filename = entry_path.filename().string();
if (!entry_filename.empty() && !isSecureFilename(entry_filename)) {
if (gVerbosity >= 1) {
std::cerr << "SECURITY: Silently removing unsafe file from ZIP: "
<< entry_filename << std::endl;
}
entry_count--; // Don't count removed files
continue;
}
// Skip system files
if (entry_path.string().substr(0, 8) == "__MACOSX") {
if (gVerbosity >= 1) {
std::cerr << "Ignoring: " << entry_path << std::endl;
}
entry_count--; // Don't count ignored files
continue;
}
// Collect DSP files
if (entry_path.extension() == ".dsp") {
dsp_files.push_back(entry_path.filename().string());
if (main_dsp_filename.empty()) {
main_dsp_filename = entry_path.filename().string();
}
}
// Extract to sourcecode/
fs::path dest_path = sourcecode_path / entry_path;
if (entry_type == AE_IFDIR) {
fs::create_directories(dest_path);
continue;
}
fs::create_directories(dest_path.parent_path());
// SECURITY: The size limit counts the bytes really extracted: the size an
// archive declares for an entry can be wrong, or missing for a streamed entry
std::ofstream dest(dest_path, std::ios::binary | std::ios::trunc);
char buffer[8192];
auto count = archive_read_data(archive, buffer, sizeof(buffer));
while (count > 0 &&
total_extracted + static_cast<size_t>(count) <= MAX_EXTRACTED_SIZE) {
dest.write(buffer, count);
total_extracted += static_cast<size_t>(count);
count = archive_read_data(archive, buffer, sizeof(buffer));
}
if (count > 0) {
if (gVerbosity >= 1) {
std::cerr << "Extraction size limit exceeded - stopping at "
<< total_extracted << " bytes" << std::endl;
}
size_limit_exceeded = true;
break;
}
}
archive_read_free(archive);
// Handle time limit exceeded case
if (time_limit_exceeded) {
if (gVerbosity >= 1) {
std::cerr << "Archive extraction timeout - creating toolong.dsp" << std::endl;
}
// Clear sourcecode directory
fs::remove_all(sourcecode_path);
fs::create_directories(sourcecode_path);
// Create toolong.dsp with error message
main_dsp_filename = "toolong.dsp";
fs::path toolong_dsp_path = sourcecode_path / main_dsp_filename;
std::ofstream toolong_file(toolong_dsp_path);
toolong_file << "// archive took too long to decompress\n";
toolong_file << "// maximum allowed: 5 seconds\n";
toolong_file.close();
}
// Handle too many entries case
else if (entries_limit_exceeded) {
if (gVerbosity >= 1) {
std::cerr << "Too many entries - creating toomanyentries.dsp" << std::endl;
}
// Clear sourcecode directory
fs::remove_all(sourcecode_path);
fs::create_directories(sourcecode_path);
// Create toomanyentries.dsp with error message
main_dsp_filename = "toomanyentries.dsp";
fs::path toomanyentries_dsp_path = sourcecode_path / main_dsp_filename;
std::ofstream toomanyentries_file(toomanyentries_dsp_path);
toomanyentries_file << "// too many files in archive\n";
toomanyentries_file << "// maximum allowed: 100 files\n";
toomanyentries_file.close();
}
// Handle size limit exceeded case
else if (size_limit_exceeded) {
if (gVerbosity >= 1) {
std::cerr << "Archive too large - creating toobig.dsp" << std::endl;
}
// Clear sourcecode directory
fs::remove_all(sourcecode_path);
fs::create_directories(sourcecode_path);
// Create toobig.dsp with error message
main_dsp_filename = "toobig.dsp";
fs::path toobig_dsp_path = sourcecode_path / main_dsp_filename;
std::ofstream toobig_file(toobig_dsp_path);
toobig_file << "// archive too large when decompressed\n";
toobig_file << "// maximum allowed: 500KB\n";
toobig_file.close();
}
// Handle multiple DSP files case
else if (dsp_files.size() > 1) {
if (gVerbosity >= 1) {
std::cerr << "Multiple DSP files found (" << dsp_files.size()
<< ") - creating multi.dsp" << std::endl;
}
// Clear sourcecode directory
fs::remove_all(sourcecode_path);
fs::create_directories(sourcecode_path);
// Create multi.dsp with error message
main_dsp_filename = "multi.dsp";
fs::path multi_dsp_path = sourcecode_path / main_dsp_filename;
std::ofstream multi_file(multi_dsp_path);
multi_file << "// more than one DSP file in your archive\n";
multi_file << "// Found files: ";
for (size_t i = 0; i < dsp_files.size(); ++i) {
if (i > 0) {
multi_file << ", ";
}
multi_file << dsp_files[i];
}
multi_file << "\n";
multi_file.close();
}
}
// Verify we found a main DSP file
if (main_dsp_filename.empty()) {
// Create empty.dsp with error message instead of failing
main_dsp_filename = "empty.dsp";
fs::path empty_dsp_path = sourcecode_path / main_dsp_filename;
std::ofstream empty_file(empty_dsp_path);
empty_file << "// no dsp file was provided\n";
empty_file.close();
if (gVerbosity >= 1) {
std::cerr << "No DSP file found - created empty.dsp with error message"
<< std::endl;
}
}
// SINGLE COMPILATION: Copy main DSP file and compile in one step
if (gVerbosity >= 2) {
std::cerr << "SINGLE COMPILATION validate_faust" << std::endl;
}
// First, copy the DSP file (no shell : the name comes from the upload)
std::error_code copy_error;
fs::copy_file(sourcecode_path / main_dsp_filename, session_path / "user_code.dsp",
fs::copy_options::overwrite_existing, copy_error);
if (copy_error) {
if (gVerbosity >= 1) {
std::cerr << "Failed to copy DSP file: " << copy_error.message() << std::endl;
}
con_info->answerstring = completebutnopipe;
return 1;
}
// Extract and process faustoptions
fs::path user_dsp_file = session_path / "user_code.dsp";
std::string raw_options = extractFaustOptions(user_dsp_file);
std::string filtered_options = filterFaustOptions(raw_options);
// Create faustoptions.txt file
fs::path faustoptions_file = session_path / "faustoptions.txt";
std::ofstream options_out(faustoptions_file);
if (options_out.is_open()) {
options_out << filtered_options;
options_out.close();
if (gVerbosity >= 2) {
std::cerr << "Created faustoptions.txt with: '" << filtered_options << "'"
<< std::endl;
}
}
// Now compile using the extracted options
std::vector<std::string> faust_args = splitArguments(readFaustOptions(session_path));
faust_args.insert(faust_args.begin(), "faust");
faust_args.insert(faust_args.end(), {main_dsp_filename, "-o", "../generated.cpp", "-svg"});
if (gVerbosity >= 2) {
std::cerr << "Executing compilation in " << sourcecode_path << ":";
for (const std::string& arg : faust_args) {
std::cerr << " " << arg;
}
std::cerr << std::endl;
}
// Execute Faust compilation
int return_code = runProgram(faust_args, sourcecode_path, "/dev/null",
session_path / "errors.log", kFaustLimits);
if (return_code < 0) {
if (gVerbosity >= 1) {
std::cerr << "Cannot launch faust command" << std::endl;
}
con_info->answerstring = completebutnopipe;
return 1;
}
if (return_code != 0) {
if (gVerbosity >= 1) {
std::cerr << "Faust compilation failed with code " << return_code << std::endl;
}
// Continue processing even with compilation errors - errors.log will contain the
// details Client will check errors.log to determine if there were compilation errors
}
// SECURITY: The session is removed, so that a new upload of the same file is checked
// again and that no target can be made from it
if (!includes_only_system_headers(session_path / "generated.cpp", sourcecode_path)) {
if (gVerbosity >= 1) {
std::cerr << "SECURITY: generated code includes a file of the session" << std::endl;
}
std::error_code error;
fs::remove_all(session_path, error);
con_info->answerstring = completebuterrorpage;
return 1;
}
// Move generated SVG files to dedicated svg/ directory
fs::path svg_path = session_path / "svg";
try {
fs::create_directories(svg_path);
// Look for SVG files in sourcecode/ directory and its subdirectories
for (const auto& entry : fs::recursive_directory_iterator(sourcecode_path)) {
if (entry.is_regular_file() && entry.path().extension() == ".svg") {
fs::path svg_file = svg_path / entry.path().filename();
fs::rename(entry.path(), svg_file);
if (gVerbosity >= 2) {
std::cerr << "Moved SVG: \"" << entry.path().filename().string()
<< "\" to svg/" << std::endl;
}
}
}
// Clean up empty SVG directories in sourcecode/
for (const auto& entry : fs::directory_iterator(sourcecode_path)) {
if (entry.is_directory() &&
entry.path().filename().string().find("-svg") != std::string::npos) {
if (fs::is_empty(entry.path())) {
fs::remove(entry.path());
if (gVerbosity >= 1) {
std::cerr << "Removed empty SVG directory: "
<< entry.path().filename().string() << std::endl;
}
}
}
}
} catch (const fs::filesystem_error& e) {
if (gVerbosity >= 1) {
std::cerr << "Warning: Could not organize SVG files: " << e.code().message()
<< std::endl;
}
}
// Create metadata.json
fs::path metadata_file = session_path / "metadata.json";
try {
std::ofstream metadata(metadata_file);
metadata << "{\n";
metadata << " \"sha1\": \"" << sha1 << "\",\n";
metadata << " \"filename\": \"" << con_info->filename << "\",\n";
metadata << " \"compilation_time\": \"" << std::time(nullptr) << "\",\n";
metadata << " \"enhanced\": true,\n";
metadata << " \"single_compilation\": true,\n";
metadata << " \"structure\": {\n";
metadata << " \"sourcecode/\": \"Original source files\",\n";
metadata << " \"generated.cpp\": \"Generated C++ code\",\n";
metadata << " \"svg/\": \"Block diagram SVG files\",\n";
metadata << " \"metadata.json\": \"This file\"\n";
metadata << " }\n";
metadata << "}\n";
metadata.close();
} catch (const fs::filesystem_error& e) {
if (gVerbosity >= 1) {
std::cerr << "Warning: Could not create metadata file: " << e.code().message()
<< std::endl;
}
}
// Save original filename for drag-and-drop functionality
try {
fs::path filename_path = session_path / "filename.txt";
std::ofstream filename_file(filename_path);
filename_file << con_info->filename << std::endl;
filename_file.close();
if (gVerbosity >= 2) {
std::cerr << "Saved original filename: " << con_info->filename << std::endl;
}
} catch (const fs::filesystem_error& e) {
if (gVerbosity >= 1) {
std::cerr << "Warning: Could not save filename: " << e.code().message()
<< std::endl;
}
}
// Create backward-compatible makefile structure
create_basic_session(sourcecode_path, session_path, fs::path(con_info->makefile_directory));
if (gVerbosity >= 2) {
std::cerr << "Session structure created successfully for: " << sha1 << std::endl;
}
}
con_info->answerstring = sha1;
if (gVerbosity >= 2) {
std::cerr << "EXIT validate_faust OK" << std::endl;
}
return 0;
}
/*
* Makes an initial directory whose name is the SHA-1 key passed in for
* a Faust file or archive, returning 0 for success or 1 for failure.
* If the evaluation fails, the appropriate error message is set.
* More info on the con_info structure is in server.hh.
*/
static fs::path make(const fs::path& dir, const fs::path& target)
{
fs::path p;
if (gVerbosity >= 2) {
std::cerr << "ENTER MAKE -C " << dir << " " << target << std::endl;
}
if (0 == runProgram({"make", "-C", dir.string(), target.string()})) {
p = dir / target;
} else {
if (gVerbosity >= 2) {
std::cerr << __LINE__ << " makefile " << dir / target << " failed !!!" << std::endl;
}
p = "";
}
if (gVerbosity >= 2) {
std::cerr << "EXIT MAKE " << p << std::endl;
}
return p;
}
/*
* Callback that puts GET parameters in a TArgs. The TArgs typedef is defined
* in utilities.hh.
*/
int FaustServer::get_params(void* cls, enum MHD_ValueKind, const char* key, const char* data)
{
TArgs* args = (TArgs*)cls;
args->insert(pair<string, string>(string(key), string(data)));
return MHD_YES;
}
/*
* Function that sends a response to the MHD_Connection after a POST or GET
* is effectuated.
*/
int FaustServer::send_page(struct MHD_Connection* connection, const char* page, int length,
int status_code, const char* type, const char* location)
{
struct MHD_Response* response =
MHD_create_response_from_buffer(length, (void*)page, MHD_RESPMEM_MUST_COPY);
if (response == 0) {
return MHD_NO;
}
// Add security headers
MHD_add_response_header(
response, "Content-Security-Policy",
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; "
"img-src 'self'; frame-ancestors "
"'none'; form-action 'self';");
MHD_add_response_header(response, "X-Frame-Options", "DENY");
MHD_add_response_header(response, "X-Content-Type-Options", "nosniff");
MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, type ? type : "text/plain");
if (location) {
MHD_add_response_header(response, MHD_HTTP_HEADER_LOCATION, location);
MHD_add_response_header(response, MHD_HTTP_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS,
MHD_HTTP_HEADER_LOCATION);
}
if (gAnyOrigin) {
MHD_add_response_header(response, MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, "*");
MHD_add_response_header(response, "Access-Control-Allow-Methods", "GET, POST, OPTIONS");
}
int ret = MHD_queue_response(connection, status_code, response);
MHD_destroy_response(response);
return ret;
}
/*
* Callback called every time a GET or POST request is completed.
* Note that this is NOT necessarily called once the entirety of
* POST data is transfered. If the data is transfered in chunks,
* this is called after every chunk.
*/
void FaustServer::request_completed(void*, struct MHD_Connection*, void** con_cls,
enum MHD_RequestTerminationCode)
{
if (gVerbosity >= 2) {
std::cerr << "FaustServer::request_completed()" << endl;
}
struct connection_info_struct* con_info = (connection_info_struct*)*con_cls;
*con_cls = NULL;
if (con_info != 0) {
if (con_info->connectiontype == POST) {
if (NULL != con_info->postprocessor) {
MHD_destroy_post_processor(con_info->postprocessor);
nr_of_uploading_clients--;
}
if (con_info->fp != 0) {
fclose(con_info->fp);
con_info->fp = 0;
}
// the uploaded file is no longer needed : the session keeps its own copy. Removed
// whatever the outcome (compiled, invalid, refused), so that nothing sent to the
// service stays in the temporary directory
if (!con_info->tmppath.empty()) {
std::error_code error;
fs::remove_all(con_info->tmppath, error);
if (error && gVerbosity >= 1) {
std::cerr << "Cannot remove " << con_info->tmppath << ": " << error.message()
<< std::endl;
}
}
}
delete con_info;
}
}
// Number of clients currently uploading
unsigned int FaustServer::nr_of_uploading_clients = 0;
/*
* Function that handles all get requests, sending back the
* appropriate response.
*
* All the components in the URL represent a file structure
* created when the file was uploaded. The last component of
* the url represents an instruction to the Makefile.
*
* Any GET parameters are set as environmetnal variables before
* calling the makefile.
*/
// Define here the various targets accepted by faustweb makefiles
static bool isValidTarget(const fs::path& target, const char*& mimetype)
{
if (target == "binary.zip") {
mimetype = "application/zip";
return true;
} else if (target == "binary.apk") {
mimetype = "application/vnd.android.package-archive";
return true;
} else if (target == "src.cpp") {
mimetype = "text/x-c";
return true;
} else if (target == "baresrc.cpp") {
mimetype = "text/x-c";
return true;
} else if (target == "svg.zip") {
mimetype = "application/zip";
return true;
} else if (target == "webapp.zip") {
mimetype = "application/zip";
return true;
} else if (target == "mdoc.zip") {
mimetype = "application/zip";
return true;
} else if (target == "installer.sh") {
mimetype = "application/x-shellscript";
return true;
} else if (target == "index.html") {
mimetype = "text/html";
return true;
} else {
// For PWA assets, check file extension
std::string extension = target.extension().string();
if (extension == ".html") {
mimetype = "text/html";
return true;
} else if (extension == ".js") {
mimetype = "application/javascript";
return true;
} else if (extension == ".css") {
mimetype = "text/css";
return true;
} else if (extension == ".json") {
mimetype = "application/json";
return true;
} else if (extension == ".wasm") {
mimetype = "application/wasm";
return true;
} else if (extension == ".png") {
mimetype = "image/png";
return true;
} else if (extension == ".svg") {
mimetype = "image/svg+xml";
return true;
} else if (extension == ".map") {
mimetype = "application/json";
return true;
} else {
return false;
}
}
}
/*
* Function that sends a file in response to a GET
*/
int FaustServer::send_file(struct MHD_Connection* connection, const fs::path& filepath,
const char* mimetype)
{
struct stat sbuf;
int fd;
if (gVerbosity >= 2) {
std::cerr << __LINE__ << " ENTER send_file : " << filepath << endl;
}
if ((-1 == (fd = open(filepath.string().c_str(), O_RDONLY))) || (0 != fstat(fd, &sbuf))) {
std::cerr << __LINE__ << " error accessing file : " << filepath << endl;
return send_page(connection, cannotcompile.c_str(), cannotcompile.size(),
MHD_HTTP_BAD_REQUEST, "text/html");
}
struct MHD_Response* response = MHD_create_response_from_fd(sbuf.st_size, fd);
if (!response) {
std::cerr << __LINE__ << " error can't create response : " << filepath << endl;
return MHD_NO;
}
MHD_add_response_header(response, "Content-Type", mimetype);
MHD_add_response_header(response, "Content-Location", filepath.filename().string().c_str());
int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
if (gVerbosity >= 2) {
if (ret == MHD_YES) {
std::cerr << __LINE__ << " MHD_queue_response() return MHD_YES " << endl;
} else {
std::cerr << __LINE__ << " MHD_queue_response() return NOT MHD_YES but " << ret << endl;
}
}
MHD_destroy_response(response);
if (gVerbosity >= 2) {
std::cerr << __LINE__ << " EXIT send_file : " << filepath << endl;
}
return ret;
}
// Start the Faust server - shallow wrapper around MHD_start_daemon
static void panicCallback(void*, const char* file, unsigned int line, const char* reason)
{
cerr << "PANIC " << line << ':' << file << ' ' << reason << endl;
}
// Removes the upload directories (tmp_*) a previous run left in the temporary directory, after a
// crash or a kill : a running server removes its own at the end of each request.
static void removeStaleUploads()
{
std::error_code error;
for (const auto& entry : fs::directory_iterator(fs::temp_directory_path(), error)) {
const std::string name = entry.path().filename().string();
// the name iterate_post gives them : tmp_<5 digits>_<5 digits>
bool upload = name.size() == 15 && name.rfind("tmp_", 0) == 0 && name[9] == '_';
for (size_t i = 4; upload && i < name.size(); i++) {
upload = (i == 9) || std::isdigit(static_cast<unsigned char>(name[i]));
}
if (upload && entry.is_directory(error)) {
fs::remove_all(entry.path(), error);
}
}
}
bool FaustServer::start()
{
removeStaleUploads();
MHD_set_panic_func(&panicCallback, NULL);
fDaemon =
MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, fPort, NULL, NULL,
(MHD_AccessHandlerCallback)&staticAnswerToConnection, this,
MHD_OPTION_NOTIFY_COMPLETED, request_completed, NULL, MHD_OPTION_END);
return fDaemon != NULL;
}
// Stop the Faust server - shallow wrapper around MHD_stop_daemon
void FaustServer::stop()
{
if (fDaemon) {
MHD_stop_daemon(fDaemon);
}
fDaemon = 0;
}
/*
* Static Callback called every time a GET or POST request is received.
* by the server.
*/
int FaustServer::staticAnswerToConnection(void* cls, struct MHD_Connection* connection,
const char* rawurl, const char* method,
const char* version, const char* upload_data,
size_t* upload_data_size, void** con_cls)
{
if (gVerbosity >= 1) {
std::cerr << "\n==> ANSWER CONNECTION (" << rawurl << ", " << method << ", " << version
<< ")" << std::endl;
}
std::string URL = simplifyURL(rawurl);
FaustServer* server = (FaustServer*)cls;
if (server == 0) {
std::cerr << "ERROR: REAL BAD ERROR, NO SERVER !!!" << std::endl;
exit(1);
}
try {
if (0 == strcmp(method, "GET")) {
return server->dispatchGETConnections(connection, URL);
} else if (0 == strcmp(method, "POST")) {
if (gVerbosity >= 2) {
struct connection_info_struct* con_info = (connection_info_struct*)*con_cls;
if (con_info) {
std::cerr << "Content of con_cls:" << std::endl;
std::cerr << " Directory: " << '"' << con_info->directory << '"' << std::endl;
std::cerr << " Makefile Directory: " << '"' << con_info->makefile_directory
<< '"' << std::endl;
std::cerr << " Filename: " << '"' << con_info->filename << '"' << std::endl;
std::cerr << " TmpPath: " << '"' << con_info->tmppath << '"' << std::endl;
// Add more fields as needed
} else {
std::cerr << "con_cls is NULL" << std::endl;
}
}
return server->dispatchPOSTConnections(connection, URL, upload_data, upload_data_size,
con_cls);
} else {
return send_page(connection, errorpage.c_str(), errorpage.size(), MHD_HTTP_BAD_REQUEST,
"text/html");
}
} catch (exception const& e) {
std::cerr << "ERROR: GLOBAL ERROR CATCHED " << e.what() << std::endl;
return send_page(connection, errorpage.c_str(), errorpage.size(), MHD_HTTP_BAD_REQUEST,
"text/html");
}
}
//
// Get the /precompile downloadable artifact name from the makefile
//
// The first line of the makefile is interrogated - if it is of the form