-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.rs
More file actions
1779 lines (1714 loc) · 81.2 KB
/
http.rs
File metadata and controls
1779 lines (1714 loc) · 81.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
#[cfg(feature = "gzip")]
extern crate libdeflater;
extern crate rslash;
extern crate simcli;
extern crate simjson;
extern crate simtpool;
extern crate simweb;
#[cfg(feature = "gzip")]
use libdeflater::{CompressionLvl, Compressor};
use simcli::{CLI, OptTyp, OptVal};
use simjson::JsonData::{self, Arr, Bool, Data, Num, Text};
use simtpool::ThreadPool;
use simweb::{http_format_time, parse_http_timestamp};
use std::{
cmp,
collections::HashMap,
convert::TryInto,
env,
error::Error as GenError,
fs::{self, File},
io::{self, BufReader, Error, ErrorKind, prelude::*},
net::{Shutdown, TcpListener, TcpStream, ToSocketAddrs},
path::PathBuf,
process::{Command, Stdio},
sync::{
Arc, LazyLock, Mutex, OnceLock,
atomic::{AtomicBool, Ordering},
mpsc,
},
thread,
time::{Duration, SystemTime, UNIX_EPOCH},
};
mod log;
use log::{Level, LogFile};
mod sha1;
#[derive(Debug)]
struct Mapping {
web_path: String,
path: String,
cgi: bool,
wrapper: Option<String>,
ext: Option<String>,
no_headers: bool,
websocket: bool,
options: Option<Vec<(String, String)>>, // "Map" doesnt't give benefits over duplication keys
}
enum BufType<T> {
BufReader((BufReader<T>, u64)),
Buf(Vec<u8>),
None,
}
macro_rules! debug {
($($rest:tt)*) => {
if !NO_TERMINAL.get().unwrap() {
std::eprintln!($($rest)*)
}
}
}
const VERSION: &str = env!("VERSION");
static ERR404: &str = include_str! {"404.html"};
static LOGGER: LazyLock<Mutex<log::SimLogger>> =
LazyLock::new(|| Mutex::new(log::SimLogger::new(log::Level::All, io::stdout())));
static MIME: OnceLock<HashMap<String, String>> = OnceLock::new();
static MAPPING: OnceLock<Vec<Mapping>> = OnceLock::new();
static NO_TERMINAL: OnceLock<bool> = OnceLock::new();
static KEEPALIVE: OnceLock<(u16, u16)> = OnceLock::new();
static PING_INTERVAL: OnceLock<u64> = OnceLock::new();
static SIZING_CONSTRAINS: OnceLock<(u64, u64, usize)> = OnceLock::new();
const MAX_LINE_LEN: usize = 64 * 1024;
const DUMMY_CHUNK_LEN: usize = 128 * 1024;
#[cfg(feature = "gzip")]
const GZIP_LOW_BOUNDARY_THRESHOLD: u64 = 256;
const PARSE_NUM_ERR: u16 = 501;
const TYPE_HTML: &str = "text/html";
const TYPE_PLAIN: &str = "text/plain";
fn init_mime(mime: HashMap<String, String>) {
MIME.set(mime).unwrap();
}
fn init_mapping(mapping: Vec<Mapping>) {
MAPPING.set(mapping).unwrap()
}
fn init_terminal(no_terminal: bool) {
NO_TERMINAL.set(no_terminal).unwrap()
}
fn init_keepalive(keepalive_constraints: (u16, u16)) {
KEEPALIVE.set(keepalive_constraints).unwrap()
}
fn init_ping_interval(interval_mins: u64) {
PING_INTERVAL.set(interval_mins).unwrap()
}
fn init_sizing_constrains(mut req_kilo: u64, mut resp_kilo: u64, chunk_kilo: usize) {
if chunk_kilo > 0 {
if req_kilo > 0 && chunk_kilo as u64 > req_kilo {
req_kilo = chunk_kilo as _
}
if resp_kilo > 0 && chunk_kilo as u64 > resp_kilo {
resp_kilo = chunk_kilo as _
}
}
SIZING_CONSTRAINS
.set((req_kilo, resp_kilo, chunk_kilo))
.unwrap()
}
fn main() -> Result<(), Box<dyn GenError>> {
let mut cli = CLI::new();
cli.opt("v", OptTyp::None)?.description("get the version");
if cli.get_opt("v") == Some(&OptVal::Empty) {
return Ok(println!("SimpleHTTP - version {VERSION}"));
}
if cli.get_errors().is_some()
|| (cli.args().len() == 1 && !cli.args()[0].is_empty())
|| cli.args().len() > 1
{
return Err("No any command line arguments accepted currently".into());
}
let Ok(env) = fs::read_to_string("env.conf")
.inspect_err(|e| eprintln!("Can't read 'env.conf' because: {e:?}"))
else {
return Err("Check 'env.conf' file in the current directory".into());
};
let env = match simjson::parse(&env) {
Data(env) => env,
err => {
return Err(
format!("Corrupted 'env.conf' ({err:?}) file in the current directory").into(),
);
}
};
let Some(Text(bind)) = env.get("bind") else {
return Err("No bound addr is specified".into());
};
let Some(Num(port)) = env.get("port") else {
return Err("No port number is properly configured".into());
};
if let Some(Data(log)) = env.get("log") {
if let Some(Data(out)) = log.get("out") {
if let Some(Text(path)) = out.get("path") {
let name = if let Some(Text(val)) = out.get("name") {
val
} else {
"simhttp-${0}" // positioned variables as time(0), bind_addr(1), and port(2) are supported
};
LOGGER
.lock()
.unwrap()
.set_output(LogFile::from(path, &name, bind, port))
} else {
LOGGER.lock().unwrap().set_output(LogFile::new());
}
}
if let Some(Num(level)) = log.get("level")
&& (0..=5).contains(&(*level as u32))
{
if let Ok(mut logger) = LOGGER.lock() {
let level = Level::from(*level as u32);
logger.info(&format! {"log level set to {:?}", &level});
logger.set_level(level);
}
} else if let Some(Text(val)) = log.get("type") {
let mut level = 0u32;
if val.contains("access") {
level = 2
} else if val.contains("error") {
level = 3
} else if val.contains("debug") {
level = 1
} else if val.contains("critical") {
level = 4
}
let level = Level::from(level);
if let Ok(mut logger) = LOGGER.lock() {
logger.set_level(level);
logger.info(&format! {"log level set to {:?}", val});
}
}
}
let no_terminal = if let Some(Bool(val)) = env.get("no terminal") {
val.to_owned()
} else {
false
};
init_terminal(no_terminal);
// TODO if a terminal is there, then can do debug printout on it bypassing log
let Some(Num(tp)) = env.get("threads") else {
return Err("No number of threads configured".into());
};
let Some(Arr(mapping)) = env.get("mapping") else {
return Err("No mapping properly configured".into());
};
let mut mime2 = HashMap::new();
if let Some(Arr(mime)) = env.get("mime") {
for el in mime {
if let Data(el) = el
&& let Some(Text(en)) = el.get("ext")
&& let Some(Text(typ)) = el.get("type")
{
mime2.insert(en.to_string(), typ.to_string());
}
}
};
init_mime(mime2);
init_keepalive(
match (
env.get("keep_alive_secs"),
env.get("max_requests_per_connection"),
) {
(Some(Num(val)), Some(Num(max))) => (
if *val >= 0.0 { *val as u16 } else { 10u16 },
if *max >= 0.0 { *max as u16 } else { 0u16 },
),
(Some(Num(val)), _) => (if *val >= 0.0 { *val as u16 } else { 10u16 }, 0),
(_, Some(Num(max))) => (12u16, if *max >= 0.0 { *max as u16 } else { 0u16 }),
(_, _) => (10_u16, 0u16),
},
);
init_ping_interval(match env.get("ping_interval_mins") {
Some(Num(val)) => *val as u64,
_ => 30_u64,
});
init_sizing_constrains(
match env.get("max_request_size_kilo") {
Some(Num(val)) => (*val as u64) * 1024,
_ => 0_u64,
},
match env.get("max_response_size_kilo") {
Some(Num(val)) => (*val as u64) * 1024,
_ => 0_u64,
},
match env.get("max_chunk_size_kilo") {
Some(Num(val)) => (*val as usize) * 1024,
_ => 0_usize,
},
);
let tp = ThreadPool::new(*tp as usize);
let listener = TcpListener::bind(format! {"{bind}:{port}"}).unwrap_or_else(|err| {
panic!("can't bind {bind} to {port}, probably it's already in use - {err}")
});
let stop = Arc::new(AtomicBool::new(false));
let stop_one = stop.clone();
init_mapping(read_mapping(mapping));
LOGGER.lock().unwrap().info(
&format! {"Server started for {bind}:{port} at {}", http_format_time(SystemTime::now())},
);
let stop_listener = listener.try_clone().unwrap();
if !no_terminal {
thread::spawn(move || {
println! {"Presss 'q' or ^C to stop"};
let mut input = String::with_capacity(4);
loop {
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
if input.starts_with("q") {
stop_one.store(true, Ordering::SeqCst);
break;
}
input.clear()
}
drop(stop_listener)
});
}
for stream in listener.incoming() {
let Ok(stream) = stream else { continue };
let stop_two = stop.clone();
//let res_stream = stream.try_clone().unwrap();
tp.execute(move || {
let mut reuse_counter = 0;
let (keep_alive_secs, max_connections) = *KEEPALIVE.get().unwrap();
let mut close_connection = false;
while !close_connection {
if keep_alive_secs > 0 {
let _ =
stream.set_read_timeout(Some(Duration::from_secs(keep_alive_secs.into())));
} else {
close_connection = true;
}
reuse_counter += 1;
if max_connections > 0 && max_connections < reuse_counter {
close_connection = true;
}
// timeout can be reset at handling long polls
match handle_connection(&stream, close_connection) {
Err(err) => {
if err.kind() != ErrorKind::BrokenPipe
&& err.kind() != ErrorKind::ConnectionReset
&& err.kind() != ErrorKind::WouldBlock
{
LOGGER.lock().unwrap().error(
&format! {"Err: {err}/{} - in handling the request", err.kind()},
);
// can do it only if response isn't commited
let _ = report_error(500, "<grabbled> HTTP/1.1", &stream);
}
break;
}
_ => {
if stop_two.load(Ordering::SeqCst) || close_connection {
let _ = stream.shutdown(Shutdown::Both);
break;
}
}
}
}
});
//drop(res_stream);
if stop.load(Ordering::SeqCst) {
break;
}
}
drop(tp);
LOGGER.lock().unwrap().info("Stopping the server...");
Ok(())
}
fn handle_connection(mut stream: &TcpStream, close_connection: bool) -> io::Result<()> {
let addr = match stream.peer_addr() {
Ok(addr) => addr.to_string(),
_ => "disconnected".to_string(),
};
let mut buf_reader = BufReader::new(stream);
let mut line = String::with_capacity(256); // is it really needed to fight the fragmentation?
//let lines = buf_reader.lines(); // may still work
let len = buf_reader.read_line(&mut line)?;
if len < 10 {
// http/1.x ...
if len > 0 {
LOGGER
.lock()
.unwrap()
.error(&format! {"bad request 0x{}", simweb::to_hex(line.as_bytes())})
}
return Err(Error::new(ErrorKind::BrokenPipe, "no data"));
}
//LOGGER.lock().unwrap().trace(&format!("request {line}"));
let mut close = false;
line.truncate(len - 2); // \r\n
let request_line = line.clone();
let mut parts = request_line.splitn(3, ' '); // split_whitespace
let method = parts
.next()
.ok_or(io::Error::other("invalid request"))?
.to_owned(); // can't be due len check
let mut path = parts
.next()
.ok_or(io::Error::other("invalid request - no path"))?
.to_string();
let protocol = parts
.next()
.ok_or(io::Error::other("invalid request - no protocol"))?
.to_owned();
let query = match path.find('?') {
Some(qp) => {
let query = &path[qp + 1..].to_string();
path = path[0..qp].to_string();
query.to_owned()
}
None => String::new(),
};
let mut path_translated = None;
let mut cgi = false;
let mut websocket = false;
let mut script = String::with_capacity(256); // to reduce fragmentation
let mut path_info = None;
let mut wrapper = None;
let mut no_headers = false;
let mapping = MAPPING.get().unwrap();
let mut preserve_env = false;
//let mut map_entry = None;
let mut env_ext = None;
for e in mapping {
if path.starts_with(&e.web_path) {
//map_entry = Some(&e); // investigate why can't hold a pointer to map entry
if e.websocket
&& (path == e.web_path || path[e.web_path.len()..e.web_path.len() + 1] == *"/")
{
websocket = true;
preserve_env = !e.cgi;
cgi = true;
let mut ws_file = PathBuf::with_capacity(256);
ws_file.push(e.path.clone());
// add ext?
if cfg!(windows) {
ws_file.set_extension("exe");
}
if e.web_path.len() < path.len() {
path_info = Some(path[e.web_path.len()..].to_string());
}
path_translated = Some(ws_file.to_str().unwrap().to_string());
// eprintln!{"mapping for ws as {path_translated:?}"}
} else {
// TODO consolidate with if below
if path.ends_with('/') {
if e.cgi && e.ext.is_some() {
path += &("index.".to_owned() + &e.ext.clone().unwrap())
} else if !e.cgi {
path += "index.html"
}
}
// it can be better to keep web_path as parts
if e.cgi {
let ext = e.ext.clone().unwrap_or_default();
// possibly normalize separators here
let mut script_parts = path[e.web_path.len()..].split('/');
let mut translated = PathBuf::from(e.path.clone());
while let Some(part) = script_parts.next() {
translated = translated.join(part);
if translated.is_dir() {
continue;
} else if translated.is_file()
|| cfg!(windows)
&& (translated.add_extension("exe") && translated.is_file()
|| translated.set_extension("bat") && translated.is_file())
{
if ext.is_empty()
|| !ext.is_empty()
&& part.len() > ext.len() + 1
&& part.ends_with(&ext)
&& part[part.len() - ext.len() - 1..part.len() - ext.len()]
== *"."
{
script = part.to_string();
let script_ext = if let Some(dot) = script.rfind('.') {
&script[dot + 1..]
} else {
""
};
cgi = ext == script_ext
|| cfg!(windows)
&& ext.is_empty()
&& (script_ext == "exe" || script_ext == "bat");
let mut acc = String::with_capacity(e.web_path.len());
for e in script_parts.by_ref() {
acc.push('/');
acc.push_str(e)
}
if !acc.is_empty() {
path_info = Some(acc)
}
path_translated = translated.to_str().map(str::to_string);
wrapper = e.wrapper.clone();
if e.no_headers {
no_headers = e.no_headers
}
env_ext = e.options.clone();
break;
}
} else {
return report_error(404, &request_line, stream); // format!("script {part} component doesn't exist")
}
}
}
if script.is_empty() {
let path_buf = PathBuf::from(&e.path);
let mut sanitized_parts = PathBuf::with_capacity(256);
for part in
simweb::as_web_path(&mut path[e.web_path.len()..].to_string()).split('/')
{
match part {
".." => {
sanitized_parts.pop();
}
"." => (),
some => sanitized_parts.push(some),
}
}
path_translated = Some(path_buf.join(sanitized_parts).display().to_string());
}
// eprintln!{"mapping found as {path_translated:?} cgi {cgi} {script}"}
}
break;
} //else { println!{"path {path} not start with {}", e.web_path} }
}
let mut content_len = 0_u64;
let mut since = 0_u64;
let mut extra = BufType::None;
#[cfg(feature = "gzip")]
let mut gzip_allowed = false;
let mut cgi_env = if cgi {
let mut env: HashMap<String, String> = if preserve_env {
env::vars().collect()
} else {
#[cfg(unix)]
{
env::vars()
.filter(|(k, _)| k == "PATH" || k == "RUST_BACKTRACE")
.collect()
}
#[cfg(target_os = "windows")]
{
env::vars()
.filter(|(k, _)| k == "Path" || k == "RUST_BACKTRACE" || k == "SystemRoot")
.collect()
}
};
// CGI spec: https://datatracker.ietf.org/doc/html/rfc3875
env.insert("GATEWAY_INTERFACE".to_string(), "CGI/1.1".to_string());
env.insert("QUERY_STRING".to_string(), query);
if let Ok(peer_addr) = stream.peer_addr() {
env.insert("REMOTE_ADDR".to_string(), peer_addr.to_string());
if let Ok(mut remote_host) = peer_addr.to_socket_addrs() {
env.insert(
"REMOTE_HOST".to_string(),
remote_host.next().unwrap().to_string(),
);
}
}
env.insert("REQUEST_METHOD".to_string(), method.to_string());
env.insert("SERVER_PROTOCOL".to_string(), protocol.to_string());
env.insert("SERVER_SOFTWARE".to_string(), VERSION.to_string());
if let Some(ref path_info) = path_info {
env.insert("PATH_INFO".to_string(), path_info.into());
}
if let Some(ref path_translated) = path_translated {
let mut path_translated = PathBuf::from(&path_translated);
path_translated.pop();
let mut path_translated = path_translated.as_path().canonicalize()?;
if !path_translated.is_absolute() {
path_translated = env::current_dir()?.join(path_translated)
}
let path_translated = if let Some(path_info) = path_info {
// sanitize path_info
let mut sanitized_parts = PathBuf::with_capacity(256);
for part in rslash::to_unix_separator(path_info).split('/') {
match part {
".." => {
sanitized_parts.pop();
}
"." => (),
some => sanitized_parts.push(some),
}
}
path_translated.join(sanitized_parts)
} else {
path_translated
};
env.insert(
"PATH_TRANSLATED".to_string(),
path_translated.to_str().unwrap().to_string(),
);
}
if !script.is_empty() {
env.insert("SCRIPT_NAME".to_string(), script);
}
line.clear();
while 2 < buf_reader.read_line(&mut line)? {
line.truncate(line.len() - 2); // \r\n
//eprintln!{"heare: {line}"}
if let Some((key, val)) = line.split_once(": ") {
let key = key.to_lowercase();
let key = key.as_str();
match key {
"user-agent" => {
env.insert("REMOTE_IDENT".to_string(), val.to_string());
}
"host" => {
if let Some((host, port)) = val.split_once(':') {
env.insert("SERVER_NAME".to_string(), host.to_string());
env.insert("SERVER_PORT".to_string(), port.to_string());
}
}
"content-length" => {
// read load
if let Ok(len) = val.parse::<u64>() {
content_len = len
}
env.insert("CONTENT_LENGTH".to_string(), val.trim().to_string());
}
"content-type" => {
env.insert("CONTENT_TYPE".to_string(), val.trim().to_string());
}
"authorization" => {
env.insert("AUTH_TYPE".to_string(), val.to_string());
}
_ => {
env.insert(
"HTTP_".to_owned() + &key.to_uppercase().replace("-", "_").to_string(),
val.to_string(),
);
#[cfg(feature = "gzip")]
if key == "accept-encoding" {
gzip_allowed = val.contains("gzip");
}
}
}
} else {
LOGGER
.lock()
.unwrap()
.error(&format! {"unrecognized header {line}"})
}
line.clear()
}
if !env.contains_key("CONTENT_TYPE") {
env.insert("CONTENT_TYPE".to_string(), TYPE_PLAIN.to_string());
}
if !websocket && env.get("HTTP_UPGRADE") == Some(&"websocket".to_string()) {
return report_error(404, &request_line, stream);
}
if content_len > 0 {
// input data for CGI can be to large, so probably a chunk proccessing
// can be reasonable
// currently introduction of size guard can be reasonable
let (req_size, _, chunk_size) = SIZING_CONSTRAINS.get().unwrap();
if *req_size > 0 && *req_size < content_len {
io::copy(
&mut buf_reader.by_ref().take(content_len),
&mut std::io::sink(),
)?;
return report_error(413, &request_line, stream);
}
if *chunk_size == 0 || content_len < *chunk_size as u64 {
let mut buffer = vec![0u8; content_len as usize];
buf_reader.read_exact(&mut buffer)?;
//println!{"input:-> {}", String::from_utf8_lossy( &buffer)}
extra = BufType::Buf(buffer)
} else {
//println!("chunk read {content_len}");
extra = BufType::BufReader((buf_reader, content_len))
}
}
Some(env)
} else {
line.clear();
while 2 < buf_reader.read_line(&mut line)? {
line.truncate(line.len() - 2); // \r\n
//eprintln!{"header: {line}"}
if let Some((key, val)) = line.split_once(": ") {
let key = key.to_lowercase();
match key.as_str() {
"content-length" => {
content_len = val.parse::<u64>().unwrap_or(0);
}
"if-modified-since" => since = parse_http_timestamp(val).unwrap_or(0),
"connection" => close = val != "keep-alive",
"referer" | "user-agent" => {
LOGGER.lock().unwrap().trace(&format!("{key}: {val}"))
}
#[cfg(feature = "gzip")]
"accept-encoding" => {
gzip_allowed = val.contains("gzip");
}
&_ => (), // all headers should be collected somewhere
}
}
line.clear();
}
if content_len > 0 {
io::copy(
&mut buf_reader.by_ref().take(content_len),
&mut std::io::sink(),
)?;
//buf_reader.seek_relative(content_len)?
}
None
};
if method == "GET" || method == "POST" {
// eprintln!{"servicing {method} to {path_translated:?} {cgi} {websocket}"}
match path_translated {
Some(ref path_translated) if PathBuf::from(&path_translated).is_file() => {
let path_translated = PathBuf::from(&path_translated);
if cgi {
let mut path_translated = path_translated.as_path().canonicalize().unwrap();
if !path_translated.is_absolute() {
path_translated = env::current_dir()?.join(path_translated)
}
if websocket {
// https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers
// generate a respose first
// it can be generate by WS CGI, but
let cgi_env = cgi_env.unwrap();
let key = &cgi_env.get("HTTP_SEC_WEBSOCKET_KEY").unwrap();
let mut hasher = sha1::Sha1::new();
let res = hasher.hash(format!("{key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
//eprintln!{"ws command {path_translated:?}"}
let mut load = Command::new(&path_translated)
.stdout(Stdio::piped())
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.current_dir(path_translated.parent().unwrap())
.env_clear() // can be a flag telling to purge system env or not
.envs(cgi_env)
.spawn()?;
let res = simweb::base64_encode_with_padding(&res);
let mes = response_message(101);
let response = format!(
"{protocol} 101 {mes}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {res}\r\n\r\n"
);
stream.write_all(response.as_bytes())?;
// log
LOGGER
.lock()
.unwrap()
.info(&format! {"{addr} -- [{:>10}] \"{request_line}\" 101 0",
SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis()});
let _ = stream.set_read_timeout(None);
let mut reader_stream = stream; //.try_clone().unwrap();
let mut stdin = load.stdin.take().unwrap(); // TODO can be no stdin endpoint just sending out some info, or for example file content
let stderr = load.stderr.take().unwrap();
let mut stdout = load.stdout.take().unwrap();
let (send, recv) = mpsc::channel();
let pong_resp = Arc::new(Mutex::new(0_u64));
let shared_data_writer = Arc::clone(&pong_resp);
thread::scope(|s| {
s.spawn( || {
let mut buffer = [0_u8;MAX_LINE_LEN];
let mut reminder = 0_usize;
'serv_ep: loop {
let mut complete = false;
let mut kind = 0u8;
let mut fin_data = vec![];
// TODO incorporate all logic in this while to decode_block and hide the mask exposing
while !complete {
// reminder can be enouth to start decoding the block
let len;
if reminder >= 8 {
len = reminder;
reminder = 0
} else {
len = match reader_stream.read(&mut buffer[reminder..]) {
Ok(len) => if len == 0 { break 'serv_ep} else { len },
Err(_) => break 'serv_ep,
};
}
debug!("decode bl of {len}/{reminder}");
if reminder + len <= 2 {
// read more data because even close(8) has to include mask
reminder += len;
continue
}
let Ok((mut data,bl_kind,last,mut extra,mask,mut mask_pos,remain)) = decode_block(&mut buffer[0..len + reminder])
.inspect_err(|e| LOGGER.lock().unwrap().error(&format!("decode bl {len} + {reminder} - err:{e}"))) else {
debug!("invalid block of {len} + {reminder}={}, WS's closing", len + reminder);
break 'serv_ep
};
if data.is_empty() && extra == 0 && u32::from_be_bytes(mask) == 0 { // need more data to decode the buffer
debug!("need more data {reminder} - len: {len}");
reminder += len;
continue
}
if remain { // there are data in buffer
debug!("there are {extra} byte(s) of data for further processing in the buffer");
reminder = extra;
} else {
debug!("required to read {extra} for bl {bl_kind} to complete initial {}", data.len());
reminder = 0;
while extra > 0 {
let len = match reader_stream.read(&mut buffer) {
Ok(len) => if len == 0 { break 'serv_ep} else { len },
Err(_) => break 'serv_ep,
};
debug!("incomplete bl {bl_kind} requires reading {extra} more, currently {len} of {} last={last}", data.len());
for i in 0..len {
extra -= 1;
//debug!("unmask {:x} ^ {:x}", buffer[i] , mask[mask_pos]);
data.push(buffer[i] ^ mask[mask_pos]);
mask_pos = (mask_pos + 1) % 4;
if extra == 0 /*&& i < len - 1*/ {
reminder = len-i-1;
debug!("there are additional bytes {reminder} in buffer");
buffer.copy_within(i+1..len, 0);
break
}
}
}
}
if kind == 0 {
kind = bl_kind;
}
complete = last;
fin_data.append(&mut data);
}
debug!("complete {complete} -> {} of kind {kind} remained {reminder}", fin_data.len());
match kind {
0 => { // not supporting continuation yet, ignore for now
continue
}
1 => (),
8 => { // close websocket
break
}
0x9 => { // ping
// a client usually doesn't send, error ?
continue // ignore for now
}
0xA => { // pong
// check if we sent matching ping and clear it
//let pong_len = fin_data.len();
let pong_data = if fin_data.len() == 8 { u64::from_be_bytes(fin_data.try_into().unwrap()) } else { 0_u64 };
let mut data = shared_data_writer.lock().unwrap(); // Acquire the lock
*data = pong_data;
//LOGGER.lock().unwrap().info(&format!("received pong len {pong_len} as {pong_data}"));
continue
}
2 => { // currently support only UTF8 strings, no continuation or binary data
LOGGER.lock().unwrap().error(&format!("binary block is not supported yet {fin_data:?}"));
continue
}
_ => {
LOGGER.lock().unwrap().error(&format!("block {kind} is wrong"));
break // because more likely something wrong with the client
}
}
// TODO think how pass a block size to endpoint as: 1. in from 4 chars len, or 2. end mark like 0x00
if stdin.write_all(fin_data.as_slice()).is_err() {break};
stdin.flush().unwrap();
//let string = String::from_utf8_lossy(&data);
//eprintln!("entered {string}");
}
if let Ok(()) = stdin.write_all(&[255_u8,255,255,4]) { stdin.flush().unwrap() } // TODO consider also using 6 - Acknowledge
LOGGER.lock().unwrap().info(&format!("websocket session has terminated at [{:>10}], endpoint {path_translated:?} will be killed",
SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis()));
// forsibly kill the endpoint at a websocket disconnection
#[cfg(extra_stable)] // set in case of instability
load.kill().expect("command couldn't be killed");
//eprintln!("need to terminate endpoint! Killed?");
});
// stderr
s.spawn(|| {
let err = BufReader::new(stderr);
err.lines().for_each(|line| {
LOGGER
.lock()
.unwrap()
.error(&format!("err: {}", line.unwrap()))
});
});
let mut heartbeat_stream = stream.try_clone().unwrap();
let shared_data_reader = Arc::clone(&pong_resp);
if *PING_INTERVAL.get().unwrap() > 0 {
let _heartbeat_handle = s.spawn(move || {
let mut count = 0_u64;
// TODO write ping and check for receiving pong can be done in one heartbeat thread for all websockets
loop {
count += 1;
match heartbeat_stream.write_all(
encode_ping(&count.to_be_bytes()).unwrap().as_slice(),
) {
Err(_) => break,
_ => heartbeat_stream.flush().unwrap(),
}
if recv
.recv_timeout(Duration::from_secs(
60 * PING_INTERVAL.get().unwrap(),
))
.is_ok()
{
break; // Handle the interruption
}
// check if pong with count received
let data = shared_data_reader.lock().unwrap();
if count != *data {
debug!("no matching pong data, closing stream");
let _ = heartbeat_stream.shutdown(Shutdown::Both); // shutdown TCP stream
break;
}
drop(data);
}
});
}
let mut writer_stream = stream;
let mut buffer = [0_u8; MAX_LINE_LEN];
while let Ok(len) = stdout.read(&mut buffer) {
if len == 0
|| writer_stream
.write_all(encode_block(&buffer[0..len]).as_slice())
.is_err()
{
break;
}
}
match writer_stream.write_all(&[0x88, 0]) {
_ => (),
}
let _ = send.send(());
});
// TODO need a thread for stdout read loop
load.wait().unwrap();
return Err(Error::new(ErrorKind::BrokenPipe, "Websocket closed")); // force to close the connection and don't try to reuse
}
if let Some(ref mut cgi_env) = cgi_env
&& let Some(options) = env_ext
{
for (name, value) in options {
cgi_env.insert(
name,
match value.as_str() {
"$SCRIPT_FILE" => path_translated.display().to_string(),
"$IP" => format!("{}", stream.local_addr().unwrap().ip()),
_ => value,
},
);
}
}
let mut load = if let Some(wrapper) = wrapper {
Command::new(wrapper)
.stdout(Stdio::piped())
.stdin(Stdio::piped())
.stderr(Stdio::piped())
//.arg(&path_translated) TODO provide a mechanism how script reaches the wrapper
// TODO decide where current dir should point, currently the actuall script
.current_dir(
path_translated
.parent()
.ok_or(io::Error::other("No parent dir for CGI"))?,
)
.env_clear()
.envs(cgi_env.unwrap())
.spawn()?
} else {
Command::new(&path_translated)
.stdout(Stdio::piped())
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.current_dir(
path_translated
.parent()
.ok_or(io::Error::other("No parent dir for CGI"))?,
)
.env_clear()
.envs(cgi_env.unwrap())
.spawn()?
};
let _ = stream.set_read_timeout(None);
if let Some(stderr) = load.stderr.take() {
// a thread for consuming error
thread::spawn(move || {
let mut buf_reader = BufReader::with_capacity(DUMMY_CHUNK_LEN, stderr);
let mut line = String::new();
while let Ok(len) = buf_reader.read_line(&mut line)
&& len > 0
{
// probably limit line len by fn take(self, limit: u64) -> Take<Self>
LOGGER.lock().unwrap().trace(&line); // maybe to do not lock for every line and do everything in batch?
line.clear()
}
});
}
let stdout = load
.stdout
.take()
.ok_or(io::Error::other("no stdout of CGI"))?;
let mut out_stream = stream.try_clone()?;
// a thread for sending CGI out to a browser
let stdout_thread = thread::spawn(move || -> io::Result<()> {
let mut buf_reader = BufReader::with_capacity(DUMMY_CHUNK_LEN, stdout);
let mut try_process = || -> io::Result<()> {
let mut line = String::with_capacity(DUMMY_CHUNK_LEN);
let mut was_content_type = false;
// process headers
let mut code_num = 200;
let mut headers = String::with_capacity(DUMMY_CHUNK_LEN);
headers.push_str(&format!(
"Date: {}\r\nServer: {VERSION}\r\n",
http_format_time(SystemTime::now())
));
if !no_headers {