-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrtjscomp.js
executable file
·1979 lines (1880 loc) · 48.6 KB
/
rtjscomp.js
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
#!/usr/bin/env node
/**
@preserve RTJSCOMP by L3P3, 2017-2025
*/
"use strict";
(async () => {
// node libs
const fs = require('fs');
const fsp = require('fs/promises');
const http = require('http');
const url = require('url');
const zlib = require('zlib');
// constants
const COMPRESS_METHOD_NONE = 0;
const COMPRESS_METHOD_GZIP = 1;
const COMPRESS_METHOD_BROTLI = 2;
const COMPRESS_METHOD_ZSTD = 3;
const GZIP_OPTIONS = {level: 9};
const HAS_BROTLI = zlib.createBrotliCompress != null;
const HAS_ZSTD = zlib.createZstdCompress != null;
const HTTP_LIST_REG = /,\s*/;
const IMPORT_REG = /\bimport\(/g;
const IS_BUN = typeof Bun !== 'undefined';
const LINENUMBER_REG = /:([0-9]+)[\):]/;
const PATH_CONFIG = 'config/';
const PATH_DATA = 'data/';
const PATH_PUBLIC = 'public/';
const PLUS_REG = /\+/g;
const RESOLVE_OPTIONS = {paths: [require('path').resolve()]};
const SERVICE_REQUIRE_REG = /\bservice_require\(([^)]*)\)/g;
const SERVICE_STATUS_PENDING = 0; // just added to list
const SERVICE_STATUS_WAITING = 1; // waiting for deps
const SERVICE_STATUS_STARTING = 2; // running startup
const SERVICE_STATUS_ACTIVE = 3; // ready for use
const SERVICE_STATUS_STOPPING = 4; // running stop fn
const SERVICE_STATUS_FAILED = 5; // waiting for fix
const VERSION = require('./package.json').version;
const WATCH_OPTIONS = {persistent: true, interval: 1000};
const ZSTD_c_compressionLevel = 100;
const ZSTD_OPTIONS = {
params: {
[ZSTD_c_compressionLevel]: 3,
}
}
// config
const log_verbose_flag = process.argv.includes('-v');
let log_verbose = log_verbose_flag;
let port_http = 0;
let port_https = 0;
let upload_limit = 0;
let compression_enabled = true;
let exiting = false;
/// any path -> file
const path_aliases = new Map([
['', 'index.html'],
]);
const path_aliases_reverse = new Map([
['index.html', '/'],
]);
const path_aliases_templates = new Map;
/// files where requests should be totally ignored
const path_ghosts = new Set;
/// hidden files
const path_hiddens = new Set;
/// forced static files
const path_statics = new Set;
const type_dynamics = new Set([
'events',
'html',
'json',
'txt',
]);
const type_mimes = new Map([
['apk', 'application/zip'],
['bpg', 'image/bpg'],
['css', 'text/css; charset=utf-8'],
['events', 'text/event-stream'],
['flac', 'audio/flac'],
['gz', 'application/gzip'],
['hta', 'application/hta'],
['html', 'text/html; charset=utf-8'],
['ico', 'image/x-icon'],
['jpg', 'image/jpeg'],
['js', 'text/javascript; charset=utf-8'],
['json', 'application/json; charset=utf-8'],
['mid', 'audio/midi'],
['mp3', 'audio/mpeg3'],
['pdf', 'application/pdf'],
['png', 'image/png'],
['rss', 'application/rss+xml; charset=utf-8'],
['txt', 'text/plain; charset=utf-8'],
['xml', 'application/xml; charset=utf-8'],
['xz', 'application/x-xz'],
['zip', 'application/zip'],
]);
const type_raws = new Set([
'apk',
'bpg',
'flac',
'gz',
'jpg',
'mp3',
'pdf',
'png',
'xz',
'zip',
]);
/// compiled file handlers
const file_cache_functions = new Map;
const actions = {};
const rtjscomp = global.rtjscomp = {
actions,
version: VERSION,
};
// polyfills
if (!Object.fromEntries) {
Object.fromEntries = entries => {
const object = {};
for (const entry of entries) object[entry[0]] = entry[1];
return object;
}
}
// workaround for bun: https://github.com/oven-sh/bun/issues/18919
let fs_watch = fs.watch;
if (IS_BUN) {
const fs_watch_original = fs_watch;
const watch_callbacks = new Map;
fs_watch = (path, options, callback) => {
if (!watch_callbacks.has(path)) {
fs_watch_original(path, options, () => {
const callback = watch_callbacks.get(path);
if (callback) {
callback();
}
});
}
watch_callbacks.set(path, callback);
return {
close: () => (
watch_callbacks.set(path, null)
),
};
}
}
// legacy, will be removed soon!
global.globals = rtjscomp;
global.actions = rtjscomp.actions;
global.data_load = name => {
log('[deprecated] synchronous load file: ' + PATH_DATA + name);
try {
return fs.readFileSync(PATH_DATA + name, 'utf8');
}
catch (err) {
return null;
}
}
global.data_save = (name, data) => (
log('[deprecated] synchronous save file: ' + PATH_DATA + name),
fs.writeFileSync(PATH_DATA + name, data, 'utf8')
)
global.number_check_int = number => (
Math.floor(number) === number
)
global.number_check_uint = number => (
number >= 0 && number_check_int(number)
)
rtjscomp.data_load = async name => {
if (log_verbose) log('load file: ' + PATH_DATA + name);
const data = await fsp.readFile(PATH_DATA + name, 'utf8').catch(() => null);
return (
name.endsWith('.json')
? JSON.parse(data || null)
: data
);
}
rtjscomp.data_load_watch = (name, callback) => (
file_keep_new(PATH_DATA + name, data => (
callback(
name.endsWith('.json')
? JSON.parse(data || null)
: data
)
))
)
rtjscomp.data_save = (name, data) => (
log_verbose && log('save file: ' + PATH_DATA + name),
fsp.writeFile(
PATH_DATA + name,
(
name.endsWith('.json')
? JSON.stringify(data)
: data
),
'utf8'
)
)
/**
hack to guess the line number of an error
*/
const linenumber_try = err => {
try {
return `:${
err.stack
.split('\n', 2)[1]
.split(',').pop()
.match(LINENUMBER_REG)[1]
- 2
}`;
}
catch (_) {
return '';
}
};
const custom_require_paths = new Set;
const custom_require_cache = new Map;
const custom_import_cache = new Map;
const custom_require = path => {
let result = custom_require_cache.get(path);
if (result != null) return result;
log_verbose && log('require module: ' + path);
const path_real = require.resolve(path, RESOLVE_OPTIONS);
custom_require_paths.add(path_real);
custom_require_cache.set(
path,
result = require(path_real)
);
return result;
}
const custom_import = async path => {
let result = custom_import_cache.get(path);
if (result != null) return result;
log_verbose && log('import module: ' + path);
custom_import_cache.set(
path,
result = await import(
'file://' + require.resolve(path, RESOLVE_OPTIONS)
)
);
return result;
}
actions.module_cache_clear = () => {
for (const path of custom_require_paths) {
delete require.cache[path];
}
custom_require_cache.clear();
custom_import_cache.clear();
}
const AsyncFunction = custom_import.constructor;
const services = new Map;
let services_loaded_promise = null;
let services_loaded_promise_resolve = null;
/**
stop/start services according to list
*/
const services_list_react = async list => {
// stop all services not in list
await Promise.all(
[...services.values()]
.filter(service_object => (
service_object.status < SERVICE_STATUS_STOPPING &&
!list.includes(service_object.path)
))
// so they will not be restarted
.map(service_object => (
service_object.dependencies = null,
service_object
))
.map(service_stop)
);
// start all services in list
const start_queue = [];
for (const path of list) {
let service_object = services.get(path);
if (service_object == null) {
services.set(path, service_object = {
content: null,
dependencies: null,
dependencies_paths: null,
file_function: null,
handler_stop: null,
path,
promise_deps: null,
promise_deps_resolve: null,
promise_stopped: null,
promise_stopped_resolve: null,
status: SERVICE_STATUS_PENDING,
watcher: null,
});
}
else if (service_object.status < SERVICE_STATUS_STOPPING) continue;
start_queue.push(service_object);
}
await Promise.all(
start_queue.map(service_start)
);
}
const services_shutdown = () => (
Promise.all(
[...services.values()]
// so they will not be restarted
.map(service_object => (
service_object.dependencies = null,
service_object
))
.map(service_stop)
)
)
/**
(re)start service
*/
const service_start = async service_object => {
if (!services_loaded_promise) {
services_loaded_promise = new Promise(resolve => {
services_loaded_promise_resolve = resolve;
});
}
const {path} = service_object;
if (log_verbose) log(path + ': prepare for (re)start');
let start_interval = 0;
try {
// if service is running, stop it
if (
service_object.status === SERVICE_STATUS_WAITING ||
service_object.status === SERVICE_STATUS_STARTING
) {
if (log_verbose) log(path + ': abort previous start');
service_object.status = SERVICE_STATUS_PENDING;
if (service_object.promise_deps_resolve) {
service_object.promise_deps_resolve();
}
}
else if (service_object.status === SERVICE_STATUS_ACTIVE) {
service_object.status = SERVICE_STATUS_PENDING;
// restart all depending services
for (const other of services.values())
if (
(
other.status === SERVICE_STATUS_STARTING ||
other.status === SERVICE_STATUS_ACTIVE
) &&
other.dependencies &&
other.dependencies.includes(service_object)
) {
other.dependencies = null;
service_start(other);
}
service_stop_inner(service_object);
}
await service_object.promise_stopped;
// service is not running, now start it
if (service_object.status > SERVICE_STATUS_ACTIVE) {
service_object.status = SERVICE_STATUS_PENDING;
}
service_object.promise_stopped = new Promise(resolve => {
service_object.promise_stopped_resolve = resolve;
});
if (!service_object.file_function) {
const path_real = PATH_PUBLIC + path + '.service.js';
const file_content = await fsp.readFile(path_real, 'utf8');
if (service_object.status !== SERVICE_STATUS_PENDING) return;
if (!service_object.watcher) {
let timeout = 0;
service_object.watcher = fs_watch(path_real, WATCH_OPTIONS, () => (
clearTimeout(timeout),
timeout = setTimeout(() => (
log_verbose && log('file updated: ' + path),
service_object.file_function = null,
service_start(service_object)
), 50)
));
}
if (file_content.includes('globals.')) {
log(`[deprecated] ${path}: uses globals object`);
}
service_object.dependencies_paths = [];
for (let [, dep] of file_content.matchAll(SERVICE_REQUIRE_REG)) {
const first_char = dep.charCodeAt(0);
const last_char = dep.charCodeAt(dep.length - 1);
if (
dep.length <3 ||
(first_char !== 34 || last_char !== 34) && // "
(first_char !== 39 || last_char !== 39) // '
) {
throw new Error('service_require() needs inline string');
}
if (
!service_object.dependencies_paths.includes(
dep = dep.slice(1, -1)
)
) {
service_object.dependencies_paths.push(dep);
}
}
service_object.file_function = new AsyncFunction(
'require',
'custom_import',
'service_require',
'service_require_try',
`const log=a=>rtjscomp.log(${
JSON.stringify(path + ': ')
}+a);${
file_content
.replace(IMPORT_REG, 'custom_import(')
}`
);
}
service_object.dependencies = [];
let waiting_needed = false;
for (const dep_path of service_object.dependencies_paths) {
const dep = services.get(dep_path);
if (dep == null) {
throw new Error('unknown required service: ' + dep_path);
}
service_object.dependencies.push(dep);
waiting_needed = (
waiting_needed ||
dep.status !== SERVICE_STATUS_ACTIVE
);
}
if (waiting_needed) {
if (log_verbose) log(path + ': wait for dependencies');
service_object.status = SERVICE_STATUS_WAITING;
service_object.promise_deps = new Promise(resolve => {
service_object.promise_deps_resolve = resolve;
});
await service_object.promise_deps;
if (service_object.status !== SERVICE_STATUS_WAITING) return;
}
log('start service: ' + path);
service_object.status = SERVICE_STATUS_STARTING;
start_interval = setInterval(() => {
log(`[warning] ${path}: still starting`);
}, 5e3);
const content_object = service_object.content = {};
const result = await service_object.file_function.call(
content_object,
custom_require,
custom_import,
service_require,
service_require_try,
);
if (service_object.status !== SERVICE_STATUS_STARTING) return;
if (typeof result === 'function') {
service_object.handler_stop = result;
}
const handler_start = content_object.start;
if (handler_start) {
log(`[deprecated] ${path}: has start method`);
delete content_object.start;
await handler_start();
if (service_object.status !== SERVICE_STATUS_STARTING) return;
}
if (content_object.stop) {
log(`[deprecated] ${path}: has stop method`);
service_object.handler_stop = content_object.stop;
delete content_object.stop;
}
if (log_verbose) log('started service: ' + path);
service_object.status = SERVICE_STATUS_ACTIVE;
}
catch (err) {
if (!(err instanceof Error)) {
err = new Error(err + '?! wtf');
}
log(`[error] ${
path
}${
linenumber_try(err)
}: ${
err.message
}`);
service_object.status = SERVICE_STATUS_FAILED;
service_object.dependencies = null;
return;
}
finally {
clearInterval(start_interval);
service_object.promise_deps =
service_object.promise_deps_resolve = null;
if (service_object.status !== SERVICE_STATUS_ACTIVE) {
service_object.promise_stopped_resolve();
services_loaded_promise_try();
}
}
// restart waiting services
other: for (const other of services.values())
if (other.status === SERVICE_STATUS_WAITING) {
for (const dep of other.dependencies)
if (dep.status !== SERVICE_STATUS_ACTIVE) {
continue other;
}
other.promise_deps_resolve();
}
services_loaded_promise_try();
}
/**
check if any loading services are left
*/
const services_loaded_promise_try = () => {
if (!services_loaded_promise) return;
for (const service_object of services.values())
if (
service_object.status < SERVICE_STATUS_ACTIVE
) return;
services_loaded_promise_resolve();
services_loaded_promise =
services_loaded_promise_resolve = null;
}
/**
stop and forget service
*/
const service_stop = async service_object => {
log('stop service: ' + service_object.path);
service_object.status = SERVICE_STATUS_STOPPING;
service_object.file_function = null;
if (service_object.watcher) {
service_object.watcher.close();
}
for (const other of services.values())
if (
other.dependencies &&
other.dependencies.includes(service_object)
) {
other.dependencies = null;
if (other.status !== SERVICE_STATUS_STOPPING) {
service_start(other);
}
}
if (service_object.promise_deps_resolve) {
service_object.promise_deps_resolve();
}
else {
await service_stop_inner(service_object);
}
services.delete(service_object.path);
if (log_verbose) log('stopped service: ' + service_object.path);
}
/**
stop service so it can be forgot or restarted
*/
const service_stop_inner = async service_object => {
const {
handler_stop,
path,
} = service_object;
if (handler_stop) {
service_object.handler_stop = null;
const stop_interval = setInterval(() => {
log(`[warning] ${path}: still stopping`);
}, 1e3);
try {
await handler_stop();
}
catch (err) {
log(`[error] ${
path
}${
linenumber_try(err)
} stop handler: ${
err.message
}`);
service_object.status = SERVICE_STATUS_FAILED;
}
clearInterval(stop_interval);
}
service_object.promise_stopped_resolve();
}
const service_require = path => {
const service_object = services.get(path);
if (
service_object != null &&
service_object.status === SERVICE_STATUS_ACTIVE
) return service_object.content;
throw new Error('service required: ' + path);
}
const service_require_try = path => {
const service_object = services.get(path);
return (
service_object != null &&
service_object.status === SERVICE_STATUS_ACTIVE
? service_object.content
: null
);
}
const file_watch_once = (path, callback) => {
const watcher = fs_watch(path, WATCH_OPTIONS, () => (
watcher.close(),
log_verbose && log('file updated: ' + path),
callback()
));
};
const file_keep_new = async (path, callback) => {
try {
const data = await fsp.readFile(path, 'utf8');
if (log_verbose) log('load file: ' + path);
await callback(data);
}
catch (err) {
await callback(null);
return null;
}
let timeout = 0;
return fs_watch(path, WATCH_OPTIONS, () => (
clearTimeout(timeout),
timeout = setTimeout(() => exiting || (
log_verbose && log('file updated: ' + path),
fsp.readFile(path, 'utf8')
.catch(() => null)
.then(callback)
), 50)
));
}
const get_prop_bool = (obj, prop, fallback) => {
if (
obj === null ||
!(prop in obj)
) return fallback;
const value = obj[prop];
if (typeof value !== 'boolean') {
throw prop + ' must be boolean';
}
delete obj[prop];
return value;
}
const get_prop_uint = (obj, prop, fallback) => {
if (
obj === null ||
!(prop in obj)
) return fallback;
const value = obj[prop];
if (
typeof value !== 'number' ||
value < 0 ||
value % 1 > 0
) {
throw prop + ' must be positive integer';
}
delete obj[prop];
return value;
}
const get_prop_list = (obj, prop) => {
if (
obj === null ||
!(prop in obj)
) return null;
const value = obj[prop];
if (
typeof value !== 'object' ||
!value ||
value.length == null ||
value.some(item => typeof item !== 'string')
) {
throw prop + ' must be array of strings';
}
delete obj[prop];
return value;
}
const get_prop_map = (obj, prop) => {
if (
obj === null ||
!(prop in obj)
) return null;
let value = obj[prop];
if (
typeof value !== 'object' ||
!value ||
(
value = Object.entries(value)
).some(([_, item]) => typeof item !== 'string')
) {
throw prop + ' must be object of strings';
}
delete obj[prop];
return value;
}
const parse_old_list = data => (
data
.split('\n')
.filter(entry =>
entry.length > 0 &&
entry.charCodeAt(0) !== 35
)
)
const parse_old_map = data => (
Object.fromEntries(
data
.split('\n')
.filter(entry =>
entry.length > 0 &&
entry.charCodeAt(0) !== 35
)
.map(entry => entry.split(':', 2))
)
)
const config_path_check = (path, allow_empty = false) => {
if (!allow_empty && !path) {
throw 'path is empty';
}
if (path.charCodeAt(0) === 47) {
throw 'path must not start with /';
}
if (path.charCodeAt(path.length - 1) === 47) {
throw 'path must not end with /';
}
if (path.includes('..')) {
throw 'path must not contain ..';
}
if (path.includes('~')) {
throw 'path must not contain ~';
}
if (path.includes('//')) {
throw 'path must not contain //';
}
}
let log_history = rtjscomp.log_history = [];
actions.log_clear = () => {
log_history = rtjscomp.log_history = [];
}
const log = rtjscomp.log = msg => (
console.log(msg),
log_history.push(msg),
spam_enabled ? spam('log', [msg]) : undefined
)
const spam_enabled = fs.existsSync('spam.csv');
rtjscomp.spam_history = '';
actions.spam_save = async (muted = false) => {
if (!spam_enabled) return;
try {
const tmp = rtjscomp.spam_history;
rtjscomp.spam_history = '';
await fsp.appendFile('spam.csv', tmp, 'utf8');
if (log_verbose && !muted) log('spam.csv saved');
}
catch (err) {
log('[error] cannot save spam.csv: ' + err.message);
}
}
const spam = (type, data) => {
rtjscomp.spam_history += (
Date.now() +
',' +
type +
',' +
JSON.stringify(data) +
'\n'
);
if (rtjscomp.spam_history.length >= 1e5) {
actions.spam_save();
}
}
const multipart_parse = (body_raw, boundary, result) => {
boundary = Buffer.from(boundary);
if (boundary[0] === 34) {
boundary = boundary.subarray(1, -1);
}
const boundary_length = boundary.length;
/// -- + boundary + \r\n
const boundary_length_full = boundary_length + 4;
/// last possible index for full boundary
const boundary_index_limit = body_raw.length - boundary_length_full;
let index_start = 0;
let index_end = 0;
while (
// find next boundary
(
index_end = body_raw.indexOf(45, index_end) // -
) >= 0 &&
index_end <= boundary_index_limit
) {
// check if it actually is a boundary
if (
body_raw[index_end + 1] !== 45 || // -
index_end > 0 && body_raw[index_end - 2] !== 13 || // \r
index_end > 0 && body_raw[index_end - 1] !== 10 || // \n
body_raw.compare(
boundary,
0,
boundary_length,
index_end + 2,
index_end + 2 + boundary_length
) !== 0
) {
++index_end;
continue;
}
// skip first boundary
if (index_start > 0) {
if (index_end - index_start < 20) {
throw 'part too short';
}
// find end of header
let index_header_end = index_start;
while (
(
index_header_end = body_raw.indexOf(13, index_header_end) // \r
) >= 0 &&
body_raw[index_header_end + 1] !== 10 || // \n
body_raw[index_header_end + 2] !== 13 || // \r
body_raw[index_header_end + 3] !== 10 // \n
) {
++index_header_end;
}
if (index_header_end < 0) {
throw 'part header end not found';
}
// parse header
let header_disposition = '';
let header_content_type = '';
for (
const header_line of
body_raw
.toString(
'utf8',
index_start,
index_header_end
)
.split('\r\n', 2)
) {
if (!header_line.startsWith('Content-')) {
throw 'illegal part header';
}
const [name, value] = header_line.slice(8).split(': ', 2);
if (name === 'Disposition') {
if (!value.startsWith('form-data; ')) {
throw 'illegal disposition part header';
}
header_disposition = value.slice(11);
}
else if (name === 'Type') {
header_content_type = value;
}
// else if (name === 'Transfer-Encoding') {}
else {
throw 'illegal part header';
}
}
if (!header_disposition) {
throw 'part disposition header missing';
}
let header_disposition_name = '';
let header_disposition_filename = '';
for (const header_disposition_entry of header_disposition.split('; ')) {
let [name, value] = header_disposition_entry.split('=', 2);
if (value.charCodeAt(0) === 34) {
value = value.slice(1, -1);
}
if (name === 'name') {
header_disposition_name = value;
}
else if (name === 'filename') {
header_disposition_filename = value;
}
else {
throw 'illegal disposition part header';
}
}
if (!header_disposition_name) {
throw 'part name header missing';
}
const part_result = (
header_content_type
? {
filename: header_disposition_filename,
data: body_raw.subarray(
index_header_end + 4,
index_end - 2
),
type: header_content_type,
}
: (
body_raw
.toString(
'utf8',
index_header_end + 4,
index_end - 2
)
)
);
if (header_disposition_name.endsWith('[]')) {
header_disposition_name = header_disposition_name.slice(0, -2);
if (header_disposition_name in result) {
if (!(result[header_disposition_name] instanceof Array)) {
throw 'duplicate part name';
}
result[header_disposition_name].push(part_result);
}
else {
result[header_disposition_name] = [part_result];
}
}
else {
if (header_disposition_name in result) {
throw 'duplicate part name';
}
result[header_disposition_name] = part_result;
}
}
index_start = index_end + boundary_length_full;
index_end = index_start + 1;
}
}
const querystring_parse = (querystring, result) => {
for (const entry of querystring.split('&')) {
let [key, value] = entry.split('=', 2);
const array = key.endsWith('[]');
if (array) {
key = key.slice(0, -2);
}
if (!key) {
throw 'key is empty';
}
value = decodeURIComponent(
(value || '').replace(PLUS_REG, ' ')
);
if (key in result) {
if ((result[key] instanceof Array) !== array) {
throw 'type mismatch';
}
if (array) {
result[key].push(value);
}
else {
result[key] = value;
}
}
else {
result[key] = array ? [value] : value;
}
}
}
const request_handle = async (request, response, https) => {
const request_method = request.method;
const request_headers = request.headers;
const request_ip = request_headers['x-forwarded-for'] || request.socket.remoteAddress;
const request_method_head = request_method === 'HEAD';
if ('x-forwarded-proto' in request_headers) {
https = request_headers['x-forwarded-proto'] === 'https';
}
if (spam_enabled) spam('request', [https, request.url, request_ip]);
try {
const request_url_parsed = url.parse(request.url, false);
let path = request_url_parsed.pathname || '/';
if (
path.charCodeAt(0) !== 47 ||
path.includes('//')
) throw 404;
if (path.length > 1 && path.endsWith('/')) {
path = path.slice(0, -1);
// is file with extension?
if (path.lastIndexOf('/') < path.lastIndexOf('.')) {
response.setHeader('Location', path);
throw 301;
}
}
path = path.slice(1);
// ignore (timeout) many hack attempts
if (
path.includes('php') ||
path.includes('sql') ||
path.includes('.git/') ||