3 * Generic converter template for a selected ASN.1 type.
4 * Copyright (c) 2005-2017 Lev Walkin <vlm@lionet.info>.
7 * To compile with your own ASN.1 type, redefine the PDU as shown:
9 * cc -DPDU=MyCustomType -o myDecoder.o -c converter-example.c
14 #define __EXTENSIONS__
16 #include <sys/types.h>
17 #include <stdlib.h> /* for atoi(3) */
18 #include <getopt.h> /* for getopt(3) */
19 #include <string.h> /* for strerror(3) */
20 #include <sysexits.h> /* for EX_* exit codes */
21 #include <errno.h> /* for errno */
22 #include <unistd.h> /* for isatty(3) */
23 #include <asn_application.h>
24 #include <asn_internal.h> /* for ASN__DEFAULT_STACK_MAX */
26 /* Convert "Type" defined by -DPDU into "asn_DEF_Type" */
28 #define ASN_DEF_PDU(t) asn_DEF_ ## t
29 #define DEF_PDU_Type(t) ASN_DEF_PDU(t)
30 #define PDU_Type DEF_PDU_Type(PDU)
31 extern asn_TYPE_descriptor_t PDU_Type; /* ASN.1 type to be decoded */
32 #define PDU_Type_Ptr (&PDU_Type)
34 #define PDU_Type_Ptr NULL
37 #ifdef ASN_PDU_COLLECTION /* Generated by asn1c -pdu=... */
38 extern asn_TYPE_descriptor_t *asn_pdu_collection[];
42 #if !defined(PDU) && !defined(ASN_PDU_COLLECTION)
43 #error Define -DPDU to compile this example converter.
44 #error `asn1c -pdu=...` adds necessary flags automatically.
49 * Open file and parse its contens.
51 static void *data_decode_from_file(enum asn_transfer_syntax,
52 asn_TYPE_descriptor_t *asnTypeOfPDU,
53 FILE *file, const char *name,
54 ssize_t suggested_bufsize, int first_pdu);
55 static int write_out(const void *buffer, size_t size, void *key);
56 static FILE *argument_to_file(char *av[], int idx);
57 static char *argument_to_name(char *av[], int idx);
59 int opt_debug; /* -d (or -dd) */
60 static int opt_check; /* -c (constraints checking) */
61 static int opt_stack; /* -s (maximum stack size) */
62 static int opt_nopad; /* -per-nopad (PER input is not padded between msgs) */
63 static int opt_onepdu; /* -1 (decode single PDU) */
65 #ifdef JUNKTEST /* Enable -J <probability> */
67 static double opt_jprob; /* Junk bit probability */
68 static int junk_failures;
69 static void junk_bytes_with_probability(uint8_t *, size_t, double prob);
72 static ssize_t random_max_size = 0; /* Size of the random data */
74 #if !defined(__FreeBSD__) && !(defined(__APPLE__) && defined(__MACH__))
77 FILE *f = fopen("/dev/urandom", "rb");
80 if(fread(&seed, 1, sizeof(seed), f) != sizeof(seed)) {
96 /* Debug output function */
97 static void CC_PRINTFLIKE(1, 2)
98 DEBUG(const char *fmt, ...) {
100 if(!opt_debug) return;
101 fprintf(stderr, "AD: ");
103 vfprintf(stderr, fmt, ap);
105 fprintf(stderr, "\n");
109 ats_simple_name(enum asn_transfer_syntax syntax) {
113 case ATS_NONSTANDARD_PLAINTEXT:
122 case ATS_CANONICAL_OER:
125 case ATS_CANONICAL_XER:
127 case ATS_UNALIGNED_BASIC_PER:
128 case ATS_UNALIGNED_CANONICAL_PER:
135 #define CODEC_OFFSET(fname) ((ptrdiff_t)&(((asn_TYPE_operation_t *)0)->fname))
138 enum asn_transfer_syntax syntax;
139 ptrdiff_t codec_offset;
140 const char *full_name;
143 static syntax_selector input_encodings[] = {
144 {"ber", ATS_BER, CODEC_OFFSET(ber_decoder),
145 "Input is in BER (Basic Encoding Rules) or DER"},
146 {"oer", ATS_BASIC_OER, CODEC_OFFSET(oer_decoder),
147 "Input is in OER (Octet Encoding Rules)"},
148 {"per", ATS_UNALIGNED_BASIC_PER, CODEC_OFFSET(uper_decoder),
149 "Input is in Unaligned PER (Packed Encoding Rules)"},
150 {"aper", ATS_ALIGNED_BASIC_PER, CODEC_OFFSET(aper_decoder),
151 "Input is in Aligned PER (Packed Encoding Rules)"},
152 {"xer", ATS_BASIC_XER, CODEC_OFFSET(xer_decoder),
153 "Input is in XER (XML Encoding Rules)"},
154 {0, ATS_INVALID, 0, 0}};
156 static syntax_selector output_encodings[] = {
157 {"der", ATS_DER, CODEC_OFFSET(der_encoder),
158 "Output as DER (Distinguished Encoding Rules)"},
159 {"oer", ATS_CANONICAL_OER, CODEC_OFFSET(oer_encoder),
160 "Output as Canonical OER (Octet Encoding Rules)"},
161 {"per", ATS_UNALIGNED_CANONICAL_PER, CODEC_OFFSET(uper_encoder),
162 "Output as Unaligned PER (Packed Encoding Rules)"},
163 {"aper", ATS_ALIGNED_CANONICAL_PER, CODEC_OFFSET(aper_encoder),
164 "Output as Aligned PER (Packed Encoding Rules)"},
165 {"xer", ATS_BASIC_XER, CODEC_OFFSET(xer_encoder),
166 "Output as XER (XML Encoding Rules)"},
167 {"text", ATS_NONSTANDARD_PLAINTEXT, CODEC_OFFSET(print_struct),
168 "Output as plain semi-structured text"},
169 {"null", ATS_INVALID, CODEC_OFFSET(print_struct),
170 "Verify (decode) input, but do not output"},
171 {0, ATS_INVALID, 0, 0}};
174 has_codec_defined(const asn_TYPE_descriptor_t *td,
175 const syntax_selector *element) {
176 return *(const void *const *)(const void *)((const char *)td->op
177 + element->codec_offset) != 0;
181 * Select ASN.1 Transfer Enocoding Syntax by command line name.
183 static const syntax_selector *
184 ats_by_name(const char *name, const asn_TYPE_descriptor_t *td,
185 const syntax_selector *first_element) {
186 const syntax_selector *element;
187 for(element = first_element; element->name; element++) {
188 if(strcmp(element->name, name) == 0) {
189 if(td && td->op && has_codec_defined(td, element)) {
198 main(int ac, char *av[]) {
200 asn_TYPE_descriptor_t *pduType = PDU_Type_Ptr;
201 asn_TYPE_descriptor_t *anyPduType = PDU_Type_Ptr;
202 ssize_t suggested_bufsize = 8192; /* close or equal to stdio buffer */
203 int number_of_iterations = 1;
206 const syntax_selector *sel;
207 enum asn_transfer_syntax isyntax = ATS_INVALID;
208 enum asn_transfer_syntax osyntax = ATS_BASIC_XER;
211 #ifdef ASN_PDU_COLLECTION
212 anyPduType = asn_pdu_collection[0];
215 "Empty PDU collection, no reference PDU to choose from.\n");
219 fprintf(stderr, "Either asn1c -pdu=... or cc -DPDU should be used.\n");
224 /* Figure out if a specialty decoder needs to be default */
225 #ifndef ASN_DISABLE_OER_SUPPORT
226 isyntax = ATS_BASIC_OER;
228 #ifndef ASN_DISABLE_PER_SUPPORT
229 isyntax = ATS_UNALIGNED_BASIC_PER;
233 * Pocess the command-line argments.
235 while((ch = getopt(ac, av, "i:o:1b:cdn:p:hs:" JUNKOPT RANDOPT)) != -1)
238 sel = ats_by_name(optarg, anyPduType, input_encodings);
240 isyntax = sel->syntax;
242 fprintf(stderr, "-i<format>: '%s': improper format selector\n",
244 exit(EX_UNAVAILABLE);
248 sel = ats_by_name(optarg, anyPduType, output_encodings);
250 osyntax = sel->syntax;
252 fprintf(stderr, "-o<format>: '%s': improper format selector\n",
254 exit(EX_UNAVAILABLE);
261 suggested_bufsize = atoi(optarg);
262 if(suggested_bufsize < 1
263 || suggested_bufsize > 16 * 1024 * 1024) {
265 "-b %s: Improper buffer size (1..16M)\n",
267 exit(EX_UNAVAILABLE);
274 opt_debug++; /* Double -dd means ASN.1 debug */
277 number_of_iterations = atoi(optarg);
278 if(number_of_iterations < 1) {
280 "-n %s: Improper iterations count\n", optarg);
281 exit(EX_UNAVAILABLE);
285 if(strcmp(optarg, "er-nopad") == 0) {
289 #ifdef ASN_PDU_COLLECTION
290 if(strcmp(optarg, "list") == 0) {
291 asn_TYPE_descriptor_t **pdu = asn_pdu_collection;
292 fprintf(stderr, "Available PDU types:\n");
293 for(; *pdu; pdu++) printf("%s\n", (*pdu)->name);
295 } else if(optarg[0] >= 'A' && optarg[0] <= 'Z') {
296 asn_TYPE_descriptor_t **pdu = asn_pdu_collection;
297 while(*pdu && strcmp((*pdu)->name, optarg)) pdu++;
298 if(*pdu) { pduType = *pdu; break; }
299 fprintf(stderr, "-p %s: Unrecognized PDU. Try '-p list'.\n",
303 #else /* Without -pdu=auto there's just a single type */
304 if(strcmp(optarg, "list") == 0) {
305 fprintf(stderr, "Available PDU types:\n");
307 printf("%s\n", pduType->name);
310 } else if(optarg[0] >= 'A' && optarg[0] <= 'Z') {
311 if(pduType && strcmp(optarg, pduType->name) == 0) {
314 fprintf(stderr, "-p %s: Unrecognized PDU. Try '-p list'.\n",
318 #endif /* ASN_PDU_COLLECTION */
319 fprintf(stderr, "-p %s: Unrecognized option\n", optarg);
320 exit(EX_UNAVAILABLE);
322 opt_stack = atoi(optarg);
325 "-s %s: Non-negative value expected\n",
327 exit(EX_UNAVAILABLE);
332 opt_jprob = strtod(optarg, 0);
333 if(opt_jprob <= 0.0 || opt_jprob > 1.0) {
335 "-J %s: Probability range 0..1 expected \n",
337 exit(EX_UNAVAILABLE);
341 isyntax = ATS_RANDOM;
342 random_max_size = atoi(optarg);
343 if(random_max_size < 0) {
345 "-R %s: Non-negative value expected\n",
347 exit(EX_UNAVAILABLE);
351 #endif /* JUNKTEST */
354 #ifdef ASN_CONVERTER_TITLE
356 #define _ASX(x) _AXS(x)
357 fprintf(stderr, "%s\n", _ASX(ASN_CONVERTER_TITLE));
359 fprintf(stderr, "Usage: %s [options] <datafile> ...\n", av[0]);
360 fprintf(stderr, "Where options are:\n");
361 for(sel = input_encodings; sel->name; sel++) {
362 if(ats_by_name(sel->name, anyPduType, sel)) {
363 fprintf(stderr, " -i%s %s%s\n", sel->name,
365 (sel->syntax == isyntax) ? " (DEFAULT)" : "");
368 for(sel = output_encodings; sel->name; sel++) {
369 if(ats_by_name(sel->name, anyPduType, sel)) {
370 fprintf(stderr, " -o%s%s %s%s\n", sel->name,
371 strlen(sel->name) > 3 ? "" : " ",
373 (sel->syntax == osyntax) ? " (DEFAULT)" : "");
376 if(anyPduType->op->uper_decoder) {
378 " -per-nopad Assume PER PDUs are not padded (-iper)\n");
380 #ifdef ASN_PDU_COLLECTION
382 " -p <PDU> Specify PDU type to decode\n"
383 " -p list List available PDUs\n");
384 #endif /* ASN_PDU_COLLECTION */
386 " -1 Decode only the first PDU in file\n"
387 " -b <size> Set the i/o buffer size (default is %ld)\n"
388 " -c Check ASN.1 constraints after decoding\n"
389 " -d Enable debugging (-dd is even better)\n"
390 " -n <num> Process files <num> times\n"
391 " -s <size> Set the stack usage limit (default is %d)\n"
393 " -J <prob> Set random junk test bit garbaging probability\n"
394 " -R <size> Generate a random value of roughly the given size,\n"
395 " instead of parsing the value from file.\n"
397 , (long)suggested_bufsize, ASN__DEFAULT_STACK_MAX);
406 fprintf(stderr, "No -DPDU defined during compilation.\n");
409 fprintf(stderr, "Use '-p <Type>' or '-p list' to select ASN.1 type.\n");
411 #endif /* NO_ASN_PDU */
414 if(ac < 1 && isyntax != ATS_RANDOM) {
415 fprintf(stderr, "%s: No input files specified. "
416 "Try '-h' for more information\n",
422 const int is_text_output = osyntax == ATS_NONSTANDARD_PLAINTEXT
423 || osyntax == ATS_BASIC_XER
424 || osyntax == ATS_CANONICAL_XER;
428 fprintf(stderr, "(Suppressing binary output to a terminal.)\n");
429 binary_out = fopen("/dev/null", "wb");
431 fprintf(stderr, "Can't open /dev/null: %s\n", strerror(errno));
438 setvbuf(stdout, 0, _IOLBF, 0);
440 for(num = 0; num < number_of_iterations; num++) {
443 * Process all files in turn.
445 for(ac_i = (isyntax == ATS_RANDOM) ? -1 : 0; ac_i < ac; ac_i++) {
446 asn_enc_rval_t erv = {0,0,0};
447 void *structure; /* Decoded structure */
454 name = "<random value generator>";
457 file = argument_to_file(av, ac_i);
458 name = argument_to_name(av, ac_i);
461 for(first_pdu = 1; (first_pdu || !opt_onepdu); first_pdu = 0) {
463 * Decode the encoded structure from file.
466 if(isyntax == ATS_RANDOM) {
468 if(asn_random_fill(pduType, &structure, random_max_size) != 0) {
469 fprintf(stderr, "Cannot generate a random value.\n");
470 assert(structure == NULL);
475 structure = data_decode_from_file(isyntax, pduType, file, name,
476 suggested_bufsize, first_pdu);
482 /* Error message is already printed */
490 /* Check ASN.1 constraints */
493 size_t errlen = sizeof(errbuf);
494 if(asn_check_constraints(pduType, structure, errbuf, &errlen)) {
496 "%s: ASN.1 constraint "
497 "check failed: %s\n",
503 if(osyntax == ATS_INVALID) {
505 if(opt_jprob == 0.0) {
506 fprintf(stderr, "%s: decoded successfully\n", name);
509 fprintf(stderr, "%s: decoded successfully\n", name);
512 erv = asn_encode(NULL, osyntax, pduType, structure, write_out,
515 if(erv.encoded == -1) {
516 fprintf(stderr, "%s: Cannot convert %s into %s\n", name,
517 pduType->name, ats_simple_name(osyntax));
518 DEBUG("Conversion failed for %s:\n", pduType->name);
519 asn_fprint(stderr, pduType, structure);
520 exit(EX_UNAVAILABLE);
522 DEBUG("Encoded in %" ASN_PRI_SSIZE " bytes of %s", erv.encoded,
523 ats_simple_name(osyntax));
526 ASN_STRUCT_FREE(*pduType, structure);
529 if(file && file != stdin) {
536 if(opt_jprob > 0.0) {
537 fprintf(stderr, "Junked %f OK (%d/%d)\n",
538 opt_jprob, junk_failures, number_of_iterations);
540 #endif /* JUNKTEST */
545 static struct dynamic_buffer {
546 uint8_t *data; /* Pointer to the data bytes */
547 size_t offset; /* Offset from the start */
548 size_t length; /* Length of meaningful contents */
549 size_t unbits; /* Unused bits in the last byte */
550 size_t allocated; /* Allocated memory for data */
551 int nreallocs; /* Number of data reallocations */
552 off_t bytes_shifted; /* Number of bytes ever shifted */
557 uint8_t *p = DynamicBuffer.data + DynamicBuffer.offset;
558 uint8_t *e = p + DynamicBuffer.length - (DynamicBuffer.unbits ? 1 : 0);
559 if(!opt_debug) return;
560 DEBUG("Buffer: { d=%p, o=%" ASN_PRI_SIZE ", l=%" ASN_PRI_SIZE
561 ", u=%" ASN_PRI_SIZE ", a=%" ASN_PRI_SIZE ", s=%" ASN_PRI_SIZE " }",
562 (const void *)DynamicBuffer.data,
563 DynamicBuffer.offset,
564 DynamicBuffer.length,
565 DynamicBuffer.unbits,
566 DynamicBuffer.allocated,
567 (size_t)DynamicBuffer.bytes_shifted);
569 fprintf(stderr, " %c%c%c%c%c%c%c%c",
570 ((*p >> 7) & 1) ? '1' : '0',
571 ((*p >> 6) & 1) ? '1' : '0',
572 ((*p >> 5) & 1) ? '1' : '0',
573 ((*p >> 4) & 1) ? '1' : '0',
574 ((*p >> 3) & 1) ? '1' : '0',
575 ((*p >> 2) & 1) ? '1' : '0',
576 ((*p >> 1) & 1) ? '1' : '0',
577 ((*p >> 0) & 1) ? '1' : '0');
579 if(DynamicBuffer.unbits) {
581 fprintf(stderr, " ");
582 for(shift = 7; shift >= DynamicBuffer.unbits; shift--)
583 fprintf(stderr, "%c", ((*p >> shift) & 1) ? '1' : '0');
584 fprintf(stderr, " %" ASN_PRI_SSIZE ":%" ASN_PRI_SSIZE "\n",
585 (ssize_t)DynamicBuffer.length - 1,
586 (ssize_t)8 - DynamicBuffer.unbits);
588 fprintf(stderr, " %ld\n", (long)DynamicBuffer.length);
593 * Move the buffer content left N bits, possibly joining it with
594 * preceeding content.
597 buffer_shift_left(size_t offset, int bits) {
598 uint8_t *ptr = DynamicBuffer.data + DynamicBuffer.offset + offset;
599 uint8_t *end = DynamicBuffer.data + DynamicBuffer.offset
600 + DynamicBuffer.length - 1;
604 DEBUG("Shifting left %d bits off %ld (o=%ld, u=%ld, l=%ld)",
606 (long)DynamicBuffer.offset,
607 (long)DynamicBuffer.unbits,
608 (long)DynamicBuffer.length);
612 right = ptr[0] >> (8 - bits);
614 DEBUG("oleft: %c%c%c%c%c%c%c%c",
615 ((ptr[-1] >> 7) & 1) ? '1' : '0',
616 ((ptr[-1] >> 6) & 1) ? '1' : '0',
617 ((ptr[-1] >> 5) & 1) ? '1' : '0',
618 ((ptr[-1] >> 4) & 1) ? '1' : '0',
619 ((ptr[-1] >> 3) & 1) ? '1' : '0',
620 ((ptr[-1] >> 2) & 1) ? '1' : '0',
621 ((ptr[-1] >> 1) & 1) ? '1' : '0',
622 ((ptr[-1] >> 0) & 1) ? '1' : '0');
624 DEBUG("oriht: %c%c%c%c%c%c%c%c",
625 ((ptr[0] >> 7) & 1) ? '1' : '0',
626 ((ptr[0] >> 6) & 1) ? '1' : '0',
627 ((ptr[0] >> 5) & 1) ? '1' : '0',
628 ((ptr[0] >> 4) & 1) ? '1' : '0',
629 ((ptr[0] >> 3) & 1) ? '1' : '0',
630 ((ptr[0] >> 2) & 1) ? '1' : '0',
631 ((ptr[0] >> 1) & 1) ? '1' : '0',
632 ((ptr[0] >> 0) & 1) ? '1' : '0');
634 DEBUG("mriht: %c%c%c%c%c%c%c%c",
635 ((right >> 7) & 1) ? '1' : '0',
636 ((right >> 6) & 1) ? '1' : '0',
637 ((right >> 5) & 1) ? '1' : '0',
638 ((right >> 4) & 1) ? '1' : '0',
639 ((right >> 3) & 1) ? '1' : '0',
640 ((right >> 2) & 1) ? '1' : '0',
641 ((right >> 1) & 1) ? '1' : '0',
642 ((right >> 0) & 1) ? '1' : '0');
644 ptr[-1] = (ptr[-1] & (0xff << bits)) | right;
646 DEBUG("after: %c%c%c%c%c%c%c%c",
647 ((ptr[-1] >> 7) & 1) ? '1' : '0',
648 ((ptr[-1] >> 6) & 1) ? '1' : '0',
649 ((ptr[-1] >> 5) & 1) ? '1' : '0',
650 ((ptr[-1] >> 4) & 1) ? '1' : '0',
651 ((ptr[-1] >> 3) & 1) ? '1' : '0',
652 ((ptr[-1] >> 2) & 1) ? '1' : '0',
653 ((ptr[-1] >> 1) & 1) ? '1' : '0',
654 ((ptr[-1] >> 0) & 1) ? '1' : '0');
659 for(; ptr < end; ptr++) {
660 int right = ptr[1] >> (8 - bits);
661 *ptr = (*ptr << bits) | right;
665 DEBUG("Unbits [%" ASN_PRI_SIZE "=>", DynamicBuffer.unbits);
666 if(DynamicBuffer.unbits == 0) {
667 DynamicBuffer.unbits += bits;
669 DynamicBuffer.unbits += bits;
670 if(DynamicBuffer.unbits > 7) {
671 DynamicBuffer.unbits -= 8;
672 DynamicBuffer.length--;
673 DynamicBuffer.bytes_shifted++;
676 DEBUG("Unbits =>%" ASN_PRI_SIZE "]", DynamicBuffer.unbits);
680 DEBUG("Shifted. Now (o=%" ASN_PRI_SIZE ", u=%" ASN_PRI_SIZE
681 " l=%" ASN_PRI_SIZE ")",
682 DynamicBuffer.offset,
683 DynamicBuffer.unbits,
684 DynamicBuffer.length);
688 * Ensure that the buffer contains at least this amount of free space.
690 static void add_bytes_to_buffer(const void *data2add, size_t bytes) {
692 if(bytes == 0) return;
694 DEBUG("=> add_bytes(%" ASN_PRI_SIZE ") { o=%" ASN_PRI_SIZE
695 " l=%" ASN_PRI_SIZE " u=%" ASN_PRI_SIZE ", s=%" ASN_PRI_SIZE " }",
697 DynamicBuffer.offset,
698 DynamicBuffer.length,
699 DynamicBuffer.unbits,
700 DynamicBuffer.allocated);
702 if(DynamicBuffer.allocated
703 >= (DynamicBuffer.offset + DynamicBuffer.length + bytes)) {
704 DEBUG("\tNo buffer reallocation is necessary");
705 } else if(bytes <= DynamicBuffer.offset) {
706 DEBUG("\tContents shifted by %ld", DynamicBuffer.offset);
708 /* Shift the buffer contents */
709 memmove(DynamicBuffer.data,
710 DynamicBuffer.data + DynamicBuffer.offset,
711 DynamicBuffer.length);
712 DynamicBuffer.bytes_shifted += DynamicBuffer.offset;
713 DynamicBuffer.offset = 0;
715 size_t newsize = (DynamicBuffer.allocated << 2) + bytes;
716 void *p = MALLOC(newsize);
721 if (DynamicBuffer.length) {
723 DynamicBuffer.data + DynamicBuffer.offset,
724 DynamicBuffer.length);
726 FREEMEM(DynamicBuffer.data);
727 DynamicBuffer.data = (uint8_t *)p;
728 DynamicBuffer.offset = 0;
729 DynamicBuffer.allocated = newsize;
730 DynamicBuffer.nreallocs++;
731 DEBUG("\tBuffer reallocated to %ld (%d time)",
732 newsize, DynamicBuffer.nreallocs);
735 memcpy(DynamicBuffer.data
736 + DynamicBuffer.offset + DynamicBuffer.length,
738 DynamicBuffer.length += bytes;
739 if(DynamicBuffer.unbits) {
740 int bits = DynamicBuffer.unbits;
741 DynamicBuffer.unbits = 0;
742 buffer_shift_left(DynamicBuffer.length - bytes, bits);
745 DEBUG("<= add_bytes(%" ASN_PRI_SIZE ") { o=%" ASN_PRI_SIZE
746 " l=%" ASN_PRI_SIZE " u=%" ASN_PRI_SIZE ", s=%" ASN_PRI_SIZE " }",
748 DynamicBuffer.offset,
749 DynamicBuffer.length,
750 DynamicBuffer.unbits,
751 DynamicBuffer.allocated);
755 is_syntax_PER(enum asn_transfer_syntax syntax) {
756 return (syntax == ATS_UNALIGNED_BASIC_PER
757 || syntax == ATS_UNALIGNED_CANONICAL_PER
758 || syntax == ATS_ALIGNED_BASIC_PER
759 || syntax == ATS_ALIGNED_CANONICAL_PER);
763 restartability_supported(enum asn_transfer_syntax syntax) {
764 return !is_syntax_PER(syntax);
768 data_decode_from_file(enum asn_transfer_syntax isyntax, asn_TYPE_descriptor_t *pduType, FILE *file, const char *name, ssize_t suggested_bufsize, int on_first_pdu) {
769 static uint8_t *fbuf;
770 static ssize_t fbuf_size;
771 static asn_codec_ctx_t s_codec_ctx;
772 asn_codec_ctx_t *opt_codec_ctx = 0;
781 fprintf(stderr, "%s: %s\n", name, strerror(errno));
787 s_codec_ctx.max_stack_size = opt_stack;
788 opt_codec_ctx = &s_codec_ctx;
791 DEBUG("Processing %s", name);
793 /* prepare the file buffer */
794 if(fbuf_size != suggested_bufsize) {
795 fbuf = (uint8_t *)REALLOC(fbuf, suggested_bufsize);
800 fbuf_size = suggested_bufsize;
804 DynamicBuffer.offset = 0;
805 DynamicBuffer.length = 0;
806 DynamicBuffer.unbits = 0;
807 DynamicBuffer.allocated = 0;
808 DynamicBuffer.bytes_shifted = 0;
809 DynamicBuffer.nreallocs = 0;
812 old_offset = DynamicBuffer.bytes_shifted + DynamicBuffer.offset;
814 /* Pretend immediate EOF */
815 rval.code = RC_WMORE;
818 for(tolerate_eof = 1; /* Allow EOF first time buffer is non-empty */
819 (rd = fread(fbuf, 1, fbuf_size, file))
821 || (tolerate_eof && DynamicBuffer.length)
823 int ecbits = 0; /* Extra consumed bits in case of PER */
828 * Copy the data over, or use the original buffer.
830 if(DynamicBuffer.allocated) {
831 /* Append new data into the existing dynamic buffer */
832 add_bytes_to_buffer(fbuf, rd);
833 i_bptr = DynamicBuffer.data + DynamicBuffer.offset;
834 i_size = DynamicBuffer.length;
840 DEBUG("Decoding %" ASN_PRI_SIZE " bytes", i_size);
843 junk_bytes_with_probability(i_bptr, i_size, opt_jprob);
846 if(is_syntax_PER(isyntax) && opt_nopad) {
847 #ifdef ASN_DISABLE_PER_SUPPORT
851 if(isyntax == ATS_UNALIGNED_BASIC_PER)
852 rval = uper_decode(opt_codec_ctx, pduType, (void **)&structure,
853 i_bptr, i_size, 0, DynamicBuffer.unbits);
855 rval = aper_decode(opt_codec_ctx, pduType, (void **)&structure,
856 i_bptr, i_size, 0, DynamicBuffer.unbits);
857 /* uper_decode() returns bits! */
858 ecbits = rval.consumed % 8; /* Bits consumed from the last byte */
859 rval.consumed >>= 3; /* Convert bits into bytes. */
861 /* Non-padded PER decoder */
863 rval = asn_decode(opt_codec_ctx, isyntax, pduType,
864 (void **)&structure, i_bptr, i_size);
866 if(rval.code == RC_WMORE && !restartability_supported(isyntax)) {
867 /* PER does not support restartability */
868 ASN_STRUCT_FREE(*pduType, structure);
871 /* Continue accumulating data */
874 DEBUG("decode(%" ASN_PRI_SIZE ") consumed %" ASN_PRI_SIZE
875 "+%db (%" ASN_PRI_SIZE "), code %d",
876 DynamicBuffer.length, rval.consumed, ecbits, i_size, rval.code);
878 if(DynamicBuffer.allocated == 0) {
880 * Flush remainder into the intermediate buffer.
882 if(rval.code != RC_FAIL && rval.consumed < rd) {
883 add_bytes_to_buffer(fbuf + rval.consumed,
885 buffer_shift_left(0, ecbits);
886 DynamicBuffer.bytes_shifted = rval.consumed;
893 * Adjust position inside the source buffer.
895 if(DynamicBuffer.allocated) {
896 DynamicBuffer.offset += rval.consumed;
897 DynamicBuffer.length -= rval.consumed;
899 DynamicBuffer.bytes_shifted += rval.consumed;
904 if(ecbits) buffer_shift_left(0, ecbits);
905 DEBUG("RC_OK, finishing up with %ld+%d",
906 (long)rval.consumed, ecbits);
909 DEBUG("RC_WMORE, continuing read=%ld, cons=%ld "
910 " with %ld..%ld-%ld..%ld",
913 (long)DynamicBuffer.offset,
914 (long)DynamicBuffer.length,
915 (long)DynamicBuffer.unbits,
916 (long)DynamicBuffer.allocated);
917 if(!rd) tolerate_eof--;
925 DEBUG("Clean up partially decoded %s", pduType->name);
926 ASN_STRUCT_FREE(*pduType, structure);
928 new_offset = DynamicBuffer.bytes_shifted + DynamicBuffer.offset;
931 * Print a message and return failure only if not EOF,
932 * unless this is our first PDU (empty file).
935 || DynamicBuffer.length
936 || new_offset - old_offset > ((isyntax == ATS_BASIC_XER)?sizeof("\r\n")-1:0)
941 * Nothing's wrong with being unable to decode junk.
944 if(opt_jprob != 0.0) {
951 DEBUG("ofp %d, no=%ld, oo=%ld, dbl=%ld",
952 on_first_pdu, (long)new_offset, (long)old_offset,
953 (long)DynamicBuffer.length);
954 fprintf(stderr, "%s: "
955 "Decode failed past byte %ld: %s\n",
956 name, (long)new_offset,
957 (rval.code == RC_WMORE)
958 ? "Unexpected end of input"
959 : "Input processing error");
961 #define ENOMSG EINVAL
964 #define EBADMSG EINVAL
966 errno = (rval.code == RC_WMORE) ? ENOMSG : EBADMSG;
968 /* Got EOF after a few successful PDUs */
975 /* Dump the buffer out to the specified FILE */
976 static int write_out(const void *buffer, size_t size, void *key) {
977 FILE *fp = (FILE *)key;
978 return (fwrite(buffer, 1, size, fp) == size) ? 0 : -1;
981 static int argument_is_stdin(char *av[], int idx) {
982 if(strcmp(av[idx], "-")) {
983 return 0; /* Certainly not <stdin> */
985 /* This might be <stdin>, unless `./program -- -` */
986 if(strcmp(av[-1], "--"))
993 static FILE *argument_to_file(char *av[], int idx) {
994 return argument_is_stdin(av, idx) ? stdin : fopen(av[idx], "rb");
997 static char *argument_to_name(char *av[], int idx) {
998 return argument_is_stdin(av, idx) ? "standard input" : av[idx];
1003 * Fill bytes with some garbage with specified probability (more or less).
1006 junk_bytes_with_probability(uint8_t *buf, size_t size, double prob) {
1007 static int junkmode;
1010 if(opt_jprob <= 0.0) return;
1011 for(ptr = buf, end = ptr + size; ptr < end; ptr++) {
1013 if(junkmode++ & 1) {
1014 if((((double)random() / RAND_MAX) < prob))
1015 byte = random() & 0xff;
1017 #define BPROB(b) ((((double)random() / RAND_MAX) < prob) ? b : 0)
1018 byte ^= BPROB(0x80);
1019 byte ^= BPROB(0x40);
1020 byte ^= BPROB(0x20);
1021 byte ^= BPROB(0x10);
1022 byte ^= BPROB(0x08);
1023 byte ^= BPROB(0x04);
1024 byte ^= BPROB(0x02);
1025 byte ^= BPROB(0x01);
1032 #endif /* JUNKTEST */