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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 std::cell::RefCell;
use std::fmt;
use std::fmt::{Display, Formatter};
use std::convert::From;
use std::rc::Rc;
use try_from::TryFrom;

use ::{ProtocolError, ProtocolErrorKind};
use ::transport::TTransport;

mod binary;
mod compact;
mod multiplexed;

pub use self::binary::{TBinaryProtocol, TBinaryProtocolFactory};
pub use self::compact::{TCompactProtocol, TCompactProtocolFactory};
pub use self::multiplexed::TMultiplexedProtocol;

/// Default maximum depth to which we will skip
/// a Thrift field. Note that we have to set a
/// default because Thrift fields may contain nested
/// fields and so we may recurse indefinitely.
const MAXIMUM_SKIP_DEPTH: i8 = 64;

// FIXME: consider splitting apart the read and write methods -> makes ownership easier
/// Implemented by Thrift protocols to write/read
/// a Thrift object to/from its serialized representation.
pub trait TProtocol {
    /// Write a marker identifying the
    /// beginning of a Thrift message. The
    /// marker may contain any or all of the
    /// parameters in `identifier`.
    fn write_message_begin(&mut self, identifier: &TMessageIdentifier) -> ::Result<()>;
    /// Write a marker identifying the end
    /// of the Thrift message.
    fn write_message_end(&mut self) -> ::Result<()>;
    fn write_struct_begin(&mut self, identifier: &TStructIdentifier) -> ::Result<()>;
    fn write_struct_end(&mut self) -> ::Result<()>;
    fn write_field_begin(&mut self, identifier: &TFieldIdentifier) -> ::Result<()>;
    fn write_field_end(&mut self) -> ::Result<()>;
    fn write_field_stop(&mut self) -> ::Result<()>;
    fn write_bool(&mut self, b: bool) -> ::Result<()>;
    fn write_bytes(&mut self, b: &[u8]) -> ::Result<()>;
    fn write_i8(&mut self, i: i8) -> ::Result<()>;
    fn write_i16(&mut self, i: i16) -> ::Result<()>;
    fn write_i32(&mut self, i: i32) -> ::Result<()>;
    fn write_i64(&mut self, i: i64) -> ::Result<()>;
    fn write_double(&mut self, d: f64) -> ::Result<()>;
    fn write_string(&mut self, s: &str) -> ::Result<()>;
    fn write_list_begin(&mut self, identifier: &TListIdentifier) -> ::Result<()>;
    fn write_list_end(&mut self) -> ::Result<()>;
    fn write_set_begin(&mut self, identifier: &TSetIdentifier) -> ::Result<()>;
    fn write_set_end(&mut self) -> ::Result<()>;
    fn write_map_begin(&mut self, identifier: &TMapIdentifier) -> ::Result<()>;
    fn write_map_end(&mut self) -> ::Result<()>;

    fn flush(&mut self) -> ::Result<()>;

    //
    // Methods to read a thrift type from its serialized form.
    //

    fn read_message_begin(&mut self) -> ::Result<TMessageIdentifier>;
    fn read_message_end(&mut self) -> ::Result<()>;
    fn read_struct_begin(&mut self) -> ::Result<Option<TStructIdentifier>>;
    fn read_struct_end(&mut self) -> ::Result<()>;
    fn read_field_begin(&mut self) -> ::Result<TFieldIdentifier>;
    fn read_field_end(&mut self) -> ::Result<()>;
    fn read_bool(&mut self) -> ::Result<bool>;
    fn read_bytes(&mut self) -> ::Result<Vec<u8>>;
    fn read_i8(&mut self) -> ::Result<i8>;
    fn read_i16(&mut self) -> ::Result<i16>;
    fn read_i32(&mut self) -> ::Result<i32>;
    fn read_i64(&mut self) -> ::Result<i64>;
    fn read_double(&mut self) -> ::Result<f64>;
    fn read_string(&mut self) -> ::Result<String>;
    fn read_list_begin(&mut self) -> ::Result<TListIdentifier>;
    fn read_list_end(&mut self) -> ::Result<()>;
    fn read_set_begin(&mut self) -> ::Result<TSetIdentifier>;
    fn read_set_end(&mut self) -> ::Result<()>;
    fn read_map_begin(&mut self) -> ::Result<TMapIdentifier>;
    fn read_map_end(&mut self) -> ::Result<()>;

    fn skip(&mut self, field_type: TType) -> ::Result<()> {
        self.skip_till_depth(field_type, MAXIMUM_SKIP_DEPTH)
    }

    fn skip_till_depth(&mut self, field_type: TType, remaining_depth: i8) -> ::Result<()> {
        if remaining_depth == 0 {
           return Err(
               ::Error::Protocol(
                   ProtocolError {
                       kind: ProtocolErrorKind::DepthLimit,
                       message: format!("cannot parse past {:?}", field_type),
                   }
               )
           )
        }

        match field_type {
            TType::Bool => {
                self.read_bool().map(|_| ())
            },
            TType::I08 => {
                self.read_i8().map(|_| ())
            },
            TType::I16 => {
                self.read_i16().map(|_| ())
            },
            TType::I32 => {
                self.read_i32().map(|_| ())
            },
            TType::I64 => {
                self.read_i64().map(|_| ())
            },
            TType::Double => {
                self.read_double().map(|_| ())
            },
            TType::String => {
                self.read_string().map(|_| ())
            },
            TType::Struct => {
                try!(self.read_struct_begin());
                loop {
                    let field_ident = try!(self.read_field_begin());
                    if field_ident.field_type == TType::Stop { break; }
                    try!(self.skip_till_depth(field_ident.field_type, remaining_depth - 1));
                }
                self.read_struct_end()
            },
            TType::List => {
                let list_ident = try!(self.read_list_begin());
                for _ in 0..list_ident.size {
                    try!(self.skip_till_depth(list_ident.element_type, remaining_depth - 1));
                }
                self.read_list_end()
            },
            TType::Set => {
                let set_ident = try!(self.read_set_begin());
                for _ in 0..set_ident.size {
                    try!(self.skip_till_depth(set_ident.element_type, remaining_depth - 1));
                }
                self.read_set_end()
            },
            TType::Map => {
                let map_ident = try!(self.read_map_begin());
                for _ in 0..map_ident.size {
                    let key_type = map_ident.key_type.expect("non-zero sized map should contain key type");
                    let val_type = map_ident.value_type.expect("non-zero sized map should contain value type");
                    try!(self.skip_till_depth(key_type, remaining_depth - 1));
                    try!(self.skip_till_depth(val_type, remaining_depth - 1));
                }
                self.read_map_end()
            },
            u => {
                Err(
                    ::Error::Protocol(
                        ProtocolError {
                            kind: ProtocolErrorKind::Unknown,
                            message: format!("cannot skip field type {:?}", &u),
                        }
                    )
                )
            },
        }
    }

    //
    // utility (DO NOT USE IN GENERATED CODE!!!!)
    //

    fn write_byte(&mut self, b: u8) -> ::Result<()>; // FIXME: REMOVE
    fn read_byte(&mut self) -> ::Result<u8>;
}

pub trait TProtocolFactory {
    fn build(&self, transport: Rc<RefCell<Box<TTransport>>>) -> Box<TProtocol>;
}

/// Identifies an instance of a Thrift message
/// in its corresponding protocol representation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TMessageIdentifier {
    pub name: String, // FIXME: allow usage of &str
    pub message_type: TMessageType,
    pub sequence_number: i32,
}

/// Identifies an instance of a Thrift struct
/// in its corresponding protocol representation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TStructIdentifier {
    pub name: String, // FIXME: allow usage of &str
}

/// Identifies an instance of a Thrift field
/// in its corresponding protocol representation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TFieldIdentifier {
    pub name: Option<String>, // FIXME: allow usage of &str
    pub field_type: TType,
    pub id: Option<i16>, // FIXME: this sucks that this is an option (only required for Field::Stop)
}

/// Identifies an instance of a list
/// in its protocol representation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TListIdentifier {
    pub element_type: TType,
    pub size: i32,
}

/// Identifies an instance of a set
/// in its protocol representation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TSetIdentifier {
    pub element_type: TType,
    pub size: i32,
}

/// Identifies an instance of a map
/// in its protocol representation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TMapIdentifier {
    pub key_type: Option<TType>,
    pub value_type: Option<TType>,
    pub size: i32,
}

/// Thrift message type.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TMessageType {
    Call,
    Reply,
    Exception,
    OneWay,
}

impl Display for TMessageType {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match *self {
            TMessageType::Call => write!(f, "Call"),
            TMessageType::Reply => write!(f, "Reply"),
            TMessageType::Exception => write!(f, "Exception"),
            TMessageType::OneWay => write!(f, "OneWay"),
        }
    }
}

// Converts a Thrift message-type enum into its
// byte representation for encoding into its serialized form.
impl From<TMessageType> for u8 {
    fn from(message_type: TMessageType) -> Self {
        match message_type {
            TMessageType::Call => 0x01,
            TMessageType::Reply => 0x02,
            TMessageType::Exception => 0x03,
            TMessageType::OneWay => 0x04,
        }
    }
}

// Converts the serialized representation of a
// Thrift message type into its enum form.
impl TryFrom<u8> for TMessageType {
    type Err = ::Error;
    fn try_from(b: u8) -> ::Result<Self> {
        match b {
            0x01 => Ok(TMessageType::Call),
            0x02 => Ok(TMessageType::Reply),
            0x03 => Ok(TMessageType::Exception),
            0x04 => Ok(TMessageType::OneWay),
            unkn => Err(
                ::Error::Protocol(
                    ProtocolError {
                        kind: ProtocolErrorKind::InvalidData,
                        message: format!("cannot convert {} to TMessageType", unkn),
                    }
                )
            )
        }
    }
}

/// Thrift field type.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TType {
    Stop,
    Void,
    Bool,
    I08,
    Double,
    I16,
    I32,
    I64,
    String,
    Utf7,
    Struct,
    Map,
    Set,
    List,
    Utf8,
    Utf16,
}

impl Display for TType {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match *self {
            TType::Stop => write!(f, "STOP"),
            TType::Void => write!(f, "void"),
            TType::Bool => write!(f, "bool"),
            TType::I08 => write!(f, "i08"),
            TType::Double => write!(f, "double"),
            TType::I16 => write!(f, "i16"),
            TType::I32 => write!(f, "i32"),
            TType::I64 => write!(f, "i64"),
            TType::String => write!(f, "string"),
            TType::Utf7 => write!(f, "UTF7"),
            TType::Struct => write!(f, "struct"),
            TType::Map => write!(f, "map"),
            TType::Set => write!(f, "set"),
            TType::List => write!(f, "list"),
            TType::Utf8 => write!(f, "UTF8"),
            TType::Utf16 => write!(f, "UTF16"),
        }
    }
}

pub fn verify_expected_sequence_number(expected: i32, actual: i32) -> ::Result<()> {
    if expected == actual {
        Ok(())
    } else {
        Err(
            ::Error::Application(
                ::ApplicationError {
                    kind: ::ApplicationErrorKind::BadSequenceId,
                    message: format!("expected {} got {}", expected, actual)
                }
            )
        )
    }
}

pub fn verify_expected_service_call(expected: &str, actual: &str) -> ::Result<()> {
    if expected == actual {
        Ok(())
    } else {
        Err(
            ::Error::Application(
                ::ApplicationError {
                    kind: ::ApplicationErrorKind::WrongMethodName,
                    message: format!("expected {} got {}", expected, actual)
                }
            )
        )
    }
}

pub fn verify_expected_message_type(expected: TMessageType, actual: TMessageType) -> ::Result<()> {
    if expected == actual {
        Ok(())
    } else {
        Err(
            ::Error::Application(
                ::ApplicationError {
                    kind: ::ApplicationErrorKind::InvalidMessageType,
                    message: format!("expected {} got {}", expected, actual)
                }
            )
        )
    }
}

pub fn verify_required_field_exists<T>(field_name: &str, field: &Option<T>) -> ::Result<()> {
    match *field {
        Some(_) => Ok(()),
        None => Err(
            ::Error::Protocol(
                ::ProtocolError {
                    kind: ::ProtocolErrorKind::Unknown,
                    message: format!("missing required field {}", field_name)
                }
            )
        ),
    }
}

pub fn field_id(field_ident: &TFieldIdentifier) -> ::Result<i16> {
    field_ident.id.ok_or(
        ::Error::Protocol(
            ::ProtocolError {
                kind: ::ProtocolErrorKind::Unknown,
                message: format!("missing field in in {:?}", field_ident)
            }
        )
    )
}