aboutsummaryrefslogtreecommitdiff
path: root/src/client.rs
blob: 339415b57b577e96437277ca2d7785c8eb33059e (plain)
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
use std::io::{
    self,
    Write,
    Read,
    BufRead,
    BufReader,
};
use std::net::TcpStream;
use std::borrow::Cow::{ self, Borrowed, Owned };
use std::sync::{ Arc, RwLock };
use std::mem;
use std::cell::UnsafeCell;

use carboxyl::{ Stream, Sink };

use message::Message;
use command::Command;
use command::Command::*;
use reply::Reply;
use event::Event;
use ::{ DEBUG, Result, IrscError };

#[cfg(feature = "ssl")]
use openssl::ssl::{ Ssl, SslContext, SslMethod, SslStream };

/// Yes, I don't like the name either, but it's private, so...
enum StreamKind {
    Plain(TcpStream),
    #[cfg(feature = "ssl")]
    Ssl(SslStream<TcpStream>)
}

impl Write for StreamKind {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match *self {
            StreamKind::Plain(ref mut s) => s.write(buf),
            #[cfg(feature = "ssl")]
            StreamKind::Ssl(ref mut s) => s.write(buf)
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match *self {
            StreamKind::Plain(ref mut s) => s.flush(),
            #[cfg(feature = "ssl")]
            StreamKind::Ssl(ref mut s) => s.flush()
        }
    }
}

impl Read for StreamKind {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match *self {
            StreamKind::Plain(ref mut s) => s.read(buf),
            #[cfg(feature = "ssl")]
            StreamKind::Ssl(ref mut s) => s.read(buf)
        }
    }
}

pub trait Client {
    fn send_message(&mut self, msg: Message) -> Result<()>;
    fn join(&mut self, channel: &str, password: Option<&str>) -> Result<()> {
        self.send_message(JOIN(vec![channel.into()], password.iter().map(|&p| p.into()).collect()).to_message())
    }

    fn msg(&mut self, to: &str, message: &str) -> Result<()> {
        self.send_message(PRIVMSG(to.into(), message.into()).to_message())
    }

    fn register(&mut self, nick: &str, user: &str, desc: &str, pass: Option<&str>) -> Result<()> {
        Result(if let Some(pass) = pass {
            self.send_message(PASS(pass.into()).to_message()).inner()
        } else { Ok(()) }
            .and_then(|_| self.send_message(NICK(nick.into()).to_message()).inner())
            .and_then(|_| self.send_message(USER(user.into(), Borrowed("0"), Borrowed("*"), desc.into()).to_message()).inner())
        )
    }

}

pub struct OwnedClient {
    stream: Option<StreamKind>,
    sink: Sink<Message>
}

impl OwnedClient {
    pub fn new() -> OwnedClient {
        OwnedClient {
            stream: None,
            sink: Sink::new()
        }
    }

    fn handle_event(&mut self, msg: &Message) {
        let _ = match Command::from_message(msg) {
            Some(PING(s1, s2)) => self.send(PONG(s1, s2)),
            _ => Result(Ok(()))
        };
    }

    pub fn connect(&mut self, host: &str, port: u16) -> Result<()> {
        let s = &mut self.stream;
        if s.is_some() { return Result(Err(IrscError::AlreadyConnected)) }
        *s = match TcpStream::connect((host, port)) {
            Ok(tcp) => Some(StreamKind::Plain(tcp)),
            Err(e) => return Result(Err(IrscError::Io(e)))
        };

        Result(Ok(()))
    }

    #[cfg(feature = "ssl")]
    pub fn connect_ssl(&mut self, host: &str, port: u16, ssl: Ssl) -> Result<()> {
        let s = &mut self.stream;
        if s.is_some() { return Result(Err(IrscError::AlreadyConnected)) };
        let tcp_stream = match TcpStream::connect((host, port)) {
            Ok(tcp) => Some(tcp),
            Err(e) => return Result(Err(IrscError::Io(e)))
        };

        match tcp_stream.map(|tcp| SslStream::new_from(ssl, tcp)) {
            Some(Ok(ssl_stream)) => {
                *s = Some(StreamKind::Ssl(ssl_stream));
                Result(Ok(()))
            },
            Some(Err(ssl_error)) => Result(Err(IrscError::Ssl(ssl_error))),
            None => Result(Err(IrscError::NotConnected))
        }
    }

    #[inline]
    fn send_raw(&mut self, s: &str) -> Result<()> {
        info!(">> {}", s);
        if DEBUG && s.len() > 512 {
            panic!("Message too long, kittens will die if this runs in release mode. Msg: {}", s)
        }

        Result(self.stream.as_mut()
            .ok_or(IrscError::NotConnected)
            .and_then(|mut stream| stream.write_all(s.as_bytes())
                                         .and_then(|_| stream.flush())
                                         .map_err(IrscError::Io)))
    }


    pub fn send(&mut self, cmd: Command) -> Result<()> {
        self.send_message(cmd.to_message())
    }

    pub fn listen_with_callback<F>(&mut self, on_event: F) -> Result<()>
    where F: Fn(&mut Client, &Message, Option<Event>) {
        let reader = BufReader::new(match self.stream {
            Some(StreamKind::Plain(ref s)) => StreamKind::Plain((*s).try_clone().unwrap()),
            #[cfg(feature = "ssl")]
            Some(StreamKind::Ssl(ref s)) => StreamKind::Ssl((*s).try_clone().unwrap()),
            None => return Result(Err(IrscError::NotConnected))
        });

        for raw_line in reader.lines() {
            let line = raw_line.as_ref().unwrap().parse();
            info!("<< {}", raw_line.unwrap());

            if let Ok(msg) = line {
                self.handle_event(&msg);

                // Try to parse the message into a Command or a Reply, and call back.
                let event = match Command::from_message(&msg) {
                    Some(m) => Some(Event::Command(m)),
                    None => match Reply::from_message(&msg) {
                        Some(r) => Some(Event::Reply(r)),
                        None => None
                    }
                };
                on_event(self, &msg, event);
            }
        }
        Result(Ok(()))
    }

    #[allow(mutable_transmutes)]
    fn listen_with_events(&self) -> Result<()> {
        let mut s: &mut OwnedClient = unsafe { mem::transmute(self) };
        let reader = BufReader::new(match self.stream {
            Some(StreamKind::Plain(ref s)) => StreamKind::Plain((*s).try_clone().unwrap()),
            #[cfg(feature = "ssl")]
            Some(StreamKind::Ssl(ref s)) => StreamKind::Ssl((*s).try_clone().unwrap()),
            None => return Result(Err(IrscError::NotConnected))
        });

        for raw_line in reader.lines() {
            let line = raw_line.as_ref().unwrap().parse();
            info!("<< {}", raw_line.unwrap());

            if let Ok(msg) = line {
                s.handle_event(&msg);
                self.sink.send(msg);
            }
        }
        Result(Ok(()))
    }

    pub fn into_shared(self) -> SharedClient {
        SharedClient {
            client: Arc::new(OwnedClientCell(UnsafeCell::new(self))),
        }
    }

    pub fn messages(&self) -> Stream<Message> { self.sink.stream() }
}

struct OwnedClientCell(UnsafeCell<OwnedClient>);
unsafe impl Sync for OwnedClientCell {}

impl Client for OwnedClient {
    fn send_message(&mut self, msg: Message) -> Result<()> {
        self.send_raw(&msg.to_string())
    }
}

#[derive(Clone)]
pub struct SharedClient {
    client: Arc<OwnedClientCell>,
}

impl SharedClient {
    pub fn messages(&self) -> Stream<(SharedClient, Message)> {
        let cl = SharedClient { client: self.client.clone() };
        unsafe { &*self.client.0.get() }.messages()
            .map(move |m| (cl.clone(), m))
    }

    pub fn events(&self) -> Stream<(SharedClient, Message, Event<'static>)> {
        self.messages().filter_map(|(cl, msg)| match Command::from_message(&msg) {
            Some(m) => Some((cl, msg.clone(), Event::Command(m.clone()).to_static())),
            None => match Reply::from_message(&msg) {
                Some(r) => Some((cl, msg.clone(), Event::Reply(r).to_static())),
                None => None
            }
        })
    }

    pub fn listen_with_events(&mut self) -> Result<()> {
        unsafe { &*self.client.0.get() }.listen_with_events()
    }

    pub fn commands(&self) -> Stream<(SharedClient, Message, Command<'static>)> {
        self.messages().filter_map(|(cl, msg)| match Command::from_message(&msg) {
            Some(m) => Some((cl, msg.clone(), m.to_static())),
            None => None
        })
    }

    pub fn replies(&self) -> Stream<(SharedClient, Message, Reply<'static>)> {
        self.messages().filter_map(|(cl, msg)| match Reply::from_message(&msg) {
            Some(m) => Some((cl, msg.clone(), m.to_static())),
            None => None
        })
    }
}

impl Client for SharedClient {
    fn send_message(&mut self, msg: Message) -> Result<()> {
        unsafe { &mut *self.client.0.get() }.send_raw(&msg.to_string())
    }
}