Simple working concept

This commit is contained in:
2025-08-12 14:19:13 -04:00
parent 4c543e2d0e
commit 708f85663a
4 changed files with 136 additions and 12 deletions
+69 -11
View File
@@ -1,33 +1,71 @@
use std::{ use std::{
io::{Read, Write}, io::{Read, Write},
net::{TcpListener, TcpStream}, net::{Shutdown, TcpListener, TcpStream},
}; };
use crate::route_tcp; use crate::route_tcp;
/// Prints a log message with a timestamp.
fn log(msg: &str) {
use std::time::{SystemTime, UNIX_EPOCH};
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let seconds = now.as_secs();
let millis = now.subsec_millis();
// Rough human-readable formatting: seconds since epoch + milliseconds
println!("[{}.{:03}] {}", seconds, millis, msg);
}
pub fn router() { pub fn router() {
let listener = TcpListener::bind("0.0.0.0:7879").unwrap(); let listener = TcpListener::bind("0.0.0.0:7879").unwrap();
println!("Router started on port 7879"); log("Router started on port 7879");
for stream in listener.incoming() { for stream in listener.incoming() {
match stream { match stream {
Ok(mut client_recv) => { Ok(mut client_recv) => {
log(&format!(
"Incoming connection from {}",
client_recv.peer_addr().unwrap()
));
let mut address = [0; 6]; let mut address = [0; 6];
let bytes_read = client_recv.read(&mut address).unwrap(); let bytes_read = client_recv.read(&mut address).unwrap();
if bytes_read == 0 { if bytes_read == 0 {
log("Client disconnected before sending address.");
continue; continue;
} }
log(&format!("Received target address: {:?}", address));
let address = format!(
"{}.{}.{}.{}:{}",
address[0],
address[1],
address[2],
address[3],
u16::from_be_bytes([address[4], address[5]])
);
log(&format!("Connecting to routed server at {address}"));
let mut client_send = client_recv.try_clone().unwrap(); let mut client_send = client_recv.try_clone().unwrap();
let mut server_recv = TcpStream::connect("127.0.0.1:7878").unwrap(); let mut server_recv = TcpStream::connect(&address).unwrap();
let mut server_send = server_recv.try_clone().unwrap(); let mut server_send = server_recv.try_clone().unwrap();
std::thread::spawn(move || while !route_tcp(&mut client_recv, &mut server_send) {}); log(&format!("Connected to routed server at {address}"));
// Client -> Server
std::thread::spawn(move || {
while !route_tcp(&mut client_recv, &mut server_send) {}
log("Client -> Server routing stopped");
});
// Server -> Client
while !route_tcp(&mut client_send, &mut server_recv) {} while !route_tcp(&mut client_send, &mut server_recv) {}
log("Server -> Client routing stopped");
} }
Err(e) => { Err(e) => {
eprintln!("Connection failed: {}", e); log(&format!("Connection failed: {}", e));
} }
} }
} }
@@ -36,35 +74,55 @@ pub fn router() {
pub fn run() -> std::io::Result<()> { pub fn run() -> std::io::Result<()> {
let listener = TcpListener::bind("0.0.0.0:7878")?; let listener = TcpListener::bind("0.0.0.0:7878")?;
let mut connections: Vec<[u8; 6]> = Vec::new(); let mut connections: Vec<[u8; 6]> = Vec::new();
println!("Gateway started on port 7878"); log("Gateway started on port 7878");
std::thread::spawn(router); std::thread::spawn(router);
for stream in listener.incoming() { for stream in listener.incoming() {
match stream { match stream {
Ok(mut stream) => { Ok(mut stream) => {
log(&format!(
"New client connected from {}",
stream.peer_addr().unwrap()
));
let mut address = [0; 6]; let mut address = [0; 6];
let bytes_read = stream.read(&mut address)?; let bytes_read = stream.read(&mut address)?;
if bytes_read == 0 { if bytes_read == 0 {
log("Client disconnected before sending data.");
break; break;
} }
log(&format!("Received address: {:?}", address));
println!("Received: {:?}", &address);
if let Some(con) = connections.last() { if let Some(con) = connections.last() {
log(&format!("Sending previous connection address: {:?}", con));
stream.write_all(con)?; stream.write_all(con)?;
} else { } else {
stream.write_all(&[127, 0, 0, 1, 0x1E, 0xBF])?; let default_addr = [0, 0, 0, 0, 0x1E, 0xC7];
log(&format!(
"No previous connections. Sending default address: {:?}",
default_addr
));
stream.write_all(&default_addr)?;
} }
connections.push(address); connections.push(address);
log(&format!(
"Stored new connection. Total connections: {}",
connections.len()
));
while stream.read(&mut []).unwrap() != 0 {} while stream.read(&mut []).unwrap() != 0 {}
log(&format!(
"Client {} disconnected",
stream.peer_addr().unwrap()
));
stream.shutdown(std::net::Shutdown::Both).unwrap(); stream.shutdown(Shutdown::Both).unwrap();
connections.remove(connections.iter().position(|v| v == &address).unwrap());
} }
Err(e) => { Err(e) => {
eprintln!("Connection failed: {}", e); log(&format!("Connection failed: {}", e));
} }
} }
} }
+42
View File
@@ -5,6 +5,48 @@ use std::{
pub mod gateway; pub mod gateway;
pub struct GhostStream(TcpStream);
impl GhostStream {
pub fn connect(ip: (u8, u8, u8, u8), port: u16) -> Self {
let addr = get_addr().unwrap();
println!("Connecting to: {addr}");
let mut stream = TcpStream::connect(addr).unwrap();
let bep = port.to_be_bytes();
stream
.write_all(&[ip.0, ip.1, ip.2, ip.3, bep[0], bep[1]])
.unwrap();
Self(stream)
}
pub fn write(&mut self, data: &[u8]) {
self.0.write_all(data).unwrap();
}
}
pub fn get_addr() -> std::io::Result<String> {
let mut stream = TcpStream::connect("0.0.0.0:7878")?;
stream.write_all(&[0, 0, 0, 0, 0x1E, 0xC7]).unwrap();
let mut address = [0; 6];
stream.read(&mut address)?;
Ok(format!(
"{}.{}.{}.{}:{}",
address[0],
address[1],
address[2],
address[3],
u16::from_be_bytes([address[4], address[5]])
))
}
pub fn route_tcp(from: &mut TcpStream, to: &mut TcpStream) -> bool { pub fn route_tcp(from: &mut TcpStream, to: &mut TcpStream) -> bool {
let mut data = [0; 2048]; let mut data = [0; 2048];
+6 -1
View File
@@ -1,3 +1,8 @@
use ghostnet_rs::GhostStream;
fn main() { fn main() {
// ghostnet_rs::gateway::run().unwrap(); if let Err(_) = ghostnet_rs::gateway::run() {
let mut stream = GhostStream::connect((0, 0, 0, 0), 7525);
stream.write("Hello, World".as_bytes());
}
} }
+19
View File
@@ -0,0 +1,19 @@
import socket
HOST = "0.0.0.0" # Standard loopback interface address (localhost)
PORT = 7525 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT)) # Bind the socket to the specified host and port
s.listen() # Start listening for incoming connections
print(f"Server listening on {HOST}:{PORT}")
conn, addr = s.accept() # Accept a new connection
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024) # Receive up to 1024 bytes of data
if not data:
break # If no data is received, the client has disconnected
conn.sendall(data) # Send the received data back to the client
print(f"Echoed: {data.decode()}") # Decode and print the echoed data