kalabukdima

Eavesdrop

Apr 1st, 2021
605
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::net::{TcpListener,TcpStream};
  2. use std::io::prelude::*;
  3. use std::io::ErrorKind::WouldBlock;
  4.  
  5. fn forward_chunk(
  6.     src: &mut TcpStream,
  7.     dst: &mut TcpStream,
  8.     buf: &mut[u8],
  9.     annotation: &str
  10. ) -> std::io::Result<bool> {
  11.     match src.read(buf) {
  12.         Ok(len) => {
  13.             if len == 0 {
  14.                 return Ok(true);
  15.             }
  16.             print!("{}{}", annotation, String::from_utf8_lossy(&buf[..len]));
  17.             dst.write_all(&buf[..len])?;
  18.         },
  19.         Err(e) if e.kind() == WouldBlock => {},
  20.         e => {
  21.             dst.shutdown(std::net::Shutdown::Both)?;
  22.             e?;
  23.         }
  24.     }
  25.     Ok(false)
  26. }
  27.  
  28. fn handle_connection(
  29.     src: &mut TcpStream,
  30.     addr: &str,
  31.     dst_addr: &str
  32. ) -> std::io::Result<()> {
  33.     println!("Connecting {} and {}", addr, dst_addr);
  34.     let mut dst = TcpStream::connect(dst_addr)?;
  35.     src.set_nonblocking(true)?;
  36.     dst.set_nonblocking(true)?;
  37.  
  38.     loop {
  39.         let mut buf = [0; 256];
  40.         if forward_chunk(src, &mut dst, &mut buf, "->")? {
  41.             break;
  42.         }
  43.         if forward_chunk(&mut dst, src, &mut buf, "<-")? {
  44.             break;
  45.         }
  46.     }
  47.     Ok(())
  48. }
  49.  
  50. fn main() -> std::io::Result<()> {
  51.     let self_port = std::env::args().nth(1).unwrap();
  52.     let dst_ip = std::env::args().nth(2).unwrap();
  53.     let dst_port = std::env::args().nth(3).unwrap();
  54.     let self_addr = format!("127.0.0.1:{}", self_port);
  55.     let dst_addr = format!("{}:{}", dst_ip, dst_port);
  56.  
  57.     let listener = TcpListener::bind(self_addr)?;
  58.     println!("Listening on {}", listener.local_addr()?);
  59.     loop {
  60.         let (mut src, addr) = listener.accept()?;
  61.         if let Err(e) = handle_connection(&mut src, &addr.to_string(), &dst_addr) {
  62.             eprintln!("Error: {}", e);
  63.         }
  64.     }
  65. }
  66.  
  67. // Test with `nc localhost 1234`
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×