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
//
// Copyright (C) 2018 Kubos Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

use super::Message;
use crate::error::ProtocolError;
use serde_cbor::Value;
use std::slice::Iter;

/// Parse out just the channel ID from a message
pub fn parse_channel_id(message: &Value) -> Result<u32, ProtocolError> {
    let data = match message {
        Value::Array(val) => val.to_owned(),
        _ => {
            return Err(ProtocolError::MessageParseError {
                err: "Data not an array".to_owned(),
            });
        }
    };

    let mut pieces = data.iter();

    let first_param: Value = pieces
        .next()
        .ok_or(ProtocolError::MessageParseError {
            err: "No contents".to_owned(),
        })?
        .to_owned();

    if let Value::U64(channel_id) = first_param {
        Ok(channel_id as u32)
    } else {
        Err(ProtocolError::MessageParseError {
            err: "No channel ID found".to_owned(),
        })
    }
}

pub fn parse_message(message: Value) -> Result<Message, ProtocolError> {
    let raw = match message {
        Value::Array(val) => val.to_owned(),
        _ => {
            return Err(ProtocolError::MessageParseError {
                err: "Data not an array".to_owned(),
            });
        }
    };

    let mut pieces = raw.iter();

    let channel_param: Value = pieces
        .next()
        .ok_or(ProtocolError::MessageParseError {
            err: "No contents".to_owned(),
        })?
        .to_owned();

    if let Value::U64(channel) = channel_param {
        let channel_id = channel as u32;
        if let Some(msg) = parse_cleanup_request(channel_id, pieces.to_owned())? {
            return Ok(msg);
        }
        if let Some(msg) = parse_export_request(channel_id, pieces.to_owned())? {
            return Ok(msg);
        }
        if let Some(msg) = parse_import_request(channel_id, pieces.to_owned())? {
            return Ok(msg);
        }
        if let Some(msg) = parse_success_receive(channel_id, pieces.to_owned())? {
            return Ok(msg);
        }
        if let Some(msg) = parse_success_transmit(channel_id, pieces.to_owned())? {
            return Ok(msg);
        }
        if let Some(msg) = parse_bad_op(channel_id, pieces.to_owned())? {
            return Ok(msg);
        }
        if let Some(msg) = parse_ack(channel_id, pieces.to_owned())? {
            return Ok(msg);
        }
        if let Some(msg) = parse_nak(channel_id, pieces.to_owned())? {
            return Ok(msg);
        }
        if let Some(msg) = parse_chunk(channel_id, pieces.to_owned())? {
            return Ok(msg);
        }
        if let Some(msg) = parse_sync(channel_id, pieces.to_owned())? {
            return Ok(msg);
        }
    }

    Err(ProtocolError::MessageParseError {
        err: "No message found".to_owned(),
    })
}

// Parse out cleanup request
// { channel_id, "cleanup", [hash] }
pub fn parse_cleanup_request(
    channel_id: u32,
    mut pieces: Iter<Value>,
) -> Result<Option<Message>, ProtocolError> {
    if let Some(Value::String(op)) = pieces.next() {
        if op == "cleanup" {
            match pieces.next() {
                Some(Value::String(hash)) => {
                    return Ok(Some(Message::Cleanup(channel_id, Some(hash.to_owned()))));
                }
                Some(Value::Null) => return Ok(Some(Message::Cleanup(channel_id, None))),
                None => return Ok(Some(Message::Cleanup(channel_id, None))),
                _ => {
                    return Err(ProtocolError::MissingParam(
                        "cleanup".to_owned(),
                        "hash".to_owned(),
                    ));
                }
            }
        }
    }

    Ok(None)
}

// Parse out export request
// { channel_id, "export", hash, path, [, mode] }
pub fn parse_export_request(
    channel_id: u32,
    mut pieces: Iter<Value>,
) -> Result<Option<Message>, ProtocolError> {
    if let Some(Value::String(op)) = pieces.next() {
        if op == "export" {
            let hash = match pieces.next().ok_or_else(|| {
                ProtocolError::MissingParam("export".to_owned(), "hash".to_owned())
            })? {
                Value::String(val) => val,
                _ => {
                    return Err(ProtocolError::InvalidParam(
                        "export".to_owned(),
                        "hash".to_owned(),
                    ));
                }
            };

            let path = match pieces.next().ok_or_else(|| {
                ProtocolError::MissingParam("export".to_owned(), "path".to_owned())
            })? {
                Value::String(val) => val,
                _ => {
                    return Err(ProtocolError::InvalidParam(
                        "export".to_owned(),
                        "path".to_owned(),
                    ));
                }
            };

            let mode = match pieces.next() {
                Some(Value::U64(num)) => Some(*num as u32),
                _ => None,
            };

            return Ok(Some(Message::ReqReceive(
                channel_id,
                hash.to_owned(),
                path.to_owned(),
                mode,
            )));
        }
    }

    Ok(None)
}

// Parse out import request
// { channel_id, "import", path }
pub fn parse_import_request(
    channel_id: u32,
    mut pieces: Iter<Value>,
) -> Result<Option<Message>, ProtocolError> {
    if let Some(Value::String(op)) = pieces.next() {
        if op == "import" {
            let path = match pieces.next().ok_or_else(|| {
                ProtocolError::MissingParam("export".to_owned(), "hash".to_owned())
            })? {
                Value::String(val) => val,
                _ => {
                    return Err(ProtocolError::InvalidParam(
                        "export".to_owned(),
                        "hash".to_owned(),
                    ));
                }
            };
            return Ok(Some(Message::ReqTransmit(
                channel_id as u32,
                path.to_owned(),
            )));
        }
    }

    Ok(None)
}

// Parse out success received message
// { channel_id, true }
pub fn parse_success_receive(
    channel_id: u32,
    mut pieces: Iter<Value>,
) -> Result<Option<Message>, ProtocolError> {
    if let Some(Value::Bool(true)) = pieces.next() {
        // Good - { channel_id, true, hash}
        if let Some(piece) = pieces.next() {
            let hash = match piece {
                Value::String(val) => val,
                _ => {
                    return Err(ProtocolError::InvalidParam(
                        "success_receive".to_owned(),
                        "hash".to_owned(),
                    ));
                }
            };

            if pieces.next().is_none() {
                return Ok(Some(Message::SuccessReceive(channel_id, hash.to_owned())));
            }
        }
    }

    Ok(None)
}

// Parse out success transmit message
// { channel_id, "true", ..values }
pub fn parse_success_transmit(
    channel_id: u32,
    mut pieces: Iter<Value>,
) -> Result<Option<Message>, ProtocolError> {
    if let Some(Value::Bool(true)) = pieces.next() {
        // Good - { channel_id, true, ...values }
        if let Some(piece) = pieces.next() {
            // It's a good result after an 'import' operation
            let hash = match piece {
                Value::String(val) => val,
                _ => {
                    return Err(ProtocolError::InvalidParam(
                        "success".to_owned(),
                        "hash".to_owned(),
                    ));
                }
            };

            let num_chunks = match pieces.next().ok_or_else(|| {
                ProtocolError::MissingParam("success".to_owned(), "num chunks".to_owned())
            })? {
                Value::U64(val) => *val,
                _ => {
                    return Err(ProtocolError::InvalidParam(
                        "success".to_owned(),
                        "num chunks".to_owned(),
                    ));
                }
            };

            let mode = match pieces.next() {
                Some(Value::U64(val)) => Some(*val as u32),
                _ => None,
            };

            // Return the file info
            return Ok(Some(Message::SuccessTransmit(
                channel_id,
                hash.to_string(),
                num_chunks as u32,
                mode,
            )));
        }
    }

    Ok(None)
}

// Parse out bad
// { channel_id, "false", ..values }
pub fn parse_bad_op(
    channel_id: u32,
    mut pieces: Iter<Value>,
) -> Result<Option<Message>, ProtocolError> {
    if let Some(Value::Bool(false)) = pieces.next() {
        let error = match pieces
            .next()
            .ok_or_else(|| ProtocolError::MissingParam("failure".to_owned(), "error".to_owned()))?
        {
            Value::String(val) => val,
            _ => {
                return Err(ProtocolError::InvalidParam(
                    "failure".to_owned(),
                    "error".to_owned(),
                ));
            }
        };

        return Ok(Some(Message::Failure(channel_id, error.to_owned())));
    }

    Ok(None)
}

// Parse out ack
// { hash, true, num_chunks }
pub fn parse_ack(
    channel_id: u32,
    mut pieces: Iter<Value>,
) -> Result<Option<Message>, ProtocolError> {
    if let Some(Value::String(hash)) = pieces.next() {
        if let Some(Value::Bool(true)) = pieces.next() {
            // It's an ACK: { hash, true, num_chunks }
            // Our data transfer (export) completed successfully
            // self.stop_push(&hash)?;

            //TODO: Do something with the third param? (num_chunks)
            // Doesn't look like we do anything with num_chunks
            return Ok(Some(Message::ACK(channel_id, hash.to_owned())));
        }
    }

    Ok(None)
}

// Parse out nak
// { hash, false, ..missing_chunks }
pub fn parse_nak(
    channel_id: u32,
    mut pieces: Iter<Value>,
) -> Result<Option<Message>, ProtocolError> {
    if let Some(Value::String(hash)) = pieces.next() {
        if let Some(Value::Bool(false)) = pieces.next() {
            let mut remaining_chunks: Vec<(u32, u32)> = vec![];
            let mut chunk_nums: Vec<u32> = vec![];
            for entry in pieces {
                if let Value::U64(chunk_num) = entry {
                    chunk_nums.push(*chunk_num as u32);
                }
            }

            for chunk in chunk_nums.chunks(2) {
                let first = chunk[0];
                let last = chunk[1];
                remaining_chunks.push((first, last));
            }

            return Ok(Some(Message::NAK(
                channel_id,
                hash.to_owned(),
                Some(remaining_chunks),
            )));
        }
    }

    Ok(None)
}

// Parse out chunk
// { hash, chunk_index, data }
pub fn parse_chunk(
    channel_id: u32,
    mut pieces: Iter<Value>,
) -> Result<Option<Message>, ProtocolError> {
    if let Some(Value::String(hash)) = pieces.next() {
        if let Some(Value::U64(num)) = pieces.next() {
            if let Some(third_param) = pieces.next() {
                if let Value::Bytes(data) = third_param {
                    return Ok(Some(Message::ReceiveChunk(
                        channel_id,
                        hash.to_owned(),
                        *num as u32,
                        data.to_vec(),
                    )));
                } else {
                    return Err(ProtocolError::InvalidParam(
                        "chunk".to_owned(),
                        "chunk data".to_owned(),
                    ));
                }
            }
        }
    }

    Ok(None)
}

// Parse out sync
// { hash, num_chunks }
// or
// { hash }
pub fn parse_sync(
    channel_id: u32,
    mut pieces: Iter<Value>,
) -> Result<Option<Message>, ProtocolError> {
    if let Some(Value::String(hash)) = pieces.next() {
        if let Some(second_param) = pieces.next() {
            if let Value::U64(num) = second_param {
                if pieces.next().is_none() {
                    // It's a sync message: { hash, num_chunks }
                    return Ok(Some(Message::Metadata(
                        channel_id,
                        hash.to_owned(),
                        *num as u32,
                    )));
                }
            }
        } else {
            // It's a sync message: { hash }
            return Ok(Some(Message::Sync(channel_id, hash.to_owned())));
        }
    }

    Ok(None)
}