Skip to content

Instantly share code, notes, and snippets.

@jb55
Created September 1, 2018 00:36
Show Gist options
  • Save jb55/c38b365c48ee3c7280ba7a525539aad5 to your computer and use it in GitHub Desktop.
Save jb55/c38b365c48ee3c7280ba7a525539aad5 to your computer and use it in GitHub Desktop.
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::io;
extern crate httparse;
fn main() {
let bind = "127.0.0.1";
let port = "7880";
let full = format!("{}:{}", bind, port);
let mlistener = TcpListener::bind(full);
match mlistener {
Err(e) => {
println!("Could not bind to {}:{}: {}\n", bind, port, e);
std::process::exit(1);
}
Ok(listener) => {
println!("Listening on {}:{}", bind, port);
for mstream in listener.incoming() {
match mstream {
Err(e) => {
println!("error on incoming stream: {}", e);
}
Ok(stream) => {
if let Err(e) = handle_connection(&stream) {
println!("error in request: {}", e);
}
}
}
}
}
}
}
fn handle_connection(mut stream: &TcpStream) -> io::Result<()> {
let mut buffer = [0; 512];
stream.read(&mut buffer)?;
let mut headers = [httparse::EMPTY_HEADER; 16];
let mut req = httparse::Request::new(&mut headers);
if let Err(_) = req.parse(&buffer) {
return respond(stream, b"400 Bad Request", b"Could not parse headers\r\n")
}
if let Some(path) = req.path {
let path_bytes = path.as_bytes();
if path_bytes.len() >= 6 && &path_bytes[0..6] == b"/inbox" {
return handle_inbox(stream, &req);
}
respond(stream, b"404 Not Found", path_bytes)?
}
else {
respond(stream, b"500 Bad Request", b"c")?
}
Ok(())
}
fn handle_inbox(stream: &TcpStream, req: &httparse::Request) -> io::Result<()> {
let s = format!("{:?}\r\n", req);
let bs = s.as_bytes();
return respond(stream, b"200 OK", bs);
}
fn respond(mut stream: &TcpStream, code: &[u8], bs: &[u8]) -> io::Result<()> {
stream.write(b"HTTP/1.1 ")?;
stream.write(code)?;
stream.write(b"\r\n")?;
stream.write(b"Server: wolfsocks\r\n")?;
stream.write_fmt(format_args!("Content-Length: {}\r\n\r\n", bs.len()))?;
stream.write(bs)?;
stream.flush()?;
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment