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
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use std::io::net::udp::UdpSocket;
use std::io::net::ip::SocketAddr;
use std::io::{IoResult, IoError, OtherIoError, TimedOut};
use std::io::Timer;
use std::sync::mpsc::{Sender, Receiver, TryRecvError, channel, Select};
use std::thread::Thread;
use std::time::duration::Duration;
use packet::{Packet, PacketType, TaskCommand};
use shared::{ConnectionConfig, SequenceManager};
use time::now;


/**
 * The current state of a connection
 */
pub enum ConnectionState {
    Disconnected,
    Connecting,
    Connected
}

/**
 * A Poll attempt failed for some reason
 */
pub enum PollFailResult {
    Empty,
    Disconnected
}

fn reader_process(mut reader: UdpSocket, send: Sender<Packet>, recv: Receiver<TaskCommand>, target_addr: SocketAddr, protocol_id: u32, timeout_period: Duration) {
    let mut buf = [0; 1024];
    reader.set_timeout(Some(1000));

    let mut expires = now().to_timespec().sec + timeout_period.num_seconds();

    loop {
        match reader.recv_from(&mut buf) {
            Ok((amt, src)) => {
                if src == target_addr {
                    match Packet::deserialize(buf.slice_to(amt)) {
                        Ok(packet) => {
                            if packet.protocol_id == protocol_id {
                                match send.send(packet) {
                                    Ok(()) => {
                                        expires = now().to_timespec().sec + timeout_period.num_seconds();
                                    },
                                    Err(_) => {
                                        //Other end hung up, we should give up
                                        break;
                                    }
                                }
                            }
                        },
                        Err(_) => ()
                    }
                }
            },
            Err(e) => {
                match e.kind {
                    TimedOut => {
                        match recv.try_recv() {
                            Ok(TaskCommand::Disconnect) => {
                                break;
                            },
                            Err(TryRecvError::Disconnected) => {
                                break;
                            },
                            Err(TryRecvError::Empty) => {
                                //Keep going
                            }
                        }
                    },
                    _ => ()
                }
            }
        };
        if now().to_timespec().sec > expires {
            //FIXME: Need a nicer way of ignoring failure for this
            //FIXME: Bad sequence ID!
            match send.send(Packet::disconnect(protocol_id, 0)) {
                _ => break
            }
        }
    }
}

fn writer_process(mut writer: UdpSocket, recv: Receiver<Packet>, target_addr: SocketAddr) {
    for msg in recv.iter() {
        match msg.serialize() {
            Ok(msg) => {
                match writer.send_to(msg.as_slice(), target_addr) {
                    Ok(()) => (),
                    Err(e) => println!("Error sending data - {}", e)
                }
            },
            Err(_) => ()
        }
    }
}

/**
 * Clientside implementation of UDP networking
 */
pub struct Client <T> {
    ///The socket we should use locally
    pub addr: SocketAddr,
    ///The socket of the server we intent to connect to
    pub target_addr: SocketAddr,
    ///Basic configuration for connecting
    pub config: ConnectionConfig<T>,

    ///What's the current state of our connection
    pub connection_state: ConnectionState,

    reader_send: Sender<TaskCommand>,
    reader_receive: Receiver<Packet>,
    writer_send: Sender<Packet>,

    sequence_manager: SequenceManager
}

/**
 * Additional configuration options for a Client connection
 */
pub struct ClientConnectionConfig {
    ///How many times should we ask for a connection before giving up?
    pub max_connect_retries: u32,
    ///How long should each connection request await an answer?
    pub connect_attempt_timeout: Duration
}

impl ClientConnectionConfig {

    /**
     * Create a new ClientConnectionConfig object
     */
    pub fn new(max_connect_retries: u32, connect_attempt_timeout: Duration) -> ClientConnectionConfig {
        ClientConnectionConfig {
            max_connect_retries: max_connect_retries,
            connect_attempt_timeout: connect_attempt_timeout
        }
    }
}

impl <T> Client <T> {

    /**
     * Connect our Client to a target Server.
     * Will block until either a valid connection is made, or we give up
     */
    pub fn connect(addr: SocketAddr, target_addr: SocketAddr, config: ConnectionConfig<T>, client_connection_config: ClientConnectionConfig) -> IoResult<Client<T>> {
         match UdpSocket::bind(addr) {
            Ok(reader) => {
                let writer = reader.clone();

                let (reader_send, reader_task_receive) = channel();
                let (reader_task_send, reader_receive) = channel();

                let protocol_id = config.protocol_id;
                let timeout_period = config.timeout_period;

                Thread::spawn(move || {
                    reader_process(reader, reader_task_send, reader_task_receive, target_addr, protocol_id, timeout_period);
                });

                let (writer_send, writer_task_receive) = channel();

                Thread::spawn(move || {
                    writer_process(writer, writer_task_receive, target_addr);
                });

                let mut client = Client {
                    addr: addr,
                    target_addr: target_addr,
                    reader_send: reader_send,
                    reader_receive: reader_receive,
                    writer_send: writer_send,
                    connection_state: ConnectionState::Disconnected,
                    config: config,
                    sequence_manager: SequenceManager::new()
                };

                if client.connection_dance(client_connection_config.max_connect_retries, client_connection_config.connect_attempt_timeout) {
                    Ok(client)
                } else {
                    Err(IoError {
                        kind: OtherIoError,
                        desc: "Failed to connect",
                        detail: None
                    })
                }
            }
            Err(e) => Err(e)
        }
    }

    /**
     * A blocking connection request
     */
    fn connection_dance(&mut self, max_attempts: u32, timeout: Duration) -> bool {
        self.connection_state = ConnectionState::Connecting;
        let mut timer = Timer::new().unwrap();
        let mut attempts = 0u32;

        while attempts < max_attempts && match self.connection_state { ConnectionState::Connecting => true, _ => false } {
            self.writer_send.send(Packet::connect(self.config.protocol_id, self.sequence_manager.next_sequence_id()));

            let timeout = timer.oneshot(timeout);

            //FIXME: Replace with the select! macro when it starts working
            let sel = Select::new();
            let mut reader = sel.handle(&self.reader_receive);
            let mut timeout = sel.handle(&timeout);
            unsafe { reader.add(); timeout.add(); }
            let ret = sel.wait();
            if ret == reader.id() {
                match self.reader_receive.recv() {
                    Ok(packet) => {
                        match packet.packet_type {
                            PacketType::Accept => {
                                self.connection_state = ConnectionState::Connected;
                            }
                            PacketType::Reject => {
                                self.connection_state = ConnectionState::Disconnected;
                            }
                            PacketType::Disconnect => {
                                self.connection_state = ConnectionState::Disconnected;
                            }
                            _ => (),
                        }
                    },
                    Err(_) => {
                        panic!("Reader disconnected while connection dancing."); //FIXME: There's gotta be a better way to do this
                    }
                }
            } else if ret == timeout.id() {
                let _ = timeout.recv();
                attempts += 1;
            } else {
                unreachable!();
            }
        }

        match self.connection_state {
            ConnectionState::Connecting => {
                self.connection_state = ConnectionState::Disconnected;
                false
            },
            ConnectionState::Disconnected => false,
            ConnectionState::Connected => {
                true
            }
        }
    }

    /**
     * Pop the last event off of our comms queue, if any
     */
    pub fn poll(&mut self) -> Result<T, PollFailResult> {
        match self.connection_state {
            ConnectionState::Connected => {
                let mut result = Err(PollFailResult::Empty);
                loop {
                    match self.reader_receive.try_recv() {
                        Ok(value) => {
                            match value.packet_type {
                                PacketType::Disconnect => {
                                    self.connection_state = ConnectionState::Disconnected;
                                    result = Err(PollFailResult::Disconnected);
                                    break;
                                },
                                PacketType::Message => {
                                    //Are we expecting this packet?
                                    if self.sequence_manager.packet_is_newer(value.sequence_id) {
                                        self.sequence_manager.set_newest_packet(value.sequence_id);
                                        match (self.config.packet_deserializer)(&value.packet_content.unwrap()) {
                                            Some(deserialized) => {
                                                result = Ok(deserialized);
                                                break;
                                            },
                                            None => ()
                                        }
                                    }
                                },
                                _ => ()
                            }
                        },
                        _ => break
                    };
                }
                result
            },
            _ => Err(PollFailResult::Disconnected)
        }
    }

    /**
     * Send a packet to the server
     */
    pub fn send(&mut self, packet: &T) {
        match self.writer_send.send(Packet::message(self.config.protocol_id, self.sequence_manager.next_sequence_id(), (self.config.packet_serializer)(packet))) {
            _ => () //FIXME: We shouldn't discard errors here
        }
    }
}

#[unsafe_destructor]
impl<T> Drop for Client<T> {

    fn drop(&mut self) {
        match (self.reader_send.send(TaskCommand::Disconnect),  self.writer_send.send(Packet::disconnect(self.config.protocol_id, self.sequence_manager.next_sequence_id()))) {
            _ => () //FIXME: This is a bad way of discarding errors
        }
    }
}