Debian Codegraph @

doc/docsrc/asn1c-usage.tex

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 \batchmode
2 \documentclass[english,oneside,12pt]{book}
3 \usepackage[no-math]{fontspec}
4 \usepackage{MnSymbol}
5 \usepackage{xunicode}
6 \usepackage{xltxtra}
7
8 \usepackage[hmargin={1in,1in},vmargin={1.5in,1.5in}]{geometry}
9
10 \defaultfontfeatures{Mapping=tex-text}
11 \setmainfont{PT Sans}
12 \setsansfont{PT Sans}
13 \setmonofont{Consolas}
14
15 \usepackage{fancyhdr}
16 \usepackage{longtable}
17 \usepackage{booktabs}
18 \usepackage{varioref}
19 \usepackage{url}
20 \usepackage{xcolor}
21 \usepackage{listings}
22 \usepackage{setspace}
23 \usepackage{unicode-math}
24 \usepackage{perpage}
25 \MakePerPage{footnote}
26
27 \setstretch{1.1}
28
29 % Courier 10 Pitch
30 \def\courierFont{Courier10 BT WGL4}
31 %\def\courierFont{Consolas}
32 \setmonofont[Scale=1.05]{\courierFont}
33 \setmathfont[Scale=1.05]{Cambria Math}
34
35
36 \makeatletter
37
38 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.
39 \lstloadlanguages{C,bash}
40 \newfontfamily\listingfont[Scale=1.05]{\courierFont}
41 \newfontfamily\inlinelistingfont[Scale=1.05]{\courierFont}
42 \definecolor{clrlcomment}{gray}{0.3}
43 \definecolor{clrlkeyword}{rgb}{0.588,0.145,0.18}
44 \newcommand{\listingkeyword}[1]{\color{clrlkeyword}{#1}}
45 \newcommand{\listingstring}[1]{\color{clrlcomment}{#1}}
46 \newcommand{\listingcomment}[1]{\color{clrlcomment}{#1}}
47 \lstset{tabsize=4,
48 showstringspaces=false,
49 showtabs=false,
50 showspaces=false,
51 keywordstyle=\listingkeyword,
52 stringstyle=\listingstring,
53 commentstyle=\listingcomment,
54 xleftmargin=\parindent,
55 columns=fixed,
56 escapechar=\%,
57 texcl
58 }
59 \lstdefinestyle{listingStyle}{
60 basicstyle=\small\listingfont,
61 stringstyle=\listingstring,
62 breaklines=true,
63 breakatwhitespace=true,
64 flexiblecolumns=false
65 }
66 \lstdefinelanguage{asn1}{
67 morekeywords={DEFINITIONS,BEGIN,END,SEQUENCE,SET,OF,CHOICE,OPTIONAL},
68 morecomment=[l]{--},
69 morecomment=[n]{/*}{*/}
70 }
71
72 \lstnewenvironment{codesample}[1][]{\lstset{style=listingStyle,language=C,#1}}{}
73 \lstnewenvironment{bash}[1][]{\lstset{style=listingStyle,language=bash,#1}}{}
74 \lstnewenvironment{asn}[1][]{\lstset{style=listingStyle,language=asn1,#1}}{}
75 \def\code{lstinline}
76
77 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.
78 \usepackage{extramarks}
79 \lhead{\firstxmark}
80 \rfoot{\lastxmark}
81 \definecolor{clrlink}{rgb}{0,0.4,0}
82 \definecolor{clrurl}{rgb}{0,0,.6}
83 \usepackage[colorlinks=true,
84 linkcolor={clrlink},
85 citecolor={clrlink},
86 urlcolor={clrurl},
87 pdfauthor={Lev Walkin},
88 pdftitle={Using the Open Source ASN.1 Compiler},
89 pdfkeywords={ASN.1,asn1c,compiler},
90 bookmarksopen,bookmarksopenlevel=1,
91 pdffitwindow,
92 xetex
93 ]{hyperref}
94
95 \makeatother
96
97 \usepackage{babel}
98
99 \begin{document}
100
101 \title{Using the Open Source ASN.1 Compiler\\
102 \vspace*{0.4cm}
103 \Large Documentation for asn1c version \asnver{}}
104 \author{Lev Walkin <\href{mailto:[email protected]?Subject=asn1c}{[email protected]}>}
105
106 \pagestyle{fancy}
107 \fancyhead[L]{\leftmark}
108 \fancyhead[R]{\href{http://lionet.info/asn1c}{asn1c-\asnver}}
109 \maketitle
110
111 \tableofcontents{}
112
113 \part{Using the ASN.1 Compiler}
114
115
116 \chapter{Introduction to the ASN.1 Compiler}
117
118 The purpose of the ASN.1 compiler is to convert the specifications
119 in ASN.1 notation into some other language. At this moment, only C
120 and C++ target languages are supported, the latter is in upward compatibility
121 mode.
122
123 The compiler reads the specification and emits a series of target
124 language structures (C structs, unions, enums) describing the corresponding
125 ASN.1 types. The compiler also creates the code which allows automatic
126 serialization and deserialization of these structures using several
127 standardized encoding rules (BER, DER, XER, PER).
128
129 For example, suppose the following ASN.1 module is given%
130 \footnote{Part \ref{par:ASN.1-Basics} provides a quick reference
131 on the ASN.1 notation.}:
132 \begin{asn}
133 RectangleTest DEFINITIONS ::= BEGIN
134
135 Rectangle ::= SEQUENCE {
136 height INTEGER, -- Height of the rectangle
137 width INTEGER -- Width of the rectangle
138 }
139
140 END
141 \end{asn}
142 The compiler would read this ASN.1 definition and produce the following
143 C type:
144 \begin{codesample}
145 typedef struct Rectangle_s {
146 long height;
147 long width;
148 } Rectangle_t;
149 \end{codesample}
150 It would also create the code for converting this structure into platform-independent
151 wire representation (a serializer API) and the decoder of such wire
152 representation back into local, machine-specific type (a deserializer
153 API).
154
155
156 \section{Quick start with asn1c}
157
158 After building and installing the compiler, the \emph{asn1c}
159 command may be used to compile the ASN.1 modules%
160 \footnote{This is probably \textbf{not} what you want to try out right now. Read through the rest of this chapter and check the Section~\ref{sec:Command-line-options}
161 to find out about \textbf{-P} and \textbf{-R} options.%
162 }:
163 \begin{bash}
164 asn1c %\emph{<modules.asn1>}%
165 \end{bash}
166 If several ASN.1 modules contain interdependencies, all of the files
167 must be specified altogether:
168 \begin{bash}
169 asn1c %\emph{<module1.asn1> <module2.asn1> ...}%
170 \end{bash}
171 The compiler \textbf{-E} and \textbf{-EF} options are used for testing
172 the parser and the semantic fixer, respectively. These options will
173 instruct the compiler to dump out the parsed (and fixed, if \textbf{-F}
174 is involved) ASN.1 specification as it was understood
175 by the compiler. It might be useful to check whether a particular
176 syntactic construct is properly supported by the compiler.
177 \begin{bash}
178 asn1c %\textbf{-EF} \emph{<module-to-test.asn1>}%
179 \end{bash}
180 The \textbf{-P} option is used to dump the compiled output on the
181 screen instead of creating a bunch of .c and .h files on disk in the
182 current directory. You would probably want to start with \textbf{-P}
183 option instead of creating a mess in your current directory. Another
184 option, \textbf{-R}, asks compiler to only generate the files which
185 need to be generated, and supress linking in the numerous support
186 files.
187
188 Print the compiled output instead of creating multiple source files:
189 \begin{bash}
190 asn1c %\textbf{-P} \emph{<module-to-compile-and-print.asn1>}%
191 \end{bash}
192
193 \clearpage{}
194 \section{Recognizing compiler output}
195
196 The asn1c compiler produces a number of files:
197 \begin{itemize}
198 \item A set of .c and .h files for each type defined
199 in the ASN.1 specification. These files will be named similarly to
200 the ASN.1 types (\emph{Rectangle.c} and \emph{Rectangle.h} for the
201 RectangleTest ASN.1 module defined in the beginning of this document).
202 \item A set of helper .c and .h files which contain the generic encoders,
203 decoders and other useful routines. There will be quite a few of them, some
204 of them are not even always necessary, but the overall amount of code
205 after compilation will be rather small anyway.
206 \item A \emph{converter-sample.c} file containing the \emph{int main()} function with a fully functioning decoder. It can convert a given PDU between BER, XER and possibly PER (if -gen-PER option to asn1c was in effect). At some point you will want to replace this file with your own file containing the \emph{int main()} function.
207 \item A \emph{Makefile.am.sample} file mentioning all the files created
208 at the earlier steps. This file is suitable for either automake suite
209 or the plain `make` utility. Just rename it into \emph{Makefile}.
210 \end{itemize}
211 It is possible to compile everything with just a couple of instructions:
212 \begin{bash}
213 asn1c -pdu=%\emph{Rectangle}% *.asn1
214 make -f Makefile.am.sample # If you use `make`
215 \end{bash}
216 or
217 \begin{bash}
218 asn1c *.asn1
219 cc -I. -DPDU=%\emph{Rectangle}% -o rectangle.exe *.c # ... or like this
220 \end{bash}
221 Refer to the Chapter \ref{cha:Step-by-step-examples} for a sample
222 \emph{int main()} function if you want some custom logic and not satisfied
223 with the supplied \emph{converter-sample.c}.
224
225 \clearpage{}
226 \section{\label{sec:Command-line-options}Command line options}
227
228 The following table summarizes the asn1c command line options.
229
230 \renewcommand{\arraystretch}{1.33}
231 \begin{longtable}{lp{4in}}
232 \textbf{Stage Selection Options} & \textbf{Description}\\
233 \midrule
234 {\ttfamily -E} & {\small Stop after the parsing stage and print the reconstructed ASN.1
235 specification code to the standard output.}\\
236 {\ttfamily -F} & {\small Used together with \texttt{-E}, instructs the compiler to stop after
237 the ASN.1 syntax tree fixing stage and dump the reconstructed ASN.1
238 specification to the standard output.}\\
239 {\ttfamily -P} & {\small Dump the compiled output to the standard output instead of
240 creating the target language files on disk.}\\
241 {\ttfamily -R} & {\small Restrict the compiler to generate only the ASN.1 tables, omitting the usual support code.}\\
242 {\ttfamily -S~\emph{<directory>}} & {\small Use the specified directory with ASN.1 skeleton files.}\\
243 {\ttfamily -X} & {\small Generate the XML DTD for the specified ASN.1 modules.}\\\\
244 \textbf{Warning Options} & \textbf{Description}\\
245 \midrule
246 {\ttfamily -Werror} & {\small Treat warnings as errors; abort if any warning is produced.}\\
247 {\ttfamily -Wdebug-lexer} & {\small Enable lexer debugging during the ASN.1 parsing stage.}\\
248 {\ttfamily -Wdebug-fixer} & {\small Enable ASN.1 syntax tree fixer debugging during the fixing stage.}\\
249 {\ttfamily -Wdebug-compiler} & {\small Enable debugging during the actual compile time.}\\ \\
250 \textbf{Language Options} & \textbf{Description}\\
251 \midrule
252 {\ttfamily -fbless-SIZE} & {\small Allow SIZE() constraint for INTEGER, ENUMERATED, and other types for which this constraint is normally prohibited by the standard.
253 This is a violation of an ASN.1 standard and compiler may fail to produce the meaningful code.}\\
254 {\ttfamily -fcompound-names} & {\small Use complex names for C structures. Using complex names prevents
255 name clashes in case the module reuses the same identifiers in multiple
256 contexts.}\\
257 {\ttfamily -findirect-choice} & {\small When generating code for a CHOICE type, compile the CHOICE
258 members as indirect pointers instead of declaring them inline. Consider
259 using this option together with \texttt{-fno-include-deps}
260 to prevent circular references.}\\
261 {\ttfamily -fincludes-quoted} & {\small Generate \#include lines in "double" instead of <angle> quotes.}\\
262 {\ttfamily -fknown-extern-type=\emph{<name>}} & {\small Pretend the specified type is known. The compiler will assume
263 the target language source files for the given type have been provided
264 manually. }\\
265 {\ttfamily -fline-refs} & {\small Include ASN.1 module's line numbers in generated code comments.}\\
266 {\ttfamily -fno-constraints} & {\small Do not generate ASN.1 subtype constraint checking code. This
267 may produce a shorter executable.}\\
268 {\ttfamily -fno-include-deps} & {\small Do not generate courtesy \#include lines for non-critical dependencies.}\\
269 {\ttfamily -funnamed-unions} & {\small Enable unnamed unions in the definitions of target language's structures.}\\
270 {\ttfamily -fwide-types} & {\small Use the wide integer types (INTEGER\_t, REAL\_t) instead of machine's native data types (long, double). }\\\\
271 \textbf{Codecs Generation Options} & \textbf{Description}\\
272 \midrule
273 {\ttfamily -gen-PER} & {\small Generate the Packed Encoding Rules (PER) support code.}\\
274 {\ttfamily -pdu=\{\textbf{all}|\textbf{auto}|\emph{Type}\}} & {\small Create a PDU table for specified types, or discover the Protocol Data Units automatically.
275 In case of \texttt{-pdu=\textbf{all}}, all ASN.1 types defined in all modules wil form a PDU table. In case of \texttt{-pdu=\textbf{auto}}, all types not referenced by any other type will form a PDU table. If \texttt{\emph{Type}} is an ASN.1 type identifier, it is added to a PDU table. The last form may be specified multiple times.}\\ \\
276 \textbf{Output Options} & \textbf{Description}\\
277 \midrule
278 {\ttfamily -print-constraints} & {\small When \texttt{-EF} are also specified, this option forces the compiler
279 to explain its internal understanding of subtype constraints.}\\
280 {\ttfamily -print-lines} & {\small Generate \texttt{``-{}- \#line''} comments
281 in \texttt{-E} output.}\\
282 \end{longtable}
283 \renewcommand{\arraystretch}{1}
284
285
286 \chapter{Using the ASN.1 Compiler}
287
288
289 \section[Invoking the helper code]{Invoking the ASN.1 helper code}
290
291 First of all, you should include one or more header files into your
292 application. Typically, it is enough to include the header file of
293 the main PDU type. For our Rectangle module, including the Rectangle.h
294 file is sufficient:
295 \begin{codesample}
296 #include <Rectangle.h>
297 \end{codesample}
298 The header files defines the C structure corresponding to the ASN.1
299 definition of a rectangle and the declaration of the ASN.1 type descriptor,
300 which is used as an argument to most of the functions provided by
301 the ASN.1 module. For example, here is the code which frees the Rectangle\_t
302 structure:
303 \begin{codesample}
304 Rectangle_t *rect = ...;
305
306 asn_DEF_Rectangle.free_struct(&asn_DEF_Rectangle, rect, 0);
307 \end{codesample}
308 This code defines a \emph{rect} pointer which points to the Rectangle\_t
309 structure which needs to be freed. The second line invokes the generic
310 \emph{free\_struct()} routine created specifically for this Rectangle\_t
311 structure. The \emph{asn\_DEF\_Rectangle} is the type descriptor,
312 which holds a collection of routines to deal with the Rectangle\_t
313 structure.
314
315 The following member functions of the asn\_DEF\_Rectangle type descriptor
316 are of interest:
317 \begin{description}
318 \item [{ber\_decoder}] This is the generic \emph{restartable}%
319 \footnote{Restartability mean that if the decoder encounters the end of the buffer it may be invoked again with the rest of the
320 buffer to continue decoding.}
321 BER decoder (Basic Encoding Rules). This decoder would create and/or
322 fill the target structure for you. See Section~\ref{sub:Decoding-BER}.
323 \item [{der\_encoder}] This is the generic DER encoder (Distinguished Encoding
324 Rules). This encoder will take the target structure and encode it
325 into a series of bytes. See Section~\ref{sub:Encoding-DER}. NOTE:
326 DER encoding is a subset of BER. Any BER decoder should be able to
327 handle DER input.
328 \item [{xer\_decoder}] This is the generic XER decoder. It takes both BASIC-XER
329 or CANONICAL-XER encodings and deserializes the data into a local,
330 machine-dependent representation. See Section~\ref{sub:Decoding-XER}.
331 \item [{xer\_encoder}] This is the XER encoder (XML Encoding Rules). This
332 encoder will take the target structure and represent it as an XML
333 (text) document using either BASIC-XER or CANONICAL-XER encoding rules.
334 See Section~\ref{sub:Encoding-XER}.
335 \item [{uper\_decoder}] This is the Unaligned PER decoder.
336 \item [{uper\_encoder}] This is the Unaligned Basic PER encoder. This encoder
337 will take the target structure and encode it into a series of bytes.
338 \item [{check\_constraints}] Check that the contents of the target structure
339 are semantically valid and constrained to appropriate implicit or
340 explicit subtype constraints. See Section~\ref{sub:Validating-the-target}.
341 \item [{print\_struct}] This function convert the contents of the passed
342 target structure into human readable form. This form is not formal
343 and cannot be converted back into the structure, but it may turn out
344 to be useful for debugging or quick-n-dirty printing. See Section~\ref{sub:Printing-the-target}.
345 \item [{free\_struct}] This is a generic disposal which frees the target
346 structure. See Section~\ref{sub:Freeing-the-target}.
347 \end{description}
348 Each of the above function takes the type descriptor (\emph{asn\_DEF\_\ldots{}})
349 and the target structure (\emph{rect}, in the above example).
350
351
352 \subsection{\label{sub:Decoding-BER}Decoding BER}
353
354 The Basic Encoding Rules describe the most widely used (by the ASN.1
355 community) way to encode and decode a given structure in a machine-independent
356 way. Several other encoding rules (CER, DER) define a more restrictive
357 versions of BER, so the generic BER parser is also capable of decoding
358 the data encoded by CER and DER encoders. The opposite is not true.
359
360 \emph{The ASN.1 compiler provides the generic BER decoder which is
361 capable of decoding BER, CER and DER encoded data.}
362
363 The decoder is restartable (stream-oriented), which means that in
364 case the buffer has less data than it is expected, the decoder will
365 process whatever there is available and ask for more data to be provided.
366 Please note that the decoder may actually process less data than it
367 was given in the buffer, which means that you must be able to make
368 the next buffer contain the unprocessed part of the previous buffer.
369
370 Suppose, you have two buffers of encoded data: 100 bytes and 200 bytes.
371 \begin{itemize}
372 \item You can concatenate these buffers and feed the BER decoder with 300
373 bytes of data, or
374 \item You can feed it the first buffer of 100 bytes of data, realize that
375 the ber\_decoder consumed only 95 bytes from it and later feed the
376 decoder with 205 bytes buffer which consists of 5 unprocessed bytes
377 from the first buffer and the additional 200 bytes from the second
378 buffer.
379 \end{itemize}
380 This is not as convenient as it could be (the BER encoder could
381 consume the whole 100 bytes and keep these 5 bytes in some temporary
382 storage), but in case of existing stream based processing it might
383 actually fit well into existing algorithm. Suggestions are welcome.
384
385 Here is the simplest example of BER decoding:
386
387 \begin{codesample}
388 Rectangle_t *
389 simple_deserializer(const void *buffer, size_t buf_size) {
390 asn_dec_rval_t rval;
391 Rectangle_t *%$\underbracket{\textrm{\listingfont rect = 0}}$%; /* %\textbf{\color{red}Note this 0\footnote{Forgetting to properly initialize the pointer to a destination structure is a major source of support requests.}!}% */
392
393 rval = %\textbf{asn\_DEF\_Rectangle.ber\_decoder}%(0,
394 &asn_DEF_Rectangle,
395 (void **) %$\underbracket{\textrm{\listingfont \&rect}}$%, /* Decoder %\emph{moves}% the pointer */
396 buffer, buf_size, 0);
397
398 if(rval%\textbf{.code}% == RC_OK) {
399 return rect; /* Decoding succeeded */
400 } else {
401 /* Free partially decoded rect */
402 asn_DEF_Rectangle.free_struct(&asn_DEF_Rectangle, rect, 0);
403 return 0;
404 }
405 }
406 \end{codesample}
407 The code above defines a function, \emph{simple\_deserializer}, which
408 takes a buffer and its length and is expected to return a pointer
409 to the Rectangle\_t structure. Inside, it tries to convert the bytes
410 passed into the target structure (rect) using the BER decoder and
411 returns the rect pointer afterwards. If the structure cannot be deserialized,
412 it frees the memory which might be left allocated by the unfinished
413 \emph{ber\_decoder} routine and returns 0 (no data). (This \textbf{freeing
414 is necessary} because the ber\_decoder is a restartable procedure,
415 and may fail just because there is more data needs to be provided
416 before decoding could be finalized). The code above obviously does
417 not take into account the way the \emph{ber\_decoder()} failed, so
418 the freeing is necessary because the part of the buffer may already
419 be decoded into the structure by the time something goes wrong.
420
421 A little less wordy would be to invoke a globally available \emph{ber\_decode()}
422 function instead of dereferencing the asn\_DEF\_Rectangle type descriptor:
423 \begin{codesample}
424 rval = ber_decode(0, &asn_DEF_Rectangle, (void **)&rect, buffer, buf_size);
425 \end{codesample}
426 Note that the initial (asn\_DEF\_Rectangle.ber\_decoder) reference
427 is gone, and also the last argument (0) is no longer necessary.
428
429 These two ways of BER decoder invocations are fully equivalent.
430
431 The BER de\emph{coder} may fail because of (\emph{the following RC\_\ldots{}
432 codes are defined in ber\_decoder.h}):
433 \begin{itemize}
434 \item RC\_WMORE: There is more data expected than it is provided (stream
435 mode continuation feature);
436 \item RC\_FAIL: General failure to decode the buffer;
437 \item \ldots{} other codes may be defined as well.
438 \end{itemize}
439 Together with the return code (.code) the asn\_dec\_rval\_t type contains
440 the number of bytes which is consumed from the buffer. In the previous
441 hypothetical example of two buffers (of 100 and 200 bytes), the first
442 call to ber\_decode() would return with .code = RC\_WMORE and .consumed
443 = 95. The .consumed field of the BER decoder return value is \textbf{always}
444 valid, even if the decoder succeeds or fails with any other return
445 code.
446
447 Look into ber\_decoder.h for the precise definition of ber\_decode()
448 and related types.
449
450
451 \subsection{\label{sub:Encoding-DER}Encoding DER}
452
453 The Distinguished Encoding Rules is the \emph{canonical} variant of
454 BER encoding rules. The DER is best suited to encode the structures
455 where all the lengths are known beforehand. This is probably exactly
456 how you want to encode: either after a BER decoding or after a manual
457 fill-up, the target structure contains the data which size is implicitly
458 known before encoding. Among other uses, the DER encoding is used
459 to encode X.509 certificates.
460
461 As with BER decoder, the DER encoder may be invoked either directly
462 from the ASN.1 type descriptor (asn\_DEF\_Rectangle) or from the stand-alone
463 function, which is somewhat simpler:
464 \begin{codesample}
465 /*
466 * This is the serializer itself.
467 * It supplies the DER encoder with the
468 * pointer to the custom output function.
469 */
470 ssize_t
471 simple_serializer(FILE *ostream, Rectangle_t *rect) {
472 asn_enc_rval_t er; /* Encoder return value */
473
474 er = der_encode(&asn_DEF_Rect, rect, write_stream, ostream);
475 if(er%\textbf{.encoded}% == -1) {
476 fprintf(stderr, "Cannot encode %\%%s: %\%%s\n",
477 er%\textbf{.failed\_type}%->name, strerror(errno));
478 return -1;
479 } else {
480 /* Return the number of bytes */
481 return er.encoded;
482 }
483 }
484 \end{codesample}
485 As you see, the DER encoder does not write into some sort of buffer
486 or something. It just invokes the custom function (possible, multiple
487 times) which would save the data into appropriate storage. The optional
488 argument \emph{app\_key} is opaque for the DER encoder code and just
489 used by \emph{\_write\_stream()} as the pointer to the appropriate
490 output stream to be used.
491
492 If the custom write function is not given (passed as 0), then the
493 DER encoder will essentially do the same thing (i.~e., encode the data)
494 but no callbacks will be invoked (so the data goes nowhere). It may
495 prove useful to determine the size of the structure's encoding before
496 actually doing the encoding%
497 \footnote{It is actually faster too: the encoder might skip over some computations
498 which aren't important for the size determination.%
499 }.
500
501 Look into der\_encoder.h for the precise definition of der\_encode()
502 and related types.
503
504
505 \subsection{\label{sub:Encoding-XER}Encoding XER}
506
507 The XER stands for XML Encoding Rules, where XML, in turn, is eXtensible
508 Markup Language, a text-based format for information exchange. The
509 encoder routine API comes in two flavors: stdio-based and callback-based.
510 With the callback-based encoder, the encoding process is very similar
511 to the DER one, described in Section~\ref{sub:Encoding-DER}. The
512 following example uses the definition of write\_stream() from up there.
513 \begin{codesample}
514 /*
515 * This procedure generates the XML document
516 * by invoking the XER encoder.
517 * NOTE: Do not copy this code verbatim!
518 * If the stdio output is necessary,
519 * use the xer_fprint() procedure instead.
520 * See Section~%\ref{sub:Printing-the-target}%.
521 */
522 int
523 print_as_XML(FILE *ostream, Rectangle_t *rect) {
524 asn_enc_rval_t er; /* Encoder return value */
525
526 er = xer_encode(&asn_DEF_Rectangle, rect,
527 XER_F_BASIC, /* BASIC-XER or CANONICAL-XER */
528 write_stream, ostream);
529
530 return (er.encoded == -1) ? -1 : 0;
531 }
532 \end{codesample}
533 Look into xer\_encoder.h for the precise definition of xer\_encode()
534 and related types.
535
536 See Section~\ref{sub:Printing-the-target} for the example of stdio-based
537 XML encoder and other pretty-printing suggestions.
538
539
540 \subsection{\label{sub:Decoding-XER}Decoding XER}
541
542 The data encoded using the XER rules can be subsequently decoded using
543 the xer\_decode() API call:
544 \begin{codesample}
545 Rectangle_t *
546 XML_to_Rectangle(const void *buffer, size_t buf_size) {
547 asn_dec_rval_t rval;
548 Rectangle_t *%$\underbracket{\textrm{\listingfont rect = 0}}$%; /* %\textbf{\color{red}Note this 0\footnote{Forgetting to properly initialize the pointer to a destination structure is a major source of support requests.}!}% */
549
550 rval = xer_decode(0, &asn_DEF_Rectangle, (void **)&rect, buffer, buf_size);
551
552 if(rval%\textbf{.code}% == RC_OK) {
553 return rect; /* Decoding succeeded */
554 } else {
555 /* Free partially decoded rect */
556 asn_DEF_Rectangle.free_struct(&asn_DEF_Rectangle, rect, 0);
557 return 0;
558 }
559 }
560 \end{codesample}
561 The decoder takes both BASIC-XER and CANONICAL-XER encodings.
562
563 The decoder shares its data consumption properties with BER decoder;
564 please read the Section~\ref{sub:Decoding-BER} to know more.
565
566 Look into xer\_decoder.h for the precise definition of xer\_decode()
567 and related types.
568
569
570 \subsection{\label{sub:Validating-the-target}Validating the target structure}
571
572 Sometimes the target structure needs to be validated. For example,
573 if the structure was created by the application (as opposed to being
574 decoded from some external source), some important information required
575 by the ASN.1 specification might be missing. On the other hand, the
576 successful decoding of the data from some external source does not
577 necessarily mean that the data is fully valid either. It might well
578 be the case that the specification describes some subtype constraints
579 that were not taken into account during decoding, and it would actually
580 be useful to perform the last check when the data is ready to be encoded
581 or when the data has just been decoded to ensure its validity according
582 to some stricter rules.
583
584 The asn\_check\_constraints() function checks the type for various
585 implicit and explicit constraints. It is recommended to use asn\_check\_constraints()
586 function after each decoding and before each encoding.
587
588 Look into constraints.h for the precise definition of asn\_check\_constraints()
589 and related types.
590
591
592 \subsection{\label{sub:Printing-the-target}Printing the target structure}
593
594 There are two ways to print the target structure: either invoke the
595 print\_struct member of the ASN.1 type descriptor, or using the asn\_fprint()
596 function, which is a simpler wrapper of the former:
597 \begin{codesample}
598 asn_fprint(stdout, &asn_DEF_Rectangle, rect);
599 \end{codesample}
600 Look into constr\_TYPE.h for the precise definition of asn\_fprint()
601 and related types.
602
603 Another practical alternative to this custom format printing would
604 be to invoke XER encoder. The default BASIC-XER encoder performs reasonable
605 formatting for the output to be useful and human readable. To invoke
606 the XER decoder in a manner similar to asn\_fprint(), use the xer\_fprint()
607 call:
608 \begin{codesample}
609 xer_fprint(stdout, &asn_DEF_Rectangle, rect);
610 \end{codesample}
611 See Section~\ref{sub:Encoding-XER} for XML-related details.
612
613
614 \subsection{\label{sub:Freeing-the-target}Freeing the target structure}
615
616 Freeing the structure is slightly more complex than it may seem to.
617 When the ASN.1 structure is freed, all the members of the structure
618 and their submembers are recursively freed as well. But it might not
619 be feasible to free the structure itself. Consider the following case:
620 \begin{codesample}
621 struct my_figure { /* The custom structure */
622 int flags; /* <some custom member> */
623 /* The type is generated by the ASN.1 compiler */
624 Rectangle_t rect;
625 /* other members of the structure */
626 };
627 \end{codesample}
628 In this example, the application programmer defined a custom structure
629 with one ASN.1-derived member (rect). This member is not a reference
630 to the Rectangle\_t, but an in-place inclusion of the Rectangle\_t
631 structure. If the freeing is necessary, the usual procedure of freeing
632 everything must not be applied to the \&rect pointer itself, because
633 it does not point to the memory block directly allocated by the memory
634 allocation routine, but instead lies within a block allocated for
635 the my\_figure structure.
636
637 To solve this problem, the free\_struct routine has the additional
638 argument (besides the obvious type descriptor and target structure
639 pointers), which is the flag specifying whether the outer pointer
640 itself must be freed (0, default) or it should be left intact (non-zero
641 value).
642 \begin{codesample}
643 /* %\textbf{1. Rectangle\_t is defined within my\_figure}% */
644 struct my_figure {
645 Rectangle_t rect;
646 } *mf = ...;
647 /*
648 * Freeing the Rectangle_t
649 * without freeing the mf->rect area.
650 */
651 asn_DEF_Rectangle.free_struct(
652 &asn_DEF_Rectangle, &mf->rect, %\textbf{1 /* !free */}%);
653
654 /* %\textbf{2. Rectangle\_t is a stand-alone pointer}% */
655 Rectangle_t *rect = ...;
656 /*
657 * Freeing the Rectangle_t
658 * and freeing the rect pointer.
659 */
660 asn_DEF_Rectangle.free_struct(
661 &asn_DEF_Rectangle, rect, %\textbf{0 /* free the pointer too */}%);
662 \end{codesample}
663 It is safe to invoke the \emph{free\_struct} function with the target
664 structure pointer set to 0 (NULL), the function will do nothing.
665
666 For the programmer's convenience, the following macros are available:
667 \begin{codesample}
668 ASN_STRUCT_FREE(asn_DEF, ptr);
669 ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF, ptr);
670 \end{codesample}
671 These macros bear the same semantics as the \emph{free\_struct} function
672 invocation, discussed above.
673
674
675 \chapter{\label{cha:Step-by-step-examples}Step by step examples}
676
677
678 \section{A ``Rectangle'' Encoder}
679
680 This example will help you create a simple BER and XER encoder of
681 a ``Rectangle'' type used throughout this document.
682 \begin{enumerate}
683 \item Create a file named \textbf{rectangle.asn1} with the following contents:
684
685 \begin{asn}
686 RectangleModule1 DEFINITIONS ::= BEGIN
687
688 Rectangle ::= SEQUENCE {
689 height INTEGER,
690 width INTEGER
691 }
692
693 END
694 \end{asn}
695 \item Compile it into the set of .c and .h files using asn1c compiler \cite{ASN1C}:
696
697 \begin{bash}
698 asn1c %\textbf{rectangle.asn1}%
699 \end{bash}
700 \item Alternatively, use the Online ASN.1 compiler \cite{AONL} by uploading
701 the \textbf{rectangle.asn1} file into the Web form and unpacking the
702 produced archive on your computer.
703 \item By this time, you should have gotten multiple files in the current
704 directory, including the \textbf{Rectangle.c} and \textbf{Rectangle.h}.
705 \item Create a main() routine which creates the Rectangle\_t structure in
706 memory and encodes it using BER and XER encoding rules. Let's name
707 the file \textbf{main.c}:
708
709 \begin{codesample}[basicstyle=\scriptsize\listingfont]
710 #include <stdio.h>
711 #include <sys/types.h>
712 #include <Rectangle.h> /* Rectangle ASN.1 type */
713
714 /* Write the encoded output into some FILE stream. */
715 static int write_out(const void *buffer, size_t size, void *app_key) {
716 FILE *out_fp = app_key;
717 size_t wrote = fwrite(buffer, 1, size, out_fp);
718 return (wrote == size) ? 0 : -1;
719 }
720
721 int main(int ac, char **av) {
722 Rectangle_t *rectangle; /* Type to encode */
723 asn_enc_rval_t ec; /* Encoder return value */
724
725 /* Allocate the Rectangle_t */
726 rectangle = calloc(1, sizeof(Rectangle_t)); /* not malloc! */
727 if(!rectangle) {
728 perror("calloc() failed");
729 exit(1);
730 }
731
732 /* Initialize the Rectangle members */
733 rectangle->height = 42; /* any random value */
734 rectangle->width = 23; /* any random value */
735
736 /* BER encode the data if filename is given */
737 if(ac < 2) {
738 fprintf(stderr, "Specify filename for BER output\n");
739 } else {
740 const char *filename = av[1];
741 FILE *fp = fopen(filename, "wb"); /* for BER output */
742
743 if(!fp) {
744 perror(filename);
745 exit(1);
746 }
747
748 /* Encode the Rectangle type as BER (DER) */
749 ec = der_encode(&asn_DEF_Rectangle, rectangle, write_out, fp);
750 fclose(fp);
751 if(ec.encoded == -1) {
752 fprintf(stderr, "Could not encode Rectangle (at %\%%s)\n",
753 ec.failed_type ? ec.failed_type->name : "unknown");
754 exit(1);
755 } else {
756 fprintf(stderr, "Created %\%%s with BER encoded Rectangle\n", filename);
757 }
758 }
759
760 /* Also print the constructed Rectangle XER encoded (XML) */
761 xer_fprint(stdout, &asn_DEF_Rectangle, rectangle);
762
763 return 0; /* Encoding finished successfully */
764 }
765 \end{codesample}
766 \item Compile all files together using C compiler (varies by platform):
767
768 \begin{bash}
769 cc -I. -o %\textbf{\emph{rencode}} \emph{*.c}%
770 \end{bash}
771 \item Voila! You have just created the BER and XER encoder of a Rectangle
772 type, named \textbf{rencode}!
773 \end{enumerate}
774
775 \section{\label{sec:A-Rectangle-Decoder}A ``Rectangle'' Decoder}
776
777 This example will help you to create a simple BER decoder of a simple
778 ``Rectangle'' type used throughout this document.
779 \begin{enumerate}
780 \item Create a file named \textbf{rectangle.asn1} with the following contents:
781
782 \begin{asn}
783 RectangleModule1 DEFINITIONS ::= BEGIN
784
785 Rectangle ::= SEQUENCE {
786 height INTEGER,
787 width INTEGER
788 }
789
790 END
791 \end{asn}
792 \item Compile it into the set of .c and .h files using asn1c compiler \cite{ASN1C}:
793
794 \begin{bash}
795 asn1c %\textbf{rectangle.asn1}%
796 \end{bash}
797 \item Alternatively, use the Online ASN.1 compiler \cite{AONL} by uploading
798 the \textbf{rectangle.asn1} file into the Web form and unpacking the
799 produced archive on your computer.
800 \item By this time, you should have gotten multiple files in the current
801 directory, including the \textbf{Rectangle.c} and \textbf{Rectangle.h}.
802 \item Create a main() routine which takes the binary input file, decodes
803 it as it were a BER-encoded Rectangle type, and prints out the text
804 (XML) representation of the Rectangle type. Let's name the file \textbf{main.c}:
805
806 \begin{codesample}[basicstyle=\scriptsize\listingfont]
807 #include <stdio.h>
808 #include <sys/types.h>
809 #include <Rectangle.h> /* Rectangle ASN.1 type */
810
811 int main(int ac, char **av) {
812 char buf[1024]; /* Temporary buffer */
813 asn_dec_rval_t rval; /* Decoder return value */
814 Rectangle_t *%$\underbracket{\textrm{\listingfont rectangle = 0}}$%; /* Type to decode. %\textbf{\color{red}Note this 0\footnote{Forgetting to properly initialize the pointer to a destination structure is a major source of support requests.}!}% */
815 FILE *fp; /* Input file handler */
816 size_t size; /* Number of bytes read */
817 char *filename; /* Input file name */
818
819 /* Require a single filename argument */
820 if(ac != 2) {
821 fprintf(stderr, "Usage: %\%%s <file.ber>\n", av[0]);
822 exit(1);
823 } else {
824 filename = av[1];
825 }
826
827 /* Open input file as read-only binary */
828 fp = fopen(filename, "rb");
829 if(!fp) {
830 perror(filename);
831 exit(1);
832 }
833
834 /* Read up to the buffer size */
835 size = fread(buf, 1, sizeof(buf), fp);
836 fclose(fp);
837 if(!size) {
838 fprintf(stderr, "%\%%s: Empty or broken\n", filename);
839 exit(1);
840 }
841
842 /* Decode the input buffer as Rectangle type */
843 rval = ber_decode(0, &asn_DEF_Rectangle, (void **)&rectangle, buf, size);
844 if(rval.code != RC_OK) {
845 fprintf(stderr, "%\%%s: Broken Rectangle encoding at byte %\%%ld\n", filename, (long)rval.consumed);
846 exit(1);
847 }
848
849 /* Print the decoded Rectangle type as XML */
850 xer_fprint(stdout, &asn_DEF_Rectangle, rectangle);
851
852 return 0; /* Decoding finished successfully */
853 }
854 \end{codesample}
855 \item Compile all files together using C compiler (varies by platform):
856
857 \begin{bash}
858 cc -I. -o %\textbf{\emph{rdecode}} \emph{*.c}%
859 \end{bash}
860 \item Voila! You have just created the BER decoder of a Rectangle type,
861 named \textbf{rdecode}!
862 \end{enumerate}
863
864 \chapter{Constraint validation examples}
865
866 This chapter shows how to define ASN.1 constraints and use the generated
867 validation code.
868
869
870 \section{Adding constraints into ``Rectangle'' type}
871
872 This example shows how to add basic constraints to the ASN.1 specification
873 and how to invoke the constraints validation code in your application.
874 \begin{enumerate}
875 \item Create a file named \textbf{rectangle.asn1} with the following contents:
876
877 \begin{asn}
878 RectangleModuleWithConstraints DEFINITIONS ::= BEGIN
879
880 Rectangle ::= SEQUENCE {
881 height INTEGER (0..100), -- Value range constraint
882 width INTEGER (0..MAX) -- Makes width non-negative
883 }
884
885 END
886 \end{asn}
887 \item Compile the file according to procedures shown in the previous chapter.
888 \item Modify the Rectangle type processing routine (you can start with the
889 main() routine shown in the Section~\ref{sec:A-Rectangle-Decoder})
890 by placing the following snippet of code \emph{before} encoding and/or
891 \emph{after} decoding the Rectangle type%
892 \footnote{Placing the constraint checking code \emph{before encoding} helps
893 to make sure the data is correct and within constraints before
894 sharing the data with anyone else.
895 Placing the constraint checking code \emph{after decoding} helps to make sure
896 the application got the valid contents before making use of it.%
897 }:
898
899 \begin{codesample}
900 int ret; /* Return value */
901 char errbuf[128]; /* Buffer for error message */
902 size_t errlen = sizeof(errbuf); /* Size of the buffer */
903
904 /* ... here goes the Rectangle %\emph{decoding}% code ... */
905
906 ret = asn_check_constraints(&asn_DEF_Rectangle, rectangle, errbuf, &errlen);
907 /* assert(errlen < sizeof(errbuf)); // you may rely on that */
908 if(ret) {
909 fprintf(stderr, "Constraint validation failed: %\%%s\n",
910 errbuf /* errbuf is properly nul-terminated */
911 );
912 /* exit(...); // Replace with appropriate action */
913 }
914
915 /* ... here goes the Rectangle %\emph{encoding}% code ... */
916 \end{codesample}
917 \item Compile the resulting C code as shown in the previous chapters.
918 \item Try to test the constraints checking code by assigning integer value
919 101 to the \textbf{.height} member of the Rectangle structure, or
920 a negative value to the \textbf{.width} member. In either case, the
921 program should print ``Constraint validation failed'' message, followed
922 by a short explanation why validation did not succeed.
923 \item Done.
924 \end{enumerate}
925
926 \part{\label{par:ASN.1-Basics}ASN.1 Basics}
927
928
929 \chapter{\label{cha:Abstract-Syntax-Notation:}Abstract Syntax Notation: ASN.1}
930
931 \emph{This chapter defines some basic ASN.1 concepts and describes
932 several most widely used types. It is by no means an authoritative
933 or complete reference. For more complete ASN.1 description, please
934 refer to Olivier Dubuisson's book \cite{Dub00} or the ASN.1 body
935 of standards itself \cite{ITU-T/ASN.1}.}
936
937 The Abstract Syntax Notation One is used to formally describe the
938 data transmitted across the network. Two communicating parties may employ
939 different formats of their native data types (e.~g., different number
940 of bits for the native integer type), thus it is important to have
941 a way to describe the data in a manner which is independent from the
942 particular machine's representation.
943 The ASN.1 specifications are used to achieve the following:
944 \begin{itemize}
945 \item The specification expressed in the ASN.1 notation is a formal and
946 precise way to communicate the structure of data to human readers;
947 \item The ASN.1 specifications may be used as input for automatic compilers
948 which produce the code for some target language (C, C++, Java, etc)
949 to encode and decode the data according to some encoding formats.
950 Several such encoding formats (called Transfer Encoding Rules)
951 have been defined by the ASN.1 standard.
952 \end{itemize}
953 Consider the following example:
954 \begin{asn}
955 Rectangle ::= SEQUENCE {
956 height INTEGER,
957 width INTEGER
958 }
959 \end{asn}
960 This ASN.1 specification describes a constructed type, \emph{Rectangle},
961 containing two integer fields. This specification may tell the reader
962 that there exists this kind of data structure and that some entity
963 may be prepared to send or receive it. The question on \emph{how}
964 that entity is going to send or receive the \emph{encoded data} is
965 outside the scope of ASN.1. For example, this data structure may be
966 encoded according to some encoding rules and sent to the destination
967 using the TCP protocol. The ASN.1 specifies several ways of encoding
968 (or ``serializing'', or ``marshaling'') the data: BER, PER, XER
969 and others, including CER and DER derivatives from BER.
970
971 The complete specification must be wrapped in a module, which looks
972 like this:
973 \begin{asn}
974 RectangleModule1
975 { iso org(3) dod(6) internet(1) private(4)
976 enterprise(1) spelio(9363) software(1)
977 asn1c(5) docs(2) rectangle(1) 1 }
978 DEFINITIONS AUTOMATIC TAGS ::=
979 BEGIN
980
981 -- This is a comment which describes nothing.
982 Rectangle ::= SEQUENCE {
983 height INTEGER, -- Height of the rectangle
984 width INTEGER -- Width of the rectangle
985 }
986
987 END
988 \end{asn}
989 The module header consists of module name (RectangleModule1), the
990 module object identifier (\{...\}), a keyword ``DEFINITIONS'', a
991 set of module flags (AUTOMATIC TAGS) and ``::= BEGIN''. The module
992 ends with an ``END'' statement.
993
994
995 \section{Some of the ASN.1 Basic Types}
996
997
998 \subsection{The BOOLEAN type}
999
1000 The BOOLEAN type models the simple binary TRUE/FALSE, YES/NO, ON/OFF
1001 or a similar kind of two-way choice.
1002
1003
1004 \subsection{The INTEGER type}
1005
1006 The INTEGER type is a signed natural number type without any restrictions
1007 on its size. If the automatic checking on INTEGER value bounds are
1008 necessary, the subtype constraints must be used.
1009 \begin{asn}
1010 SimpleInteger ::= INTEGER
1011
1012 -- An integer with a very limited range
1013 SmallPositiveInt ::= INTEGER (0..127)
1014
1015 -- Integer, negative
1016 NegativeInt ::= INTEGER (MIN..0)
1017 \end{asn}
1018
1019 \subsection{The ENUMERATED type}
1020
1021 The ENUMERATED type is semantically equivalent to the INTEGER type
1022 with some integer values explicitly named.
1023 \begin{asn}
1024 FruitId ::= ENUMERATED { apple(1), orange(2) }
1025
1026 -- The numbers in braces are optional,
1027 -- the enumeration can be performed
1028 -- automatically by the compiler
1029 ComputerOSType ::= ENUMERATED {
1030 FreeBSD, -- acquires value 0
1031 Windows, -- acquires value 1
1032 Solaris(5), -- remains 5
1033 Linux, -- becomes 6
1034 MacOS -- becomes 7
1035 }
1036 \end{asn}
1037
1038 \subsection{The OCTET STRING type}
1039
1040 This type models the sequence of 8-bit bytes. This may be used to
1041 transmit some opaque data or data serialized by other types of encoders
1042 (e.~g., video file, photo picture, etc).
1043
1044 \subsection{The OBJECT IDENTIFIER type}
1045
1046 The OBJECT IDENTIFIER is used to represent the unique identifier of
1047 any object, starting from the very root of the registration tree.
1048 If your organization needs to uniquely identify something (a router,
1049 a room, a person, a standard, or whatever), you are encouraged to
1050 get your own identification subtree at \url{http://www.iana.org/protocols/forms.htm}.
1051
1052 For example, the very first ASN.1 module in this Chapter (RectangleModule1)
1053 has the following OBJECT IDENTIFIER: 1 3 6 1 4 1 9363 1 5 2 1 1.
1054 \begin{asn}
1055 ExampleOID ::= OBJECT IDENTIFIER
1056
1057 rectangleModule1-oid ExampleOID
1058 ::= { 1 3 6 1 4 1 9363 1 5 2 1 1 }
1059
1060 -- An identifier of the Internet.
1061 internet-id OBJECT IDENTIFIER
1062 ::= { iso(1) identified-organization(3)
1063 dod(6) internet(1) }
1064 \end{asn}
1065 As you see, names are optional.
1066
1067
1068 \subsection{The RELATIVE-OID type}
1069
1070 The RELATIVE-OID type has the semantics of a subtree of an OBJECT
1071 IDENTIFIER. There may be no need to repeat the whole sequence of numbers
1072 from the root of the registration tree where the only thing of interest
1073 is some of the tree's subsequence.
1074 \begin{asn}
1075 this-document RELATIVE-OID ::= { docs(2) usage(1) }
1076
1077 this-example RELATIVE-OID ::= {
1078 this-document assorted-examples(0) this-example(1) }
1079 \end{asn}
1080
1081 \section{Some of the ASN.1 String Types}
1082
1083
1084 \subsection{The IA5String type}
1085
1086 This is essentially the ASCII, with 128 character codes available
1087 (7 lower bits of an 8-bit byte).
1088
1089
1090 \subsection{The UTF8String type}
1091
1092 This is the character string which encodes the full Unicode range
1093 (4 bytes) using multibyte character sequences.
1094
1095
1096 \subsection{The NumericString type}
1097
1098 This type represents the character string with the alphabet consisting
1099 of numbers (``0'' to ``9'') and a space.
1100
1101
1102 \subsection{The PrintableString type}
1103
1104 The character string with the following alphabet: space, ``\textbf{'}''
1105 (single quote), ``\textbf{(}'', ``\textbf{)}'', ``\textbf{+}'',
1106 ``\textbf{,}'' (comma), ``\textbf{-}'', ``\textbf{.}'', ``\textbf{/}'',
1107 digits (``0'' to ``9''), ``\textbf{:}'', ``\textbf{=}'', ``\textbf{?}'',
1108 upper-case and lower-case letters (``A'' to ``Z'' and ``a''
1109 to ``z'').
1110
1111
1112 \subsection{The VisibleString type}
1113
1114 The character string with the alphabet which is more or less a subset
1115 of ASCII between the space and the ``\textbf{\textasciitilde{}}''
1116 symbol (tilde).
1117
1118 Alternatively, the alphabet may be described as the PrintableString
1119 alphabet presented earlier, plus the following characters: ``\textbf{!}'',
1120 ``\textbf{``}'', ``\textbf{\#}'', ``\textbf{\$}'', ``\textbf{\%}'',
1121 ``\textbf{\&}'', ``\textbf{*}'', ``\textbf{;}'', ``\textbf{<}'',
1122 ``\textbf{>}'', ``\textbf{{[}}'', ``\textbf{\textbackslash{}}'',
1123 ``\textbf{{]}}'', ``\textbf{\textasciicircum{}}'', ``\textbf{\_}'',
1124 ``\textbf{`}`` (single left quote), ``\textbf{\{}'', ``\textbf{|}'',
1125 ``\textbf{\}}'', ``\textbf{\textasciitilde{}}''.
1126
1127
1128 \section{ASN.1 Constructed Types}
1129
1130
1131 \subsection{The SEQUENCE type}
1132
1133 This is an ordered collection of other simple or constructed types.
1134 The SEQUENCE constructed type resembles the C ``struct'' statement.
1135 \begin{asn}
1136 Address ::= SEQUENCE {
1137 -- The apartment number may be omitted
1138 apartmentNumber NumericString OPTIONAL,
1139 streetName PrintableString,
1140 cityName PrintableString,
1141 stateName PrintableString,
1142 -- This one may be omitted too
1143 zipNo NumericString OPTIONAL
1144 }
1145 \end{asn}
1146
1147 \subsection{The SET type}
1148
1149 This is a collection of other simple or constructed types. Ordering
1150 is not important. The data may arrive in the order which is different
1151 from the order of specification. Data is encoded in the order not
1152 necessarily corresponding to the order of specification.
1153
1154
1155 \subsection{The CHOICE type}
1156
1157 This type is just a choice between the subtypes specified in it. The
1158 CHOICE type contains at most one of the subtypes specified, and it
1159 is always implicitly known which choice is being decoded or encoded.
1160 This one resembles the C ``union'' statement.
1161
1162 The following type defines a response code, which may be either an
1163 integer code or a boolean ``true''/``false'' code.
1164 \begin{asn}
1165 ResponseCode ::= CHOICE {
1166 intCode INTEGER,
1167 boolCode BOOLEAN
1168 }
1169 \end{asn}
1170
1171 \subsection{The SEQUENCE OF type}
1172
1173 This one is the list (array) of simple or constructed types:
1174 \begin{asn}
1175 -- Example 1
1176 ManyIntegers ::= SEQUENCE OF INTEGER
1177
1178 -- Example 2
1179 ManyRectangles ::= SEQUENCE OF Rectangle
1180
1181 -- More complex example:
1182 -- an array of structures defined in place.
1183 ManyCircles ::= SEQUENCE OF SEQUENCE {
1184 radius INTEGER
1185 }
1186 \end{asn}
1187
1188 \subsection{The SET OF type}
1189
1190 The SET OF type models the bag of structures. It resembles the SEQUENCE
1191 OF type, but the order is not important. The elements may arrive
1192 in the order which is not necessarily the same as the in-memory order
1193 on the remote machines.
1194 \begin{asn}
1195 -- A set of structures defined elsewhere
1196 SetOfApples :: SET OF Apple
1197
1198 -- Set of integers encoding the kind of a fruit
1199 FruitBag ::= SET OF ENUMERATED { apple, orange }
1200 \end{asn}
1201 \begin{thebibliography}{ITU-T/ASN.1}
1202 \bibitem[ASN1C]{ASN1C}The Open Source ASN.1 Compiler. \url{http://lionet.info/asn1c}
1203
1204 \bibitem[AONL]{AONL}Online ASN.1 Compiler. \url{http://lionet.info/asn1c/asn1c.cgi}
1205
1206 \bibitem[Dub00]{Dub00}Olivier Dubuisson --- \emph{ASN.1 Communication
1207 between heterogeneous systems} --- Morgan Kaufmann Publishers, 2000.
1208 \url{http://asn1.elibel.tm.fr/en/book/}. ISBN:0-12-6333361-0.
1209
1210 \bibitem[ITU-T/ASN.1]{ITU-T/ASN.1}ITU-T Study Group 17 --- Languages
1211 for Telecommunication Systems \url{http://www.itu.int/ITU-T/studygroups/com17/languages/}
1212 \end{thebibliography}
1213
1214 \end{document}