8dcb274e6b3f6621ccebe01c6e431ee3a63000ec
[ric-plt/resource-status-manager.git] / RSM / asn1codec / e2ap_engine / converter-example.c
1
2 /*
3  * Generic converter template for a selected ASN.1 type.
4  * Copyright (c) 2005-2017 Lev Walkin <vlm@lionet.info>.
5  * All rights reserved.
6  * 
7  * To compile with your own ASN.1 type, redefine the PDU as shown:
8  * 
9  * cc -DPDU=MyCustomType -o myDecoder.o -c converter-example.c
10  */
11 #ifdef    HAVE_CONFIG_H
12 #include <config.h>
13 #endif
14 #define __EXTENSIONS__
15 #include <stdio.h>
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 */
25
26 /* Convert "Type" defined by -DPDU into "asn_DEF_Type" */
27 #ifdef PDU
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)
33 #else   /* !PDU */
34 #define PDU_Type_Ptr    NULL
35 #endif  /* PDU */
36
37 #ifdef ASN_PDU_COLLECTION /* Generated by asn1c -pdu=... */
38 extern asn_TYPE_descriptor_t *asn_pdu_collection[];
39 #endif
40
41 #ifndef NO_ASN_PDU
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.
45 #endif
46 #endif
47
48 /*
49  * Open file and parse its contens.
50  */
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);
58
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) */
64
65 #ifdef    JUNKTEST        /* Enable -J <probability> */
66 #define JUNKOPT "J:"
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);
70
71 #define RANDOPT "R:"
72 static ssize_t random_max_size = 0; /* Size of the random data */
73
74 #if !defined(__FreeBSD__) && !(defined(__APPLE__) && defined(__MACH__))
75 static void
76 srandomdev(void) {
77     FILE *f = fopen("/dev/urandom", "rb");
78     unsigned seed;
79     if(f) {
80         if(fread(&seed, 1, sizeof(seed), f) != sizeof(seed)) {
81             seed = time(NULL);
82         }
83         fclose(f);
84     } else {
85         seed = time(NULL);
86     }
87     srandom(seed);
88 }
89 #endif
90
91 #else   /* !JUNKTEST */
92 #define    JUNKOPT
93 #define    RANDOPT
94 #endif  /* JUNKTEST */
95
96 /* Debug output function */
97 static void CC_PRINTFLIKE(1, 2)
98 DEBUG(const char *fmt, ...) {
99     va_list ap;
100     if(!opt_debug) return;
101     fprintf(stderr, "AD: ");
102     va_start(ap, fmt);
103     vfprintf(stderr, fmt, ap);
104     va_end(ap);
105     fprintf(stderr, "\n");
106 }
107
108 static const char *
109 ats_simple_name(enum asn_transfer_syntax syntax) {
110     switch(syntax) {
111     case ATS_INVALID:
112         return "/dev/null";
113     case ATS_NONSTANDARD_PLAINTEXT:
114         return "plaintext";
115     case ATS_BER:
116         return "BER";
117     case ATS_DER:
118         return "DER";
119     case ATS_CER:
120         return "CER";
121     case ATS_BASIC_OER:
122     case ATS_CANONICAL_OER:
123         return "OER";
124     case ATS_BASIC_XER:
125     case ATS_CANONICAL_XER:
126         return "XER";
127     case ATS_UNALIGNED_BASIC_PER:
128     case ATS_UNALIGNED_CANONICAL_PER:
129         return "PER";
130     default:
131         return "<?>";
132     }
133 }
134
135 #define CODEC_OFFSET(fname)  ((ptrdiff_t)&(((asn_TYPE_operation_t *)0)->fname))
136 typedef struct {
137     const char *name;
138     enum asn_transfer_syntax syntax;
139     ptrdiff_t codec_offset;
140     const char *full_name;
141 } syntax_selector;
142
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}};
155
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}};
172
173 static int
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;
178 }
179
180 /*
181  * Select ASN.1 Transfer Enocoding Syntax by command line name.
182  */
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)) {
190                 return element;
191             }
192         }
193     }
194     return NULL;
195 }
196
197 int
198 main(int ac, char *av[]) {
199     FILE *binary_out;
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;
204     int num;
205     int ch;
206     const syntax_selector *sel;
207     enum asn_transfer_syntax isyntax = ATS_INVALID;
208     enum asn_transfer_syntax osyntax = ATS_BASIC_XER;
209
210     if(!anyPduType) {
211 #ifdef  ASN_PDU_COLLECTION
212         anyPduType = asn_pdu_collection[0];
213         if(!anyPduType) {
214             fprintf(stderr,
215                     "Empty PDU collection, no reference PDU to choose from.\n");
216             exit(EX_SOFTWARE);
217         }
218 #else
219         fprintf(stderr, "Either asn1c -pdu=... or cc -DPDU should be used.\n");
220         exit(EX_SOFTWARE);
221 #endif
222     }
223
224     /* Figure out if a specialty decoder needs to be default */
225 #ifndef ASN_DISABLE_OER_SUPPORT
226     isyntax = ATS_BASIC_OER;
227 #endif
228 #ifndef ASN_DISABLE_PER_SUPPORT
229     isyntax = ATS_UNALIGNED_BASIC_PER;
230 #endif
231
232     /*
233      * Pocess the command-line argments.
234      */
235     while((ch = getopt(ac, av, "i:o:1b:cdn:p:hs:" JUNKOPT RANDOPT)) != -1)
236     switch(ch) {
237     case 'i':
238         sel = ats_by_name(optarg, anyPduType, input_encodings);
239         if(sel) {
240             isyntax = sel->syntax;
241         } else {
242             fprintf(stderr, "-i<format>: '%s': improper format selector\n",
243                     optarg);
244             exit(EX_UNAVAILABLE);
245         }
246         break;
247     case 'o':
248         sel = ats_by_name(optarg, anyPduType, output_encodings);
249         if(sel) {
250             osyntax = sel->syntax;
251         } else {
252             fprintf(stderr, "-o<format>: '%s': improper format selector\n",
253                     optarg);
254             exit(EX_UNAVAILABLE);
255         }
256         break;
257     case '1':
258         opt_onepdu = 1;
259         break;
260     case 'b':
261         suggested_bufsize = atoi(optarg);
262         if(suggested_bufsize < 1
263             || suggested_bufsize > 16 * 1024 * 1024) {
264             fprintf(stderr,
265                 "-b %s: Improper buffer size (1..16M)\n",
266                 optarg);
267             exit(EX_UNAVAILABLE);
268         }
269         break;
270     case 'c':
271         opt_check = 1;
272         break;
273     case 'd':
274         opt_debug++;    /* Double -dd means ASN.1 debug */
275         break;
276     case 'n':
277         number_of_iterations = atoi(optarg);
278         if(number_of_iterations < 1) {
279             fprintf(stderr,
280                 "-n %s: Improper iterations count\n", optarg);
281             exit(EX_UNAVAILABLE);
282         }
283         break;
284     case 'p':
285         if(strcmp(optarg, "er-nopad") == 0) {
286             opt_nopad = 1;
287             break;
288         }
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);
294             exit(0);
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",
300                     optarg);
301             exit(EX_USAGE);
302         }
303 #else   /* Without -pdu=auto there's just a single type */
304         if(strcmp(optarg, "list") == 0) {
305             fprintf(stderr, "Available PDU types:\n");
306             if(pduType) {
307                 printf("%s\n", pduType->name);
308             }
309             exit(0);
310         } else if(optarg[0] >= 'A' && optarg[0] <= 'Z') {
311             if(pduType && strcmp(optarg, pduType->name) == 0) {
312                 break;
313             }
314             fprintf(stderr, "-p %s: Unrecognized PDU. Try '-p list'.\n",
315                     optarg);
316             exit(EX_USAGE);
317         }
318 #endif    /* ASN_PDU_COLLECTION */
319         fprintf(stderr, "-p %s: Unrecognized option\n", optarg);
320         exit(EX_UNAVAILABLE);
321     case 's':
322         opt_stack = atoi(optarg);
323         if(opt_stack < 0) {
324             fprintf(stderr,
325                 "-s %s: Non-negative value expected\n",
326                 optarg);
327             exit(EX_UNAVAILABLE);
328         }
329         break;
330 #ifdef    JUNKTEST
331     case 'J':
332         opt_jprob = strtod(optarg, 0);
333         if(opt_jprob <= 0.0 || opt_jprob > 1.0) {
334             fprintf(stderr,
335                 "-J %s: Probability range 0..1 expected \n",
336                 optarg);
337             exit(EX_UNAVAILABLE);
338         }
339         break;
340     case 'R':
341         isyntax = ATS_RANDOM;
342         random_max_size = atoi(optarg);
343         if(random_max_size < 0) {
344             fprintf(stderr,
345                 "-R %s: Non-negative value expected\n",
346                 optarg);
347             exit(EX_UNAVAILABLE);
348         }
349         srandomdev();
350         break;
351 #endif    /* JUNKTEST */
352     case 'h':
353     default:
354 #ifdef    ASN_CONVERTER_TITLE
355 #define    _AXS(x)    #x
356 #define    _ASX(x)    _AXS(x)
357         fprintf(stderr, "%s\n", _ASX(ASN_CONVERTER_TITLE));
358 #endif
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,
364                         sel->full_name,
365                         (sel->syntax == isyntax) ? " (DEFAULT)" : "");
366             }
367         }
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 ? "" : " ",
372                         sel->full_name,
373                         (sel->syntax == osyntax) ? " (DEFAULT)" : "");
374             }
375         }
376         if(anyPduType->op->uper_decoder) {
377             fprintf(stderr,
378                     "  -per-nopad   Assume PER PDUs are not padded (-iper)\n");
379         }
380 #ifdef    ASN_PDU_COLLECTION
381         fprintf(stderr,
382         "  -p <PDU>     Specify PDU type to decode\n"
383         "  -p list      List available PDUs\n");
384 #endif    /* ASN_PDU_COLLECTION */
385         fprintf(stderr,
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"
392 #ifdef    JUNKTEST
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"
396 #endif
397         , (long)suggested_bufsize, ASN__DEFAULT_STACK_MAX);
398         exit(EX_USAGE);
399     }
400
401     ac -= optind;
402     av += optind;
403
404     if(!pduType) {
405 #ifdef  NO_ASN_PDU
406         fprintf(stderr, "No -DPDU defined during compilation.\n");
407         exit(0);
408 #else
409         fprintf(stderr, "Use '-p <Type>' or '-p list' to select ASN.1 type.\n");
410         exit(EX_USAGE);
411 #endif  /* NO_ASN_PDU */
412     }
413
414     if(ac < 1 && isyntax != ATS_RANDOM) {
415         fprintf(stderr, "%s: No input files specified. "
416                 "Try '-h' for more information\n",
417                 av[-optind]);
418         exit(EX_USAGE);
419     }
420
421     if(isatty(1)) {
422         const int is_text_output = osyntax == ATS_NONSTANDARD_PLAINTEXT
423                                    || osyntax == ATS_BASIC_XER
424                                    || osyntax == ATS_CANONICAL_XER;
425         if(is_text_output) {
426             binary_out = stdout;
427         } else {
428             fprintf(stderr, "(Suppressing binary output to a terminal.)\n");
429             binary_out = fopen("/dev/null", "wb");
430             if(!binary_out) {
431                 fprintf(stderr, "Can't open /dev/null: %s\n", strerror(errno));
432                 exit(EX_OSERR);
433             }
434         }
435     } else {
436         binary_out = stdout;
437     }
438     setvbuf(stdout, 0, _IOLBF, 0);
439
440     for(num = 0; num < number_of_iterations; num++) {
441       int ac_i;
442       /*
443        * Process all files in turn.
444        */
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 */
448         FILE *file;
449         char *name;
450         int first_pdu;
451
452         if(ac_i == -1) {
453             file = NULL;
454             name = "<random value generator>";
455             opt_onepdu = 1;
456         } else {
457             file = argument_to_file(av, ac_i);
458             name = argument_to_name(av, ac_i);
459         }
460
461         for(first_pdu = 1; (first_pdu || !opt_onepdu); first_pdu = 0) {
462             /*
463              * Decode the encoded structure from file.
464              */
465 #ifdef  JUNKTEST
466             if(isyntax == ATS_RANDOM) {
467                 structure = NULL;
468                 if(asn_random_fill(pduType, &structure, random_max_size) != 0) {
469                     fprintf(stderr, "Cannot generate a random value.\n");
470                     assert(structure == NULL);
471                     errno = EINVAL;
472                 }
473             } else {
474 #endif
475                 structure = data_decode_from_file(isyntax, pduType, file, name,
476                                                   suggested_bufsize, first_pdu);
477 #ifdef  JUNKTEST
478             }
479 #endif
480             if(!structure) {
481                 if(errno) {
482                     /* Error message is already printed */
483                     exit(EX_DATAERR);
484                 } else {
485                     /* EOF */
486                     break;
487                 }
488             }
489
490             /* Check ASN.1 constraints */
491             if(opt_check) {
492                 char errbuf[128];
493                 size_t errlen = sizeof(errbuf);
494                 if(asn_check_constraints(pduType, structure, errbuf, &errlen)) {
495                     fprintf(stderr,
496                             "%s: ASN.1 constraint "
497                             "check failed: %s\n",
498                             name, errbuf);
499                     exit(EX_DATAERR);
500                 }
501             }
502
503             if(osyntax == ATS_INVALID) {
504 #ifdef JUNKTEST
505                 if(opt_jprob == 0.0) {
506                     fprintf(stderr, "%s: decoded successfully\n", name);
507                 }
508 #else
509                 fprintf(stderr, "%s: decoded successfully\n", name);
510 #endif
511             } else {
512                 erv = asn_encode(NULL, osyntax, pduType, structure, write_out,
513                                  binary_out);
514
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);
521                 }
522                 DEBUG("Encoded in %" ASN_PRI_SSIZE " bytes of %s", erv.encoded,
523                       ats_simple_name(osyntax));
524             }
525
526             ASN_STRUCT_FREE(*pduType, structure);
527         }
528
529         if(file && file != stdin) {
530             fclose(file);
531         }
532       }
533     }
534
535 #ifdef    JUNKTEST
536     if(opt_jprob > 0.0) {
537         fprintf(stderr, "Junked %f OK (%d/%d)\n",
538             opt_jprob, junk_failures, number_of_iterations);
539     }
540 #endif    /* JUNKTEST */
541
542     return 0;
543 }
544
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 */
553 } DynamicBuffer;
554
555 static void
556 buffer_dump() {
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);
568     for(; p < e; p++) {
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');
578     }
579     if(DynamicBuffer.unbits) {
580         unsigned int shift;
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);
587     } else {
588         fprintf(stderr, " %ld\n", (long)DynamicBuffer.length);
589     }
590 }
591
592 /*
593  * Move the buffer content left N bits, possibly joining it with
594  * preceeding content.
595  */
596 static void
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;
601     
602     if(!bits) return;
603
604     DEBUG("Shifting left %d bits off %ld (o=%ld, u=%ld, l=%ld)",
605         bits, (long)offset,
606         (long)DynamicBuffer.offset,
607         (long)DynamicBuffer.unbits,
608         (long)DynamicBuffer.length);
609
610     if(offset) {
611         int right;
612         right = ptr[0] >> (8 - bits);
613
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');
623
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');
633
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');
643
644         ptr[-1] = (ptr[-1] & (0xff << bits)) | right;
645
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');
655     }
656
657     buffer_dump();
658
659     for(; ptr < end; ptr++) {
660         int right = ptr[1] >> (8 - bits);
661         *ptr = (*ptr << bits) | right;
662     }
663     *ptr <<= bits;
664
665     DEBUG("Unbits [%" ASN_PRI_SIZE "=>", DynamicBuffer.unbits);
666     if(DynamicBuffer.unbits == 0) {
667         DynamicBuffer.unbits += bits;
668     } else {
669         DynamicBuffer.unbits += bits;
670         if(DynamicBuffer.unbits > 7) {
671             DynamicBuffer.unbits -= 8;
672             DynamicBuffer.length--;
673             DynamicBuffer.bytes_shifted++;
674         }
675     }
676     DEBUG("Unbits =>%" ASN_PRI_SIZE "]", DynamicBuffer.unbits);
677
678     buffer_dump();
679
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);
685 }
686
687 /*
688  * Ensure that the buffer contains at least this amount of free space.
689  */
690 static void add_bytes_to_buffer(const void *data2add, size_t bytes) {
691
692     if(bytes == 0) return;
693
694     DEBUG("=> add_bytes(%" ASN_PRI_SIZE ") { o=%" ASN_PRI_SIZE
695           " l=%" ASN_PRI_SIZE " u=%" ASN_PRI_SIZE ", s=%" ASN_PRI_SIZE " }",
696         bytes,
697         DynamicBuffer.offset,
698         DynamicBuffer.length,
699         DynamicBuffer.unbits,
700         DynamicBuffer.allocated);
701
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);
707
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;
714     } else {
715         size_t newsize = (DynamicBuffer.allocated << 2) + bytes;
716         void *p = MALLOC(newsize);
717         if(!p) {
718             perror("malloc()");
719             exit(EX_OSERR);
720         }
721                 if (DynamicBuffer.length) {
722                         memcpy(p,
723                                         DynamicBuffer.data + DynamicBuffer.offset,
724                                         DynamicBuffer.length);
725                 }
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);
733     }
734
735     memcpy(DynamicBuffer.data
736         + DynamicBuffer.offset + DynamicBuffer.length,
737         data2add, bytes);
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);
743     }
744
745     DEBUG("<= add_bytes(%" ASN_PRI_SIZE ") { o=%" ASN_PRI_SIZE
746           " l=%" ASN_PRI_SIZE " u=%" ASN_PRI_SIZE ", s=%" ASN_PRI_SIZE " }",
747         bytes,
748         DynamicBuffer.offset,
749         DynamicBuffer.length,
750         DynamicBuffer.unbits,
751         DynamicBuffer.allocated);
752 }
753
754 static int
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);
760 }
761
762 static int
763 restartability_supported(enum asn_transfer_syntax syntax) {
764     return !is_syntax_PER(syntax);
765 }
766
767 static void *
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;
773     void *structure = 0;
774     asn_dec_rval_t rval;
775     size_t old_offset;    
776     size_t new_offset;
777     int tolerate_eof;
778     size_t rd;
779
780     if(!file) {
781         fprintf(stderr, "%s: %s\n", name, strerror(errno));
782         errno = EINVAL;
783         return 0;
784     }
785
786     if(opt_stack) {
787         s_codec_ctx.max_stack_size = opt_stack;
788         opt_codec_ctx = &s_codec_ctx;
789     }
790
791     DEBUG("Processing %s", name);
792
793     /* prepare the file buffer */
794     if(fbuf_size != suggested_bufsize) {
795         fbuf = (uint8_t *)REALLOC(fbuf, suggested_bufsize);
796         if(!fbuf) {
797             perror("realloc()");
798             exit(EX_OSERR);
799         }
800         fbuf_size = suggested_bufsize;
801     }
802
803     if(on_first_pdu) {
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;
810     }
811
812     old_offset = DynamicBuffer.bytes_shifted + DynamicBuffer.offset;
813
814     /* Pretend immediate EOF */
815     rval.code = RC_WMORE;
816     rval.consumed = 0;
817
818     for(tolerate_eof = 1;    /* Allow EOF first time buffer is non-empty */
819         (rd = fread(fbuf, 1, fbuf_size, file))
820         || feof(file) == 0
821         || (tolerate_eof && DynamicBuffer.length)
822         ;) {
823         int      ecbits = 0;    /* Extra consumed bits in case of PER */
824         uint8_t *i_bptr;
825         size_t   i_size;
826
827         /*
828          * Copy the data over, or use the original buffer.
829          */
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;
835         } else {
836             i_bptr = fbuf;
837             i_size = rd;
838         }
839
840         DEBUG("Decoding %" ASN_PRI_SIZE " bytes", i_size);
841
842 #ifdef    JUNKTEST
843         junk_bytes_with_probability(i_bptr, i_size, opt_jprob);
844 #endif
845
846         if(is_syntax_PER(isyntax) && opt_nopad) {
847 #ifdef  ASN_DISABLE_PER_SUPPORT
848             rval.code = RC_FAIL;
849             rval.consumed = 0;
850 #else
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);
854             else
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. */
860 #endif
861             /* Non-padded PER decoder */
862         } else {
863             rval = asn_decode(opt_codec_ctx, isyntax, pduType,
864                               (void **)&structure, i_bptr, i_size);
865         }
866         if(rval.code == RC_WMORE && !restartability_supported(isyntax)) {
867             /* PER does not support restartability */
868             ASN_STRUCT_FREE(*pduType, structure);
869             structure = 0;
870             rval.consumed = 0;
871             /* Continue accumulating data */
872         }
873
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);
877
878         if(DynamicBuffer.allocated == 0) {
879             /*
880              * Flush remainder into the intermediate buffer.
881              */
882             if(rval.code != RC_FAIL && rval.consumed < rd) {
883                 add_bytes_to_buffer(fbuf + rval.consumed,
884                     rd - rval.consumed);
885                 buffer_shift_left(0, ecbits);
886                 DynamicBuffer.bytes_shifted = rval.consumed;
887                 rval.consumed = 0;
888                 ecbits = 0;
889             }
890         }
891
892         /*
893          * Adjust position inside the source buffer.
894          */
895         if(DynamicBuffer.allocated) {
896             DynamicBuffer.offset += rval.consumed;
897             DynamicBuffer.length -= rval.consumed;
898         } else {
899             DynamicBuffer.bytes_shifted += rval.consumed;
900         }
901
902         switch(rval.code) {
903         case RC_OK:
904             if(ecbits) buffer_shift_left(0, ecbits);
905             DEBUG("RC_OK, finishing up with %ld+%d",
906                 (long)rval.consumed, ecbits);
907             return structure;
908         case RC_WMORE:
909             DEBUG("RC_WMORE, continuing read=%ld, cons=%ld "
910                 " with %ld..%ld-%ld..%ld",
911                 (long)rd,
912                 (long)rval.consumed,
913                 (long)DynamicBuffer.offset,
914                 (long)DynamicBuffer.length,
915                 (long)DynamicBuffer.unbits,
916                 (long)DynamicBuffer.allocated);
917             if(!rd) tolerate_eof--;
918             continue;
919         case RC_FAIL:
920             break;
921         }
922         break;
923     }
924
925     DEBUG("Clean up partially decoded %s", pduType->name);
926     ASN_STRUCT_FREE(*pduType, structure);
927
928     new_offset = DynamicBuffer.bytes_shifted + DynamicBuffer.offset;
929
930     /*
931      * Print a message and return failure only if not EOF,
932      * unless this is our first PDU (empty file).
933      */
934     if(on_first_pdu
935     || DynamicBuffer.length
936     || new_offset - old_offset > ((isyntax == ATS_BASIC_XER)?sizeof("\r\n")-1:0)
937     ) {
938
939 #ifdef    JUNKTEST
940         /*
941          * Nothing's wrong with being unable to decode junk.
942          * Simulate EOF.
943          */
944         if(opt_jprob != 0.0) {
945             junk_failures++;
946             errno = 0;
947             return 0;
948         }
949 #endif
950
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");
960 #ifndef    ENOMSG
961 #define    ENOMSG EINVAL
962 #endif
963 #ifndef    EBADMSG
964 #define    EBADMSG EINVAL
965 #endif
966         errno = (rval.code == RC_WMORE) ? ENOMSG : EBADMSG;
967     } else {
968         /* Got EOF after a few successful PDUs */
969         errno = 0;
970     }
971
972     return 0;
973 }
974
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;
979 }
980
981 static int argument_is_stdin(char *av[], int idx) {
982     if(strcmp(av[idx], "-")) {
983         return 0; /* Certainly not <stdin> */
984     } else {
985         /* This might be <stdin>, unless `./program -- -` */
986         if(strcmp(av[-1], "--"))
987             return 1;
988         else
989             return 0;
990     }
991 }
992
993 static FILE *argument_to_file(char *av[], int idx) {
994     return argument_is_stdin(av, idx) ? stdin : fopen(av[idx], "rb");
995 }
996
997 static char *argument_to_name(char *av[], int idx) {
998     return argument_is_stdin(av, idx) ? "standard input" : av[idx];
999 }
1000
1001 #ifdef    JUNKTEST
1002 /*
1003  * Fill bytes with some garbage with specified probability (more or less).
1004  */
1005 static void
1006 junk_bytes_with_probability(uint8_t *buf, size_t size, double prob) {
1007     static int junkmode;
1008     uint8_t *ptr;
1009     uint8_t *end;
1010     if(opt_jprob <= 0.0) return;
1011     for(ptr = buf, end = ptr + size; ptr < end; ptr++) {
1012         int byte = *ptr;
1013         if(junkmode++ & 1) {
1014             if((((double)random() / RAND_MAX) < prob))
1015                 byte = random() & 0xff;
1016         } else {
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);
1026         }
1027         if(byte != *ptr) {
1028             *ptr = byte;
1029         }
1030     }
1031 }
1032 #endif    /* JUNKTEST */
1033