-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #25 from th7nder/t-17
Add listening interface and port selection
- Loading branch information
Showing
3 changed files
with
136 additions
and
58 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
use std::{ | ||
net::SocketAddr, | ||
sync::mpsc::Receiver, | ||
thread::{self, JoinHandle}, | ||
}; | ||
|
||
use proxyapi::{Proxy, ProxyHandler}; | ||
use tokio::{runtime::Runtime, sync::oneshot::Sender}; | ||
|
||
use crate::requests::RequestInfo; | ||
|
||
pub struct ManagedProxy { | ||
rx: Receiver<ProxyHandler>, | ||
close: Option<Sender<()>>, | ||
thread: Option<JoinHandle<()>>, | ||
} | ||
|
||
impl ManagedProxy { | ||
pub fn new(addr: SocketAddr) -> ManagedProxy { | ||
let (tx, rx) = std::sync::mpsc::sync_channel(1); | ||
let (close_tx, close_rx) = tokio::sync::oneshot::channel(); | ||
|
||
let rt = Runtime::new().unwrap(); | ||
|
||
let thread = thread::spawn(move || { | ||
rt.block_on(async move { | ||
if let Err(e) = Proxy::new(addr, Some(tx.clone())) | ||
.start(async move { | ||
let _ = close_rx.await; | ||
}) | ||
.await | ||
{ | ||
eprintln!("Error running proxy on {:?}: {e}", addr); | ||
} | ||
}) | ||
}); | ||
|
||
ManagedProxy { | ||
rx, | ||
close: Some(close_tx), | ||
thread: Some(thread), | ||
} | ||
} | ||
|
||
pub fn try_recv_request(&mut self) -> Option<RequestInfo> { | ||
match self.rx.try_recv() { | ||
Ok(l) => { | ||
let (request, response) = l.to_parts(); | ||
Some(RequestInfo::new(request, response)) | ||
} | ||
_ => None, | ||
} | ||
} | ||
} | ||
|
||
impl Drop for ManagedProxy { | ||
fn drop(&mut self) { | ||
if let Some(t) = self.thread.take() { | ||
if let Some(close) = self.close.take() { | ||
let _ = close.send(()); | ||
} | ||
t.join().expect("Couldn't gracefully shutdown the proxy.") | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters