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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! Frame data types for describing the wire format abstractly.
//!
//! In this context, we use "client" to refer to the initiator that makes an
//! outgoing connection and "server" to refer to the responder that receives
//! an incoming connection.  This doesn't have to map onto high-level protocol
//! concepts in the consumer, naturally.

use std::io;

use borsh::{BorshDeserialize, BorshSerialize};
use num_enum::{IntoPrimitive, TryFromPrimitive};

use crate::topic;

#[derive(Clone, Debug)]
pub struct Frame {
    header: FrameHeader,
    body: FrameBody,
}

impl Frame {
    pub fn with_body(body: FrameBody) -> Self {
        Self {
            header: FrameHeader {
                // TODO determine how we specify flags
                flags: 0,
            },
            body,
        }
    }

    /// Gets the frame body.
    pub fn body(&self) -> &FrameBody {
        &self.body
    }

    /// Gets the frame type.
    pub fn ty(&self) -> FrameType {
        self.body.ty()
    }
}

#[derive(Clone, Debug)]
pub struct FrameHeader {
    flags: u16,
}

/// Flags sent along with a message payload to signal various conditions.
#[derive(Copy, Clone, Debug, Eq, PartialEq, BorshDeserialize, BorshSerialize)]
pub struct MsgFlags {
    /// If this closes the sending side of the channel (two close messages have
    /// to be sent to fully close it).
    pub close: bool,

    /// If this data is an unusual error condition.
    pub err: bool,
}

impl MsgFlags {
    /// New flagset with all unset.
    pub fn none() -> Self {
        Self {
            close: false,
            err: false,
        }
    }

    /// New flagset with only close set.
    pub fn close() -> Self {
        let mut this = Self::default();
        this.close = true;
        this
    }

    /// New flagset with just close set to a particular value.
    pub fn with_close(close: bool) -> Self {
        Self { close, err: false }
    }
}

impl Default for MsgFlags {
    fn default() -> Self {
        Self::none()
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
#[repr(u8)]
pub enum FrameType {
    /// Hello used to announce client to server.
    ClientHello = 0,

    /// Hello used to exchange protocols.
    ServerHello = 1,

    /// Finished authentication, picking a protocol.
    ClientFinish = 2,

    /// Open a new channel on a topic with some payload and possibly closing it.
    OpenChan = 3,

    /// Push data on a channel, also possibly closing it.
    PushChan = 4,

    /// Close a channel without sending any data.
    CloseChan = 5,

    /// Unconditional message that does not open a channel but does have a
    /// topic, which may or may not be able to handle it.  Can be used to send
    /// one-off messages that don't need the overhead of initing a new channel
    /// only to close it and require the other side ack the closure.
    Notification = 6,

    /// Graceful goodbye with some reason.
    Goodbye = 7,

    /// Queries the protocols a server reports.
    ClientQuery = 16,

    /// Response with the protocols the server reports.
    ServerDump = 17,

    /// Ping with data.
    Ping = 252,

    /// Pong with data.
    Pong = 253,
}

/// Roughly parsed frame body.
#[derive(Clone, Debug, BorshDeserialize, BorshSerialize)]
pub enum FrameBody {
    ClientHello(ClientHelloData),
    ServerHello(ServerHelloData),
    ClientFinish(ClientFinishData),
    OpenChan(OpenData),
    PushChan(PushData),
    CloseChan(CloseData),
    Notification(NotificationData),
    Goodbye(GoodbyeData),
    ClientQuery(ClientQueryData),
    ServerDump(ServerDumpData),
    Ping(Vec<u8>),
    Pong(Vec<u8>),
}

impl FrameBody {
    /// Decodes an instance from a buf.
    pub fn from_buf(buf: &[u8]) -> Result<Self, io::Error> {
        borsh::from_slice(buf)
    }

    /// Encodes self into an existing vec.
    pub fn into_vec(&self, dest: &mut Vec<u8>) -> Result<(), io::Error> {
        borsh::to_writer(dest, self)
    }

    /// Encodes self to a new vec.
    pub fn to_vec(&self) -> Result<Vec<u8>, io::Error> {
        borsh::to_vec(self)
    }

    pub fn ty(&self) -> FrameType {
        match self {
            Self::ClientHello(_) => FrameType::ClientHello,
            Self::ServerHello(_) => FrameType::ServerHello,
            Self::ClientFinish(_) => FrameType::ClientFinish,
            Self::OpenChan(_) => FrameType::OpenChan,
            Self::PushChan(_) => FrameType::PushChan,
            Self::CloseChan(_) => FrameType::CloseChan,
            Self::Notification(_) => FrameType::Notification,
            Self::Goodbye(_) => FrameType::Goodbye,
            Self::ClientQuery(_) => FrameType::ClientQuery,
            Self::ServerDump(_) => FrameType::ServerDump,
            Self::Ping(_) => FrameType::Ping,
            Self::Pong(_) => FrameType::Pong,
        }
    }
}

/// Initial message client sends to server to begin identifying itself and pick
/// the protocol.
#[derive(Clone, Debug, BorshDeserialize, BorshSerialize)]
pub struct ClientHelloData {
    /// Client brand.
    agent: String,

    /// Protocol we're picking.
    protocol: topic::Topic,

    /// If we want an identity challenge.  This also indicates that the client
    /// wants to identify itself too.
    server_challenge: Option<ChallengeData>,
}

impl ClientHelloData {
    pub fn new(
        agent: String,
        protocol: topic::Topic,
        server_challenge: Option<ChallengeData>,
    ) -> Self {
        Self {
            agent,
            protocol,
            server_challenge,
        }
    }

    pub fn agent(&self) -> &str {
        &self.agent
    }

    pub fn protocol(&self) -> topic::Topic {
        self.protocol
    }

    pub fn challenge(&self) -> Option<&ChallengeData> {
        self.server_challenge.as_ref()
    }
}

/// Acknowledgement of the `ClientHello` and the choice of protocol.  Includes
/// challenges and responses as necessary.
#[derive(Clone, Debug, BorshDeserialize, BorshSerialize)]
pub struct ServerHelloData {
    /// Server brand.
    agent: String,

    /// Response if the client asked for it and the server is giving it.
    response: Option<ResponseData>,

    /// Challenge if `ClientHello`'s `want_challenge` is set.
    challenge: Option<ChallengeData>,
}

impl ServerHelloData {
    pub fn new(
        agent: String,
        response: Option<ResponseData>,
        challenge: Option<ChallengeData>,
    ) -> Self {
        Self {
            agent,
            response,
            challenge,
        }
    }

    pub fn agent(&self) -> &str {
        &self.agent
    }

    pub fn response(&self) -> Option<&ResponseData> {
        self.response.as_ref()
    }

    pub fn challenge(&self) -> Option<&ChallengeData> {
        self.challenge.as_ref()
    }
}

/// Finishes the client's side of the handshake if we're identifying ourselves.
/// This is omitted if we're not doing the full self-identification handshake.
#[derive(Clone, Debug, BorshDeserialize, BorshSerialize)]
pub struct ClientFinishData {
    response: Option<ResponseData>,
}

impl ClientFinishData {
    pub fn new(response: Option<ResponseData>) -> Self {
        Self { response }
    }

    pub fn response(&self) -> Option<&ResponseData> {
        self.response.as_ref()
    }
}

/// Data passed when opening a new channel.  Channel ID is implicit.
#[derive(Clone, Debug, BorshDeserialize, BorshSerialize)]
pub struct OpenData {
    /// Topic of the new channel we're opening.
    topic: topic::Topic,

    /// Payload flags.
    flags: MsgFlags,

    /// Initial message.
    payload: Vec<u8>,
}

impl OpenData {
    pub fn new(topic: topic::Topic, flags: MsgFlags, payload: Vec<u8>) -> Self {
        Self {
            topic,
            flags,
            payload,
        }
    }

    pub fn topic(&self) -> topic::Topic {
        self.topic
    }

    pub fn flags(&self) -> &MsgFlags {
        &self.flags
    }

    pub fn close(&self) -> bool {
        self.flags.close
    }

    pub fn payload(&self) -> &[u8] {
        &self.payload
    }

    pub fn into_payload(self) -> Vec<u8> {
        self.payload
    }
}

/// Data passed when pushing data on a channel.
#[derive(Clone, Debug, BorshDeserialize, BorshSerialize)]
pub struct PushData {
    /// Channel ID.
    chan_id: u32,

    /// Payload flags.
    flags: MsgFlags,

    /// Initial message.
    payload: Vec<u8>,
}

impl PushData {
    pub fn new(chan_id: u32, flags: MsgFlags, payload: Vec<u8>) -> Self {
        Self {
            chan_id,
            flags,
            payload,
        }
    }

    pub fn chan_id(&self) -> u32 {
        self.chan_id
    }

    pub fn flags(&self) -> &MsgFlags {
        &self.flags
    }

    pub fn close(&self) -> bool {
        self.flags.close
    }

    pub fn payload(&self) -> &[u8] {
        &self.payload
    }

    pub fn into_payload(self) -> Vec<u8> {
        self.payload
    }
}

#[derive(Clone, Debug, BorshDeserialize, BorshSerialize)]
pub struct CloseData {
    chan_id: u32,
}

impl CloseData {
    pub fn new(chan_id: u32) -> Self {
        Self { chan_id }
    }

    pub fn chan_id(&self) -> u32 {
        self.chan_id
    }
}

#[derive(Clone, Debug, BorshDeserialize, BorshSerialize)]
pub struct NotificationData {
    topic: topic::Topic,
    payload: Vec<u8>,
}

impl NotificationData {
    pub fn new(topic: topic::Topic, payload: Vec<u8>) -> Self {
        Self { topic, payload }
    }

    pub fn topic(&self) -> topic::Topic {
        self.topic
    }

    pub fn payload(&self) -> &[u8] {
        &self.payload
    }

    pub fn into_payload(self) -> Vec<u8> {
        self.payload
    }
}

/// Sent before closing a connection.
#[derive(Clone, Debug, BorshDeserialize, BorshSerialize)]
pub struct GoodbyeData {
    /// Code, 0 is ok.  Any other value is an application-defined error code.
    code: i16,

    /// Human-readable message.
    msg: String,
}

impl GoodbyeData {
    pub fn new(code: i16, msg: String) -> Self {
        Self { code, msg }
    }

    pub fn code(&self) -> i16 {
        self.code
    }

    pub fn msg(&self) -> &str {
        &self.msg
    }
}

/// Challenge data used when identifying self.  This includes a nonce that
/// we'll use with another nonce for the challenge.
#[derive(Copy, Clone, Debug, BorshDeserialize, BorshSerialize)]
pub struct ChallengeData {
    nonce: [u8; 16],
}

impl ChallengeData {
    pub fn from_nonce_buf(nonce: [u8; 16]) -> Self {
        Self { nonce }
    }

    pub fn nonce(&self) -> &[u8; 16] {
        &self.nonce
    }
}

/// Protocol-specific response message, which we expect to be a signature and
/// maybe the also the pubkey we're identifying ourselves as.
#[derive(Clone, Debug, BorshDeserialize, BorshSerialize)]
pub struct ResponseData {
    data: Vec<u8>,
}

impl ResponseData {
    pub fn new(data: Vec<u8>) -> Self {
        Self { data }
    }

    pub fn from_buf(buf: &[u8]) -> Self {
        Self::new(buf.to_vec())
    }

    pub fn data(&self) -> &[u8] {
        &self.data
    }
}

/// Query for the protocols the server supports.
#[derive(Clone, Debug, BorshDeserialize, BorshSerialize)]
pub struct ClientQueryData {
    /// Client brand.
    agent: String,
}

impl ClientQueryData {
    pub fn new(agent: String) -> Self {
        Self { agent }
    }
}

/// Response to the query of the protocols the server supports.
#[derive(Clone, Debug, BorshDeserialize, BorshSerialize)]
pub struct ServerDumpData {
    /// Server brand.
    agent: String,

    /// Protocols the server supports.
    protocols: Vec<topic::Topic>,
}

impl ServerDumpData {
    pub fn new(agent: String, protocols: Vec<topic::Topic>) -> Self {
        Self { agent, protocols }
    }

    pub fn agent(&self) -> &str {
        &self.agent
    }

    pub fn protocols(&self) -> &[topic::Topic] {
        &self.protocols
    }
}

/// Viewpoint-agnostic side of a channel, where client is generically the
/// initator and server is generically the acceptor.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Side {
    Client,
    Server,
}

/// Describes what auth relationship we want to set up with the server.  This
/// ignores any authentication that may be provided by the underlying transport.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum AuthIntent {
    /// Neither side is doing any authentication.
    Neither,

    /// Only the client (initiator) authenticates to the server.
    ClientOnly,

    /// Only the server (acceptor) authenticates to the client.
    ServerOnly,

    /// Both sides of the connection authenticate with each other.
    Mutual,
}

impl AuthIntent {
    /// Gets if the side in question should sign, given the signing intent.
    pub fn should_sign(&self, side: Side) -> bool {
        match (self, side) {
            (Self::ClientOnly | Self::Mutual, Side::Client) => true,
            (Self::ServerOnly | Self::Mutual, Side::Server) => true,
            _ => false,
        }
    }

    pub fn should_exchange_chals(&self) -> bool {
        !matches!(self, Self::Neither)
    }
}