JSON.cc 50.8 KB
Newer Older
Elemer Lelik's avatar
Elemer Lelik committed
1
/******************************************************************************
balaskoa's avatar
balaskoa committed
2
 * Copyright (c) 2000-2018 Ericsson Telecom AB
Elemer Lelik's avatar
Elemer Lelik committed
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v2.0
Elemer Lelik's avatar
Elemer Lelik committed
5
 * which accompanies this distribution, and is available at
6
 * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html
Elemer Lelik's avatar
Elemer Lelik committed
7
8
9
10
11
 *
 * Contributors:
 *   Baji, Laszlo
 *   Balasko, Jeno
 *   Baranyi, Botond
12
 *   Szabo, Bence Janos
Elemer Lelik's avatar
Elemer Lelik committed
13
14
 *
 ******************************************************************************/
Elemer Lelik's avatar
Elemer Lelik committed
15
#include "JSON.hh"
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include "../common/memory.h"
#include "Integer.hh"
#include "Float.hh"
#include "Bitstring.hh"
#include "Hexstring.hh"
#include "Octetstring.hh"
#include "Charstring.hh"
#include "Universal_charstring.hh"
#include "Addfunc.hh"

#include <openssl/bn.h>

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
Elemer Lelik's avatar
Elemer Lelik committed
33
34

// JSON descriptors for base types
35
const TTCN_JSONdescriptor_t INTEGER_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
36

37
const TTCN_JSONdescriptor_t FLOAT_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
38

39
const TTCN_JSONdescriptor_t BOOLEAN_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
40

41
const TTCN_JSONdescriptor_t BITSTRING_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
42

43
const TTCN_JSONdescriptor_t HEXSTRING_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
44

45
const TTCN_JSONdescriptor_t OCTETSTRING_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
46

47
const TTCN_JSONdescriptor_t CHARSTRING_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
48

49
const TTCN_JSONdescriptor_t UNIVERSAL_CHARSTRING_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
50

51
const TTCN_JSONdescriptor_t VERDICTTYPE_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
52

53
const TTCN_JSONdescriptor_t GeneralString_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
54

55
const TTCN_JSONdescriptor_t NumericString_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
56

57
const TTCN_JSONdescriptor_t UTF8String_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
58

59
const TTCN_JSONdescriptor_t PrintableString_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
60

61
const TTCN_JSONdescriptor_t UniversalString_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
62

63
const TTCN_JSONdescriptor_t BMPString_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
64

65
const TTCN_JSONdescriptor_t GraphicString_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
66

67
const TTCN_JSONdescriptor_t IA5String_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
68

69
const TTCN_JSONdescriptor_t TeletexString_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
70

71
const TTCN_JSONdescriptor_t VideotexString_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
72

73
const TTCN_JSONdescriptor_t VisibleString_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
74

75
const TTCN_JSONdescriptor_t ASN_NULL_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
76

77
const TTCN_JSONdescriptor_t OBJID_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
78

79
const TTCN_JSONdescriptor_t ASN_ROID_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
80

81
const TTCN_JSONdescriptor_t ASN_ANY_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
Elemer Lelik's avatar
Elemer Lelik committed
82

83
const TTCN_JSONdescriptor_t ENUMERATED_json_ = { FALSE, NULL, FALSE, NULL, FALSE, FALSE, FALSE, 0, NULL };
84
85
86



87
88
89
90
////////////////////////////////////////////////////////////////////////////////
//// CBOR conversion
////////////////////////////////////////////////////////////////////////////////

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
// Never use buff.get_read_data() without checking if it has enough bytes in the
// buffer.
const unsigned char* check_and_get_buffer(const TTCN_Buffer& buff, int bytes) {
  if (bytes < 0) {
    TTCN_error("Incorrect length byte received: %d, while decoding using cbor2json()", bytes);
  }
  if (buff.get_pos() + bytes > buff.get_len()) {
    TTCN_error("Not enough bytes in bytestream while decoding using cbor2json().");
  }
  return buff.get_read_data();
}

void encode_ulong_long_int_cbor(TTCN_Buffer& buff, int bytes, unsigned long long int value) {
  for (int i = bytes - 1; i >= 0; i--) {
    buff.put_c(static_cast<unsigned char>((value >> i*8)));
  }
}


// major_type parameter needed for the string encoding
void encode_int_cbor(TTCN_Buffer& buff, int major_type, INTEGER& int_num) {
  bool is_negative = false;
  int_val_t num = int_num.get_val();
  if (num.is_negative()) {
    major_type = 1 << 5;
    int_num = (int_num * -1) - 1;
    num = int_num.get_val();
    is_negative = true;
  }
  if (num.is_native()) {
    unsigned int uns_num = num.get_val();
    if (uns_num <= 23) {
      buff.put_c(static_cast<unsigned char>(major_type + uns_num));
    } else if (uns_num <= 0xFF) { // 8 bit
      buff.put_c(static_cast<unsigned char>(major_type + 24));
      encode_ulong_long_int_cbor(buff, 1, uns_num);
    } else if (uns_num <= 0xFFFF) { // 16 bit
      buff.put_c(static_cast<unsigned char>(major_type + 25));
      encode_ulong_long_int_cbor(buff, 2, uns_num);
    } else if (uns_num <= 0xFFFFFFFF) { // 32 bit
      buff.put_c(static_cast<unsigned char>(major_type + 26));
      encode_ulong_long_int_cbor(buff, 4, uns_num);
    }
  } else {
    BIGNUM* bn = BN_dup(int_num.get_val().get_val_openssl());
    INTEGER bn_length = BN_num_bytes(bn);
    long long int long_int = int_num.get_long_long_val();
    if (bn_length <= 4) { // 32 bit
      buff.put_c(static_cast<unsigned char>(major_type + 26));
      encode_ulong_long_int_cbor(buff, 4, long_int);
    } else if (bn_length <= 8) {
      buff.put_c(static_cast<unsigned char>(major_type + 27));
      encode_ulong_long_int_cbor(buff, 8, long_int);
    } else {
      // It is a bignum. Encode as bytestring
      major_type = 6 << 5; // Major type 6 for bignum
      major_type += is_negative ? 3 : 2; // Tag 2 or 3 for negative
      buff.put_c(static_cast<unsigned char>(major_type));
      major_type = 2 << 5; // Major type 2 for bytestring
      encode_int_cbor(buff, major_type, bn_length); // encode the length of the bignum
      size_t buff_len = bn_length.get_val().get_val();
      unsigned char* tmp_num = static_cast<unsigned char*>(Malloc(buff_len*sizeof(unsigned char)));
      BN_bn2bin(bn, tmp_num);
      buff.put_s(buff_len, reinterpret_cast<const unsigned char*>(tmp_num));
      Free(tmp_num);
    }
    BN_free(bn);
  }
}


void decode_int_cbor(TTCN_Buffer& buff, int bytes, INTEGER& value) {
  const unsigned char* tmp = check_and_get_buffer(buff, bytes);
  TTCN_Buffer tmp_buf;
  tmp_buf.put_s(bytes, tmp);
  OCTETSTRING os;
  tmp_buf.get_string(os);
  value = oct2int(os);
  buff.increase_pos(bytes);
}

void decode_uint_cbor(TTCN_Buffer& buff, int bytes, unsigned int& value) {
  value = 0;
  const unsigned char* tmp = check_and_get_buffer(buff, bytes);
  for (int i = bytes - 1; i >= 0; i--) {
    value += *(tmp) << i*8;
    tmp++;
  }
  buff.increase_pos(bytes);
}

void decode_ulong_long_int_cbor(TTCN_Buffer& buff, int bytes, unsigned long long int& value) {
  value = 0;
  const unsigned char* tmp = check_and_get_buffer(buff, bytes);
  for (int i = bytes - 1; i >= 0; i--) {
    value += *(tmp) << i*8;
    tmp++;
  }
  buff.increase_pos(bytes);
}

void decode_integer_cbor(TTCN_Buffer& buff, int minor_type, INTEGER& result) {
  if (minor_type <= 23) {
    result = minor_type;
  } else if (minor_type == 24) { // A number in 8 bits
    unsigned int num;
    decode_uint_cbor(buff, 1, num);
    result = num;
  } else if (minor_type == 25) { // A number in 16 bits
    unsigned int num;
    decode_uint_cbor(buff, 2, num);
    result = num;
  } else if (minor_type == 26) { // A number in 32 bits
    unsigned int num;
    decode_uint_cbor(buff, 4, num);
    result = num;
  } else if (minor_type == 27) { // A number in 64 bits
    decode_int_cbor(buff, 8, result);
  }
}


void decode_bytestring_cbor(TTCN_Buffer& buff, JSON_Tokenizer& tok, int minor_type, int tag) {
  INTEGER length;
  decode_integer_cbor(buff, minor_type, length);
  const unsigned char* tmp = check_and_get_buffer(buff, length.get_val().get_val());
  OCTETSTRING os(length.get_val().get_val(), tmp);
  buff.increase_pos(length.get_val().get_val());
  CHARSTRING cs;
  if (tag == 22 || tag == 23 || tag == 2 || tag == 3) { // base64 or base64url or +-bigint
    cs = encode_base64(os);
    // The difference between the base64 and base64url encoding is that the
    // + is replaced with -, the / replaced with _ and the trailing = padding
    // is removed.
    if (tag != 22) { // if tag is not base64 >--> base64url
      const char* data = (const char*)cs;
      char* pch = strchr(const_cast<char*>(data),'+');
      while (pch!=NULL)
      {
        *pch = '-';
        pch=strchr(pch+1,'+');
      }
      pch = strchr(const_cast<char*>(data),'/');
      while (pch!=NULL)
      {
        *pch = '_';
        pch=strchr(pch+1,'/');
      }
      // Max 2 padding = is possible
      if (cs[cs.lengthof()-1] == "=") {
        cs = replace(cs, cs.lengthof()-1, 1, "");
      }
      if (cs[cs.lengthof()-1] == "=") {
        cs = replace(cs, cs.lengthof()-1, 1, "");
      }
    }    
  } else if (tag == 21) { // base16
    cs = oct2str(os);
  }
  // If the bignum encoded as bytestring is negative the tilde is needed before
  // the base64url encoding
  char* tmp_str = mprintf("\"%s%s\"", tag == 3 ? "~" : "", (const char*)cs);
  tok.put_next_token(JSON_TOKEN_STRING, tmp_str);
  Free(tmp_str);
}

// RAW descriptor for raw encoding
TTCN_RAWdescriptor_t cbor_float_raw_ = {64,SG_NO,ORDER_LSB,ORDER_LSB,ORDER_LSB,ORDER_LSB,EXT_BIT_NO,ORDER_LSB,ORDER_LSB,TOP_BIT_INHERITED,0,0,0,8,0,NULL,-1,CharCoding::UNKNOWN};
259
const TTCN_Typedescriptor_t cbor_float_descr_ = { NULL, NULL, &cbor_float_raw_, NULL, NULL, NULL, NULL, NULL, TTCN_Typedescriptor_t::DONTCARE };
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


void json2cbor_coding(TTCN_Buffer& buff, JSON_Tokenizer& tok, size_t& num_of_items) {
  json_token_t token;
  char* content = NULL;
  size_t len;
  size_t prev_pos = tok.get_buf_pos();
  tok.get_next_token(&token, &content, &len);
  switch(token) {
    case JSON_TOKEN_NUMBER: {
      char *str = mcopystrn(content, len);
      size_t curr_pos = tok.get_buf_pos();
      tok.set_buf_pos(prev_pos);
      bool is_float = false;
      tok.check_for_number(&is_float);
      tok.set_buf_pos(curr_pos);
      if (is_float) {
        int c = 7 << 5; // Major type 7
        c += 27; // Minor type 27 (64 bit floating point) always
        buff.put_c(c);
        double d;
        sscanf(str, "%lf", &d);
        FLOAT f = d;
        f.encode(cbor_float_descr_, buff, TTCN_EncDec::CT_RAW);
      } else {
        int c = 0; // Major type 0
        INTEGER int_num = str2int(str);
        encode_int_cbor(buff, c, int_num);
      }
      Free(str);
      num_of_items++;
      break;
    }
    case JSON_TOKEN_STRING:
    case JSON_TOKEN_NAME: {
      int c = 3 << 5; // Major type 3
      INTEGER length = token == JSON_TOKEN_NAME ? len : len - 2; // 2 "-s
      encode_int_cbor(buff, c, length);
      char * str = mcopystrn(token == JSON_TOKEN_NAME ? content : content+1, length.get_val().get_val()); // Remove "-s
      buff.put_string(str);
      Free(str);
      num_of_items++;
      break;
    }
    case JSON_TOKEN_ARRAY_START: {
      int c = 4 << 5; // Major type 4
      size_t nof_items = 0;
      TTCN_Buffer sub_buff;
      while ((prev_pos = tok.get_buf_pos(), tok.get_next_token(&token, NULL, NULL))) {
        if (token != JSON_TOKEN_ARRAY_END) {
          tok.set_buf_pos(prev_pos);
          json2cbor_coding(sub_buff, tok, nof_items);
        } else {
          INTEGER num = nof_items;
          encode_int_cbor(buff, c, num);
          buff.put_buf(sub_buff);
          break;
        }
      }
      num_of_items++;
      break;
    }
    case JSON_TOKEN_ARRAY_END:
      TTCN_error("Unexpected array end character while encoding using json2cbor().");
      break;
    case JSON_TOKEN_OBJECT_START: {
      int c = 5 << 5; // Major type 5
      size_t nof_items = 0;
      TTCN_Buffer sub_buff;
      while ((prev_pos = tok.get_buf_pos(), tok.get_next_token(&token, NULL, NULL))) {
        if (token != JSON_TOKEN_OBJECT_END) { // todo hibas json eseten vegtelen ciklus?
          tok.set_buf_pos(prev_pos);
          json2cbor_coding(sub_buff, tok, nof_items);
        } else {
          INTEGER num = nof_items / 2; // num is the number of key-value pairs
          encode_int_cbor(buff, c, num);
          buff.put_buf(sub_buff);
          break;
        }
      }
      num_of_items++;
      break;
    }
    case JSON_TOKEN_OBJECT_END:
      TTCN_error("Unexpected object end character while encoding using json2cbor().");
    case JSON_TOKEN_LITERAL_FALSE:
    case JSON_TOKEN_LITERAL_TRUE:
    case JSON_TOKEN_LITERAL_NULL: {
      int c = 7 << 5; // Major type 7
      INTEGER i;
      if (token == JSON_TOKEN_LITERAL_FALSE) {
        i = 20;
      } else if (token == JSON_TOKEN_LITERAL_TRUE) {
        i = 21;
      } else if (token == JSON_TOKEN_LITERAL_NULL) {
        i = 22;
      }
      encode_int_cbor(buff, c, i);
      num_of_items++;
      break;
    }
    default:
      TTCN_error("Unexpected json token %i, while encoding using json2cbor().", token);
  }
}

void cbor2json_coding(TTCN_Buffer& buff, JSON_Tokenizer& tok, bool in_object) {
  unsigned char type = *(check_and_get_buffer(buff, 1));
  buff.increase_pos(1);
  int major_type = type >> 5; // First 3 bit of byte
  int minor_type = type & 0x1F; // Get the last 5 bits
  switch(major_type) {
    case 0: { // Integer
      INTEGER i;
      decode_integer_cbor(buff, minor_type, i);
      if (i.is_native()) {
        char* tmp_str = mprintf("%u", i.get_val().get_val());
        tok.put_next_token(JSON_TOKEN_NUMBER, tmp_str);
        Free(tmp_str);
      } else {
        char* tmp_str = i.get_val().as_string();
        tok.put_next_token(JSON_TOKEN_NUMBER, tmp_str);
        Free(tmp_str);
      }
      break;
    }
    case 1: // Negative integer
      switch (minor_type) {
        case 24: { // Integer on 1 byte
          unsigned int num;
          decode_uint_cbor(buff, 1, num);
          char* tmp_str = mprintf("%d", (num+1)*-1);
          tok.put_next_token(JSON_TOKEN_NUMBER, tmp_str);
          Free(tmp_str);
          break;
        }
        case 25: { // Integer on 2 byte
          unsigned int num;
          decode_uint_cbor(buff, 2, num);
          char* tmp_str = mprintf("%d", (num+1)*-1);
          tok.put_next_token(JSON_TOKEN_NUMBER, tmp_str);
          Free(tmp_str);
          break;
        }
        case 26: { // Integer on 4 byte
          unsigned long long int num;
          decode_ulong_long_int_cbor(buff, 4, num);
          INTEGER i;
          i.set_long_long_val((num+1)*-1);
          char* tmp_str = i.get_val().as_string();
          tok.put_next_token(JSON_TOKEN_NUMBER, tmp_str);
          Free(tmp_str);
          break;
        }
        case 27: { // Integer on 8 byte
          INTEGER i;
          decode_int_cbor(buff, 8, i);
          i = i + 1;
          i = i * -1;
          char* tmp_str = i.get_val().as_string();
          tok.put_next_token(JSON_TOKEN_NUMBER, tmp_str);
          Free(tmp_str);
          break;
        }
        default:
          if (minor_type < 24) { // Integer  0 <= num <= 24
            char* tmp_str = mprintf("%d", (minor_type+1)*-1);
            tok.put_next_token(JSON_TOKEN_NUMBER, tmp_str);
            Free(tmp_str);
          }
      }
      break;
    case 2: // Bytestring, encoded into a base64url json string
      decode_bytestring_cbor(buff, tok, minor_type, 23); // base64url by default
      break;
    case 3: { // String
      INTEGER length;
      decode_integer_cbor(buff, minor_type, length);
      const unsigned char* tmp = check_and_get_buffer(buff, length.get_val().get_val());
      
      char* json_str = mcopystrn((const char*)tmp, length.get_val().get_val());
      if (in_object) {
        tok.put_next_token(JSON_TOKEN_NAME, json_str);
      } else {
        char* tmp_str = mprintf("\"%s\"", json_str);
        tok.put_next_token(JSON_TOKEN_STRING, tmp_str);
        Free(tmp_str);
      }
      Free(json_str);
      buff.increase_pos(length.get_val().get_val());
      break;
    }
    case 4: { // Array
      tok.put_next_token(JSON_TOKEN_ARRAY_START, NULL);
      INTEGER num_of_items;
      decode_integer_cbor(buff, minor_type, num_of_items);
      for (INTEGER i = 0; i < num_of_items; i = i + 1) {
        cbor2json_coding(buff, tok, false);
      }
      tok.put_next_token(JSON_TOKEN_ARRAY_END, NULL);
      break;
    }
    case 5: { // Object
      tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
      INTEGER num_of_items;
      decode_integer_cbor(buff, minor_type, num_of_items);
      num_of_items = num_of_items * 2; // Number of all keys and values
      for (INTEGER i = 0; i < num_of_items; i = i + 1) {
        // whether to put : or , after the next token
        in_object = i.get_val().get_val() % 2 == 0;
        cbor2json_coding(buff, tok, in_object); 
      }
      tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
      break;
    }
    case 6: {
      int tag = minor_type;
      switch(tag) {
        case 2: // Positive bignum
        case 3: // Negative bignum
        case 21: // bytestring as base16
        case 22: // bytestring as base64
        case 23: // bytestring as base64url
          type = *(check_and_get_buffer(buff, 1));
          buff.increase_pos(1);
          minor_type = type & 0x1F; // Get the last 5 bits
          decode_bytestring_cbor(buff, tok, minor_type, tag);
          break;
        default:
          cbor2json_coding(buff, tok, in_object);
      }
      break;
    }
    case 7: // Other values
      switch (minor_type) {
        case 20: // False
          tok.put_next_token(JSON_TOKEN_LITERAL_FALSE, NULL);
          break;
        case 21: // True
          tok.put_next_token(JSON_TOKEN_LITERAL_TRUE, NULL);
          break;
        case 22: // NULL
        tok.put_next_token(JSON_TOKEN_LITERAL_NULL, NULL);
          break;
        case 25: { // Half precision float 16 bit
          // Decoding algorithm from the standard
          const unsigned char* halfp = check_and_get_buffer(buff, 2);
          buff.increase_pos(2);
          int half = (halfp[0] << 8) + halfp[1];
          int exp = (half >> 10) & 0x1f;
          int mant = half & 0x3ff;
          double val;
          if (exp == 0) val = ldexp(mant, -24);
          else if (exp != 31) val = ldexp(mant + 1024, exp - 25);
514
          else val = mant == 0 ? PLUS_INFINITY : NOT_A_NUMBER;
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
          val = half & 0x8000 ? -val : val;
          FLOAT f = val;
          f.JSON_encode(cbor_float_descr_, tok);
          break;
        }
        case 26: { // Single precision float 32bit
          OCTETSTRING os(4, check_and_get_buffer(buff, 4));
          buff.increase_pos(4);
          INTEGER i = oct2int(os);
          // Some non standard way but it is widely accepted
          union
          {
            unsigned int num;
            float fnum;
          } my_union;
          my_union.num = i.get_long_long_val();
          float f2 = my_union.fnum;
          FLOAT f = f2;
          f.JSON_encode(cbor_float_descr_, tok);
          break;
        }
        case 27: { // Double precision float 64bit
          cbor_float_raw_.fieldlength = 64;
          FLOAT f;
          OCTETSTRING os(8, check_and_get_buffer(buff, 8));
          INTEGER i = oct2int(os);
541
          if (i.get_long_long_val() != 0x7FF8000000000000ULL) { // NAN    
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
            f.decode(FLOAT_descr_, buff, TTCN_EncDec::CT_RAW);
            f.JSON_encode(cbor_float_descr_, tok);
          } else {
            tok.put_next_token(JSON_TOKEN_STRING, "\"not_a_number\"");
            buff.increase_pos(8);
          }
          break;
        }
        default: {
          // put the simple value into the the json
          if (minor_type >= 0 && minor_type <= 23) {
            char* tmp_str = mprintf("%d", minor_type);
            tok.put_next_token(JSON_TOKEN_NUMBER, tmp_str);
            Free(tmp_str);
          } else if (minor_type == 24) { // The value is on the next byte
            int simple_value = *(buff.get_read_data());
            buff.increase_pos(1);
            char* tmp_str = mprintf("%d", simple_value);
            tok.put_next_token(JSON_TOKEN_NUMBER, tmp_str);
            Free(tmp_str);
          }
        }
      }
      break;
    default:
      TTCN_error("Unexpected major type %i while decoding using cbor2json().", major_type);
  }
}
570
571
572
573
574
575
576


////////////////////////////////////////////////////////////////////////////////
////  BSON conversion
////////////////////////////////////////////////////////////////////////////////

const TTCN_RAWdescriptor_t bson_float_raw_ = {64,SG_NO,ORDER_MSB,ORDER_LSB,ORDER_LSB,ORDER_LSB,EXT_BIT_NO,ORDER_LSB,ORDER_LSB,TOP_BIT_INHERITED,0,0,0,8,0,NULL,-1,CharCoding::UNKNOWN};
577
const TTCN_Typedescriptor_t bson_float_descr_ = { NULL, NULL, &bson_float_raw_, NULL, NULL, NULL, NULL, NULL, TTCN_Typedescriptor_t::DONTCARE };
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894

// Never use buff.get_read_data() without checking if it has enough bytes in the
// buffer.
const unsigned char* check_and_get_buffer_bson(const TTCN_Buffer& buff, int bytes) {
  if (bytes < 0) {
    TTCN_error("Incorrect length byte received: %d, while decoding using bson2json()", bytes);
  }
  if (buff.get_pos() + bytes > buff.get_len()) {
    TTCN_error("Not enough bytes in bytestream while decoding using bson2json().");
  }
  return buff.get_read_data();
}

void encode_int_bson(TTCN_Buffer& buff, const INTEGER& int_num, INTEGER& length) {
  if (int_num.is_native()) { // 32 bit
    length = length + 4;
    RInt value = (int)int_num;
    for (size_t i = 0; i < 4; i++) {
      buff.put_c(static_cast<unsigned char>(value >> i*8));
    }
  } else {
    BIGNUM* bn = BN_dup(int_num.get_val().get_val_openssl());
    INTEGER bn_length = BN_num_bytes(bn);
    BN_free(bn);
    long long int long_int = 0;
    int bytes = 0;
    if (bn_length <= 4) { // 32 bit
      bytes = 4;
      long_int = int_num.get_long_long_val();
    } else if (bn_length <= 8) { //64 bit
      bytes = 8;
      long_int = int_num.get_long_long_val();
    } else {
      // The standard encodes max 64 bits
      TTCN_error("An integer value which cannot be represented "
                 "on 64bits cannot be encoded using json2bson()");
    }
    for (int i = 0; i < bytes; i++) {
      buff.put_c(static_cast<unsigned char>(long_int >> i*8));
    }
    length = length + bytes;
  }
}

INTEGER decode_int_bson(TTCN_Buffer& buff, int bytes) {
  const unsigned char* uc = check_and_get_buffer_bson(buff, bytes);
  buff.increase_pos(bytes);
  if (bytes <= 4) { //32 bit
    RInt value = 0;
    for (size_t i = 0; i < 4; i++) {
      value += uc[i] << i*8;
    }
    return INTEGER(value);
  } else if (bytes <= 8) {
    TTCN_Buffer tmp_buf;
    for (int i = 0; i < bytes; i++) {
      tmp_buf.put_c(uc[bytes-i-1]);
    }
    OCTETSTRING os;
    tmp_buf.get_string(os);
    INTEGER value = oct2int(os);
    return value;
  } else {
    TTCN_error("An integer value larger than "
               "64 bytes cannot be decoded using bson2json()");
  }
}

void put_name(TTCN_Buffer& buff, INTEGER& length, CHARSTRING& name, bool in_array) {
  if (in_array) {
    buff.put_cs(name);
    buff.put_c(0); // Closing 0
    length = length + name.lengthof() + 1;
    // TODO: is it very slow?
    // Increment index
    INTEGER num = str2int(name);
    num = num + 1;
    name = int2str(num);
  } else {
    buff.put_cs(name);
    buff.put_c(0); // Closing 0
    length = length + name.lengthof() + 1;
  }
}

void get_name(TTCN_Buffer& buff, JSON_Tokenizer& tok, bool in_array) {
  const unsigned char* uc = buff.get_read_data();
  // Copy until closing 0
  char* tmp_str = mcopystr(reinterpret_cast<const char*>(uc));
  if (in_array == false) { // We dont need name when in array
    tok.put_next_token(JSON_TOKEN_NAME, tmp_str);
  }
  buff.increase_pos(strlen(tmp_str)+1);
  Free(tmp_str);
}

bool encode_bson_binary(TTCN_Buffer& buff, JSON_Tokenizer& tok, INTEGER& length) {
  char *content;
  size_t len;
  json_token_t token;
  // Check if this is really binary
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_STRING) {
    return false;
  }
  CHARSTRING cs2(len-2, content+1);
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_NAME) {
    return false;
  }
  CHARSTRING cs3(len, content);
  if (cs3 != "$type") {
    return false;
  }
  
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_STRING) {
    return false;
  }
  CHARSTRING cs4(len-2, content+1);
  if (cs4.lengthof() != 2) {
    return false;
  }
  
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_OBJECT_END) {
    return false;
  }
  
  buff.put_c(5);
  length = length + 1;
  // We do not know the name here. It will be inserted later.
  OCTETSTRING os = decode_base64(cs2);
  INTEGER os_len = os.lengthof();
  encode_int_bson(buff, os_len, length);
  unsigned int type = 0;
  if (sscanf((const char*)cs4, "%02x", &type) != 1) {
    TTCN_error("Incorrect binary format while encoding with json2bson()");
  }
  buff.put_c(type);
  length = length + 1;
  buff.put_os(os);
  length = length + os_len;
  return true;
}

bool encode_bson_date(TTCN_Buffer& buff, JSON_Tokenizer& tok, INTEGER& length) {
  char *content;
  size_t len;
  json_token_t token;
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_START) {
    return false;
  }
  
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_NAME) {
    return false;
  }
  CHARSTRING cs(len, content);
  if (cs != "$numberLong") {
    return false;
  }
  
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_NUMBER) {
    return false;
  }
  CHARSTRING cs2(len, content);
  
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_END) {
    return false;
  }
  
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_END) {
    return false;
  }
  INTEGER int_num = str2int(cs2);
  buff.put_c(9); // datetime
  length = length + 1;
  // We do not know the name here. It will be inserted later.
  // Encode on 64 bit
  long long int long_int = int_num.get_long_long_val();
  for (int i = 0; i < 8; i++) {
    buff.put_c(static_cast<unsigned char>(long_int >> i*8));
  }
  length = length + 8;
  return true;
}
  

bool encode_bson_timestamp(TTCN_Buffer& buff, JSON_Tokenizer& tok, INTEGER& length) {
  char *content;
  size_t len;
  json_token_t token;
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_START) {
    return false;
  }
  
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_NAME) {
    return false;
  }
  CHARSTRING cs(len, content);
  if (cs != "t") {
    return false;
  }
  
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_NUMBER) {
    return false;
  }
  CHARSTRING cs2(len, content);
  
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_NAME) {
    return false;
  }
  CHARSTRING cs3(len, content);
  if (cs3 != "i") {
    return false;
  }
  
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_NUMBER) {
    return false;
  }
  CHARSTRING cs4(len, content);
  
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_END) {
    return false;
  }
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_END) {
    return false;
  }
  INTEGER timestamp = str2int(cs2);
  INTEGER increment = str2int(cs4);
  buff.put_c(17);
  length = length + 1;
  // We do not know the name here. It will be inserted later.
  encode_int_bson(buff, increment, length);
  encode_int_bson(buff, timestamp, length);
  return true;
}

bool encode_bson_regex(TTCN_Buffer& buff, JSON_Tokenizer& tok, INTEGER& length) {
  char *content;
  size_t len;
  json_token_t token;
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_STRING) {
    return false;
  }
  CHARSTRING regex(len-2, content+1);
  
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_NAME) {
    return false;
  }
  CHARSTRING cs2(len, content);
  if (cs2 != "$options") {
    return false;
  }
  
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_STRING) {
    return false;
  }
  CHARSTRING options(len-2, content+1);
  
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_END) {
    return false;
  }
  
  buff.put_c(11);
  length = length + 1;
  // We do not know the name here. It will be inserted later.
  buff.put_cs(regex);
  length = length + regex.lengthof();
  buff.put_c(0); // Closing 0
  length = length + 1;
  buff.put_cs(options);
  length = length + options.lengthof();
  buff.put_c(0); // Closing 0
  length = length + 1;
  return true;
}

bool encode_bson_oid(TTCN_Buffer& buff, JSON_Tokenizer& tok, INTEGER& length) {
  char *content;
  size_t len;
  json_token_t token;
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_STRING) {
    return false;
  }
  CHARSTRING id(len-2, content+1);
  if (id.lengthof() != 24) {
    return false;
  }
  
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_END) {
    return false;
  }
  
  buff.put_c(7);
  length = length + 1;
  // We do not know the name here. It will be inserted later.
  unsigned char hex[12];
  for (size_t i = 0; i < 24; i = i + 2) {
BenceJanosSzabo's avatar
BenceJanosSzabo committed
895
896
    unsigned int value;
    if (sscanf(((const char*)id)+i, "%02x", &value) != 1) {
897
898
      TTCN_error("Incorrect binary format while encoding with json2bson()");
    }
BenceJanosSzabo's avatar
BenceJanosSzabo committed
899
    hex[i/2] = value;
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
  }
  buff.put_s(12, hex);
  length = length + 12;
  return true;
}

bool encode_bson_ref(TTCN_Buffer& buff, JSON_Tokenizer& tok, INTEGER& length) {
  char *content;
  size_t len;
  json_token_t token;
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_STRING) {
    return false;
  }
  CHARSTRING name(len-2, content+1);
  
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_NAME) {
    return false;
  }
  CHARSTRING cs(len, content);
  if (cs != "$id") {
    return false;
  }
  
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_STRING) {
    return false;
  }
  CHARSTRING id(len-2, content+1);
  if (id.lengthof() != 24) {
    return false;
  }
  
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_END) {
    return false;
  }

  buff.put_c(12);
  length = length + 1;
  // We do not know the name here. It will be inserted later.
  INTEGER name_length = name.lengthof()+1;
  encode_int_bson(buff, name_length, length);
  buff.put_cs(name);
  buff.put_c(0); // Closing 0
  length = length + name_length;
  unsigned char hex[12];
  for (size_t i = 0; i < 24; i = i + 2) {
BenceJanosSzabo's avatar
BenceJanosSzabo committed
949
950
    unsigned int value;
    if (sscanf(((const char*)id)+i, "%02x", &value) != 1) {
951
952
      TTCN_error("Incorrect binary format while encoding with json2bson()");
    }
BenceJanosSzabo's avatar
BenceJanosSzabo committed
953
    hex[i/2] = value;
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
  }
  buff.put_s(12, hex);
  length = length + 12;
  return true;
}

bool encode_bson_undefined(TTCN_Buffer& buff, JSON_Tokenizer& tok, INTEGER& length) {
  char *content;
  size_t len;
  json_token_t token;
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_LITERAL_TRUE) {
    return false;
  }
  
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_END) {
    return false;
  }
  
  buff.put_c(6);
  length = length + 1;
  // We do not know the name here. It will be inserted later.
  return true;
}

bool encode_bson_minkey(TTCN_Buffer& buff, JSON_Tokenizer& tok, INTEGER& length) {
  char *content;
  size_t len;
  json_token_t token;
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_NUMBER) {
    return false;
  }
  CHARSTRING cs(len, content);
  if (cs != "1") {
    return false;
  }
  
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_END) {
    return false;
  }
  
  buff.put_c(255);
  length = length + 1;
  // We do not know the name here. It will be inserted later.
  return true;
}

bool encode_bson_maxkey(TTCN_Buffer& buff, JSON_Tokenizer& tok, INTEGER& length) {
  char *content;
  size_t len;
  json_token_t token;
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_NUMBER) {
    return false;
  }
  CHARSTRING cs(len, content);
  if (cs != "1") {
    return false;
  }
  
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_END) {
    return false;
  }
  
  buff.put_c(127);
  length = length + 1;
  // We do not know the name here. It will be inserted later.
  return true;
}

bool encode_bson_numberlong(TTCN_Buffer& buff, JSON_Tokenizer& tok, INTEGER& length) {
  char *content;
  size_t len;
  json_token_t token;
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_STRING) {
    return false;
  }
  CHARSTRING cs(len-2, content+1);
  
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_END) {
    return false;
  }
  
  buff.put_c(18);
  length = length + 1;
  // We do not know the name here. It will be inserted later.
  INTEGER number = str2int(cs);
  long long int value = number.get_long_long_val();
  for (int i = 0; i < 8; i++) {
    buff.put_c(static_cast<unsigned char>(value >> i*8));
  }
  length = length + 8;
  return true;
}

bool encode_bson_code_with_scope(TTCN_Buffer& buff, JSON_Tokenizer& tok, INTEGER& length) {
  char *content;
  size_t len;
  json_token_t token;
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_STRING) {
    return false;
  }
  CHARSTRING cs(len-2, content+1);
  
  tok.get_next_token(&token, &content, &len);
  if (token != JSON_TOKEN_NAME) {
    return false;
  }
  CHARSTRING cs2(len, content);
  if (cs2 != "$scope") {
    return false;
  }
  
  INTEGER code_w_scope_length = 0;
  bool is_special = false;
  CHARSTRING f_name;
  TTCN_Buffer sub_buff;
  json2bson_coding(sub_buff, tok, false, false, code_w_scope_length, f_name, is_special);
  
  tok.get_next_token(&token, NULL, NULL);
  if (token != JSON_TOKEN_OBJECT_END) {
    return false;
  }
  
  buff.put_c(15);
  length = length + 1;
  // We do not know the name here. It will be inserted later.
  code_w_scope_length = code_w_scope_length + cs.lengthof() + 4 + 1;
  encode_int_bson(buff, code_w_scope_length, code_w_scope_length);
  encode_int_bson(buff, cs.lengthof()+1, length);
  buff.put_string(cs);
  buff.put_c(0); // Closing 0
  buff.put_buf(sub_buff);
  length = length + code_w_scope_length - 4; // We added the length of cs twice
  return true;
}


void json2bson_coding(TTCN_Buffer& buff, JSON_Tokenizer& tok, bool in_object,
       bool in_array, INTEGER& length, CHARSTRING& obj_name, bool& is_special) {
  json_token_t token;
  char* content = NULL;
  size_t len;
  size_t prev_pos = tok.get_buf_pos();
  tok.get_next_token(&token, &content, &len);
1106
1107
  if (in_object == false && token != JSON_TOKEN_OBJECT_START && token != JSON_TOKEN_ARRAY_START) {
    TTCN_error("Json document must be an object or array when encoding with json2bson()");
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
  }
  switch(token) {
    case JSON_TOKEN_OBJECT_START: {
      TTCN_Buffer sub_buff;
      INTEGER sub_len = 0;
      CHARSTRING subobj_name;
      if (obj_name.is_bound()) {
        subobj_name = obj_name;
      }
      while ((prev_pos = tok.get_buf_pos(), tok.get_next_token(&token, NULL, NULL))) {
        if (token != JSON_TOKEN_OBJECT_END) {
          tok.set_buf_pos(prev_pos);
          json2bson_coding(sub_buff, tok, true, false, sub_len, subobj_name, is_special);
          // We found a specially translated json
          if (is_special) {
            // The sub_buff contains the encoded bson except the obj_name.
            // We put it in here after the first byte
            TTCN_Buffer tmp_buff;
            tmp_buff.put_c(*(sub_buff.get_data()));
            put_name(tmp_buff, sub_len, subobj_name, in_array);
            tmp_buff.put_s(sub_buff.get_len()-1, sub_buff.get_data()+1);
            sub_buff = tmp_buff;
            in_object = false;
            break;
          }
        } else {
          sub_buff.put_c(0);// Closing zero
          sub_len = sub_len + 1;
          break;
        }
      }
      
      if (in_object == true) {
        TTCN_Buffer tmp_buff;
        tmp_buff.put_c(3); // embedded document
        length = length + 1;
        put_name(tmp_buff, length, obj_name, in_array);
        encode_int_bson(tmp_buff, sub_len, sub_len);
        length = length + sub_len;
        tmp_buff.put_buf(sub_buff);
        sub_buff = tmp_buff;
      } else if (is_special == false) {
        length = length + sub_len;
        encode_int_bson(buff, length, length);
      } else {
        length = length + sub_len;
        is_special = false;
      }
      buff.put_buf(sub_buff);
      break;
    }
    case JSON_TOKEN_OBJECT_END:
      TTCN_error("Unexpected object end character while encoding using json2bson().");
      break;
    case JSON_TOKEN_NAME: {
      CHARSTRING cs(len, content);
      prev_pos = tok.get_buf_pos();
      if (cs == "$binary") {
        is_special = encode_bson_binary(buff, tok, length);
      } else if (cs == "$date") {
        is_special = encode_bson_date(buff, tok, length);
      } else if (cs == "$timestamp") {
        is_special = encode_bson_timestamp(buff, tok, length);
      } else if (cs == "$regex") {
        is_special = encode_bson_regex(buff, tok, length);
      } else if (cs == "$oid") {
        is_special = encode_bson_oid(buff, tok, length);
      } else if (cs == "$ref") {
        is_special = encode_bson_ref(buff, tok, length);
      } else if (cs == "$undefined") {
        is_special = encode_bson_undefined(buff, tok, length);
      } else if (cs == "$minKey") {
        is_special = encode_bson_minkey(buff, tok, length);
      } else if (cs == "$maxKey") {
        is_special = encode_bson_maxkey(buff, tok, length);
      } else if (cs == "$numberLong") {
        is_special = encode_bson_numberlong(buff, tok, length);
      } else if (cs == "$code") {
        is_special = encode_bson_code_with_scope(buff, tok, length);
      } else {
        obj_name = cs;
      }
      if (!is_special) {
        tok.set_buf_pos(prev_pos);
        obj_name = cs;
      }
      break; }
    case JSON_TOKEN_STRING: {
      buff.put_c(2); // string
      length = length + 1;
      put_name(buff, length, obj_name, in_array);
      encode_int_bson(buff, len-1, length); // Remove "-s but add terminating null
      char * tmp_str = mcopystrn(content+1, len-2); // Remove "-s
      buff.put_string(tmp_str);
      buff.put_c(0); // Closing 0
      length = length + (int)len-1; // Remove "-s but add terminating null
      Free(tmp_str);
      break; }
    case JSON_TOKEN_NUMBER: {
      char *str = mcopystrn(content, len);
      size_t curr_pos = tok.get_buf_pos();
      tok.set_buf_pos(prev_pos);
      bool is_float = false;
      tok.check_for_number(&is_float);
      tok.set_buf_pos(curr_pos);
      if (is_float) {
        buff.put_c(1); // 64bit float
        put_name(buff, length, obj_name, in_array);
        double d;
        sscanf(str, "%lf", &d);
        FLOAT f = d;
        f.encode(bson_float_descr_, buff, TTCN_EncDec::CT_RAW);
      } else {
        INTEGER int_num = str2int(str);
        if (int_num.is_native()) {
          buff.put_c(16); //32bit integer
          length = length + 1;
        } else {
          buff.put_c(18); // 64bit integer
          length = length + 1;
        }
        put_name(buff, length, obj_name, in_array);
        encode_int_bson(buff, int_num, length);
      }
      Free(str);
      break; }
    case JSON_TOKEN_LITERAL_FALSE: {
      buff.put_c(8); // true or false
      put_name(buff, length, obj_name, in_array);
      buff.put_c(0); // false
      break; }
    case JSON_TOKEN_LITERAL_TRUE: {
      buff.put_c(8); // true or false
      put_name(buff, length, obj_name, in_array);
      buff.put_c(1); // true
      break; }
    case JSON_TOKEN_LITERAL_NULL: {
      buff.put_c(10); // null
      put_name(buff, length, obj_name, in_array);
      break; }
    case JSON_TOKEN_ARRAY_START: {
1249
1250
1251
1252
1253
1254
1255
      if (in_object == false) { // The top level json is an array
        in_object = true;
      } else {
        buff.put_c(4); // array
        length = length + 1;
        put_name(buff, length, obj_name, in_array);
      }
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
      obj_name = "0"; // arrays are objects but the key is a number which increases
      TTCN_Buffer sub_buff;
      INTEGER sub_length = 0;
      while ((prev_pos = tok.get_buf_pos(), tok.get_next_token(&token, NULL, NULL))) {
        if (token != JSON_TOKEN_ARRAY_END) {
          tok.set_buf_pos(prev_pos);
          in_array = true;
          json2bson_coding(sub_buff, tok, in_object, in_array, sub_length, obj_name, is_special);
        } else {
          sub_buff.put_c(0);// Closing zero
          sub_length = sub_length + 1;
          break;
        }
      }
      encode_int_bson(buff, sub_length, sub_length);
      length = length + sub_length;
      buff.put_buf(sub_buff);
      break; }
    default:
      TTCN_error("Unexpected json token %i, while encoding using json2bson().", token);
  }
}

void bson2json_coding(TTCN_Buffer& buff, JSON_Tokenizer& tok, bool in_object, bool in_array) {
  INTEGER length = 0;
  // Beginning of the document
  if (in_object == false) {
    length = decode_int_bson(buff, 4);
    // Check if the input is long enough
    check_and_get_buffer_bson(buff, length-4);
    tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
    while (*(check_and_get_buffer_bson(buff, 1)) != 0) {
      bson2json_coding(buff, tok, true, in_array);
    }
    buff.increase_pos(1);
    tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
  } else {
    const unsigned char* type = check_and_get_buffer_bson(buff, 1);
    buff.increase_pos(1);
    // There is always a name
    get_name(buff, tok, in_array);
    switch(*type) {
      case 0: // document end
        TTCN_error("Unexpected document end character while decoding with bson2json()");
        break;
      case 1: { // 64bit float
        FLOAT f;
        check_and_get_buffer_bson(buff, 8);
        f.decode(bson_float_descr_, buff, TTCN_EncDec::CT_RAW);
        f.JSON_encode(bson_float_descr_, tok);
        break;
      }
      case 13: // Javascript code. Decoded as string
      case 14: // Symbol. Decoded as string
      case 2: { // UTF8 string
        INTEGER len = decode_int_bson(buff, 4);
        // Get the value of the pair
        const unsigned char* uc = check_and_get_buffer_bson(buff, (int)len);
        char *tmp_str = mcopystrn(reinterpret_cast<const char*>(uc), (int)len);
        buff.increase_pos((int)len);
        char* tmp_str2 = mprintf("\"%s\"", tmp_str);
        tok.put_next_token(JSON_TOKEN_STRING, tmp_str2);
        Free(tmp_str2);
        Free(tmp_str);
        break; }
      case 3: { // Embedded document
        length = decode_int_bson(buff, 4);
        // Check if the input is long enough
        check_and_get_buffer_bson(buff, length-4);
        tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
        while (*(check_and_get_buffer_bson(buff, 1)) != 0) { // error message while converting
          bson2json_coding(buff, tok, in_object, false);
        }
        buff.increase_pos(1); // Skip the closing 0
        tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
        break; }
      case 4: { // array
        length = decode_int_bson(buff, 4);
        // Check if the input is long enough
        check_and_get_buffer_bson(buff, length-4);
        tok.put_next_token(JSON_TOKEN_ARRAY_START, NULL);
        in_array = true;
        while (*(check_and_get_buffer_bson(buff, 1)) != 0) { // erorr message while converting
          bson2json_coding(buff, tok, in_object, in_array);
        }
        buff.increase_pos(1); // Skip the closing 0
        tok.put_next_token(JSON_TOKEN_ARRAY_END, NULL);
        break; }
      case 5: { // bytestring
        // decode bytestring length
        INTEGER bytestr_length = decode_int_bson(buff, 4);
        OCTETSTRING os(1, check_and_get_buffer_bson(buff, 1));
        buff.increase_pos(1);
        INTEGER typestr_type = oct2int(os);
        char* str_type = mprintf("\"%02x\"", (int)typestr_type);
        OCTETSTRING data(bytestr_length, check_and_get_buffer_bson(buff, bytestr_length));
        buff.increase_pos(bytestr_length);
        CHARSTRING cs = encode_base64(data);
        char* data_str = mprintf("\"%s\"", (const char*)cs);
        tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
        tok.put_next_token(JSON_TOKEN_NAME, "$binary");
        tok.put_next_token(JSON_TOKEN_STRING, data_str);
        tok.put_next_token(JSON_TOKEN_NAME, "$type");
        tok.put_next_token(JSON_TOKEN_STRING, str_type);
        tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
        Free(data_str);
        Free(str_type);
        break; }
      case 6: { // undefined
        tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
        tok.put_next_token(JSON_TOKEN_NAME, "$undefined");
        tok.put_next_token(JSON_TOKEN_LITERAL_TRUE);
        tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
        break; }
      case 7: { // oid
        OCTETSTRING os(12, check_and_get_buffer_bson(buff, 12));
        char* tmp_oct = NULL;
        for (size_t i = 0; i < 12; i++) {
          tmp_oct = mputprintf(tmp_oct, "%02X", os[i].get_octet());
        }
        char *str_hex = mprintf("\"%s\"", tmp_oct);
        buff.increase_pos(12);
        tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
        tok.put_next_token(JSON_TOKEN_NAME, "$oid");
        tok.put_next_token(JSON_TOKEN_STRING, str_hex);
        tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
        Free(str_hex);
        Free(tmp_oct);
        break; }
      case 8: {  // true or false
        const unsigned char* uc = check_and_get_buffer_bson(buff, 1);
        if (*uc == 0) {
          tok.put_next_token(JSON_TOKEN_LITERAL_FALSE, NULL);
        } else {
          tok.put_next_token(JSON_TOKEN_LITERAL_TRUE, NULL);
        }
        buff.increase_pos(1);
        break;
      }
      case 9: { // datetime
        INTEGER date = decode_int_bson(buff, 8);
        char *tmp_str = mprintf("%lld", date.get_long_long_val());
        tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
        tok.put_next_token(JSON_TOKEN_NAME, "$date");
        tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
        tok.put_next_token(JSON_TOKEN_NAME, "$numberLong");
        tok.put_next_token(JSON_TOKEN_NUMBER, tmp_str);
        tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
        tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
        Free(tmp_str);
        break; }
      case 10: { // null
        tok.put_next_token(JSON_TOKEN_LITERAL_NULL, NULL);
        break;
      }
      case 11: { // regex
        // copy until closing 0
        const unsigned char* uc = check_and_get_buffer_bson(buff, 1);
        char *tmp_str = mcopystr(reinterpret_cast<const char*>(uc));
        buff.increase_pos(strlen(tmp_str)+1);
        char *regex = mprintf("\"%s\"", tmp_str);
        Free(tmp_str);
        uc = check_and_get_buffer_bson(buff, 1);
        tmp_str = mcopystr(reinterpret_cast<const char*>(uc));
        buff.increase_pos(strlen(tmp_str)+1);
        char *options = mprintf("\"%s\"", tmp_str);
        Free(tmp_str);
        tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
        tok.put_next_token(JSON_TOKEN_NAME, "$regex");
        tok.put_next_token(JSON_TOKEN_STRING, regex);
        tok.put_next_token(JSON_TOKEN_NAME, "$options");
        tok.put_next_token(JSON_TOKEN_STRING, options);
        tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
        Free(options);
        Free(regex);
        break; }
      case 12: { // dbref
        INTEGER name_len = decode_int_bson(buff, 4);
        const unsigned char* uc = check_and_get_buffer_bson(buff, (int)name_len);
        char *tmp_name = mcopystrn(reinterpret_cast<const char*>(uc), (int)name_len);
        buff.increase_pos((int)name_len);
        char* tmp_str = mprintf("\"%s\"", tmp_name);
        OCTETSTRING os(12, check_and_get_buffer_bson(buff, 12));
        buff.increase_pos(12);
        char* tmp_oct = NULL;
        for (size_t i = 0; i < 12; i++) {
          tmp_oct = mputprintf(tmp_oct, "%02X", os[i].get_octet());
        }
        char *str_hex = mprintf("\"%s\"", tmp_oct);
        tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
        tok.put_next_token(JSON_TOKEN_NAME, "$ref");
        tok.put_next_token(JSON_TOKEN_STRING, tmp_str);
        tok.put_next_token(JSON_TOKEN_NAME, "$id");
        tok.put_next_token(JSON_TOKEN_STRING, str_hex);
        tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
        Free(tmp_oct);
        Free(str_hex);
        Free(tmp_str);
        Free(tmp_name);
        break; }
      case 15: { // code_with_scope
        INTEGER len = decode_int_bson(buff, 4);
        check_and_get_buffer_bson(buff, (int)len-4); // len contains the length of itself
        len = decode_int_bson(buff, 4);
        const unsigned char* uc = check_and_get_buffer_bson(buff, (int)len);
        char *tmp_str = mcopystrn(reinterpret_cast<const char*>(uc), (int)len);
        char *tmp_str2 = mprintf("\"%s\"", tmp_str);
        buff.increase_pos((int)len);
        tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
        tok.put_next_token(JSON_TOKEN_NAME, "$code");
        tok.put_next_token(JSON_TOKEN_STRING, tmp_str2);
        tok.put_next_token(JSON_TOKEN_NAME, "$scope");
        bson2json_coding(buff, tok, false, false);
        tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
        Free(tmp_str2);
        Free(tmp_str);
        break; }
      case 16: { // 32bit integer
        INTEGER value = decode_int_bson(buff, 4);
        char *tmp_str = mprintf("%d", (int)value);
        tok.put_next_token(JSON_TOKEN_NUMBER, tmp_str);
        Free(tmp_str);
        break; }
      case 17: { // timestamp
        INTEGER increment = decode_int_bson(buff, 4);
        INTEGER timestamp = decode_int_bson(buff, 4);
        char *increment_str = mprintf("%i", (int)increment);
        char *timestamp_str = mprintf("%i", (int)timestamp);
        tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
        tok.put_next_token(JSON_TOKEN_NAME, "$timestamp");
        tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
        tok.put_next_token(JSON_TOKEN_NAME, "t");
        tok.put_next_token(JSON_TOKEN_STRING, timestamp_str);
        tok.put_next_token(JSON_TOKEN_NAME, "i");
        tok.put_next_token(JSON_TOKEN_STRING, increment_str);
        tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
        tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
        Free(timestamp_str);
        Free(increment_str);
        break; }
      case 18: { //64 bit integer
        INTEGER value = decode_int_bson(buff, 8);
        char *tmp_str = mprintf("%lld", value.get_long_long_val());
        tok.put_next_token(JSON_TOKEN_NUMBER, tmp_str);
        Free(tmp_str);
        break; }
      case 127: { // maxkey
        tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
        tok.put_next_token(JSON_TOKEN_NAME, "$maxKey");
        tok.put_next_token(JSON_TOKEN_NUMBER, "1");
        tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
        break; }
      case 255: { // minkey
        tok.put_next_token(JSON_TOKEN_OBJECT_START, NULL);
        tok.put_next_token(JSON_TOKEN_NAME, "$minKey");
        tok.put_next_token(JSON_TOKEN_NUMBER, "1");
        tok.put_next_token(JSON_TOKEN_OBJECT_END, NULL);
        break; }
      default:
        TTCN_error("Unexpected type %i while decoding using bson2json().", *type);
    }
  }
}