Supply id on all sections + examples.
[yaz-moved-to-github.git] / doc / odr.xml
1 <!-- $Id: odr.xml,v 1.19 2006-10-05 08:26:58 adam Exp $ -->
2  <chapter id="odr"><title>The ODR Module</title>
3   
4   <sect1 id="odr.introduction"><title>Introduction</title>
5
6    <para>
7      &odr; is the BER-encoding/decoding subsystem of &yaz;. Care as been taken
8     to isolate &odr; from the rest of the package - specifically from the
9     transport interface. &odr; may be used in any context where basic
10     ASN.1/BER representations are used.
11    </para>
12
13    <para>
14     If you are only interested in writing a Z39.50 implementation based on
15     the PDUs that are already provided with &yaz;, you only need to concern
16     yourself with the section on managing ODR streams
17     (<xref linkend="odr.use"/>). Only if you need to
18     implement ASN.1 beyond that which has been provided, should you
19     worry about the second half of the documentation
20     (<xref linkend="odr.programming"/>).
21     If you use one of the higher-level interfaces, you can skip this
22     section entirely.
23    </para>
24
25    <para>
26     This is important, so we'll repeat it for emphasis: <emphasis>You do
27      not need to read <xref linkend="odr.programming"/>
28      to implement Z39.50 with &yaz;.</emphasis>
29    </para>
30
31    <para>
32     If you need a part of the protocol that isn't already in &yaz;, you
33     should contact the authors before going to work on it yourself: We
34     might already be working on it. Conversely, if you implement a useful
35     part of the protocol before us, we'd be happy to include it in a
36     future release.
37    </para>
38
39   </sect1>
40   <sect1 id="odr.use"><title>Using ODR</title>
41
42    <sect2 id="odr.streams"><title>ODR Streams</title>
43
44     <para>
45      Conceptually, the ODR stream is the source of encoded data in the
46      decoding mode; when encoding, it is the receptacle for the encoded
47      data. Before you can use an ODR stream it must be allocated. This is
48      done with the function
49     </para>
50
51     <synopsis>
52      ODR odr_createmem(int direction);
53     </synopsis>
54
55     <para>
56      The <function>odr_createmem()</function> function takes as argument one
57      of three manifest constants: <literal>ODR_ENCODE</literal>,
58      <literal>ODR_DECODE</literal>, or <literal>ODR_PRINT</literal>.
59      An &odr; stream can be in only one mode - it is not possible to change
60      its mode once it's selected. Typically, your program will allocate
61      at least two ODR streams - one for decoding, and one for encoding.
62     </para>
63
64     <para>
65      When you're done with the stream, you can use
66     </para>
67
68     <synopsis>
69      void odr_destroy(ODR o);
70     </synopsis>
71
72     <para>
73      to release the resources allocated for the stream.
74     </para>
75    </sect2>
76
77    <sect2 id="odr.memory.management"><title id="memory">Memory Management</title>
78
79     <para>
80      Two forms of memory management take place in the &odr; system. The first
81      one, which has to do with allocating little bits of memory (sometimes
82      quite large bits of memory, actually) when a protocol package is
83      decoded, and turned into a complex of interlinked structures. This
84      section deals with this system, and how you can use it for your own
85      purposes. The next section deals with the memory management which is
86      required when encoding data - to make sure that a large enough buffer is
87      available to hold the fully encoded PDU.
88     </para>
89
90     <para>
91      The &odr; module has its own memory management system, which is
92      used whenever memory is required. Specifically, it is used to allocate
93      space for data when decoding incoming PDUs. You can use the memory
94      system for your own purposes, by using the function
95     </para>
96
97     <synopsis>
98      void *odr_malloc(ODR o, int size);
99     </synopsis>
100
101     <para>
102      You can't use the normal <function>free(2)</function> routine to free
103      memory allocated by this function, and &odr; doesn't provide a parallel
104      function. Instead, you can call
105     </para>
106
107     <synopsis>
108      void odr_reset(ODR o, int size);
109     </synopsis>
110
111     <para>
112      when you are done with the
113      memory: Everything allocated since the last call to
114      <function>odr_reset()</function> is released.
115      The <function>odr_reset()</function> call is also required to clear
116      up an error condition on a stream.
117     </para>
118
119     <para>
120      The function
121     </para>
122
123     <synopsis>
124      int odr_total(ODR o);
125     </synopsis>
126
127     <para>
128      returns the number of bytes allocated on the stream since the last call to
129      <function>odr_reset()</function>.
130     </para>
131
132     <para>
133      The memory subsystem of &odr; is fairly efficient at allocating and
134      releasing little bits of memory. Rather than managing the individual,
135      small bits of space, the system maintains a free-list of larger chunks
136      of memory, which are handed out in small bits. This scheme is
137      generally known as a <emphasis>nibble memory</emphasis> system.
138      It is very useful for maintaining short-lived constructions such
139      as protocol PDUs.
140     </para>
141
142     <para>
143      If you want to retain a bit of memory beyond the next call to
144      <function>odr_reset()</function>, you can use the function
145     </para>
146
147     <synopsis>
148      ODR_MEM odr_extract_mem(ODR o);
149     </synopsis>
150
151     <para>
152      This function will give you control of the memory recently allocated
153      on the ODR stream. The memory will live (past calls to
154      <function>odr_reset()</function>), until you call the function
155     </para>
156
157     <synopsis>
158      void odr_release_mem(ODR_MEM p);
159     </synopsis>
160
161     <para>
162      The opaque <literal>ODR_MEM</literal> handle has no other purpose than
163      referencing the memory block for you until you want to release it.
164     </para>
165
166     <para>
167      You can use <function>odr_extract_mem()</function> repeatedly between
168      allocating data, to retain individual control of separate chunks of data.
169     </para>
170
171    </sect2>
172    <sect2 id="odr.encoding.and.decoding"><title>Encoding and Decoding Data</title>
173
174     <para>
175      When encoding data, the ODR stream will write the encoded octet string
176      in an internal buffer. To retrieve the data, use the function
177     </para>
178
179     <synopsis>
180      char *odr_getbuf(ODR o, int *len, int *size);
181     </synopsis>
182
183     <para>
184      The integer pointed to by len is set to the length of the encoded
185      data, and a pointer to that data is returned. <literal>*size</literal>
186      is set to the size of the buffer (unless <literal>size</literal> is null,
187      signaling that you are not interested in the size). The next call to
188      a primitive function using the same &odr; stream will overwrite the
189      data, unless a different buffer has been supplied using the call
190     </para>
191
192     <synopsis>
193      void odr_setbuf(ODR o, char *buf, int len, int can_grow);
194     </synopsis>
195
196     <para>
197      which sets the encoding (or decoding) buffer used by
198      <literal>o</literal> to <literal>buf</literal>, using the length
199      <literal>len</literal>.
200      Before a call to an encoding function, you can use
201      <function>odr_setbuf()</function> to provide the stream with an encoding
202      buffer of sufficient size (length). The <literal>can_grow</literal>
203      parameter tells the encoding &odr; stream whether it is allowed to use
204      <function>realloc(2)</function> to increase the size of the buffer when
205      necessary. The default condition of a new encoding stream is equivalent
206      to the results of calling
207     </para>
208
209     <synopsis>
210      odr_setbuf(stream, 0, 0, 1);
211     </synopsis>
212
213     <para>
214      In this case, the stream will allocate and reallocate memory as
215      necessary. The stream reallocates memory by repeatedly doubling the
216      size of the buffer - the result is that the buffer will typically
217      reach its maximum, working size with only a small number of reallocation
218      operations. The memory is freed by the stream when the latter is destroyed,
219      unless it was assigned by the user with the <literal>can_grow</literal>
220      parameter set to zero (in this case, you are expected to retain
221      control of the memory yourself).
222     </para>
223
224     <para>
225      To assume full control of an encoded buffer, you must first call
226      <function>odr_getbuf()</function> to fetch the buffer and its length.
227      Next, you should call <function>odr_setbuf()</function> to provide a
228      different buffer (or a null pointer) to the stream. In the simplest
229      case, you will reuse the same buffer over and over again, and you
230      will just need to call <function>odr_getbuf()</function> after each
231      encoding operation to get the length and address of the buffer.
232      Note that the stream may reallocate the buffer during an encoding
233      operation, so it is necessary to retrieve the correct address after
234      each encoding operation.
235     </para>
236
237     <para>
238      It is important to realize that the ODR stream will not release this
239      memory when you call <function>odr_reset()</function>: It will
240      merely update its internal pointers to prepare for the encoding of a
241      new data value.
242      When the stream is released by the <function>odr_destroy()</function>
243      function, the memory given to it by <function>odr_setbuf</function> will
244      be released <emphasis>only</emphasis> if the <literal>can_grow</literal>
245      parameter to <function>odr_setbuf()</function> was nonzero. The
246      <literal>can_grow</literal> parameter, in other words, is a way of
247      signaling who is to own the buffer, you or the ODR stream. If you never call
248      <function>odr_setbuf()</function> on your encoding stream, which is
249      typically the case, the buffer allocated by the stream will belong to
250      the stream by default.
251     </para>
252
253     <para>
254      When you wish to decode data, you should first call
255      <function>odr_setbuf()</function>, to tell the decoding stream
256      where to find the encoded data, and how long the buffer is
257      (the <literal>can_grow</literal> parameter is ignored by a decoding
258      stream). After this, you can call the function corresponding to the
259      data you wish to decode (eg, <function>odr_integer()</function> odr
260      <function>z_APDU()</function>).
261     </para>
262     
263     <example id="example.odr.encoding.and.decoding.functions">
264      <title>Encoding and decoding functions</title>
265      <synopsis>
266       int odr_integer(ODR o, int **p, int optional, const char *name);
267       
268       int z_APDU(ODR o, Z_APDU **p, int optional, const char *name);
269      </synopsis>
270     </example>
271
272     <para>
273      If the data is absent (or doesn't match the tag corresponding to
274      the type), the return value will be either 0 or 1 depending on the
275      <literal>optional</literal> flag. If <literal>optional</literal>
276      is 0 and the data is absent, an error flag will be raised in the
277      stream, and you'll need to call <function>odr_reset()</function> before
278      you can use the stream again. If <literal>optional</literal> is
279      nonzero, the pointer <emphasis>pointed</emphasis> to/ by
280      <literal>p</literal> will be set to the null value, and the function
281      will return 1.
282      The <literal>name</literal> argument is used to pretty-print the
283      tag in question. It may be set to <literal>NULL</literal> if
284      pretty-printing is not desired.
285     </para>
286
287     <para>
288      If the data value is found where it's expected, the pointer
289      <emphasis>pointed to</emphasis> by the <literal>p</literal> argument
290      will be set to point to the decoded type.
291      The space for the type will be allocated and owned by the &odr;
292      stream, and it will live until you call
293      <function>odr_reset()</function> on the stream. You cannot use
294      <function>free(2)</function> to release the memory.
295      You can decode several data elements (by repeated calls to
296      <function>odr_setbuf()</function> and your decoding function), and
297      new memory will be allocated each time. When you do call 
298      <function>odr_reset()</function>, everything decoded since the
299      last call to <function>odr_reset()</function> will be released.
300     </para>
301
302     <example id="example.odr.encoding.of.integer">
303      <title>Encoding and decoding of an integer</title>
304      <para>
305       The use of the double indirection can be a little confusing at first
306       (its purpose will become clear later on, hopefully),
307       so an example is in order. We'll encode an integer value, and
308       immediately decode it again using a different stream. A useless, but
309       informative operation.
310      </para>
311      <programlisting><![CDATA[
312 void do_nothing_useful(int value)
313 {
314     ODR encode, decode;
315     int *valp, *resvalp;
316     char *bufferp;
317     int len;
318      
319     /* allocate streams */
320     if (!(encode = odr_createmem(ODR_ENCODE)))
321         return;
322     if (!(decode = odr_createmem(ODR_DECODE)))
323         return;
324
325     valp = &amp;value;
326     if (odr_integer(encode, &amp;valp, 0, 0) == 0)
327     {
328         printf("encoding went bad\n");
329         return;
330     }
331     bufferp = odr_getbuf(encode, &amp;len);
332     printf("length of encoded data is &percnt;d\n", len);
333
334     /* now let's decode the thing again */
335     odr_setbuf(decode, bufferp, len);
336     if (odr_integer(decode, &amp;resvalp, 0, 0) == 0)
337     {
338         printf("decoding went bad\n");
339         return;
340     }
341     printf("the value is &percnt;d\n", *resvalp);
342
343     /* clean up */
344     odr_destroy(encode);
345     odr_destroy(decode);
346 }
347 ]]>
348      </programlisting>
349      <para>
350       This looks like a lot of work, offhand. In practice, the &odr; streams
351       will typically be allocated once, in the beginning of your program
352       (or at the beginning of a new network session), and the encoding
353       and decoding will only take place in a few, isolated places in your
354       program, so the overhead is quite manageable.
355      </para>
356     </example>
357     
358    </sect2>
359
360    <sect2 id="odr.printing"><title>Printing</title>
361     <para>
362      When an ODR stream is created of type <literal>ODR_PRINT</literal>
363      the ODR module will print the contents of a PDU in a readable format.
364      By default output is written to the <literal>stderr</literal> stream.
365      This behavior can be changed, however, by calling the function
366      <synopsis>
367       odr_setprint(ODR o, FILE *file);
368      </synopsis>
369      before encoders or decoders are being invoked.
370      It is also possible to direct the output to a buffer (of indeed
371      another file), by using the more generic mechanism:
372      <synopsis>
373       void odr_set_stream(ODR o, void *handle,
374                          void (*stream_write)(ODR o, void *handle, int type,
375                                               const char *buf, int len),
376                          void (*stream_close)(void *handle));
377      </synopsis>
378      Here the user provides an opaque handle and two handlers,
379      <replaceable>stream_write</replaceable> for writing,
380      and <replaceable>stream_close</replaceable> which is supposed
381      to close/free resources associated with handle. 
382      The <replaceable>stream_close</replaceable> handler is optional and
383      if NULL for the function is provided, it will not be invoked.
384      The <replaceable>stream_write</replaceable> takes the ODR handle
385      as parameter, the user defined handle, a type 
386      <literal>ODR_OCTETSTRING</literal>, <literal>ODR_VISIBLESTRING</literal>
387      which indicates the type of contents is being written.
388     </para>
389     <para>
390      Another utility useful for diagnostics (error handling) or as
391      part of the printing facilities is:
392      <synopsis>
393       const char **odr_get_element_path(ODR o);
394      </synopsis>
395      which returns a list of current elements that ODR deals with at the 
396      moment. For the returned array, say <literal>ar</literal>, 
397      <literal>ar[0]</literal> is the top level element,
398      <literal>ar[n]</literal> is the last. The last element has the
399      property that <literal>ar[n+1] == NULL</literal>.
400     </para>
401     <example id="example.odr.element.path.record">
402      <title>Element Path for record</title>
403      <para>
404       For a database record part of a PresentResponse the
405       array returned by <function>odr_get_element</function>
406       is <literal>presentResponse</literal>, <literal>databaseOrSurDiagnostics</literal>, <literal>?</literal>, <literal>record</literal>, <literal>?</literal>, <literal>databaseRecord</literal> . The question mark appears due to 
407       unnamed constructions.
408      </para>
409      </example>
410    </sect2>
411    <sect2 id="odr.diagnostics"><title>Diagnostics</title>
412
413     <para>
414      The encoding/decoding functions all return 0 when an error occurs.
415      Until you call <function>odr_reset()</function>, you cannot use the
416      stream again, and any function called will immediately return 0.
417     </para>
418
419     <para>
420      To provide information to the programmer or administrator, the function
421     </para>
422
423     <synopsis>
424      void odr_perror(ODR o, char *message);
425     </synopsis>
426
427     <para>
428      is provided, which prints the <literal>message</literal> argument to
429      <literal>stderr</literal> along with an error message from the stream.
430     </para>
431
432     <para>
433      You can also use the function
434     </para>
435
436     <synopsis>
437      int odr_geterror(ODR o);
438     </synopsis>
439
440     <para>
441      to get the current error number from the screen. The number will be
442      one of these constants:
443     </para>
444
445     <table frame="top" id="odr.error.codes">
446      <title>ODR Error codes</title>
447      <tgroup cols="2">
448       <thead>
449        <row>
450         <entry>code</entry>
451         <entry>Description</entry>
452        </row>
453       </thead>
454       <tbody>
455        <row>
456         <entry>OMEMORY</entry><entry>Memory allocation failed.</entry>
457        </row>
458
459        <row>
460         <entry>OSYSERR</entry><entry>A system- or library call has failed.
461          The standard diagnostic variable <literal>errno</literal> should be
462          examined to determine the actual error.</entry>
463        </row>
464
465        <row>
466         <entry>OSPACE</entry><entry>No more space for encoding.
467          This will only occur when the user has explicitly provided a
468          buffer for an encoding stream without allowing the system to
469          allocate more space.</entry>
470        </row>
471
472        <row>
473         <entry>OREQUIRED</entry><entry>This is a common protocol error; A
474          required data element was missing during encoding or decoding.</entry>
475        </row>
476
477        <row>
478         <entry>OUNEXPECTED</entry><entry>An unexpected data element was
479          found during decoding.</entry>
480        </row>
481
482        <row><entry>OOTHER</entry><entry>Other error. This is typically an
483          indication of misuse of the &odr; system by the programmer, and also
484          that the diagnostic system isn't as good as it should be, yet.</entry>
485        </row>
486       </tbody>
487      </tgroup>
488     </table>
489
490     <para>
491      The character string array
492     </para>
493
494     <synopsis>
495      char *odr_errlist&lsqb;&rsqb;
496     </synopsis>
497
498     <para>
499      can be indexed by the error code to obtain a human-readable
500      representation of the problem.
501     </para>
502
503    </sect2>
504    <sect2 id="odr.summary.and.synopsis">
505     <title>Summary and Synopsis</title>
506
507     <synopsis>
508      #include &lt;odr.h>
509
510      ODR odr_createmem(int direction);
511
512      void odr_destroy(ODR o);
513
514      void odr_reset(ODR o);
515
516      char *odr_getbuf(ODR o, int *len);
517
518      void odr_setbuf(ODR o, char *buf, int len);
519
520      void *odr_malloc(ODR o, int size);
521
522      ODR_MEM odr_extract_mem(ODR o);
523
524      void odr_release_mem(ODR_MEM r);
525
526      int odr_geterror(ODR o);
527
528      void odr_perror(char *message);
529
530      extern char *odr_errlist[];
531     </synopsis>
532
533    </sect2>
534   </sect1>
535
536   <sect1 id="odr.programming"><title>Programming with ODR</title>
537
538    <para>
539     The API of &odr; is designed to reflect the structure of ASN.1, rather
540     than BER itself. Future releases may be able to represent data in
541     other external forms.
542    </para>
543
544    <tip>
545     <para>
546      There is an ASN.1 tutorial available at
547      <ulink url="&url.asn.1.tutorial;">this site</ulink>.
548      This site also has standards for ASN.1 (X.680) and BER (X.690) 
549      <ulink url="&url.asn.1.standards;">online</ulink>.
550     </para>
551    </tip>
552    
553    <para>
554     The ODR interface is based loosely on that of the Sun Microsystems
555     XDR routines.
556     Specifically, each function which corresponds to an ASN.1 primitive
557     type has a dual function. Depending on the settings of the ODR
558     stream which is supplied as a parameter, the function may be used
559     either to encode or decode data. The functions that can be built
560     using these primitive functions, to represent more complex data types,
561     share this quality. The result is that you only have to enter the
562     definition for a type once - and you have the functionality of encoding,
563     decoding (and pretty-printing) all in one unit.
564     The resulting C source code is quite compact, and is a pretty
565     straightforward representation of the source ASN.1 specification. 
566    </para>
567    
568    <para>
569     In many cases, the model of the XDR functions works quite well in this
570     role.
571     In others, it is less elegant. Most of the hassle comes from the optional
572     SEQUENCE members which don't exist in XDR.
573    </para>
574
575    <sect2 id="odr.primitive.asn1.types">
576     <title>The Primitive ASN.1 Types</title>
577
578     <para>
579      ASN.1 defines a number of primitive types (many of which correspond
580      roughly to primitive types in structured programming languages, such as C).
581     </para>
582
583     <sect3 id="odr.integer"><title>INTEGER</title>
584
585      <para>
586       The &odr; function for encoding or decoding (or printing) the ASN.1
587       INTEGER type looks like this:
588      </para>
589
590      <synopsis>
591       int odr_integer(ODR o, int **p, int optional, const char *name);
592      </synopsis>
593
594      <para>
595       (we don't allow values that can't be contained in a C integer.)
596      </para>
597      
598      <para>
599       This form is typical of the primitive &odr; functions. They are named
600       after the type of data that they encode or decode. They take an &odr;
601       stream, an indirect reference to the type in question, and an
602       <literal>optional</literal> flag (corresponding to the OPTIONAL keyword
603       of ASN.1) as parameters. They all return an integer value of either one
604       or zero.
605       When you use the primitive functions to construct encoders for complex
606       types of your own, you should follow this model as well. This
607       ensures that your new types can be reused as elements in yet more
608       complex types.
609      </para>
610
611      <para>
612       The <literal>o</literal> parameter should obviously refer to a properly
613       initialized &odr; stream of the right type (encoding/decoding/printing)
614       for the operation that you wish to perform.
615      </para>
616
617      <para>
618       When encoding or printing, the function first looks at
619       <literal>* p</literal>. If <literal>* p</literal> (the pointer pointed
620       to by <literal>p</literal>) is a null pointer, this is taken to mean that
621       the data element is absent. If the <literal>optional</literal> parameter
622       is nonzero, the function will return one (signifying success) without
623       any further processing. If the <literal>optional</literal> is zero, an
624       internal error flag is set in the &odr; stream, and the function will
625       return 0. No further operations can be carried out on the stream without
626       a call to the function <function>odr_reset()</function>.
627      </para>
628
629      <para>
630       If <literal>*p</literal> is not a null pointer, it is expected to
631       point to an instance of the data type. The data will be subjected to
632       the encoding rules, and the result will be placed in the buffer held
633       by the &odr; stream.
634      </para>
635
636      <para>
637       The other ASN.1 primitives have similar functions that operate in
638       similar manners:
639      </para>
640     </sect3>
641     <sect3 id="odr.boolean"><title>BOOLEAN</title>
642
643      <synopsis>
644 int odr_bool(ODR o, bool_t **p, int optional, const char *name);
645      </synopsis>
646
647     </sect3>
648     <sect3 id="odr.real"><title>REAL</title>
649
650      <para>
651       Not defined.
652      </para>
653
654     </sect3>
655     <sect3 id="odr.null"><title>NULL</title>
656
657      <synopsis>
658 int odr_null(ODR o, bool_t **p, int optional, const char *name);
659      </synopsis>
660
661      <para>
662       In this case, the value of **p is not important. If <literal>*p</literal>
663       is different from the null pointer, the null value is present, otherwise
664       it's absent.
665      </para>
666
667     </sect3>
668     <sect3 id="odr.octet.string"><title>OCTET STRING</title>
669
670      <synopsis>
671 typedef struct odr_oct
672 {
673     unsigned char *buf;
674     int len;
675     int size;
676 } Odr_oct;
677
678 int odr_octetstring(ODR o, Odr_oct **p, int optional,
679                     const char *name);
680      </synopsis>
681
682      <para>
683       The <literal>buf</literal> field should point to the character array
684       that holds the octetstring. The <literal>len</literal> field holds the
685       actual length, while the <literal>size</literal> field gives the size
686       of the allocated array (not of interest to you, in most cases).
687       The character array need not be null terminated.
688      </para>
689
690      <para>
691       To make things a little easier, an alternative is given for string
692       types that are not expected to contain embedded NULL characters (eg.
693       VisibleString):
694      </para>
695
696      <synopsis>
697       int odr_cstring(ODR o, char **p, int optional, const char *name);
698      </synopsis>
699
700      <para>
701       Which encoded or decodes between OCTETSTRING representations and
702       null-terminates C strings.
703      </para>
704
705      <para>
706       Functions are provided for the derived string types, eg:
707      </para>
708
709      <synopsis>
710 int odr_visiblestring(ODR o, char **p, int optional,
711                       const char *name);
712      </synopsis>
713
714     </sect3>
715     <sect3 id="odr.bit.string"><title>BIT STRING</title>
716
717      <synopsis>
718 int odr_bitstring(ODR o, Odr_bitmask **p, int optional,
719                   const char *name);
720      </synopsis>
721
722      <para>
723       The opaque type <literal>Odr_bitmask</literal> is only suitable for
724       holding relatively brief bit strings, eg. for options fields, etc.
725       The constant <literal>ODR_BITMASK_SIZE</literal> multiplied by 8
726       gives the maximum possible number of bits.
727      </para>
728
729      <para>
730       A set of macros are provided for manipulating the
731       <literal>Odr_bitmask</literal> type:
732      </para>
733
734      <synopsis>
735 void ODR_MASK_ZERO(Odr_bitmask *b);
736
737 void ODR_MASK_SET(Odr_bitmask *b, int bitno);
738
739 void ODR_MASK_CLEAR(Odr_bitmask *b, int bitno);
740
741 int ODR_MASK_GET(Odr_bitmask *b, int bitno);
742      </synopsis>
743
744      <para>
745       The functions are modeled after the manipulation functions that
746       accompany the <literal>fd_set</literal> type used by the
747       <function>select(2)</function> call.
748       <literal>ODR_MASK_ZERO</literal> should always be called first on a
749       new bitmask, to initialize the bits to zero.
750      </para>
751     </sect3>
752
753     <sect3 id="odr.object.identifier"><title>OBJECT IDENTIFIER</title>
754
755      <synopsis>
756 int odr_oid(ODR o, Odr_oid **p, int optional, const char *name);
757      </synopsis>
758
759      <para>
760       The C OID representation is simply an array of integers, terminated by
761       the value -1 (the <literal>Odr_oid</literal> type is synonymous with
762       the <literal>int</literal> type).
763       We suggest that you use the OID database module (see
764       <xref linkend="asn.oid"/>) to handle object identifiers
765       in your application.
766      </para>
767
768     </sect3>
769    </sect2>
770    <sect2 id="odr.tagging.primitive.types"><title>Tagging Primitive Types</title> <!-- tag.prim -->
771
772     <para>
773      The simplest way of tagging a type is to use the
774      <function>odr_implicit_tag()</function> or 
775      <function>odr_explicit_tag()</function> macros:
776     </para>
777
778     <synopsis>
779 int odr_implicit_tag(ODR o, Odr_fun fun, int class, int tag,
780                      int optional, const char *name);
781
782 int odr_explicit_tag(ODR o, Odr_fun fun, int class, int tag,
783                      int optional, const char *name);
784     </synopsis>
785
786     <para>
787      To create a type derived from the integer type by implicit tagging, you
788      might write:
789     </para>
790
791     <screen>
792      MyInt ::= &lsqb;210&rsqb; IMPLICIT INTEGER
793     </screen>
794
795     <para>
796      In the &odr; system, this would be written like:
797     </para>
798
799     <screen>
800 int myInt(ODR o, int **p, int optional, const char *name)
801 {
802     return odr_implicit_tag(o, odr_integer, p,
803                             ODR_CONTEXT, 210, optional, name);
804 }
805     </screen>
806
807     <para>
808      The function <function>myInt()</function> can then be used like any of
809      the primitive functions provided by &odr;. Note that the behavior of
810      <function>odr_explicit_tag()</function>
811      and <function>odr_implicit_tag()</function> macros
812      act exactly the same as the functions they are applied to - they
813      respond to error conditions, etc, in the same manner - they
814      simply have three extra parameters. The class parameter may
815      take one of the values: <literal>ODR_CONTEXT</literal>,
816      <literal>ODR_PRIVATE</literal>, <literal>ODR_UNIVERSAL</literal>, or
817      <literal>/ODR_APPLICATION</literal>.
818     </para>
819
820    </sect2>
821    <sect2 id="odr.constructed.types"><title>Constructed Types</title>
822
823     <para>
824      Constructed types are created by combining primitive types. The
825       &odr; system only implements the SEQUENCE and SEQUENCE OF constructions
826      (although adding the rest of the container types should be simple
827      enough, if the need arises).
828     </para>
829
830     <para>
831      For implementing SEQUENCEs, the functions
832     </para>
833
834     <synopsis>
835 int odr_sequence_begin(ODR o, void *p, int size, const char *name);
836 int odr_sequence_end(ODR o);
837     </synopsis>
838
839     <para>
840      are provided.
841     </para>
842
843     <para>
844      The <function>odr_sequence_begin()</function> function should be
845      called in the beginning of a function that implements a SEQUENCE type.
846      Its parameters are the &odr; stream, a pointer (to a pointer to the type
847      you're implementing), and the <literal>size</literal> of the type
848      (typically a C structure). On encoding, it returns 1 if
849      <literal>* p</literal> is a null pointer. The <literal>size</literal>
850      parameter is ignored. On decoding, it returns 1 if the type is found in
851      the data stream. <literal>size</literal> bytes of memory are allocated,
852      and <literal>*p</literal> is set to point to this space.
853      <function>odr_sequence_end()</function> is called at the end of the
854      complex function. Assume that a type is defined like this:
855     </para>
856
857     <screen>
858 MySequence ::= SEQUENCE {
859      intval INTEGER,
860      boolval BOOLEAN OPTIONAL
861 }
862     </screen>
863
864     <para>
865      The corresponding &odr; encoder/decoder function and the associated data
866      structures could be written like this:
867     </para>
868
869     <screen>
870 typedef struct MySequence
871 {
872     int *intval;
873     bool_t *boolval;
874 } MySequence;
875      
876 int mySequence(ODR o, MySequence **p, int optional, const char *name)
877 {
878     if (odr_sequence_begin(o, p, sizeof(**p), name) == 0)
879         return optional &amp;&amp; odr_ok(o);
880     return
881         odr_integer(o, &amp;(*p)->intval, 0, "intval") &amp;&amp;
882         odr_bool(o, &amp;(*p)->boolval, 1, "boolval") &amp;&amp;
883         odr_sequence_end(o);
884 }
885
886     </screen>
887
888     <para>
889      Note the 1 in the call to <function>odr_bool()</function>, to mark
890      that the sequence member is optional.
891      If either of the member types had been tagged, the macros
892      <function>odr_implicit_tag()</function> or
893      <function>odr_explicit_tag()</function>
894      could have been used.
895      The new function can be used exactly like the standard functions provided
896      with &odr;. It will encode, decode or pretty-print a data value of the
897      <literal>MySequence</literal> type. We like to name types with an
898      initial capital, as done in ASN.1 definitions, and to name the
899      corresponding function with the first character of the name in lower case.
900      You could, of course, name your structures, types, and functions any way
901      you please - as long as you're consistent, and your code is easily readable.
902      <literal>odr_ok</literal> is just that - a predicate that returns the
903      state of the stream. It is used to ensure that the behavior of the new
904      type is compatible with the interface of the primitive types.
905     </para>
906
907    </sect2>
908    <sect2 id="odr.tagging.constructed.types">
909     <title>Tagging Constructed Types</title>
910
911     <note>
912      <para>
913       See <xref linkend="odr.tagging.primitive.types"/> for information on how to tag
914       the primitive types, as well as types that are already defined.
915      </para>
916     </note>
917
918     <sect3 id="odr.implicit.tagging">
919      <title>Implicit Tagging</title>
920
921      <para>
922       Assume the type above had been defined as
923      </para>
924
925      <screen>
926 MySequence ::= &lsqb;10&rsqb; IMPLICIT SEQUENCE {
927       intval INTEGER,
928       boolval BOOLEAN OPTIONAL
929 }
930      </screen>
931
932      <para>
933       You would implement this in &odr; by calling the function
934      </para>
935
936      <synopsis>
937 int odr_implicit_settag(ODR o, int class, int tag);
938      </synopsis>
939
940      <para>
941       which overrides the tag of the type immediately following it. The
942       macro <function>odr_implicit_tag()</function> works by calling
943       <function>odr_implicit_settag()</function> immediately
944       before calling the function pointer argument.
945       Your type function could look like this:
946      </para>
947
948      <screen>
949 int mySequence(ODR o, MySequence **p, int optional, const char *name)
950 {
951     if (odr_implicit_settag(o, ODR_CONTEXT, 10) == 0 ||
952         odr_sequence_begin(o, p, sizeof(**p), name) == 0)
953         return optional &amp;&amp; odr_ok(o);
954     return
955         odr_integer(o, &amp;(*p)->intval, 0, "intval") &amp;&amp;
956         odr_bool(o, &amp;(*p)->boolval, 1, "boolval") &amp;&amp;
957         odr_sequence_end(o);
958 }
959      </screen>
960
961      <para>
962       The definition of the structure <literal>MySequence</literal> would be
963       the same.
964      </para>
965     </sect3>
966
967     <sect3 id="odr.explicit.tagging"><title>Explicit Tagging</title>
968
969      <para>
970       Explicit tagging of constructed types is a little more complicated,
971       since you are in effect adding a level of construction to the data.
972      </para>
973
974      <para>
975       Assume the definition:
976      </para>
977
978      <screen>
979 MySequence ::= &lsqb;10&rsqb; IMPLICIT SEQUENCE {
980    intval INTEGER,
981    boolval BOOLEAN OPTIONAL
982 }
983      </screen>
984
985      <para>
986       Since the new type has an extra level of construction, two new functions
987       are needed to encapsulate the base type:
988      </para>
989
990      <synopsis>
991 int odr_constructed_begin(ODR o, void *p, int class, int tag,
992                           const char *name);
993
994 int odr_constructed_end(ODR o);
995      </synopsis>
996
997      <para>
998       Assume that the IMPLICIT in the type definition above were replaced
999       with EXPLICIT (or that the IMPLICIT keyword were simply deleted, which
1000       would be equivalent). The structure definition would look the same,
1001       but the function would look like this:
1002      </para>
1003
1004      <screen>
1005 int mySequence(ODR o, MySequence **p, int optional, const char *name)
1006 {
1007     if (odr_constructed_begin(o, p, ODR_CONTEXT, 10, name) == 0)
1008         return optional &amp;&amp; odr_ok(o);
1009     if (o->direction == ODR_DECODE)
1010         *p = odr_malloc(o, sizeof(**p));
1011     if (odr_sequence_begin(o, p, sizeof(**p), 0) == 0)
1012     {
1013         *p = 0; /* this is almost certainly a protocol error */
1014         return 0;
1015     }
1016     return
1017         odr_integer(o, &amp;(*p)->intval, 0, "intval") &amp;&amp;
1018         odr_bool(o, &amp;(*p)->boolval, 1, "boolval") &amp;&amp;
1019         odr_sequence_end(o) &amp;&amp;
1020         odr_constructed_end(o);
1021 }
1022      </screen>
1023
1024      <para>
1025       Notice that the interface here gets kind of nasty. The reason is
1026       simple: Explicitly tagged, constructed types are fairly rare in
1027       the protocols that we care about, so the
1028       esthetic annoyance (not to mention the dangers of a cluttered
1029       interface) is less than the time that would be required to develop a
1030       better interface. Nevertheless, it is far from satisfying, and it's a
1031       point that will be worked on in the future. One option for you would
1032       be to simply apply the <function>odr_explicit_tag()</function> macro to
1033       the first function, and not
1034       have to worry about <function>odr_constructed_*</function> yourself.
1035       Incidentally, as you might have guessed, the
1036       <function>odr_sequence_</function> functions are themselves
1037       implemented using the <function>/odr_constructed_</function> functions.
1038      </para>
1039
1040     </sect3>
1041    </sect2>
1042    <sect2 id="odr.sequence.of"><title>SEQUENCE OF</title>
1043
1044     <para>
1045      To handle sequences (arrays) of a specific type, the function
1046     </para>
1047
1048     <synopsis>
1049 int odr_sequence_of(ODR o, int (*fun)(ODR o, void *p, int optional),
1050                     void *p, int *num, const char *name);
1051     </synopsis>
1052
1053     <para>
1054      The <literal>fun</literal> parameter is a pointer to the decoder/encoder
1055      function of the type. <literal>p</literal> is a pointer to an array of
1056      pointers to your type. <literal>num</literal> is the number of elements
1057      in the array.
1058     </para>
1059
1060     <para>
1061      Assume a type
1062     </para>
1063
1064     <screen>
1065 MyArray ::= SEQUENCE OF INTEGER
1066     </screen>
1067
1068     <para>
1069      The C representation might be
1070     </para>
1071
1072     <screen>
1073 typedef struct MyArray
1074 {
1075     int num_elements;
1076     int **elements;
1077 } MyArray;
1078     </screen>
1079
1080     <para>
1081      And the function might look like
1082     </para>
1083
1084     <screen>
1085 int myArray(ODR o, MyArray **p, int optional, const char *name)
1086 {
1087     if (o->direction == ODR_DECODE)
1088         *p = odr_malloc(o, sizeof(**p));
1089     if (odr_sequence_of(o, odr_integer, &amp;(*p)->elements,
1090         &amp;(*p)->num_elements, name))
1091         return 1;
1092     *p = 0;
1093         return optional &amp;&amp; odr_ok(o);
1094 }
1095     </screen>
1096
1097    </sect2>
1098    <sect2 id="odr.choice.types"><title>CHOICE Types</title>
1099
1100     <para>
1101      The choice type is used fairly often in some ASN.1 definitions, so
1102      some work has gone into streamlining its interface.
1103     </para>
1104
1105     <para>
1106      CHOICE types are handled by the function:
1107     </para>
1108
1109     <synopsis>
1110 int odr_choice(ODR o, Odr_arm arm&lsqb;&rsqb;, void *p, void *whichp,
1111                const char *name);
1112     </synopsis>
1113
1114     <para>
1115      The <literal>arm</literal> array is used to describe each of the possible
1116      types that the CHOICE type may assume. Internally in your application,
1117      the CHOICE type is represented as a discriminated union. That is, a
1118      C union accompanied by an integer (or enum) identifying the active
1119      'arm' of the union.
1120      <literal>whichp</literal> is a pointer to the union discriminator.
1121      When encoding, it is examined to determine the current type.
1122      When decoding, it is set to reference the type that was found in
1123      the input stream.
1124     </para>
1125
1126     <para>
1127      The Odr_arm type is defined thus:
1128     </para>
1129
1130     <screen>
1131 typedef struct odr_arm
1132 {
1133     int tagmode;
1134     int class;
1135     int tag;
1136     int which;
1137     Odr_fun fun;
1138     char *name;
1139 } Odr_arm;
1140     </screen>
1141
1142     <para>
1143      The interpretation of the fields are:
1144     </para>
1145
1146     <variablelist>
1147      <varlistentry><term>tagmode</term>
1148       <listitem><para>Either <literal>ODR_IMPLICIT</literal>,
1149         <literal>ODR_EXPLICIT</literal>, or <literal>ODR_NONE</literal> (-1)
1150         to mark no tagging.</para></listitem>
1151      </varlistentry>
1152
1153      <varlistentry><term>which</term>
1154       <listitem><para>The value of the discriminator that corresponds to
1155         this CHOICE element. Typically, it will be a &num;defined constant, or
1156         an enum member.</para></listitem>
1157      </varlistentry>
1158
1159      <varlistentry><term>fun</term>
1160       <listitem><para>A pointer to a function that implements the type of
1161         the CHOICE member. It may be either a standard &odr; type or a type
1162         defined by yourself.</para></listitem>
1163      </varlistentry>
1164
1165      <varlistentry><term>name</term>
1166       <listitem><para>Name of tag.</para></listitem>
1167      </varlistentry>
1168     </variablelist>
1169
1170     <para>
1171      A handy way to prepare the array for use by the
1172      <function>odr_choice()</function> function is to
1173      define it as a static, initialized array in the beginning of your
1174      decoding/encoding function. Assume the type definition:
1175     </para>
1176
1177     <screen>
1178 MyChoice ::= CHOICE {
1179     untagged INTEGER,
1180     tagged   &lsqb;99&rsqb; IMPLICIT INTEGER,
1181     other    BOOLEAN
1182 }
1183     </screen>
1184
1185     <para>
1186      Your C type might look like
1187     </para>
1188
1189     <screen>
1190 typedef struct MyChoice
1191 {
1192     enum
1193     {
1194         MyChoice_untagged,
1195         MyChoice_tagged,
1196         MyChoice_other
1197     } which;
1198     union
1199     {
1200         int *untagged;
1201         int *tagged;
1202         bool_t *other;
1203     } u;
1204 };
1205     </screen>
1206
1207     <para>
1208      And your function could look like this:
1209     </para>
1210
1211     <screen>
1212 int myChoice(ODR o, MyChoice **p, int optional, const char *name)
1213 {
1214     static Odr_arm arm&lsqb;&rsqb; =
1215     {
1216       {-1, -1, -1, MyChoice_untagged, odr_integer, "untagged"},
1217       {ODR_IMPLICIT, ODR_CONTEXT, 99, MyChoice_tagged, odr_integer,
1218       "tagged"},
1219       {-1, -1, -1, MyChoice_other, odr_boolean, "other"},
1220       {-1, -1, -1, -1, 0}
1221     };
1222
1223     if (o->direction == ODR_DECODE)
1224         *p = odr_malloc(o, sizeof(**p);
1225     else if (!*p)
1226         return optional &amp;&amp; odr_ok(o);
1227
1228     if (odr_choice(o, arm, &amp;(*p)->u, &amp;(*p)->which), name)
1229         return 1;
1230     *p = 0;
1231         return optional &amp;&amp; odr_ok(o);
1232 }
1233     </screen>
1234
1235     <para>
1236      In some cases (say, a non-optional choice which is a member of a
1237      sequence), you can "embed" the union and its discriminator in the
1238      structure belonging to the enclosing type, and you won't need to
1239      fiddle with memory allocation to create a separate structure to
1240      wrap the discriminator and union.
1241     </para>
1242
1243     <para>
1244      The corresponding function is somewhat nicer in the Sun XDR interface.
1245      Most of the complexity of this interface comes from the possibility of
1246      declaring sequence elements (including CHOICEs) optional.
1247     </para>
1248
1249     <para>
1250      The ASN.1 specifications naturally requires that each member of a
1251      CHOICE have a distinct tag, so they can be told apart on decoding.
1252      Sometimes it can be useful to define a CHOICE that has multiple types
1253      that share the same tag. You'll need some other mechanism, perhaps
1254      keyed to the context of the CHOICE type. In effect, we would like to
1255      introduce a level of context-sensitiveness to our ASN.1 specification.
1256      When encoding an internal representation, we have no problem, as long
1257      as each CHOICE member has a distinct discriminator value. For
1258      decoding, we need a way to tell the choice function to look for a
1259      specific arm of the table. The function
1260     </para>
1261
1262     <synopsis>
1263 void odr_choice_bias(ODR o, int what);
1264     </synopsis>
1265
1266     <para>
1267      provides this functionality. When called, it leaves a notice for the next
1268      call to <function>odr_choice()</function> to be called on the decoding
1269      stream <literal>o</literal> that only the <literal>arm</literal> entry with
1270      a <literal>which</literal> field equal to <literal>what</literal>
1271      should be tried.
1272     </para>
1273
1274     <para>
1275      The most important application (perhaps the only one, really) is in
1276      the definition of application-specific EXTERNAL encoders/decoders
1277      which will automatically decode an ANY member given the direct or
1278      indirect reference.
1279     </para>
1280
1281    </sect2>
1282   </sect1>
1283
1284   <sect1 id="odr.debugging"><title>Debugging</title>
1285
1286    <para>
1287     The protocol modules are suffering somewhat from a lack of diagnostic
1288     tools at the moment. Specifically ways to pretty-print PDUs that
1289     aren't recognized by the system. We'll include something to this end
1290     in a not-too-distant release. In the meantime, what we do when we get
1291     packages we don't understand is to compile the ODR module with
1292     <literal>ODR_DEBUG</literal> defined. This causes the module to dump tracing
1293     information as it processes data units. With this output and the
1294     protocol specification (Z39.50), it is generally fairly easy to see
1295     what goes wrong.
1296    </para>
1297   </sect1>
1298  </chapter>
1299  <!-- Keep this comment at the end of the file
1300  Local variables:
1301  mode: sgml
1302  sgml-omittag:t
1303  sgml-shorttag:t
1304  sgml-minimize-attributes:nil
1305  sgml-always-quote-attributes:t
1306  sgml-indent-step:1
1307  sgml-indent-data:t
1308  sgml-parent-document: "yaz.xml"
1309  sgml-local-catalogs: nil
1310  sgml-namecase-general:t
1311  End:
1312  -->