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
//! This module contains implementation of Variable and Fixed fields
//!
use crate::iso8583::iso_spec::IsoMsg;
use std::fmt;
use crate::iso8583::field::Encoding::{ASCII, EBCDIC, BCD, BINARY};
use std::collections::HashMap;
use std::io::{BufRead, Write};

use serde::{Serialize, Deserialize};
use byteorder::ByteOrder;


/// This enum represents the encoding of a field (or length indicator for variable fields)
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
pub enum Encoding {
    ASCII,
    EBCDIC,
    BINARY,
    BCD,
}

/// This struct represents a error in parsing a field/message
#[derive(Debug)]
pub struct ParseError {
    pub msg: String
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "(iso8583:: parse-error: {})", self.msg)
    }
}

/// This trait represents a ISO field (specific implementations are FixedField, VarField and BmpField)
pub trait Field: Sync {
    /// Returns the name of the field
    fn name(&self) -> &String;

    /// Parses the field by reading from in_buf and stores the result into f2d_map
    /// Returns a ParseError on failure
    fn parse(&self, in_buf: &mut dyn BufRead, f2d_map: &mut HashMap<String, Vec<u8>>) -> Result<(), ParseError>;

    /// Assembles the field i.e. appends it data into out_buf
    /// Returns the number of bytes written on success or a ParseError on failure
    fn assemble(&self, out_buf: &mut Vec<u8>, iso_msg: &IsoMsg) -> Result<u32, ParseError>;

    /// Returns the position of the field in the parent field (mostly applicable for chlidren of BmpField)
    fn position(&self) -> u32;

    /// Returns children as Vec
    fn children(&self) -> Vec<&dyn Field>;

    /// Returns the child field by position
    fn child_by_pos(&self, pos: u32) -> &dyn Field;

    /// Returns child field by name
    fn child_by_name(&self, name: &String) -> &dyn Field;

    /// Returns a string that represents the field value in ascii
    fn to_string(&self, data: &Vec<u8>) -> String;

    /// Returns field value as binary (wire format)
    fn to_raw(&self, val: &str) -> Vec<u8>;
}

/// This struct represents a Fixed field
pub struct FixedField {
    /// Name of the field
    pub name: String,
    /// ID of the field (unused)
    pub id: u32,
    // Fixed length of the field
    pub len: u32,
    // Encoding of the field content
    pub encoding: Encoding,
    // Position of the field within the parent
    pub position: u32,
}

impl Field for FixedField {
    fn name(&self) -> &String {
        &self.name
    }

    fn parse(self: &Self, in_buf: &mut dyn BufRead, f2d_map: &mut HashMap<String, Vec<u8>>) -> Result<(), ParseError> {
        let mut f_data = vec![0; self.len as usize];
        match in_buf.read_exact(&mut f_data[..]) {
            Ok(_) => {
                f2d_map.insert(self.name.clone(), f_data);
                Ok(())
            }
            Err(_) => {
                Err(ParseError { msg: format!("not enough data to parse - {}", self.name) })
            }
        }
    }

    fn assemble(self: &Self, out_buf: &mut Vec<u8>, iso_msg: &IsoMsg) -> Result<u32, ParseError> {
        match iso_msg.fd_map.get(&self.name) {
            Some(fd) => {
                out_buf.extend(fd);
                Ok(fd.as_slice().len() as u32)
            }
            None => {
                Err(ParseError { msg: format!("field {} is not available!", self.name) })
            }
        }
    }

    fn position(&self) -> u32 {
        return self.position;
    }

    fn children(&self) -> Vec<&dyn Field> {
        //unimplemented!("nested fields not supported for {}", self.name)
        vec![]
    }

    fn child_by_pos(&self, _pos: u32) -> &dyn Field {
        unimplemented!()
    }

    fn child_by_name(&self, _name: &String) -> &dyn Field {
        unimplemented!()
    }

    fn to_string(&self, data: &Vec<u8>) -> String {
        vec_to_string(&self.encoding, data)
    }

    fn to_raw(&self, val: &str) -> Vec<u8> {
        string_to_vec(&self.encoding, val)
    }
}

/// This struct represents a Variable field
pub struct VarField {
    // Name of the field
    pub name: String,
    pub id: u32,
    /// Number of bytes in the length indicator
    pub len: u32,
    /// Encoding of the length indicator
    pub len_encoding: Encoding,
    /// Encoding of field content
    pub encoding: Encoding,
    // Position of field within parent
    pub position: u32,
}


impl VarField {
    /// Returns the length of data in the variable field
    fn data_len(&self, data: &Vec<u8>) -> usize
    {
        match self.len_encoding {
            Encoding::ASCII => {
                String::from_utf8(data.clone()).expect("").parse::<usize>().unwrap()
            }
            Encoding::EBCDIC => {
                ebcdic_to_ascii(data).parse::<usize>().unwrap()
            }
            Encoding::BINARY => {
                match data.len() {
                    1 => data[0] as usize,
                    2 => byteorder::BigEndian::read_u16(&data[..]) as usize,
                    _ => panic!("Cannot support more than 2 bytes of length indicator when expressed in binary")
                }
            }
            Encoding::BCD => {
                match data.len() {
                    1 => hex::encode(data).parse::<usize>().unwrap(),
                    2 => hex::encode(data).parse::<usize>().unwrap(),
                    _ => panic!("Cannot support more than 2 bytes (4 BCD digits) of length indicator when expressed in bcd")
                }
            }
        }
    }

    /// Builds and returns the length indicator based on encoding of the field as a Vec<u8>
    fn build_len_ind(&self, len: usize) -> Vec<u8> {
        match self.len_encoding {
            Encoding::ASCII => {
                match self.len {
                    1 => format!("{:01}", len).into_bytes(),
                    2 => format!("{:02}", len).into_bytes(),
                    3 => format!("{:03}", len).into_bytes(),
                    _ => unimplemented!("len-ind cannot exceed 3")
                }
            }
            Encoding::EBCDIC => {
                match self.len {
                    1 => ascii_to_ebcdic(&mut format!("{:01}", len).into_bytes()),
                    2 => ascii_to_ebcdic(&mut format!("{:02}", len).into_bytes()),
                    3 => ascii_to_ebcdic(&mut format!("{:03}", len).into_bytes()),
                    _ => unimplemented!("len-ind cannot exceed 3")
                }
            }

            Encoding::BINARY => {
                let mut len_ind = Vec::<u8>::new();
                match self.len {
                    1 => {
                        len_ind.write(&vec![len as u8]).unwrap();
                        len_ind
                    }
                    2 => {
                        byteorder::BigEndian::write_u16(&mut len_ind, len as u16);
                        len_ind
                    }
                    _ => panic!("Cannot support more than 2 bytes of length indicator when expressed in binary")
                }
            }
            Encoding::BCD => {
                match self.len {
                    1 => hex::decode(format!("{:02}", len)).unwrap(),
                    2 => hex::decode(format!("{:04}", len)).unwrap(),
                    _ => panic!("Cannot support more than 2 bytes (4 BCD digits) of length indicator when expressed in bcd")
                }
            }
        }
    }
}

impl Field for VarField
{
    fn name(&self) -> &String {
        &self.name
    }

    fn parse(&self, in_buf: &mut dyn BufRead, f2d_map: &mut HashMap<String, Vec<u8>>) -> Result<(), ParseError> {
        let mut len_data = vec![0; self.len as usize];
        match in_buf.read_exact(&mut len_data[..]) {
            Ok(_) => {
                trace!("parsed-data (len-ind) : {}", hex::encode(&len_data));


                let data_len = self.data_len(&len_data);
                let mut f_data = vec![0; data_len as usize];

                match in_buf.read_exact(&mut f_data[..]) {
                    Ok(_) => {
                        f2d_map.insert(self.name.clone(), f_data);
                        Ok(())
                    }
                    Err(e) => {
                        Result::Err(ParseError { msg: format!("insufficient data, failed to parse {}, Error = {}", self.name, e.to_string()) })
                    }
                }
            }
            Err(_) => {
                Result::Err(ParseError { msg: format!("insufficient data, failed to parse length indicator for -  {}", self.name) })
            }
        }
    }


    fn assemble(&self, out_buf: &mut Vec<u8>, iso_msg: &IsoMsg) -> Result<u32, ParseError> {
        match iso_msg.fd_map.get(&self.name) {
            Some(fd) => {
                let len_ind = self.build_len_ind(fd.len());
                out_buf.extend(len_ind);
                out_buf.extend(fd);
                //fd.as_slice().iter().for_each(|d| out_buf.push(*d));
                Ok(fd.as_slice().len() as u32)
            }
            None => {
                Err(ParseError { msg: format!("field {} is not available!", self.name) })
            }
        }
    }


    fn position(&self) -> u32 {
        return self.position;
    }


    fn children(&self) -> Vec<&dyn Field> {
        //unimplemented!("nested fields not supported for {}", self.name)
        vec![]
    }


    fn child_by_pos(&self, _pos: u32) -> &dyn Field {
        unimplemented!()
    }

    fn child_by_name(&self, _name: &String) -> &dyn Field {
        unimplemented!()
    }

    fn to_string(&self, data: &Vec<u8>) -> String {
        vec_to_string(&self.encoding, data)
    }

    fn to_raw(&self, val: &str) -> Vec<u8> {
        string_to_vec(&self.encoding, val)
    }
}

pub(in crate::iso8583) fn vec_to_string(encoding: &Encoding, data: &Vec<u8>) -> String {
    match encoding {
        ASCII => {
            String::from_utf8(data.clone()).unwrap()
        }
        EBCDIC => {
            ebcdic_to_ascii(data)
        }
        BINARY => {
            hex::encode(data.as_slice())
        }
        BCD => {
            hex::encode(data.as_slice())
        }
    }
}

/// Converts EBCDIC bytes into a ASCII string
fn ebcdic_to_ascii(data: &Vec<u8>) -> String {
    let mut ascii_str = String::new();
    data.iter().for_each(|f| ascii_str.push(char::from(encoding8::ebcdic::to_ascii(f.clone()))));
    ascii_str
}

/// Converts ASCII bytes to EBCDIC bytes
fn ascii_to_ebcdic(data: &mut Vec<u8>) -> Vec<u8> {
    for i in 0..data.len() {
        encoding8::ascii::make_ebcdic(data.get_mut(i).unwrap())
    }
    data.to_vec()
}


pub(in crate::iso8583) fn string_to_vec(encoding: &Encoding, data: &str) -> Vec<u8> {
    match encoding {
        ASCII => {
            data.to_string().into_bytes()
        }
        EBCDIC => {
            let mut ebcdic = vec![];
            (&mut data.to_string()).as_bytes().iter().for_each(|b| ebcdic.push(encoding8::ascii::to_ebcdic(b.clone())));
            ebcdic
        }
        BINARY => {
            hex::decode(data).unwrap()
        }
        BCD => {
            hex::decode(data).unwrap()
        }
    }
}