2 use std
::io
::{ MemWriter
, Acceptor
, Listener
, TcpStream
, IoResult
, IoError
, EndOfFile
};
3 use std
::io
::net
::tcp
::{ TcpAcceptor
, TcpListener
};
5 use packet
::{ Packet
, Command
, Answer
, Error
, ReadingResult
, PacketType
};
7 // Default timeout when waiting data on a stream (for instance: 'TcpStream::read').
8 static DEFAULT_TIMEOUT
: Option
<u64> = Some(500); // [ms].
11 acceptor
: TcpAcceptor
,
20 current_timestamp
: u64,
21 variant
: packet
::Variant
,
25 pub fn new(interface
: &str, port
: u16, variant
: packet
::Variant
) -> IoResult
<Server
> {
26 let mut acceptor
= try!(TcpListener
::bind(interface
, port
).listen());
29 acceptor
: acceptor
.clone()
34 for stream
in acceptor
.incoming() {
36 Ok(stream
) => spawn(proc() {
37 Server
::handle_client(EndPoint
::new(stream
, variant
));
48 pub fn close(&mut self) -> IoResult
<()> {
49 self.acceptor
.close_accept()
52 fn handle_client(mut end_point
: EndPoint
) {
54 match end_point
.read() {
55 Ok(packet@Packet
{ t
: Command(..), .. }) => {
56 end_point
.print("Server", format!("Valid command received: {}", packet
));
57 let answer
= Answer(Packet
::random_packet_data([]));
58 match end_point
.send(answer
.clone()) {
60 end_point
.print("Server", format!("Answer sent: {}", answer
)),
62 end_point
.print("Server", format!("Can't send the answer. Error: {}", e
))
65 // Socket has been closed.
66 Err(packet
::IOReadError(IoError
{ kind
: EndOfFile
, .. })) => {
67 end_point
.print("Server", format!("Connection closed: EOF"));
71 end_point
.print("Server", format!("Error or invalid packet: {}", other
))
78 pub fn new(address
: &str, port
: u16, variant
: packet
::Variant
) -> IoResult
<Client
> {
79 Ok(Client
{ end_point
: EndPoint
{
80 socket
: try!(TcpStream
::connect(address
, port
)),
87 pub fn close(&mut self) -> IoResult
<()> {
88 self.end_point
.close()
91 pub fn send(&mut self, packet
: PacketType
) -> bool
{
94 self.end_point
.print("Client", format!("Sending: {}", packet
));
95 match self.end_point
.send_with_result(packet
) {
96 Ok(Ok(packet@Packet
{ t
: Answer(..), .. })) => {
97 self.end_point
.print("Client", format!("Command transmitted correctly, answer: {}", packet
));
101 self.end_point
.print("Client", format!("Command transmitted correctly, wrong answer: {}", packet
));
105 self.end_point
.print("Client", format!("Answer error: {}", e
));
109 self.end_point
.print("Client", format!("Can't send the packet. Error: {}", e
));
115 self.end_point
.print("Client", format!("Cannot send this type of packet: {}", other
));
121 /// Send some valid and not-valid packets to the server and check the result.
122 /// For each test a new client is created.
123 pub fn start_tests(address
: &str, port
: u16, variant
: packet
::Variant
) {
124 let execute
= |f
: &mut |&mut Client
| -> bool
| -> bool
{
125 match Client
::new(address
, port
, variant
) {
126 Ok(ref mut client
) => (*f
)(client
),
128 println!("Unable to create a client. Error: {}", e
);
134 fn raw_packet(timestamp
: u64) -> Vec
<u8> {
135 let mut m
= MemWriter
::new();
136 match (Packet
{ t
: Command(Packet
::random_packet_data([42])), timestamp
: timestamp
}).write(&mut m
, packet
::Weak
) {
142 let mut tests
= vec!(
144 |client
: &mut Client
| -> bool
{
145 println!("Sending a valid packet...");
146 client
.send(Command(Packet
::random_packet_data([42])))
149 |client
: &mut Client
| -> bool
{
150 println!("Sending a packet with an unknown type...");
151 client
.end_point
.current_timestamp
+= 1;
152 let mut raw_packet
= raw_packet(client
.end_point
.current_timestamp
);
153 raw_packet
[2] = 0xEE; // Alter the type.
154 match client
.end_point
.send_raw_with_result(raw_packet
.as_slice()) {
155 Ok(Err(packet
::IOReadError( IoError
{ kind
: io
::TimedOut
, .. }))) => true, // OK: the server should not send any packet.
157 println!("Error: {}", other
);
163 |client
: &mut Client
| -> bool
{
164 println!("Sending a packet with an old timestamp...");
165 client
.end_point
.current_timestamp
+= 1;
166 let raw_packet
= raw_packet(0);
167 match client
.end_point
.send_raw_with_result(raw_packet
.as_slice()) {
168 Ok(Err(packet
::IOReadError( IoError
{ kind
: io
::TimedOut
, .. }))) => true, // OK: the server should not send any packet.
170 println!("Error: {}", other
);
176 |client
: &mut Client
| -> bool
{
177 println!("Sending a packet with altered crypted data (do not alter the padding)...");
178 client
.end_point
.current_timestamp
+= 1;
179 let mut raw_packet
= raw_packet(client
.end_point
.current_timestamp
);
180 raw_packet
[11] = 0xDE;
181 raw_packet
[12] = 0xAD;
182 raw_packet
[13] = 0xBE;
183 raw_packet
[14] = 0xEF;
184 match client
.end_point
.send_raw_with_result(raw_packet
.as_slice()) {
185 Ok(Ok(Packet
{ t
: Error(packet
::AuthError
), .. })) => true,
187 println!("Error: {}", other
);
193 |client
: &mut Client
| -> bool
{
194 println!("Sending a packet with too small data...");
195 let command
= Command(Packet
::new_packet_data(0, Vec
::from_elem(6, 0x00)));
196 match client
.end_point
.send_with_result(command
) {
197 Ok(Err(packet
::IOReadError( IoError
{ kind
: io
::TimedOut
, .. }))) => true, // OK: the server should not send any packet.
199 println!("Error: {}", other
);
205 |client
: &mut Client
| -> bool
{
206 println!("Sending a packet with too large data...");
207 let command
= Command(Packet
::new_packet_data(0, Vec
::from_elem(40, 0x00)));
208 match client
.end_point
.send_with_result(command
) {
209 Ok(Err(packet
::IOReadError( IoError
{ kind
: io
::TimedOut
, .. }))) => true, // OK: the server should not send any packet.
211 println!("Error: {}", other
);
217 |client
: &mut Client
| -> bool
{
218 println!("Sending a packet with wrong padding (all 0)...");
219 client
.end_point
.current_timestamp
+= 1;
220 let mut m
= MemWriter
::new();
221 let raw_packet
= match (Packet
{ t
: Command(Packet
::random_packet_data([42])), timestamp
: client
.end_point
.current_timestamp
}).write_with_padding_fun(&mut m
, packet
::Weak
, |_
, _
| -> u8 { 0 }) {
226 match client
.end_point
.send_raw_with_result(raw_packet
.as_slice()) {
227 Ok(Ok(Packet
{ t
: Error(packet
::CryptError
), .. })) => true,
229 println!("Error: {}", other
);
236 let mut nb_test_passed
= 0;
237 for (i
, test
) in range(1, tests
.len()+1).zip(tests
.iter_mut()) {
238 println!("===== Test case #{}:", i
)
241 println!("===== Test passed");
243 println!("===== Test failed");
247 if nb_test_passed
== tests
.len() {
248 println!("All tests passed");
250 println!("#{} test(s) failed", tests
.len() - nb_test_passed
);
256 pub fn new(mut socket
: TcpStream
, variant
: packet
::Variant
) -> EndPoint
{
257 let _
= socket
.set_nodelay(true);
258 EndPoint
{ socket
: socket
, current_timestamp
: 0 , variant
: variant
}
262 fn close(&mut self) -> IoResult
<()> {
263 try!(self.socket
.close_read());
264 try!(self.socket
.close_write());
268 fn print(&self, prefix
: &str, s
: String
) {
269 println!("[{}] time: {}. {}", prefix
, self.current_timestamp
, s
);
272 /// Send a packet and wait for an answer synchronously.
273 fn send_with_result(&mut self, p
: PacketType
) -> IoResult
<ReadingResult
> {
280 /// Send arbitrary data and wait for an answer synchronously.
281 /// Do not increment the current timestamp.
282 pub fn send_raw_with_result(&mut self, p
: &[u8]) -> IoResult
<ReadingResult
> {
283 self.socket
.set_timeout(DEFAULT_TIMEOUT
);
284 match self.socket
.write(p
) {
290 fn send(&mut self, p
: PacketType
) -> IoResult
<()> {
291 self.socket
.set_timeout(DEFAULT_TIMEOUT
);
292 self.current_timestamp
+= 1;
293 match (Packet
{ t
: p
, timestamp
: self.current_timestamp
}).write(&mut self.socket
, self.variant
) {
294 Err(packet
::WriteIOError(e
)) => Err(e
),
299 fn read(&mut self) -> ReadingResult
{
300 fn send_error(ep
: &mut EndPoint
, error_type
: packet
::ErrorType
) {
301 match ep
.send(Error(error_type
)) {
302 Err(e
) => println!("Unable to send error packet: {}", e
),
307 self.socket
.set_timeout(DEFAULT_TIMEOUT
);
308 match Packet
::read(&mut self.socket
, self.variant
) {
310 if packet
.timestamp
<= self.current_timestamp
{
311 println!("Error, timestamp mismatch, current timestamp: {}, packet received: {}", self.current_timestamp
, packet
);
312 Err(packet
::InvalidTimestampError
)
314 self.current_timestamp
= packet
.timestamp
+ 1;
318 e @
Err(packet
::PaddingError
) => {
319 self.current_timestamp
+= 1;
320 send_error(self, packet
::CryptError
);
323 e @
Err(packet
::MACMismatchError
) => {
324 self.current_timestamp
+= 1;
325 send_error(self, packet
::AuthError
);