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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*
 * Copyright 2020, Ulf Lilleengen
 * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
 */

//! The conn module contains basic primitives for establishing and accepting AMQP connections and performing the initial handshake. Once handshake is complete, the connection can be used to send and receive frames.

use log::{debug, trace};
use std::time::Duration;
use std::time::Instant;
use std::vec::Vec;

use crate::error::*;
use crate::framing::*;
use crate::sasl::*;
use crate::transport::*;

#[derive(Debug, Clone)]
pub struct ConnectionOptions {
    pub username: Option<String>,
    pub password: Option<String>,
    pub sasl_mechanism: Option<SaslMechanism>,
}

impl ConnectionOptions {
    #[allow(clippy::new_without_default)]
    pub fn new() -> ConnectionOptions {
        ConnectionOptions {
            username: None,
            password: None,
            sasl_mechanism: None,
        }
    }

    pub fn sasl_mechanism(mut self, mechanism: SaslMechanism) -> Self {
        self.sasl_mechanism = Some(mechanism);
        self
    }

    pub fn username(mut self, username: &str) -> Self {
        self.username = Some(username.to_string());
        self
    }

    pub fn password(mut self, password: &str) -> Self {
        self.password = Some(password.to_string());
        self
    }
}

/*
// TODO: Listener
#[derive(Debug)]
pub struct ListenOptions {}
*/

#[derive(Debug)]
pub struct Connection<N: Network> {
    sasl: Option<Sasl>,
    state: ConnectionState,
    transport: Transport<N>,
    tx_frames: Vec<Frame>,
    header_sent: bool,
}

pub type ChannelId = u16;
pub type HandleId = u32;

#[derive(Debug)]
enum ConnectionState {
    Start,
    // TODO: Listener
    // StartWait,
    Sasl,
    Opened,
    Closed,
}

const AMQP_10_HEADER: ProtocolHeader = ProtocolHeader::AMQP(Version(1, 0, 0));
const SASL_10_HEADER: ProtocolHeader = ProtocolHeader::SASL(Version(1, 0, 0));

pub fn connect<N: Network>(
    transport: Transport<N>,
    opts: ConnectionOptions,
) -> Result<Connection<N>> {
    let mut connection = Connection::new(transport);
    if opts.username.is_some() || opts.password.is_some() || opts.sasl_mechanism.is_some() {
        connection.sasl = Some(Sasl {
            role: SaslRole::Client(SaslClient {
                mechanism: opts.sasl_mechanism.unwrap_or(SaslMechanism::Plain),
                username: opts.username,
                password: opts.password,
            }),
            state: SaslState::InProgress,
        });
    }
    connection.state = ConnectionState::Start;

    Ok(connection)
}

/*
pub struct Listener {
    pub listener: TcpListener,
    pub sasl_mechanisms: Option<Vec<SaslMechanism>>,
}

pub fn listen(host: &str, port: u16, _opts: ListenOptions) -> Result<Listener> {
    let addr = format!("{}:{}", host, port).parse().unwrap();
    let listener = TcpListener::bind(addr)?;
    Ok(Listener {
        listener,
        sasl_mechanisms: None,
    })
}

impl Listener {
    pub fn accept(&mut self) -> Result<Connection> {
        let (stream, _addr) = self.listener.accept()?;
        let transport: Transport = Transport::new(stream, 1024)?;

        let mut connection = Connection::new(transport);
        connection.state = ConnectionState::StartWait;
        Ok(connection)
    }
}
*/

impl<N: Network> Connection<N> {
    pub fn new(transport: Transport<N>) -> Connection<N> {
        Connection {
            transport,
            state: ConnectionState::Start,
            sasl: None,
            tx_frames: Vec::new(),
            header_sent: false,
        }
    }

    pub fn open(&mut self, open: Open) -> Result<()> {
        self.tx_frames.push(Frame::AMQP(AmqpFrame {
            channel: 0,
            performative: Some(Performative::Open(open)),
            payload: None,
        }));
        Ok(())
    }

    pub fn begin(&mut self, channel: ChannelId, begin: Begin) -> Result<()> {
        self.tx_frames.push(Frame::AMQP(AmqpFrame {
            channel: channel as u16,
            performative: Some(Performative::Begin(begin)),
            payload: None,
        }));
        Ok(())
    }

    pub fn attach(&mut self, channel: ChannelId, attach: Attach) -> Result<()> {
        self.tx_frames.push(Frame::AMQP(AmqpFrame {
            channel: channel as u16,
            performative: Some(Performative::Attach(attach)),
            payload: None,
        }));
        Ok(())
    }

    pub fn flow(&mut self, channel: ChannelId, flow: Flow) -> Result<()> {
        self.tx_frames.push(Frame::AMQP(AmqpFrame {
            channel: channel as u16,
            performative: Some(Performative::Flow(flow)),
            payload: None,
        }));
        Ok(())
    }

    pub fn transfer(
        &mut self,
        channel: ChannelId,
        transfer: Transfer,
        payload: Option<Vec<u8>>,
    ) -> Result<()> {
        self.tx_frames.push(Frame::AMQP(AmqpFrame {
            channel: channel as u16,
            performative: Some(Performative::Transfer(transfer)),
            payload,
        }));
        Ok(())
    }

    pub fn disposition(&mut self, channel: ChannelId, disposition: Disposition) -> Result<()> {
        self.tx_frames.push(Frame::AMQP(AmqpFrame {
            channel: channel as u16,
            performative: Some(Performative::Disposition(disposition)),
            payload: None,
        }));
        Ok(())
    }

    pub fn keepalive(&mut self, remote_idle_timeout: Duration, now: Instant) -> Result<Instant> {
        if remote_idle_timeout.as_millis() > 0 {
            trace!(
                "Remote idle timeout millis: {:?}. Last sent: {:?}",
                remote_idle_timeout.as_millis(),
                now - self.transport.last_sent()
            );

            if now - self.transport.last_sent() >= remote_idle_timeout {
                self.tx_frames.push(Frame::AMQP(AmqpFrame {
                    channel: 0,
                    performative: None,
                    payload: None,
                }));
            }
        }
        Ok(self.transport.last_received())
    }

    pub fn detach(&mut self, channel: ChannelId, detach: Detach) -> Result<()> {
        self.tx_frames.push(Frame::AMQP(AmqpFrame {
            channel: channel as u16,
            performative: Some(Performative::Detach(detach)),
            payload: None,
        }));
        Ok(())
    }

    pub fn end(&mut self, channel: ChannelId, end: End) -> Result<()> {
        self.tx_frames.push(Frame::AMQP(AmqpFrame {
            channel: channel as u16,
            performative: Some(Performative::End(end)),
            payload: None,
        }));
        Ok(())
    }

    pub fn close(&mut self, close: Close) -> Result<()> {
        self.tx_frames.push(Frame::AMQP(AmqpFrame {
            channel: 0,
            performative: Some(Performative::Close(close)),
            payload: None,
        }));
        Ok(())
    }

    pub fn shutdown(&mut self) -> Result<()> {
        self.transport.close()
    }

    fn skip_sasl(&self) -> bool {
        self.sasl.is_none() || self.sasl.as_ref().unwrap().is_done()
    }

    // Write outgoing frames
    pub fn flush(&mut self) -> Result<()> {
        match self.state {
            ConnectionState::Opened | ConnectionState::Closed => {
                for frame in self.tx_frames.drain(..) {
                    debug!("TX {:?}", frame);
                    self.transport.write_frame(&frame)?;
                }
            }
            _ => {}
        }
        Ok(())
    }

    pub fn transport(&mut self) -> &mut Transport<N> {
        &mut self.transport
    }

    pub fn process(&mut self, frames: &mut Vec<Frame>) -> Result<()> {
        match self.state {
            ConnectionState::Start => {
                if !self.header_sent {
                    if self.skip_sasl() {
                        self.transport.write_protocol_header(&AMQP_10_HEADER)?;
                    } else {
                        self.transport.write_protocol_header(&SASL_10_HEADER)?;
                    }
                    self.header_sent = true;
                }
                self.transport.flush()?;
                let header = self.transport.read_protocol_header()?;
                if let Some(header) = header {
                    match header {
                        SASL_10_HEADER if self.sasl.is_some() => {
                            self.state = ConnectionState::Sasl;
                        }
                        AMQP_10_HEADER if self.skip_sasl() => {
                            self.state = ConnectionState::Opened;
                        }
                        _ => {
                            self.transport.close()?;
                            self.state = ConnectionState::Closed;
                        }
                    }
                }
            }
            /*
            TODO: Listener
            ConnectionState::StartWait => {
                let header = self.transport.read_protocol_header()?;
                if let Some(header) = header {
                    match header {
                        SASL_10_HEADER if self.sasl.is_some() => {
                            self.transport.write_protocol_header(&SASL_10_HEADER)?;
                            self.state = ConnectionState::Sasl;
                            self.transport.flush()?;
                        }
                        AMQP_10_HEADER if self.skip_sasl() => {
                            self.transport.write_protocol_header(&AMQP_10_HEADER)?;
                            self.state = ConnectionState::Opened;
                            self.transport.flush()?;
                        }
                        _ => {
                            self.transport.write_protocol_header(&AMQP_10_HEADER)?;
                            self.state = ConnectionState::Closed;
                            self.transport.flush()?;
                            self.transport.close()?;
                        }
                    }
                }
            }
            */
            ConnectionState::Sasl => {
                let sasl = self.sasl.as_mut().unwrap();
                match sasl.state {
                    SaslState::Success => {
                        self.header_sent = false;
                        self.state = ConnectionState::Start;
                    }
                    SaslState::Failed => {
                        self.transport.close()?;
                        self.state = ConnectionState::Closed;
                    }
                    SaslState::InProgress => {
                        sasl.perform_handshake(None, &mut self.transport)?;
                    }
                }
            }
            ConnectionState::Opened => {
                let frame = self.transport.read_frame()?;
                frames.push(frame);
            }
            ConnectionState::Closed => {
                return Err(AmqpError::amqp_error(
                    condition::connection::CONNECTION_FORCED,
                    None,
                ));
            }
        }
        Ok(())
    }
}