-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.rs
77 lines (69 loc) · 1.91 KB
/
main.rs
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
#![crate_type = "bin"]
extern crate nix;
extern crate libc;
extern crate core;
#[macro_use]
extern crate error_chain;
extern crate transform;
extern crate common;
use nix::errno::Errno;
use nix::sys::socket;
use std::os::unix::io::RawFd;
use std::net::ToSocketAddrs;
use libc::{c_void, recv, MSG_WAITALL};
use transform::decode;
use common::{MSGLEN, SOCK};
use common::errors::*;
quick_main!(|| -> Result<i32> {
let fd: Result<RawFd> = {
let fd = socket::socket(
socket::AddressFamily::Inet,
socket::SockType::Stream,
socket::SockFlag::empty(),
socket::SOL_TCP,
)?;
let address = SOCK.to_socket_addrs()?.next().expect(
"Cannot convert bind to socket address",
);
socket::bind(
fd,
&socket::SockAddr::new_inet(socket::InetAddr::from_std(&address)),
)?;
socket::listen(fd, 16)?;
Ok(fd)
};
let fd = match fd {
Ok(fd) => fd,
Err(err) => {
bail!("Socket error: {}", err);
}
};
let mut payload = vec![0u8; MSGLEN];
let mut fd_ = socket::accept(fd)?;
loop {
let nread = unsafe {
recv(
fd_,
payload.as_mut_ptr() as *mut c_void,
MSGLEN,
MSG_WAITALL,
)
};
if nread == 0 {
fd_ = socket::accept(fd)?;
continue;
} else if nread < 1 {
bail!("recv failed: {}", Errno::last());
} else if nread != MSGLEN as isize {
bail!("Incomplete read of size {}", nread)
}
println!("Read {} bytes...\n", nread);
let vers = decode(&payload[..8]);
let body = decode(&payload[8..16]);
println!(
"\tversion: {:?}\n\tbody: {:?}",
String::from_utf8_lossy(&vers),
String::from_utf8_lossy(&body)
);
}
});