odd-box 0.1.10

a dead simple reverse proxy server and web server
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
use std::borrow::Cow;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use axum::http::{HeaderName, HeaderValue};
use bytes::Bytes;
use http_body::Frame;
use http_body_util::{Either, Full, StreamBody};
use hyper::service::Service;
use hyper::{body::Incoming as IncomingBody, Request, Response};
use hyper_rustls::HttpsConnector;
use hyper_util::client::legacy::connect::HttpConnector;
use hyper_util::client::legacy::Client;
use hyper_util::rt::TokioExecutor;
use tokio_stream::wrappers::ReceiverStream;
use std::future::Future;
use std::pin::Pin;
use crate::global_state::GlobalState;
use crate::tcp_proxy::{GenericManagedStream, ReverseTcpProxyTarget};
use crate::types::app_state::ProcState;
use crate::types::proxy_state::ConnectionKey;
use crate::CustomError;
use hyper::{HeaderMap, Method, StatusCode};
use lazy_static::lazy_static;
use super::{ProcMessage, ReverseProxyService, WrappedNormalResponse};
use super::proxy;



lazy_static! {
    static ref SERVER_ONE: hyper_util::server::conn::auto::Builder<TokioExecutor> = 
        hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
}
pub async fn serve(service:ReverseProxyService,io:GenericManagedStream) {
    
    let result = match io {
        // GenericManagedStream::TLS(peekable_tls_stream) => 
        //     SERVER_ONE.serve_connection_with_upgrades(hyper_util::rt::TokioIo::new(peekable_tls_stream.managed_tls_stream), service).await,
        GenericManagedStream::TerminatedTLS(stream) => 
            SERVER_ONE.serve_connection_with_upgrades(hyper_util::rt::TokioIo::new(stream), service).await,
        GenericManagedStream::TCP(peekable_tcp_stream) => 
            SERVER_ONE.serve_connection_with_upgrades(hyper_util::rt::TokioIo::new(peekable_tcp_stream), service).await,

            
    };
        
       
    match result {
        Ok(_) => {},
        Err(e) => {
            tracing::warn!("{e:?}")
        }
    }
}

type FullOrStreamBody = 
    http_body_util::Either<
        Full<bytes::Bytes>, 
        StreamBody<
            ReceiverStream<
                Result<
                    hyper::body::Frame<bytes::Bytes>, 
                    CustomError
                >
            >
        >
    >;

pub type EpicBody = 
    http_body_util::Either<
        super::WrappedNormalResponseBody,
        FullOrStreamBody
    >;

pub type EpicResponse = hyper::Response<EpicBody>;

pub struct OddResponse(EpicResponse);
impl OddResponse {
    pub fn new(body:EpicBody) -> Self {
        Self(EpicResponse::new(body))
    }
    pub fn empty() -> Self {
        Self(EpicResponse::new(Either::Right(FullOrStreamBody::Left(Full::new(Bytes::new())))))
    }
}
impl From<EpicResponse> for OddResponse {
    fn from(r:EpicResponse) -> Self {
        OddResponse(r)
    }
}
impl From<OddResponse> for EpicResponse {
    fn from(r:OddResponse) -> Self {
        r.0
    }
}
impl OddResponse {
    pub fn with_status(self, status:StatusCode) -> Self {
        let (parts,body) = self.0.into_parts();
        let mut response = Response::from_parts(parts,body);
        *response.status_mut() = status;
        Self(response)
    }
    pub fn with_headers(self, headers:Vec<(&str,&str)>) -> Self {
        let (parts,body) = self.0.into_parts();
        let mut response = Response::from_parts(parts,body);
        let headers = HeaderMap::from_iter(headers.iter().filter_map(|(k,v)| {
            match (HeaderName::from_str(k), HeaderValue::from_str(v)) {
                (Ok(k), Ok(v)) => Some((k,v)),
                _ => { None }
            }
        }));
        *response.headers_mut() = headers;
        Self(response)
    }
}


pub fn create_response_channel(buf_size:usize) -> (
    tokio::sync::mpsc::Sender<Result<Frame<Bytes>, CustomError>>,
    tokio::sync::mpsc::Receiver<Result<Frame<Bytes>, CustomError>>,
 ) { tokio::sync::mpsc::channel(buf_size) }

pub fn create_epic_string_full_body(text:&str) -> EpicBody {
    EpicBody::Right(FullOrStreamBody::Left(Full::new(Bytes::from(text.to_owned()))))
}

pub fn create_stream_response(rx:tokio::sync::mpsc::Receiver<Result<Frame<Bytes>, CustomError>>) -> EpicResponse {
    EpicResponse::new(EpicBody::Right(Either::Right(StreamBody::new(ReceiverStream::new(rx)))))
}



pub fn create_simple_response_from_bytes(res:Response<bytes::Bytes>) -> Result<EpicResponse,CustomError> {
    let (a,b) = res.into_parts();
    Ok(EpicResponse::from_parts(a,Either::Right(Either::Left(b.into()))))
}
pub async fn create_simple_response_from_incoming(res:WrappedNormalResponse) -> Result<EpicResponse,CustomError> {
    let (p,b) = res.into_parts();
    Ok(EpicResponse::from_parts(p,Either::Left(b)))
}

fn handle_ws(svc:ReverseProxyService,mut req:hyper::Request<hyper::body::Incoming>) -> Result<EpicResponse,CustomError> {

    let (response, websocket) = hyper_tungstenite::upgrade(&mut req, None)
        .map_err(|e|CustomError(format!("{e:?}")))?;
    
    tokio::spawn(async move {crate::http_proxy::websockets::handle_ws(req, svc,websocket).await });
    let (p,b) = response.into_parts();
    Ok(EpicResponse::from_parts(p,Either::Right(Either::Left(b.into()))))
}


impl<'a> Service<Request<hyper::body::Incoming>> for ReverseProxyService {
    type Response = EpicResponse;
    type Error = CustomError;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
    
    fn call(&self, req: hyper::Request<hyper::body::Incoming>) -> Self::Future {    
        
        // tracing::trace!("INCOMING REQ: {:?}",req);
        // tracing::trace!("VERSION: {:?}",req.version());

        // handle websocket upgrades separately
        if hyper_tungstenite::is_upgrade_request(&req) {
            let res =  handle_ws(self.clone(),req);
            return Box::pin(async move { res })         
        }

        //handle h2 stream handler test req
        if req.version() == hyper::Version::HTTP_2 && req.uri().query().filter(|x|x.contains("stream_test_odd_box")).is_some() {
            let f= crate::http_proxy::utils::h2_stream_test(req);
            return Box::pin(async move {
               f.await
            })
        }

        // handle letsencrypt verification requests
        if req.uri().path().starts_with("/.well-known/acme-challenge/") {

            let host = match req.headers().get("host") {
                Some(value) => match value.to_str() {
                    Ok(host_str) => host_str.to_string(),
                    Err(e) => {
                        tracing::error!("Failed to convert host header to string: {:?}", e);
                        return Box::pin(async move { Err(CustomError(format!("{e:?}"))) });
                    }
                },
                None => {
                    tracing::error!("Host header not found");
                    return Box::pin(async move { Err(CustomError(format!("Host header not found"))) });
                }
            };

            // strip any :port from host:
            let host = host.split(":").collect::<Vec<&str>>()[0].to_string();
            let f = async move {
                let host = host;
                tracing::info!("Got incoming LE req for {host:?}");
                // http://whatever_domain/.well-known/acme-challenge/<TOKEN>
                crate::letsencrypt::DOMAIN_TO_CHALLENGE_TOKEN_MAP.get(&host)
                    .map(|x| {
                        let (_domain_name,challenge_token) = x.pair();
                        tracing::info!("Got incoming LE req and found challenge for {host} : {challenge_token:?}");
                        if let Some(response) = crate::letsencrypt::CHALLENGE_MAP.get(challenge_token) {
                            let (_,response) = response.pair();
                            tracing::info!("Responding with challenge response: {response:?}");
                            Ok(EpicResponse::new(create_epic_string_full_body(response)))
                        } else {
                            tracing::info!("Responding no response... because no challenge found for {host}");
                            Ok(EpicResponse::new(create_epic_string_full_body("nothing here 1")))
                        } 
                    })
                    .unwrap_or_else(|| {
                        tracing::warn!("Got incoming LE req but no challenge found for {host:?}");
                        Ok(EpicResponse::new(create_epic_string_full_body("nothing here 2")))
                    })
            };
            return Box::pin(async move {
                f.await
            })
        }

        
        // handle normal proxy path
        let f = handle_http_request(
            self.remote_addr.expect("there must always be a client"),
            req,
            self.tx.clone(),
            self.state.clone(),
            self.is_https_only,
            self.client.clone(),
            self.h2_client.clone(),
            self.resolved_target.clone(),
            self.configuration.clone(),
            self.connection_key.clone()
        );
        
        return Box::pin(async move {
            match f.await {
                Ok(x) => {
                    //x.headers_mut().insert("odd-box", HeaderValue::from_static("YEAH BABY YEAH"));
                    Ok(x)
                },
                Err(e) => {
                    //Err(CustomError(format!("{e:?}")))
                    let body = create_epic_string_full_body(&format!("{e:?}"));
                    let mut response = EpicResponse::new(body);
                    *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
                    Ok(response)
                },
            }
        })
    

    }
}

async fn handle_http_request(
    client_ip: std::net::SocketAddr, 
    req: Request<hyper::body::Incoming>,
    tx: Arc<tokio::sync::broadcast::Sender<ProcMessage>>,
    state: Arc<GlobalState>,
    is_https:bool,
    client:  Client<HttpsConnector<HttpConnector>, hyper::body::Incoming>,
    h2_client: Client<HttpsConnector<HttpConnector>, hyper::body::Incoming>,
    peeked_target: Option<Arc<ReverseTcpProxyTarget>>,
    configuration: Arc<crate::configuration::ConfigWrapper>,
    connection_key: ConnectionKey

) -> Result<EpicResponse, CustomError> {
    
    let req_host_name = 
        if let Some(t) = &peeked_target {
            t.host_name.to_string()
        } else if let Some(hh) = req.headers().get("host") { 
            let hostname_and_port = hh.to_str().map_err(|e|CustomError(format!("{e:?}")))?.to_string();
            hostname_and_port.split(":").collect::<Vec<&str>>()[0].to_owned()
        } else { 
            req.uri().authority().ok_or(CustomError(format!("No hostname and no Authority found")))?.host().to_string()
        };


    let req_path = req.uri().path();

    let params: std::collections::HashMap<String, String> = req
        .uri()
        .query()
        .map(|v| {
            url::form_urlencoded::parse(v.as_bytes())
                .into_owned()
                .collect()
        })
        .unwrap_or_else(std::collections::HashMap::new);

    if peeked_target.is_none() && !is_https { 

            
        if let Some(r) = intercept_local_commands(&req_host_name,&params,req_path,tx.clone()).await {
            return Ok(r)
        }
        
        // if no target was found and the request is for the odd-box ui, it means we have gotten a request to the odd-box ui
        // over a non-encrypted channel. if so we will just redirect to https.
        let odd_box_url = configuration.odd_box_url.clone().unwrap_or("!".to_string());
        if req_host_name == odd_box_url || req_host_name == "localhost" || req_host_name == "oddbox.localhost" || req_host_name == "odd-box.localhost"  {
            crate::proxy::mutate_tracked_connection(&state, &connection_key, |x|{
                x.is_odd_box_admin_api_req = true;
                x.outgoing_connection_is_tls = false;
            });
            let p = configuration.tls_port.unwrap_or(4343);
            return Ok(
                OddResponse::empty()
                    .with_headers(vec![
                        ("Location", &format!("https://{}:{p}",req_host_name))
                    ])
                    .with_status(StatusCode::TEMPORARY_REDIRECT)
                    .into()
            ); 
        }
    }
    
    tracing::trace!("Handling request from {client_ip:?} on hostname {req_host_name:?}");
    
    // THIS SHOULD BE THE ONLY PLACE WE INCREMENT THE TERMINATION COUNTER
    match state.app_state.statistics.connections_per_hostname.get_mut(&req_host_name) {
        Some(mut guard) => {
            let (_k,v) = guard.pair_mut();
            1 + v.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
        },
        None => {
            state.app_state.statistics.connections_per_hostname.insert(req_host_name.clone(), std::sync::atomic::AtomicUsize::new(1));
            1
        }
    };
    


    if let Some(r) = intercept_local_commands(&req_host_name,&params,req_path,tx.clone()).await {
        return Ok(r)
    }
    
    // todo - cache this?
    let dir_target = if peeked_target.is_some() { None } else { configuration.dir_server.iter().flatten().find_map(|x| {
        if x.host_name == req_host_name {
            match configuration.resolve_dir_server_configuration(x) {
                Ok(r) => {
                    crate::proxy::mutate_tracked_connection(&state, &connection_key, |x|{
                        x.dir_server = Some(r.clone());
                        x.outgoing_connection_is_tls = x.incoming_connection_uses_tls;
                    });            
                    Some(r)
                },
                Err(e) => {
                    tracing::warn!("Failed to resolve dir server configuration: {e:?}");
                    None
                },
            }
        } else {
            None
        }
    })};

    if let Some(t) = dir_target {
        if let Some(true) = t.redirect_to_https {
            if !is_https {
                let mut rr = EpicResponse::new(create_epic_string_full_body(&format!("Please use https://{req_host_name} instead of http://{req_host_name}")));
                *rr.status_mut() = StatusCode::PERMANENT_REDIRECT;
                rr.headers_mut().insert("Location", hyper::header::HeaderValue::from_str(&format!("https://{req_host_name}:{}{}",configuration.tls_port.unwrap_or(4343),req.uri())).unwrap());
                return Ok(rr)
            }
        }
        match crate::custom_servers::directory::handle(t.clone(),req).await {
            Ok(r) => return Ok(r),
            Err(e) => {
                tracing::error!("Failed to handle file request: {e:?}");
                let mut rr = EpicResponse::new(create_epic_string_full_body(&e.0));
                *rr.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
                return Ok(rr)
            },
        }
    }

    if peeked_target.is_none() && dir_target.is_none() {
        let fresh_container_info = { state.config.read().await.docker_containers.clone()} ;
        if let Some(rc) = fresh_container_info.get(&req_host_name).and_then(|x|Some(x.generate_remote_config())) {
            return perform_remote_forwarding(
                req_host_name,is_https,
                state.clone(),
                client_ip,
                &rc,
                req,client.clone(),
                h2_client.clone(),
                connection_key
            ).await
        }        
    }

    let found_hosted_target = 
        if let Some(p) = peeked_target.as_ref().and_then(|x| x.hosted_target_config.clone()) {
            tracing::trace!("Found peeked target for {req_host_name}");
            Some(p)
        } else {
            if let Some(processes) = &configuration.hosted_process {
                if let Some(pp) = processes.iter().find(|p| {
                    req_host_name == p.host_name
                    || p.capture_subdomains.unwrap_or_default() 
                    && req_host_name.ends_with(&format!(".{}",p.host_name))
                }) {
                    tracing::trace!("Found hosted target for {req_host_name}");
                    Some(pp.clone())
                } else {
                    None
                }
            } else {
                None
            }
        };

    if let Some(target_proc_cfg) = found_hosted_target {

        let current_target_status : Option<crate::ProcState> = {
            let info = state.app_state.site_status_map.get(&target_proc_cfg.host_name);
            match info {
                Some(data) => Some(data.value().clone()),
                None => None,
            }
        };

        match current_target_status {
            Some(ProcState::Running) | Some(ProcState::Faulty) | Some(ProcState::Starting) => {},
            _ => {
                // auto start site in case its been disabled by other requests
                _ = tx.send(super::ProcMessage::Start(target_proc_cfg.host_name.to_owned())).map_err(|e|format!("{e:?}"));
            }
        }

        
        if let Some(cts) = current_target_status {
            if cts == crate::ProcState::Stopped || cts == crate::ProcState::Starting || cts == crate::ProcState::Faulty {
                match req.method() {
                    &Method::GET => {
                        if let Some(ua) = req.headers().get("user-agent") {
                            let hv = ua.to_str().unwrap_or_default().to_uppercase() ;
                            // we only want to risk showing the please wait page to browsers..
                            // not perfect but should be good enough for now..?
                            // todo: opt in/out thru config ?
                            if hv.contains("MOZILLA") || hv.contains("SAFARI") || hv.contains("CHROME") || hv.contains("EDGE") {
                                return Ok(EpicResponse::new(create_epic_string_full_body(&please_wait_response())))
                            }
                            // todo - we dont seem to set the content type here..?
                            
                        } else {
                            tracing::trace!("waiting for site to start.. 5 seconds..");
                            tokio::time::sleep(Duration::from_secs(5)).await
                        }
                    }  
                    _ => {
                        // we do this to give services some time to wake up instead of failing requests while cold-starting sites
                        tracing::trace!("waiting for site to start.. 5 seconds...");
                        tokio::time::sleep(Duration::from_secs(5)).await
                    }           
                }                 
            }
        }

        let port;
        let mut wait_count = 0;
        loop {
            if wait_count > 10 {
                return Err(CustomError(format!("No active port found for {req_host_name}.")))
            } else {
                let id: &crate::types::proc_info::ProcId = target_proc_cfg.get_id();
                let name = target_proc_cfg.host_name.clone();
                tracing::trace!("Attempting to find active port found for {req_host_name}... id: {id:?} - name: {name:?}");
            }
            if let Some(info) = crate::PROC_THREAD_MAP.get(target_proc_cfg.get_id()) {
                if info.pid.is_some() {
                    if let Some(p) = info.config.active_port {
                        port = p;
                        break;
                    } else {
                        tracing::warn!("No active port found for {req_host_name}.");
                    }
                };
            } else {
                return Err(CustomError(format!("No site info found! (proc id missing: {:?})",target_proc_cfg.get_id())))
            };
            wait_count += 1;
            tokio::time::sleep(Duration::from_millis(1000)).await;
        }


        let enforce_https = target_proc_cfg.https.is_some_and(|x|x);
        let scheme = if enforce_https { "https" } else { "http" };

        let mut original_path_and_query = req.uri().path_and_query()
            .and_then(|x| Some(x.as_str())).unwrap_or_default();
        if original_path_and_query == "/" { original_path_and_query = ""}


        let (parsed_host_name,subdomain) = {
            let forward_subdomains = target_proc_cfg.forward_subdomains.unwrap_or_default();
            let sub = get_subdomain(&req_host_name, &target_proc_cfg.host_name);
            if forward_subdomains {
                if let Some(subdomain) = sub {
                    (Cow::Owned(format!("{subdomain}.{}", &target_proc_cfg.host_name)),Some(subdomain))
                } else {
                    (Cow::Borrowed(&target_proc_cfg.host_name),sub)
                }
            } else {
                (Cow::Borrowed(&target_proc_cfg.host_name),sub)
            }
        };

        let target_url = format!("{scheme}://{}:{}{}",
            parsed_host_name,
            port,
            original_path_and_query
        );
        
        // we add the host flag manually in proxy method, this is only to avoid dns lookup for local targets.
        // todo: opt in/out via cfg (?)
        let skip_dns_for_local_target_url = format!("{scheme}://{}:{}{}",
            "localhost",
            port,
            original_path_and_query
        );

        let target_cfg = target_proc_cfg.clone();
        let hints = target_cfg.hints.clone();
        let target = crate::http_proxy::Target::Proc(target_cfg.clone());

        let backend = crate::configuration::Backend {
            hints: hints,
            // we are hosting this service so clearly it is local
            address: "localhost".to_string(),
            port: port,
            https: Some(enforce_https)
        };

        crate::proxy::mutate_tracked_connection(&state, &connection_key, |x| {
            x.backend = Some(backend.clone());
            x.outgoing_connection_is_tls = enforce_https;
            x.target = Some(ReverseTcpProxyTarget { 
                proc_id : Some(target_cfg.get_id().clone()),
                disable_tcp_tunnel_mode: false,
                host_name: target_cfg.host_name.to_owned(),
                capture_subdomains: target_cfg.capture_subdomains.unwrap_or_default(),
                forward_wildcard: target_cfg.forward_subdomains.unwrap_or_default(),
                hosted_target_config: Some(target_cfg),
                remote_target_config: None,
                backends: vec![backend.clone()],
                is_hosted: true,
                sub_domain: subdomain
            });
        });

        let result = 
            proxy(
                &parsed_host_name,
                is_https,
                state.clone(),
                req,
                &skip_dns_for_local_target_url,
                target,
                client_ip,
                client,
                h2_client,
                &target_url,
                enforce_https,
                backend
            ).await;

        map_result(&target_url,result).await
    }

    else {
        if let Some(peeked_remote_config) = peeked_target.and_then(|x| x.remote_target_config.clone() ) {

            return perform_remote_forwarding(
                req_host_name,is_https,
                state.clone(),
                client_ip,
                &peeked_remote_config,
                req,client.clone(),
                h2_client.clone(),
                connection_key
            ).await
        }
        else if let Some(remote_target_cfg) = &configuration.remote_target.iter().flatten().find(|p|{
            //tracing::info!("comparing incoming req: {} vs {} ",req_host_name,p.host_name);
            req_host_name == p.host_name
            || p.capture_subdomains.unwrap_or_default() && req_host_name.ends_with(&format!(".{}",p.host_name))
        }) {
            return perform_remote_forwarding(
                req_host_name,is_https,
                state.clone(),
                client_ip,
                remote_target_cfg,
                req,client.clone(),
                h2_client.clone(),
                connection_key
            ).await
        };

        tracing::warn!("Received request that does not match any known target: {:?}", req_host_name);
        let body_str = format!("Sorry, I don't know how to proxy this request.. {:?}", req);
        
        let mut response = EpicResponse::new(create_epic_string_full_body(&body_str));
        *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
        Ok(response)
    }

}

fn get_subdomain(requested_hostname: &str, backend_hostname: &str) -> Option<String> {
    if requested_hostname == backend_hostname { return None };
    if requested_hostname.to_uppercase().ends_with(&backend_hostname.to_uppercase()) {
        let part_to_remove_len = backend_hostname.len();
        let start_index = requested_hostname.len() - part_to_remove_len;
        if start_index == 0 || requested_hostname.as_bytes()[start_index - 1] == b'.' {
            return Some(requested_hostname[..start_index].trim_end_matches('.').to_string());
        }
    }
    None
}

async fn perform_remote_forwarding(
    req_host_name:String,
    is_https:bool,
    state: Arc<GlobalState>,
    client_ip:std::net::SocketAddr,
    remote_target_config:&crate::configuration::RemoteSiteConfig,
    req:hyper::Request<IncomingBody>,
    client:  Client<HttpsConnector<HttpConnector>, hyper::body::Incoming>,
    h2_client: Client<HttpsConnector<HttpConnector>, hyper::body::Incoming>,
    connection_key: ConnectionKey
) -> Result<EpicResponse,CustomError> {
    
    
    let mut original_path_and_query = req.uri().path_and_query()
        .and_then(|x| Some(x.as_str())).unwrap_or_default();
    if original_path_and_query == "/" { original_path_and_query = ""}
   
    let next_backend_target = if let Some(b) = remote_target_config.next_backend(&state, crate::configuration::BackendFilter::Any).await {
        b
    } else {
        return Err(CustomError("No backend found".to_string()))
    };
    
    // if a target is marked with http, we wont try to use http
    let enforce_https = next_backend_target.https.unwrap_or_default();
   
    let scheme = if enforce_https { "https" } else { "http" }; 
    
    let (resolved_host_name,subdomain) = {
        let sub = get_subdomain(&req_host_name, &remote_target_config.host_name);
        if remote_target_config.forward_subdomains.unwrap_or_default() {
            if let Some(subdomain) = sub {
            //tracing::debug!("remote forward terminating proxy rewrote subdomain: {subdomain}!");
                (format!("{subdomain}.{}", &next_backend_target.address),Some(subdomain))
            } else {
                (next_backend_target.address.clone(),sub)
            }
        } else {
            (next_backend_target.address.clone(),sub)
        }
    };
        
    let target_url = format!("{scheme}://{}:{}{}",
        resolved_host_name,
        next_backend_target.port,
        original_path_and_query
    );

    crate::proxy::mutate_tracked_connection(&state, &connection_key, |x| {
        
        x.backend = Some(next_backend_target.clone());
        x.outgoing_connection_is_tls = enforce_https;

        x.target = Some(ReverseTcpProxyTarget { 
            proc_id : None,
            disable_tcp_tunnel_mode: false,
            host_name: remote_target_config.host_name.to_owned(),
            capture_subdomains: remote_target_config.capture_subdomains.unwrap_or_default(),
            forward_wildcard: remote_target_config.forward_subdomains.unwrap_or_default(),
            hosted_target_config: None,
            remote_target_config: Some(remote_target_config.clone()),
            backends: remote_target_config.backends.clone(),
            is_hosted: true,
            sub_domain: subdomain
        });
    });

    //tracing::info!("Incoming request to '{}' for remote proxy target {target_url}",next_backend_target.address);
    let result = 
        proxy(
            &req_host_name,
            is_https,
            state.clone(),
            req,
            &target_url,
            crate::http_proxy::Target::Remote(remote_target_config.clone()),
            client_ip,
            client,
            h2_client,
            &target_url,
            next_backend_target.https.unwrap_or_default(),
            next_backend_target
        ).await;

    map_result(&target_url,result).await

}

async fn map_result(target_url:&str,result:Result<crate::http_proxy::ProxyCallResult,crate::http_proxy::ProxyError>) -> Result<EpicResponse,CustomError> {
    
    match result {
        // Ok(crate::http_proxy::ProxyCallResult::Bytes(response)) => {
        //     return create_simple_response_from_bytes(response);
        // }
        Ok(super::ProxyCallResult::EpicResponse(epic_response)) => {
            return Ok(epic_response)
        }
        Ok(crate::http_proxy::ProxyCallResult::NormalResponse(response)) => {
                return create_simple_response_from_incoming(response).await;
        }
        Err(crate::http_proxy::ProxyError::LegacyError(error)) => {
            tracing::debug!("HyperLegacyError - Failed to call {}: {error:?}", &target_url);
            Ok(Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .body(create_epic_string_full_body(&format!("HyperLegacyError - {error:?}")))
                .expect("body building always works"))
        },
        Err(crate::http_proxy::ProxyError::HyperError(error)) => {
            tracing::debug!("HyperError - Failed to call {}: {error:?}", &target_url);
            Ok(Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .body(create_epic_string_full_body(&format!("HyperError - {error:?}")))
                .expect("body building always works"))
        },
        Err(crate::http_proxy::ProxyError::OddBoxError(error)) => {
            tracing::debug!("OddBoxError - Failed to call {}: {error:?}", &target_url);
            Ok(Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .body(create_epic_string_full_body(&format!("ODD-BOX-ERROR: {error:?}")))
                .expect("body building always works"))
        },
        Err(crate::http_proxy::ProxyError::ForwardHeaderError) => {
            tracing::debug!("ForwardHeaderError - Failed to call {}", &target_url);
            Ok(Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .body(create_epic_string_full_body("ForwardHeaderError"))
                .expect("body building always works"))
        },
        Err(crate::http_proxy::ProxyError::InvalidUri(error)) => {
            tracing::debug!("InvalidUri - Failed to call {}: {error:?}", &target_url);
            Ok(Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .body(create_epic_string_full_body(&format!("InvalidUri: {error:?}")))
                .expect("body building always works"))
        }, 
        Err(crate::http_proxy::ProxyError::UpgradeError(error)) => {
            tracing::debug!("UpgradeError - Failed to call {}: {error:?}", &target_url);
            Ok(Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .body(create_epic_string_full_body(&format!("UpgradeError: {error:?}")))
                .expect("body building always works"))
        }
    }
}


// TODO:
//        make this it opt-in with cfg v2.
//        make it true when coming from legacy or v1 to have backward compatibility
//        (we have admin-api for this now and so it is bad for performance to use this instead)
pub async fn intercept_local_commands(
    req_host_name:&str,
    params:&std::collections::HashMap<String, String>,
    req_path:&str,
    tx:Arc<tokio::sync::broadcast::Sender<ProcMessage>>
) -> Option<EpicResponse> {

    if req_host_name != "127.0.0.1" && req_host_name != "localhost" {
        return None
    }
    
    if req_path.eq("/STOP") {
        let target : Option<&String> = params.get("proc");
        
        let s = target.unwrap_or(&String::from("all")).clone();
        tracing::warn!("Handling order STOP ({})",s);
        let result = tx.send(ProcMessage::Stop(s)).map_err(|e|format!("{e:?}"));
        
        if let Err(e) = result {
            let mut response = EpicResponse::new(create_epic_string_full_body(&format!("{e:?}")))
;            *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
            return Some(response)
        }

        let html = r#"
            <center>
                <h2>Stop signal received!</h2>
                
                <form action="/START">
                    <input type="submit" value="Resume" />
                </form>            

                <p>The proxy will also resume if you visit any of the stopped sites</p>
            </center>
        "#;
        return Some(EpicResponse::new(create_epic_string_full_body(html)))
    } 
    
    if req_path.eq("/START") {
        

        let target : Option<&String> = params.get("proc");
        
        let s = target.unwrap_or(&String::from("all")).clone();
        tracing::warn!("Handling order START ({})",s);
        let result: Result<usize, String> = tx.send(ProcMessage::Start(s)).map_err(|e|format!("{e:?}"));
        
        if let Err(e) = result {
            let mut response = EpicResponse::new(create_epic_string_full_body(&format!("{e:?}")))
;            *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
            return Some(response)
        }

        let html = r#"
            <center>
                <h2>Start signal received.</h2>
                
                <form action="/STOP">
                    <input type="submit" value="Stop" />
                </form>            

            </center>
        "#;
        return Some(EpicResponse::new(create_epic_string_full_body(html)))
    }

    None
}

// TODO - package these mjs/jsons with the binary if we want to keep it as is
// otherwise get rid of the deps
fn please_wait_response() -> String {
    r#"
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="refresh" content="5;">
            <title>please wait...</title>
            <style>
                body {
                    margin: 0;
                    padding: 0;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    height: 100vh;
                    background-color: #111;
                    color: white;
                    font-family: Arial, sans-serif;
                    text-align: center;
                }

                .loading-text {
                    font-size: 34px;
                    margin-bottom: 20px;
                }

                .subtitle {
                    font-size: 16px;
                    margin-bottom: 40px;
                    color: #cccccc;
                }

                .spinner {
                    border: 4px solid rgba(255, 255, 255, 0.3);
                    border-radius: 50%;
                    border-top: 4px solid white;
                    width: 40px;
                    height: 40px;
                    animation: spin 1s linear infinite;
                }

                @keyframes spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                }
            </style>
        </head>
        <body>
            <div class="loading-text">Initializing sub-systems, please wait..</div>
            <div class="subtitle">The backend server responsible for handling this request is not awake, we are attempting to wake it up now!</div>
            <div class="spinner"></div>
        </body>
        </html>
    "#.to_string()
}