xref: /freebsd/contrib/libxo/doc/api.rst (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1.. index:: API
2
3The libxo API
4=============
5
6This section gives details about the functions in libxo, how to call
7them, and the actions they perform.
8
9.. index:: Handles
10.. _handles:
11
12Handles
13-------
14
15libxo uses "handles" to control its rendering functionality.  The
16handle contains state and buffered data, as well as callback functions
17to process data.
18
19Handles give an abstraction for libxo that encapsulates the state of a
20stream of output.  Handles have the data type "`xo_handle_t`" and are
21opaque to the caller.
22
23The library has a default handle that is automatically initialized.
24By default, this handle will send text style output (`XO_STYLE_TEXT`) to
25standard output.  The xo_set_style and xo_set_flags functions can be
26used to change this behavior.
27
28For the typical command that is generating output on standard output,
29there is no need to create an explicit handle, but they are available
30when needed, e.g., for daemons that generate multiple streams of
31output.
32
33Many libxo functions take a handle as their first parameter; most that
34do not use the default handle.  Any function taking a handle can be
35passed NULL to access the default handle.  For the convenience of
36callers, the libxo library includes handle-less functions that
37implicitly use the default handle.
38
39For example, the following are equivalent::
40
41    xo_emit("test");
42    xo_emit_h(NULL, "test");
43
44Handles are created using `xo_create` and destroy using
45`xo_destroy`.
46
47.. index:: xo_create
48
49xo_create
50~~~~~~~~~
51
52.. c:function:: xo_handle_t *xo_create (xo_style_t style, xo_xof_flags_t flags)
53
54  The `xo_create` function allocates a new handle which can be passed
55  to further libxo function calls.  The `xo_handle_t` structure is
56  opaque.
57
58  :param xo_style_t style: Output style (XO_STYLE\_*)
59  :param xo_xof_flags_t flags: Flags for this handle (XOF\_*)
60  :return: New libxo handle
61  :rtype: xo_handle_t \*
62
63  ::
64
65    EXAMPLE:
66        xo_handle_t *xop = xo_create(XO_STYLE_JSON, XOF_WARN | XOF_PRETTY);
67        ....
68        xo_emit_h(xop, "testing\n");
69
70  See also :ref:`output-styles` and :ref:`flags`.
71
72.. index:: xo_create_to_file
73.. index:: XOF_CLOSE_FP
74
75xo_create_to_file
76~~~~~~~~~~~~~~~~~
77
78.. c:function::
79  xo_handle_t *xo_create_to_file (FILE *fp, unsigned style, unsigned flags)
80
81  The `xo_create_to_file` function is aconvenience function is
82  provided for situations when output should be written to a different
83  file, rather than the default of standard output.
84
85  The `XOF_CLOSE_FP` flag can be set on the returned handle to trigger a
86  call to fclose() for the FILE pointer when the handle is destroyed,
87  avoiding the need for the caller to perform this task.
88
89  :param fp: FILE to use as base for this handle
90  :type fp: FILE *
91  :param xo_style_t style: Output style (XO_STYLE\_*)
92  :param xo_xof_flags_t flags: Flags for this handle (XOF\_*)
93  :return: New libxo handle
94  :rtype: xo_handle_t \*
95
96.. index:: xo_set_writer
97.. index:: xo_write_func_t
98.. index:: xo_close_func_t
99.. index:: xo_flush_func_t
100
101xo_set_writer
102~~~~~~~~~~~~~
103
104.. c:function::
105  void xo_set_writer (xo_handle_t *xop, void *opaque, \
106  xo_write_func_t write_func, xo_close_func_t close_func, \
107  xo_flush_func_t flush_func)
108
109  The `xo_set_writer` function allows custom functions which can
110  tailor how libxo writes data.  The `opaque` argument is recorded and
111  passed back to the functions, allowing the function to acquire
112  context information. The *write_func* function writes data to the
113  output stream.  The *close_func* function can release this opaque
114  data and any other resources as needed.  The *flush_func* function
115  is called to flush buffered data associated with the opaque object.
116
117  :param xop: Handle to modify (or NULL for default handle)
118  :type xop: xo_handle_t *
119  :param opaque: Pointer to opaque data passed to the given functions
120  :type opaque: void *
121  :param xo_write_func_t write_func: New write function
122  :param xo_close_func_t close_func: New close function
123  :param xo_flush_func_t flush_func: New flush function
124  :returns: void
125
126.. index:: xo_get_style
127
128xo_get_style
129~~~~~~~~~~~~
130
131.. c:function:: xo_style_t xo_get_style(xo_handle_t *xop)
132
133  Use the `xo_get_style` function to find the current output style for
134  a given handle.  To use the default handle, pass a `NULL` handle.
135
136  :param xop: Handle to interrogate (or NULL for default handle)
137  :type xop: xo_handle_t *
138  :returns: Output style (XO_STYLE\_*)
139  :rtype: xo_style_t
140
141  ::
142
143    EXAMPLE::
144        style = xo_get_style(NULL);
145
146.. index::  XO_STYLE_TEXT
147.. index::  XO_STYLE_XML
148.. index::  XO_STYLE_JSON
149.. index::  XO_STYLE_HTML
150
151.. _output-styles:
152
153Output Styles (XO_STYLE\_\*)
154++++++++++++++++++++++++++++
155
156The libxo functions accept a set of output styles:
157
158  =============== =========================
159   Flag            Description
160  =============== =========================
161   XO_STYLE_TEXT   Traditional text output
162   XO_STYLE_XML    XML encoded data
163   XO_STYLE_JSON   JSON encoded data
164   XO_STYLE_HTML   HTML encoded data
165  =============== =========================
166
167The "XML", "JSON", and "HTML" output styles all use the UTF-8
168character encoding.  "TEXT" using locale-based encoding.
169
170.. index:: xo_set_style
171
172xo_set_style
173~~~~~~~~~~~~
174
175.. c:function:: void xo_set_style(xo_handle_t *xop, xo_style_t style)
176
177  The `xo_set_style` function is used to change the output style
178  setting for a handle.  To use the default handle, pass a `NULL`
179  handle.
180
181  :param xop: Handle to modify
182  :type xop: xo_handle_t *
183  :param xo_style_t style: Output style (XO_STYLE\_*)
184  :returns: void
185
186  ::
187
188    EXAMPLE:
189        xo_set_style(NULL, XO_STYLE_XML);
190
191.. index:: xo_set_style_name
192
193xo_set_style_name
194~~~~~~~~~~~~~~~~~
195
196.. c:function:: int xo_set_style_name (xo_handle_t *xop, const char *style)
197
198  The `xo_set_style_name` function can be used to set the style based
199  on a name encoded as a string: The name can be any of the supported
200  styles: "text", "xml", "json", or "html".
201
202  :param xop: Handle for modify (or NULL for default handle)
203  :type xop: xo_handle_t \*
204  :param style: Text name of the style
205  :type style: const char \*
206  :returns: zero for success, non-zero for error
207  :rtype: int
208
209  ::
210
211    EXAMPLE:
212        xo_set_style_name(NULL, "html");
213
214.. index:: xo_set_flags
215
216xo_set_flags
217~~~~~~~~~~~~
218
219.. c:function:: void xo_set_flags(xo_handle_t *xop, xo_xof_flags_t flags)
220
221  :param xop: Handle for modify (or NULL for default handle)
222  :type xop: xo_handle_t \*
223  :param xo_xof_flags_t flags: Flags to add for the handle
224  :returns: void
225
226  Use the `xo_set_flags` function to turn on flags for a given libxo
227  handle.  To use the default handle, pass a `NULL` handle.
228
229  ::
230
231    EXAMPLE:
232        xo_set_flags(NULL, XOF_PRETTY | XOF_WARN);
233
234.. index:: Flags; XOF_*
235.. index:: XOF_CLOSE_FP
236.. index:: XOF_COLOR
237.. index:: XOF_COLOR_ALLOWED
238.. index:: XOF_DTRT
239.. index:: XOF_INFO
240.. index:: XOF_KEYS
241.. index:: XOF_NO_ENV
242.. index:: XOF_NO_HUMANIZE
243.. index:: XOF_PRETTY
244.. index:: XOF_UNDERSCORES
245.. index:: XOF_UNITS
246.. index:: XOF_WARN
247.. index:: XOF_WARN_XML
248.. index:: XOF_XPATH
249.. index:: XOF_COLUMNS
250.. index:: XOF_FLUSH
251
252.. _flags:
253
254Flags (XOF\_\*)
255+++++++++++++++
256
257The set of valid flags include:
258
259  =================== =========================================
260   Flag                Description
261  =================== =========================================
262   XOF_CLOSE_FP        Close file pointer on `xo_destroy`
263   XOF_COLOR           Enable color and effects in output
264   XOF_COLOR_ALLOWED   Allow color/effect for terminal output
265   XOF_DTRT            Enable "do the right thing" mode
266   XOF_INFO            Display info data attributes (HTML)
267   XOF_KEYS            Emit the key attribute (XML)
268   XOF_NO_ENV          Do not use the :ref:`libxo-options` env var
269   XOF_NO_HUMANIZE     Display humanization (TEXT, HTML)
270   XOF_PRETTY          Make "pretty printed" output
271   XOF_UNDERSCORES     Replaces hyphens with underscores
272   XOF_UNITS           Display units (XML, HMTL)
273   XOF_WARN            Generate warnings for broken calls
274   XOF_WARN_XML        Generate warnings in XML on stdout
275   XOF_XPATH           Emit XPath expressions (HTML)
276   XOF_COLUMNS         Force xo_emit to return columns used
277   XOF_FLUSH           Flush output after each `xo_emit` call
278  =================== =========================================
279
280The `XOF_CLOSE_FP` flag will trigger the call of the *close_func*
281(provided via `xo_set_writer`) when the handle is destroyed.
282
283The `XOF_COLOR` flag enables color and effects in output regardless
284of output device, while the `XOF_COLOR_ALLOWED` flag allows color
285and effects only if the output device is a terminal.
286
287The `XOF_PRETTY` flag requests "pretty printing", which will trigger
288the addition of indentation and newlines to enhance the readability of
289XML, JSON, and HTML output.  Text output is not affected.
290
291The `XOF_WARN` flag requests that warnings will trigger diagnostic
292output (on standard error) when the library notices errors during
293operations, or with arguments to functions.  Without warnings enabled,
294such conditions are ignored.
295
296Warnings allow developers to debug their interaction with libxo.
297The function `xo_failure` can used as a breakpoint for a debugger,
298regardless of whether warnings are enabled.
299
300If the style is `XO_STYLE_HTML`, the following additional flags can be
301used:
302
303  =============== =========================================
304   Flag            Description
305  =============== =========================================
306   XOF_XPATH       Emit "data-xpath" attributes
307   XOF_INFO        Emit additional info fields
308  =============== =========================================
309
310The `XOF_XPATH` flag enables the emission of XPath expressions detailing
311the hierarchy of XML elements used to encode the data field, if the
312XPATH style of output were requested.
313
314The `XOF_INFO` flag encodes additional informational fields for HTML
315output.  See :ref:`field-information` for details.
316
317If the style is `XO_STYLE_XML`, the following additional flags can be
318used:
319
320  =============== =========================================
321   Flag            Description
322  =============== =========================================
323   XOF_KEYS        Flag "key" fields for XML
324  =============== =========================================
325
326The `XOF_KEYS` flag adds "key" attribute to the XML encoding for
327field definitions that use the "k" modifier.  The key attribute has
328the value "key"::
329
330    xo_emit("{k:name}", item);
331
332  XML:
333      <name key="key">truck</name>
334
335.. index:: xo_clear_flags
336
337xo_clear_flags
338++++++++++++++
339
340.. c:function:: void xo_clear_flags (xo_handle_t *xop, xo_xof_flags_t flags)
341
342  :param xop: Handle for modify (or NULL for default handle)
343  :type xop: xo_handle_t \*
344  :param xo_xof_flags_t flags: Flags to clear for the handle
345  :returns: void
346
347  Use the `xo_clear_flags` function to turn off the given flags in a
348  specific handle.  To use the default handle, pass a `NULL` handle.
349
350.. index:: xo_set_options
351
352xo_set_options
353++++++++++++++
354
355.. c:function:: int xo_set_options (xo_handle_t *xop, const char *input)
356
357  :param xop: Handle for modify (or NULL for default handle)
358  :type xop: xo_handle_t \*
359  :param input: string containing options to set
360  :type input: const char *
361  :returns: zero for success, non-zero for error
362  :rtype: int
363
364  The `xo_set_options` function accepts a comma-separated list of
365  output styles and modifier flags and enables them for a specific
366  handle.  The options are identical to those listed in
367  :ref:`options`.  To use the default handle, pass a `NULL` handle.
368
369.. index:: xo_destroy
370
371xo_destroy
372++++++++++
373
374.. c:function:: void xo_destroy(xo_handle_t *xop)
375
376  :param xop: Handle for modify (or NULL for default handle)
377  :type xop: xo_handle_t \*
378  :returns: void
379
380  The `xo_destroy` function releases a handle and any resources it is
381  using.  Calling `xo_destroy` with a `NULL` handle will release any
382  resources associated with the default handle.
383
384.. index:: xo_emit
385
386Emitting Content (xo_emit)
387--------------------------
388
389The functions in this section are used to emit output.  They use a
390`format` string containing field descriptors as specified in
391:ref:`format-strings`.  The use of a handle is optional and `NULL` can
392be passed to access the internal "default" handle.  See
393:ref:`handles`.
394
395The remaining arguments to `xo_emit` and `xo_emit_h` are a set of
396arguments corresponding to the fields in the format string.  Care must
397be taken to ensure the argument types match the fields in the format
398string, since an inappropriate or missing argument can ruin your day.
399The `vap` argument to `xo_emit_hv` points to a variable argument list
400that can be used to retrieve arguments via `va_arg`.
401
402.. c:function:: xo_ssize_t xo_emit (const char *fmt, ...)
403
404  :param fmt: The format string, followed by zero or more arguments
405  :returns: If XOF_COLUMNS is set, the number of columns used; otherwise the number of bytes emitted
406  :rtype: xo_ssize_t
407
408.. c:function:: xo_ssize_t xo_emit_h (xo_handle_t *xop, const char *fmt, ...)
409
410  :param xop: Handle for modify (or NULL for default handle)
411  :type xop: xo_handle_t \*
412  :param fmt: The format string, followed by zero or more arguments
413  :returns: If XOF_COLUMNS is set, the number of columns used; otherwise the number of bytes emitted
414  :rtype: xo_ssize_t
415
416.. c:function:: xo_ssize_t xo_emit_hv (xo_handle_t *xop, const char *fmt, va_list vap)
417
418  :param xop: Handle for modify (or NULL for default handle)
419  :type xop: xo_handle_t \*
420  :param fmt: The format string
421  :param va_list vap: A set of variadic arguments
422  :returns: If XOF_COLUMNS is set, the number of columns used; otherwise the number of bytes emitted
423  :rtype: xo_ssize_t
424
425.. index:: xo_emit_field
426
427Single Field Emitting Functions (xo_emit_field)
428~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
429
430The functions in this section emit formatted output similar to
431`xo_emit` but where `xo_emit` uses a single string argument containing
432the description for multiple fields, `xo_emit_field` emits a single
433field using multiple ar- guments to contain the field description.
434`xo_emit_field_h` adds an ex- plicit handle to use instead of the
435default handle, while `xo_emit_field_hv` accepts a va_list for
436additional flexibility.
437
438The arguments `rolmod`, `content`, `fmt`, and `efmt` are detailed in
439:ref:`field-formatting`.  Using distinct arguments allows callers to
440pass the field description in pieces, rather than having to use
441something like `snprintf` to build the format string required by
442`xo_emit`.  The arguments are each NUL-terminated strings. The `rolmod`
443argument contains the `role` and `modifier` portions of the field
444description, the `content` argument contains the `content` portion, and
445the `fmt` and `efmt` contain the `field-format` and `encoding-format` por-
446tions, respectively.
447
448As with `xo_emit`, the `fmt` and `efmt` values are both optional,
449since the `field-format` string defaults to "%s", and the
450`encoding-format`'s default value is derived from the `field-format`
451per :ref:`field-formatting`.  However, care must be taken to avoid
452using a value directly as the format, since characters like '{', '%',
453and '}' will be interpreted as formatting directives, and may cause
454xo_emit_field to dereference arbitrary values off the stack, leading
455to bugs, core files, and gnashing of teeth.
456
457.. c:function:: xo_ssize_t xo_emit_field (const char *rolmod, const char *content, const char *fmt, const char *efmt, ...)
458
459  :param rolmod: A comma-separated list of field roles and field modifiers
460  :type rolmod: const char *
461  :param content: The "content" portion of the field description string
462  :type content: const char *
463  :param fmt: Contents format string
464  :type fmt: const char *
465  :param efmt: Encoding format string, followed by additional arguments
466  :type efmt: const char *
467  :returns: If XOF_COLUMNS is set, the number of columns used; otherwise the number of bytes emitted
468  :rtype: xo_ssize_t
469
470  ::
471
472    EXAMPLE::
473        xo_emit_field("T", title, NULL, NULL, NULL);
474        xo_emit_field("T", "Host name is ", NULL, NULL);
475        xo_emit_field("V", "host-name", NULL, NULL, host-name);
476        xo_emit_field(",leaf-list,quotes", "sku", "%s-%u", "%s-000-%u",
477                        "gum", 1412);
478
479.. c:function:: xo_ssize_t xo_emit_field_h (xo_handle_t *xop, const char *rolmod, const char *contents, const char *fmt, const char *efmt, ...)
480
481  :param xop: Handle for modify (or NULL for default handle)
482  :type xop: xo_handle_t \*
483  :param rolmod: A comma-separated list of field roles and field modifiers
484  :type rolmod: const char *
485  :param contents: The "contents" portion of the field description string
486  :type contents: const char *
487  :param fmt: Content format string
488  :type fmt: const char *
489  :param efmt: Encoding format string, followed by additional arguments
490  :type efmt: const char *
491  :returns: If XOF_COLUMNS is set, the number of columns used; otherwise the number of bytes emitted
492  :rtype: xo_ssize_t
493
494.. c:function:: xo_ssize_t xo_emit_field_hv (xo_handle_t *xop, const char *rolmod, const char *contents, const char *fmt, const char *efmt, va_list vap)
495
496  :param xop: Handle for modify (or NULL for default handle)
497  :type xop: xo_handle_t \*
498  :param rolmod: A comma-separated list of field roles and field modifiers
499  :type rolmod: const char *
500  :param contents: The "contents" portion of the field description string
501  :type contents: const char *
502  :param fmt: Content format string
503  :type fmt: const char *
504  :param efmt: Encoding format string
505  :type efmt: const char *
506  :param va_list vap: A set of variadic arguments
507  :returns: If XOF_COLUMNS is set, the number of columns used; otherwise the number of bytes emitted
508  :rtype: xo_ssize_t
509
510.. index:: xo_attr
511.. _xo_attr:
512
513Attributes (xo_attr)
514~~~~~~~~~~~~~~~~~~~~
515
516The functions in this section emit an XML attribute with the given name
517and value.  This only affects the XML output style.
518
519The `name` parameter give the name of the attribute to be encoded.  The
520`fmt` parameter gives a printf-style format string used to format the
521value of the attribute using any remaining arguments, or the vap
522parameter passed to `xo_attr_hv`.
523
524All attributes recorded via `xo_attr` are placed on the next
525container, instance, leaf, or leaf list that is emitted.
526
527Since attributes are only emitted in XML, their use should be limited
528to meta-data and additional or redundant representations of data
529already emitted in other form.
530
531.. c:function:: xo_ssize_t xo_attr (const char *name, const char *fmt, ...)
532
533  :param name: Attribute name
534  :type name: const char *
535  :param fmt: Attribute value, as variadic arguments
536  :type fmt: const char *
537  :returns: -1 for error, or the number of bytes in the formatted attribute value
538  :rtype: xo_ssize_t
539
540  ::
541
542    EXAMPLE:
543        xo_attr("seconds", "%ld", (unsigned long) login_time);
544        struct tm *tmp = localtime(login_time);
545        strftime(buf, sizeof(buf), "%R", tmp);
546        xo_emit("Logged in at {:login-time}\n", buf);
547    XML:
548        <login-time seconds="1408336270">00:14</login-time>
549
550
551.. c:function:: xo_ssize_t xo_attr_h (xo_handle_t *xop, const char *name, const char *fmt, ...)
552
553  :param xop: Handle for modify (or NULL for default handle)
554  :type xop: xo_handle_t \*
555
556  The `xo_attr_h` function follows the conventions of `xo_attr` but
557  adds an explicit libxo handle.
558
559.. c:function:: xo_ssize_t xo_attr_hv (xo_handle_t *xop, const char *name, const char *fmt, va_list vap)
560
561  The `xo_attr_h` function follows the conventions of `xo_attr_h`
562  but replaced the variadic list with a variadic pointer.
563
564.. index:: xo_flush
565
566Flushing Output (xo_flush)
567~~~~~~~~~~~~~~~~~~~~~~~~~~
568
569.. c:function:: xo_ssize_t xo_flush (void)
570
571  :returns: -1 for error, or the number of bytes generated
572  :rtype: xo_ssize_t
573
574  libxo buffers data, both for performance and consistency, but also
575  to allow for the proper function of various advanced features.  At
576  various times, the caller may wish to flush any data buffered within
577  the library.  The `xo_flush` call is used for this.
578
579  Calling `xo_flush` also triggers the flush function associated with
580  the handle.  For the default handle, this is equivalent to
581  "fflush(stdio);".
582
583.. c:function:: xo_ssize_t xo_flush_h (xo_handle_t *xop)
584
585  :param xop: Handle for flush (or NULL for default handle)
586  :type xop: xo_handle_t \*
587  :returns: -1 for error, or the number of bytes generated
588  :rtype: xo_ssize_t
589
590  The `xo_flush_h` function follows the conventions of `xo_flush`,
591  but adds an explicit libxo handle.
592
593.. index:: xo_finish
594.. index:: xo_finish_atexit
595.. index:: atexit
596
597Finishing Output (xo_finish)
598~~~~~~~~~~~~~~~~~~~~~~~~~~~~
599
600When the program is ready to exit or close a handle, a call to
601`xo_finish` or `xo_finish_h` is required.  This flushes any buffered
602data, closes open libxo constructs, and completes any pending
603operations.
604
605Calling this function is vital to the proper operation of libxo,
606especially for the non-TEXT output styles.
607
608.. c:function:: xo_ssize_t xo_finish (void)
609
610  :returns: -1 on error, or the number of bytes flushed
611  :rtype: xo_ssize_t
612
613.. c:function:: xo_ssize_t xo_finish_h (xo_handle_t *xop)
614
615  :param xop: Handle for finish (or NULL for default handle)
616  :type xop: xo_handle_t \*
617  :returns: -1 on error, or the number of bytes flushed
618  :rtype: xo_ssize_t
619
620.. c:function:: void xo_finish_atexit (void)
621
622  The `xo_finish_atexit` function is suitable for use with
623  :manpage:`atexit(3)` to ensure that `xo_finish` is called
624  on the default handle when the application exits.
625
626.. index:: UTF-8
627.. index:: xo_open_container
628.. index:: xo_close_container
629
630Emitting Hierarchy
631------------------
632
633libxo represents two types of hierarchy: containers and lists.  A
634container appears once under a given parent where a list consists of
635instances that can appear multiple times.  A container is used to hold
636related fields and to give the data organization and scope.
637
638.. index:: YANG
639
640.. admonition:: YANG Terminology
641
642  libxo uses terminology from YANG (:RFC:`7950`), the data modeling
643  language for NETCONF: container, list, leaf, and leaf-list.
644
645For XML and JSON, individual fields appear inside hierarchies which
646provide context and meaning to the fields.  Unfortunately, these
647encoding have a basic disconnect between how lists is similar objects
648are represented.
649
650XML encodes lists as set of sequential elements::
651
652    <user>phil</user>
653    <user>pallavi</user>
654    <user>sjg</user>
655
656JSON encodes lists using a single name and square brackets::
657
658    "user": [ "phil", "pallavi", "sjg" ]
659
660This means libxo needs three distinct indications of hierarchy: one
661for containers of hierarchy appear only once for any specific parent,
662one for lists, and one for each item in a list.
663
664.. index:: Containers
665
666Containers
667~~~~~~~~~~
668
669A "*container*" is an element of a hierarchy that appears only once
670under any specific parent.  The container has no value, but serves to
671contain and organize other nodes.
672
673To open a container, call xo_open_container() or
674xo_open_container_h().  The former uses the default handle and the
675latter accepts a specific handle.  To close a level, use the
676xo_close_container() or xo_close_container_h() functions.
677
678Each open call must have a matching close call.  If the XOF_WARN flag
679is set and the name given does not match the name of the currently open
680container, a warning will be generated.
681
682.. c:function:: xo_ssize_t xo_open_container (const char *name)
683
684  :param name: Name of the container
685  :type name: const char *
686  :returns: -1 on error, or the number of bytes generated
687  :rtype: xo_ssize_t
688
689  The `name` parameter gives the name of the container, encoded in
690  UTF-8.  Since ASCII is a proper subset of UTF-8, traditional C
691  strings can be used directly.
692
693.. c:function:: xo_ssize_t xo_open_container_h (xo_handle_t *xop, const char *name)
694
695  :param xop: Handle to use (or NULL for default handle)
696  :type xop: xo_handle_t *
697
698  The `xo_open_container_h` function adds a `handle` parameter.
699
700.. c:function:: xo_ssize_t xo_close_container (const char *name)
701
702  :param name: Name of the container
703  :type name: const char *
704  :returns: -1 on error, or the number of bytes generated
705  :rtype: xo_ssize_t
706
707.. c:function:: xo_ssize_t xo_close_container_h (xo_handle_t *xop, const char *name)
708
709  :param xop: Handle to use (or NULL for default handle)
710  :type xop: xo_handle_t *
711
712  The `xo_close_container_h` function adds a `handle` parameter.
713
714Use the :index:`XOF_WARN` flag to generate a warning if the name given
715on the close does not match the current open container.
716
717For TEXT and HTML output, containers are not rendered into output
718text, though for HTML they are used to record an XPath value when the
719:index:`XOF_XPATH` flag is set.
720
721::
722
723    EXAMPLE:
724        xo_open_container("top");
725        xo_open_container("system");
726        xo_emit("{:host-name/%s%s%s}", hostname,
727                domainname ? "." : "", domainname ?: "");
728        xo_close_container("system");
729        xo_close_container("top");
730    TEXT:
731        my-host.example.org
732    XML:
733        <top>
734          <system>
735              <host-name>my-host.example.org</host-name>
736          </system>
737        </top>
738    JSON:
739        "top" : {
740          "system" : {
741              "host-name": "my-host.example.org"
742          }
743        }
744    HTML:
745        <div class="data"
746             data-tag="host-name">my-host.example.org</div>
747
748.. index:: xo_open_instance
749.. index:: xo_close_instance
750.. index:: xo_open_list
751.. index:: xo_close_list
752
753Lists and Instances
754~~~~~~~~~~~~~~~~~~~
755
756A "*list*" is set of one or more instances that appear under the same
757parent.  The instances contain details about a specific object.  One
758can think of instances as objects or records.  A call is needed to
759open and close the list, while a distinct call is needed to open and
760close each instance of the list.
761
762The name given to all calls must be identical, and it is strongly
763suggested that the name be singular, not plural, as a matter of
764style and usage expectations::
765
766  EXAMPLE:
767      xo_open_list("item");
768
769      for (ip = list; ip->i_title; ip++) {
770          xo_open_instance("item");
771          xo_emit("{L:Item} '{:name/%s}':\n", ip->i_title);
772          xo_close_instance("item");
773      }
774
775      xo_close_list("item");
776
777Getting the list and instance calls correct is critical to the proper
778generation of XML and JSON data.
779
780Opening Lists
781+++++++++++++
782
783.. c:function:: xo_ssize_t xo_open_list (const char *name)
784
785  :param name: Name of the list
786  :type name: const char *
787  :returns: -1 on error, or the number of bytes generated
788  :rtype: xo_ssize_t
789
790  The `xo_open_list` function open a list of instances.
791
792.. c:function:: xo_ssize_t xo_open_list_h (xo_handle_t *xop, const char *name)
793
794  :param xop: Handle to use (or NULL for default handle)
795  :type xop: xo_handle_t *
796
797Closing Lists
798+++++++++++++
799
800.. c:function:: xo_ssize_t xo_close_list (const char *name)
801
802  :param name: Name of the list
803  :type name: const char *
804  :returns: -1 on error, or the number of bytes generated
805  :rtype: xo_ssize_t
806
807  The `xo_close_list` function closes a list of instances.
808
809.. c:function:: xo_ssize_t xo_close_list_h (xo_handle_t *xop, const char *name)
810
811  :param xop: Handle to use (or NULL for default handle)
812  :type xop: xo_handle_t *
813
814   The `xo_close_container_h` function adds a `handle` parameter.
815
816Opening Instances
817+++++++++++++++++
818
819.. c:function:: xo_ssize_t xo_open_instance (const char *name)
820
821  :param name: Name of the instance (same as the list name)
822  :type name: const char *
823  :returns: -1 on error, or the number of bytes generated
824  :rtype: xo_ssize_t
825
826  The `xo_open_instance` function open a single instance.
827
828.. c:function:: xo_ssize_t xo_open_instance_h (xo_handle_t *xop, const char *name)
829
830  :param xop: Handle to use (or NULL for default handle)
831  :type xop: xo_handle_t *
832
833   The `xo_open_instance_h` function adds a `handle` parameter.
834
835Closing Instances
836+++++++++++++++++
837
838.. c:function:: xo_ssize_t xo_close_instance (const char *name)
839
840  :param name: Name of the instance
841  :type name: const char *
842  :returns: -1 on error, or the number of bytes generated
843  :rtype: xo_ssize_t
844
845  The `xo_close_instance` function closes an open instance.
846
847.. c:function:: xo_ssize_t xo_close_instance_h (xo_handle_t *xop, const char *name)
848
849  :param xop: Handle to use (or NULL for default handle)
850  :type xop: xo_handle_t *
851
852  The `xo_close_instance_h` function adds a `handle` parameter.
853
854  ::
855
856    EXAMPLE:
857        xo_open_list("user");
858        for (i = 0; i < num_users; i++) {
859            xo_open_instance("user");
860            xo_emit("{k:name}:{:uid/%u}:{:gid/%u}:{:home}\n",
861                    pw[i].pw_name, pw[i].pw_uid,
862                    pw[i].pw_gid, pw[i].pw_dir);
863            xo_close_instance("user");
864        }
865        xo_close_list("user");
866    TEXT:
867        phil:1001:1001:/home/phil
868        pallavi:1002:1002:/home/pallavi
869    XML:
870        <user>
871            <name>phil</name>
872            <uid>1001</uid>
873            <gid>1001</gid>
874            <home>/home/phil</home>
875        </user>
876        <user>
877            <name>pallavi</name>
878            <uid>1002</uid>
879            <gid>1002</gid>
880            <home>/home/pallavi</home>
881        </user>
882    JSON:
883        user: [
884            {
885                "name": "phil",
886                "uid": 1001,
887                "gid": 1001,
888                "home": "/home/phil",
889            },
890            {
891                "name": "pallavi",
892                "uid": 1002,
893                "gid": 1002,
894                "home": "/home/pallavi",
895            }
896        ]
897
898Markers
899~~~~~~~
900
901Markers are used to protect and restore the state of open hierarchy
902constructs (containers, lists, or instances).  While a marker is open,
903no other open constructs can be closed.  When a marker is closed, all
904constructs open since the marker was opened will be closed.
905
906Markers use names which are not user-visible, allowing the caller to
907choose appropriate internal names.
908
909In this example, the code whiffles through a list of fish, calling a
910function to emit details about each fish.  The marker "fish-guts" is
911used to ensure that any constructs opened by the function are closed
912properly::
913
914  EXAMPLE:
915      for (i = 0; fish[i]; i++) {
916          xo_open_instance("fish");
917          xo_open_marker("fish-guts");
918          dump_fish_details(i);
919          xo_close_marker("fish-guts");
920      }
921
922.. c:function:: xo_ssize_t xo_open_marker(const char *name)
923
924  :param name: Name of the instance
925  :type name: const char *
926  :returns: -1 on error, or the number of bytes generated
927  :rtype: xo_ssize_t
928
929  The `xo_open_marker` function records the current state of open tags
930  in order for `xo_close_marker` to close them at some later point.
931
932.. c:function:: xo_ssize_t xo_open_marker_h(const char *name)
933
934  :param xop: Handle to use (or NULL for default handle)
935  :type xop: xo_handle_t *
936
937  The `xo_open_marker_h` function adds a `handle` parameter.
938
939.. c:function:: xo_ssize_t xo_close_marker(const char *name)
940
941  :param name: Name of the instance
942  :type name: const char *
943  :returns: -1 on error, or the number of bytes generated
944  :rtype: xo_ssize_t
945
946  The `xo_close_marker` function closes any open containers, lists, or
947  instances as needed to return to the state recorded when
948  `xo_open_marker` was called with the matching name.
949
950.. c:function:: xo_ssize_t xo_close_marker(const char *name)
951
952  :param xop: Handle to use (or NULL for default handle)
953  :type xop: xo_handle_t *
954
955  The `xo_close_marker_h` function adds a `handle` parameter.
956
957DTRT Mode
958~~~~~~~~~
959
960Some users may find tracking the names of open containers, lists, and
961instances inconvenient.  libxo offers a "Do The Right Thing" mode, where
962libxo will track the names of open containers, lists, and instances so
963the close function can be called without a name.  To enable DTRT mode,
964turn on the XOF_DTRT flag prior to making any other libxo output::
965
966    xo_set_flags(NULL, XOF_DTRT);
967
968.. index:: XOF_DTRT
969
970Each open and close function has a version with the suffix "_d", which
971will close the open container, list, or instance::
972
973    xo_open_container_d("top");
974    ...
975    xo_close_container_d();
976
977This also works for lists and instances::
978
979    xo_open_list_d("item");
980    for (...) {
981        xo_open_instance_d("item");
982        xo_emit(...);
983        xo_close_instance_d();
984    }
985    xo_close_list_d();
986
987.. index:: XOF_WARN
988
989Note that the XOF_WARN flag will also cause libxo to track open
990containers, lists, and instances.  A warning is generated when the
991name given to the close function and the name recorded do not match.
992
993Support Functions
994-----------------
995
996.. index:: xo_parse_args
997.. _xo_parse_args:
998
999Parsing Command-line Arguments (xo_parse_args)
1000~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1001
1002.. c:function:: int xo_parse_args (int argc, char **argv)
1003
1004  :param int argc: Number of arguments
1005  :param argv: Array of argument strings
1006  :return: -1 on error, or the number of remaining arguments
1007  :rtype: int
1008
1009  The `xo_parse_args` function is used to process a program's
1010  arguments.  libxo-specific options are processed and removed from
1011  the argument list so the calling application does not need to
1012  process them.  If successful, a new value for argc is returned.  On
1013  failure, a message is emitted and -1 is returned::
1014
1015    argc = xo_parse_args(argc, argv);
1016    if (argc < 0)
1017        exit(EXIT_FAILURE);
1018
1019  Following the call to xo_parse_args, the application can process the
1020  remaining arguments in a normal manner.  See :ref:`options` for a
1021  description of valid arguments.
1022
1023.. index:: xo_set_program
1024
1025xo_set_program
1026~~~~~~~~~~~~~~
1027
1028.. c:function:: void xo_set_program (const char *name)
1029
1030  :param name: Name to use as the program name
1031  :type name: const char *
1032  :returns: void
1033
1034  The `xo_set_program` function sets the name of the program as
1035  reported by functions like `xo_failure`, `xo_warn`, `xo_err`, etc.
1036  The program name is initialized by `xo_parse_args`, but subsequent
1037  calls to `xo_set_program` can override this value::
1038
1039    EXAMPLE:
1040        xo_set_program(argv[0]);
1041
1042  Note that the value is not copied, so the memory passed to
1043  `xo_set_program` (and `xo_parse_args`) must be maintained by the
1044  caller.
1045
1046.. index:: xo_set_version
1047
1048xo_set_version
1049~~~~~~~~~~~~~~
1050
1051.. c:function:: void xo_set_version (const char *version)
1052
1053  :param name: Value to use as the version string
1054  :type name: const char *
1055  :returns: void
1056
1057  The `xo_set_version` function records a version number to be emitted
1058  as part of the data for encoding styles (XML and JSON).  This
1059  version number is suitable for tracking changes in the content,
1060  allowing a user of the data to discern which version of the data
1061  model is in use.
1062
1063.. c:function:: void xo_set_version_h (xo_handle_t *xop, const char *version)
1064
1065  :param xop: Handle to use (or NULL for default handle)
1066  :type xop: xo_handle_t *
1067
1068  The `xo_set_version` function adds a `handle` parameter.
1069
1070.. index:: --libxo
1071.. index:: XOF_INFO
1072.. index:: xo_info_t
1073
1074.. _field-information:
1075
1076Field Information (xo_info_t)
1077~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1078
1079HTML data can include additional information in attributes that
1080begin with "data-".  To enable this, three things must occur:
1081
1082First the application must build an array of xo_info_t structures,
1083one per tag.  The array must be sorted by name, since libxo uses a
1084binary search to find the entry that matches names from format
1085instructions.
1086
1087Second, the application must inform libxo about this information using
1088the `xo_set_info` call::
1089
1090    typedef struct xo_info_s {
1091        const char *xi_name;    /* Name of the element */
1092        const char *xi_type;    /* Type of field */
1093        const char *xi_help;    /* Description of field */
1094    } xo_info_t;
1095
1096    void xo_set_info (xo_handle_t *xop, xo_info_t *infop, int count);
1097
1098Like other libxo calls, passing `NULL` for the handle tells libxo to
1099use the default handle.
1100
1101If the count is -1, libxo will count the elements of infop, but there
1102must be an empty element at the end.  More typically, the number is
1103known to the application::
1104
1105    xo_info_t info[] = {
1106        { "in-stock", "number", "Number of items in stock" },
1107        { "name", "string", "Name of the item" },
1108        { "on-order", "number", "Number of items on order" },
1109        { "sku", "string", "Stock Keeping Unit" },
1110        { "sold", "number", "Number of items sold" },
1111    };
1112    int info_count = (sizeof(info) / sizeof(info[0]));
1113    ...
1114    xo_set_info(NULL, info, info_count);
1115
1116Third, the emission of info must be triggered with the `XOF_INFO` flag
1117using either the `xo_set_flags` function or the "`--libxo=info`"
1118command line argument.
1119
1120The type and help values, if present, are emitted as the "data-type"
1121and "data-help" attributes::
1122
1123  <div class="data" data-tag="sku" data-type="string"
1124       data-help="Stock Keeping Unit">GRO-000-533</div>
1125
1126.. c:function:: void xo_set_info (xo_handle_t *xop, xo_info_t *infop, int count)
1127
1128  :param xop: Handle to use (or NULL for default handle)
1129  :type xop: xo_handle_t *
1130  :param infop: Array of information structures
1131  :type infop: xo_info_t *
1132  :returns: void
1133
1134.. index:: xo_set_allocator
1135.. index:: xo_realloc_func_t
1136.. index:: xo_free_func_t
1137
1138Memory Allocation
1139~~~~~~~~~~~~~~~~~
1140
1141The `xo_set_allocator` function allows libxo to be used in
1142environments where the standard :manpage:`realloc(3)` and
1143:manpage:`free(3)` functions are not appropriate.
1144
1145.. c:function:: void xo_set_allocator (xo_realloc_func_t realloc_func, xo_free_func_t free_func)
1146
1147  :param xo_realloc_func_t realloc_func:  Allocation function
1148  :param xo_free_func_t free_func: Free function
1149
1150  *realloc_func* should expect the same arguments as
1151  :manpage:`realloc(3)` and return a pointer to memory following the
1152  same convention.  *free_func* will receive the same argument as
1153  :manpage:`free(3)` and should release it, as appropriate for the
1154  environment.
1155
1156By default, the standard :manpage:`realloc(3)` and :manpage:`free(3)`
1157functions are used.
1158
1159.. index:: --libxo
1160
1161.. _libxo-options:
1162
1163LIBXO_OPTIONS
1164~~~~~~~~~~~~~
1165
1166The environment variable "LIBXO_OPTIONS" can be set to a subset of
1167libxo options, including:
1168
1169- color
1170- flush
1171- flush-line
1172- no-color
1173- no-humanize
1174- no-locale
1175- no-retain
1176- pretty
1177- retain
1178- underscores
1179- warn
1180
1181For example, warnings can be enabled by::
1182
1183    % env LIBXO_OPTIONS=warn my-app
1184
1185Since environment variables are inherited, child processes will have
1186the same options, which may be undesirable, making the use of the
1187"`--libxo`" command-line option preferable in most situations.
1188
1189.. index:: xo_warn
1190.. index:: xo_err
1191.. index:: xo_errx
1192.. index:: xo_message
1193
1194Errors, Warnings, and Messages
1195~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1196
1197Many programs make use of the standard library functions
1198:manpage:`err(3)` and :manpage:`warn(3)` to generate errors and
1199warnings for the user.  libxo wants to pass that information via the
1200current output style, and provides compatible functions to allow
1201this::
1202
1203    void xo_warn (const char *fmt, ...);
1204    void xo_warnx (const char *fmt, ...);
1205    void xo_warn_c (int code, const char *fmt, ...);
1206    void xo_warn_hc (xo_handle_t *xop, int code,
1207                     const char *fmt, ...);
1208    void xo_err (int eval, const char *fmt, ...);
1209    void xo_errc (int eval, int code, const char *fmt, ...);
1210    void xo_errx (int eval, const char *fmt, ...);
1211
1212::
1213
1214    void xo_message (const char *fmt, ...);
1215    void xo_message_c (int code, const char *fmt, ...);
1216    void xo_message_hc (xo_handle_t *xop, int code,
1217                        const char *fmt, ...);
1218    void xo_message_hcv (xo_handle_t *xop, int code,
1219                         const char *fmt, va_list vap);
1220
1221These functions display the program name, a colon, a formatted message
1222based on the arguments, and then optionally a colon and an error
1223message associated with either *errno* or the *code* parameter::
1224
1225    EXAMPLE:
1226        if (open(filename, O_RDONLY) < 0)
1227            xo_err(1, "cannot open file '%s'", filename);
1228
1229.. index:: xo_error
1230.. index:: xo_error_h
1231.. index:: xo_error_hv
1232.. index:: xo_errorn
1233.. index:: xo_errorn_h
1234.. index:: xo_errorn_hv
1235
1236xo_error
1237~~~~~~~~
1238
1239.. c:function:: void xo_error (const char *fmt, ...)
1240
1241  :param fmt: Format string
1242  :type fmt: const char *
1243  :returns: void
1244
1245.. c:function:: void xo_error_h (xo_handle_t *xop, const char *fmt, ...)
1246
1247  :param xop: libxo handle pointer
1248  :type xop: xo_handle_t *
1249  :param fmt: Format string
1250  :type fmt: const char *
1251  :returns: void
1252
1253.. c:function:: void xo_error_hv (xo_handle_t *xop, const char *fmt, va_list vap)
1254
1255  :param xop: libxo handle pointer
1256  :type xop: xo_handle_t *
1257  :param fmt: Format string
1258  :type fmt: const char *
1259  :param vap: variadic arguments
1260  :type xop: va_list
1261  :returns: void
1262
1263.. c:function:: void xo_errorn (const char *fmt, ...)
1264
1265  :param fmt: Format string
1266  :type fmt: const char *
1267  :returns: void
1268
1269.. c:function:: void xo_errorn_h (xo_handle_t *xop, const char *fmt, ...)
1270
1271  :param xop: libxo handle pointer
1272  :type xop: xo_handle_t *
1273  :param fmt: Format string
1274  :type fmt: const char *
1275  :returns: void
1276
1277.. c:function:: void xo_errorn_hv (xo_handle_t *xop, int need_newline, const char *fmt, va_list vap)
1278
1279  :param xop: libxo handle pointer
1280  :type xop: xo_handle_t *
1281  :param need_newline: boolean indicating need for trailing newline
1282  :type need_newline: int
1283  :param fmt: Format string
1284  :type fmt: const char *
1285  :param vap: variadic arguments
1286  :type xop: va_list
1287  :returns: void
1288
1289  The `xo_error` function can be used for generic errors that should
1290  be reported over the handle, rather than to stderr.  The `xo_error`
1291  function behaves like `xo_err` for TEXT and HTML output styles, but
1292  puts the error into XML or JSON elements::
1293
1294    EXAMPLE::
1295        xo_error("Does not %s", "compute");
1296    XML::
1297        <error><message>Does not compute</message></error>
1298    JSON::
1299        "error": { "message": "Does not compute" }
1300
1301  The `xo_error_h` and `xo_error_hv` add a handle object and a
1302  variadic-ized parameter to the signature, respectively.
1303
1304  The `xo_errorn` function supplies a newline at the end the error
1305  message if the format string does not include one.  The
1306  `xo_errorn_h` and `xo_errorn_hv` functions add a handle object and
1307  a variadic-ized parameter to the signature, respectively.  The
1308  `xo_errorn_hv` function also adds a boolean to indicate the need for
1309  a trailing newline.
1310
1311.. index:: xo_no_setlocale
1312.. index:: Locale
1313
1314xo_no_setlocale
1315~~~~~~~~~~~~~~~
1316
1317.. c:function:: void xo_no_setlocale (void)
1318
1319  libxo automatically initializes the locale based on setting of the
1320  environment variables LC_CTYPE, LANG, and LC_ALL.  The first of this
1321  list of variables is used and if none of the variables, the locale
1322  defaults to "UTF-8".  The caller may wish to avoid this behavior,
1323  and can do so by calling the `xo_no_setlocale` function.
1324
1325Emitting syslog Messages
1326------------------------
1327
1328syslog is the system logging facility used throughout the unix world.
1329Messages are sent from commands, applications, and daemons to a
1330hierarchy of servers, where they are filtered, saved, and forwarded
1331based on configuration behaviors.
1332
1333syslog is an older protocol, originally documented only in source
1334code.  By the time :RFC:`3164` published, variation and mutation left the
1335leading "<pri>" string as only common content.  :RFC:`5424` defines a new
1336version (version 1) of syslog and introduces structured data into the
1337messages.  Structured data is a set of name/value pairs transmitted
1338distinctly alongside the traditional text message, allowing filtering
1339on precise values instead of regular expressions.
1340
1341These name/value pairs are scoped by a two-part identifier; an
1342enterprise identifier names the party responsible for the message
1343catalog and a name identifying that message.  `Enterprise IDs`_ are
1344defined by IANA, the Internet Assigned Numbers Authority.
1345
1346.. _Enterprise IDs:
1347    https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers
1348
1349Use the `xo_set_syslog_enterprise_id` function to set the Enterprise
1350ID, as needed.
1351
1352The message name should follow the conventions in
1353:ref:`good-field-names`\ , as should the fields within the message::
1354
1355    /* Both of these calls are optional */
1356    xo_set_syslog_enterprise_id(32473);
1357    xo_open_log("my-program", 0, LOG_DAEMON);
1358
1359    /* Generate a syslog message */
1360    xo_syslog(LOG_ERR, "upload-failed",
1361              "error <%d> uploading file '{:filename}' "
1362              "as '{:target/%s:%s}'",
1363              code, filename, protocol, remote);
1364
1365    xo_syslog(LOG_INFO, "poofd-invalid-state",
1366              "state {:current/%u} is invalid {:connection/%u}",
1367	      state, conn);
1368
1369The developer should be aware that the message name may be used in the
1370future to allow access to further information, including
1371documentation.  Care should be taken to choose quality, descriptive
1372names.
1373
1374.. _syslog-details:
1375
1376Priority, Facility, and Flags
1377~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1378
1379The `xo_syslog`, `xo_vsyslog`, and `xo_open_log` functions
1380accept a set of flags which provide the priority of the message, the
1381source facility, and some additional features.  These values are OR'd
1382together to create a single integer argument::
1383
1384    xo_syslog(LOG_ERR | LOG_AUTH, "login-failed",
1385             "Login failed; user '{:user}' from host '{:address}'",
1386             user, addr);
1387
1388These values are defined in <syslog.h>.
1389
1390The priority value indicates the importance and potential impact of
1391each message:
1392
1393  ============= =======================================================
1394   Priority      Description
1395  ============= =======================================================
1396   LOG_EMERG     A panic condition, normally broadcast to all users
1397   LOG_ALERT     A condition that should be corrected immediately
1398   LOG_CRIT      Critical conditions
1399   LOG_ERR       Generic errors
1400   LOG_WARNING   Warning messages
1401   LOG_NOTICE    Non-error conditions that might need special handling
1402   LOG_INFO      Informational messages
1403   LOG_DEBUG     Developer-oriented messages
1404  ============= =======================================================
1405
1406The facility value indicates the source of message, in fairly generic
1407terms:
1408
1409  =============== =======================================================
1410   Facility        Description
1411  =============== =======================================================
1412   LOG_AUTH        The authorization system (e.g. :manpage:`login(1)`)
1413   LOG_AUTHPRIV    As LOG_AUTH, but logged to a privileged file
1414   LOG_CRON        The cron daemon: :manpage:`cron(8)`
1415   LOG_DAEMON      System daemons, not otherwise explicitly listed
1416   LOG_FTP         The file transfer protocol daemons
1417   LOG_KERN        Messages generated by the kernel
1418   LOG_LPR         The line printer spooling system
1419   LOG_MAIL        The mail system
1420   LOG_NEWS        The network news system
1421   LOG_SECURITY    Security subsystems, such as :manpage:`ipfw(4)`
1422   LOG_SYSLOG      Messages generated internally by :manpage:`syslogd(8)`
1423   LOG_USER        Messages generated by user processes (default)
1424   LOG_UUCP        The uucp system
1425   LOG_LOCAL0..7   Reserved for local use
1426  =============== =======================================================
1427
1428In addition to the values listed above, xo_open_log accepts a set of
1429addition flags requesting specific logging behaviors:
1430
1431  ============ ====================================================
1432   Flag         Description
1433  ============ ====================================================
1434   LOG_CONS     If syslogd fails, attempt to write to /dev/console
1435   LOG_NDELAY   Open the connection to :manpage:`syslogd(8)` immediately
1436   LOG_PERROR   Write the message also to standard error output
1437   LOG_PID      Log the process id with each message
1438  ============ ====================================================
1439
1440.. index:: xo_syslog
1441
1442xo_syslog
1443~~~~~~~~~
1444
1445.. c:function:: void xo_syslog (int pri, const char *name, const char *fmt, ...)
1446
1447  :param int pri: syslog priority
1448  :param name: Name of the syslog event
1449  :type name: const char *
1450  :param fmt: Format string, followed by arguments
1451  :type fmt: const char *
1452  :returns: void
1453
1454  Use the `xo_syslog` function to generate syslog messages by calling
1455  it with a log priority and facility, a message name, a format
1456  string, and a set of arguments.  The priority/facility argument are
1457  discussed above, as is the message name.
1458
1459  The format string follows the same conventions as `xo_emit`'s format
1460  string, with each field being rendered as an SD-PARAM pair::
1461
1462    xo_syslog(LOG_ERR, "poofd-missing-file",
1463              "'{:filename}' not found: {:error/%m}", filename);
1464
1465    ... [poofd-missing-file@32473 filename="/etc/poofd.conf"
1466          error="Permission denied"] '/etc/poofd.conf' not
1467          found: Permission denied
1468
1469Support functions
1470~~~~~~~~~~~~~~~~~
1471
1472.. index:: xo_vsyslog
1473
1474xo_vsyslog
1475++++++++++
1476
1477.. c:function:: void xo_vsyslog (int pri, const char *name, const char *fmt, va_list vap)
1478
1479  :param int pri: syslog priority
1480  :param name: Name of the syslog event
1481  :type name: const char *
1482  :param fmt: Format string
1483  :type fmt: const char *
1484  :param va_list vap: Variadic argument list
1485  :returns: void
1486
1487  xo_vsyslog is identical in function to xo_syslog, but takes the set of
1488  arguments using a va_list::
1489
1490    EXAMPLE:
1491        void
1492        my_log (const char *name, const char *fmt, ...)
1493        {
1494            va_list vap;
1495            va_start(vap, fmt);
1496            xo_vsyslog(LOG_ERR, name, fmt, vap);
1497            va_end(vap);
1498        }
1499
1500.. index:: xo_open_log
1501
1502xo_open_log
1503+++++++++++
1504
1505.. c:function:: void xo_open_log (const char *ident, int logopt, int facility)
1506
1507  :param indent:
1508  :type indent: const char *
1509  :param int logopt: Bit field containing logging options
1510  :param int facility:
1511  :returns: void
1512
1513  xo_open_log functions similar to :manpage:`openlog(3)`, allowing
1514  customization of the program name, the log facility number, and the
1515  additional option flags described in :ref:`syslog-details`.
1516
1517.. index:: xo_close_log
1518
1519xo_close_log
1520++++++++++++
1521
1522.. c:function:: void xo_close_log (void)
1523
1524  The `xo_close_log` function is similar to :manpage:`closelog(3)`,
1525  closing the log file and releasing any associated resources.
1526
1527.. index:: xo_set_logmask
1528
1529xo_set_logmask
1530++++++++++++++
1531
1532.. c:function:: int xo_set_logmask (int maskpri)
1533
1534  :param int maskpri: the log priority mask
1535  :returns: The previous log priority mask
1536
1537  The `xo_set_logmask` function is similar to :manpage:`setlogmask(3)`,
1538  restricting the set of generated log event to those whose associated
1539  bit is set in maskpri.  Use `LOG_MASK(pri)` to find the appropriate bit,
1540  or `LOG_UPTO(toppri)` to create a mask for all priorities up to and
1541  including toppri::
1542
1543    EXAMPLE:
1544        setlogmask(LOG_UPTO(LOG_WARN));
1545
1546.. index:: xo_set_syslog_enterprise_id
1547
1548xo_set_syslog_enterprise_id
1549+++++++++++++++++++++++++++
1550
1551.. c:function:: void xo_set_syslog_enterprise_id (unsigned short eid)
1552
1553  Use the `xo_set_syslog_enterprise_id` to supply a platform- or
1554  application-specific enterprise id.  This value is used in any future
1555  syslog messages.
1556
1557  Ideally, the operating system should supply a default value via the
1558  "kern.syslog.enterprise_id" sysctl value.  Lacking that, the
1559  application should provide a suitable value.
1560
1561Enterprise IDs are administered by IANA, the Internet Assigned Number
1562Authority.  The complete list is EIDs on their web site::
1563
1564    https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers
1565
1566New EIDs can be requested from IANA using the following page::
1567
1568    http://pen.iana.org/pen/PenApplication.page
1569
1570Each software development organization that defines a set of syslog
1571messages should register their own EID and use that value in their
1572software to ensure that messages can be uniquely identified by the
1573combination of EID + message name.
1574
1575Creating Custom Encoders
1576------------------------
1577
1578The number of encoding schemes in current use is staggering, with new
1579and distinct schemes appearing daily.  While libxo provide XML, JSON,
1580HMTL, and text natively, there are requirements for other encodings.
1581
1582Rather than bake support for all possible encoders into libxo, the API
1583allows them to be defined externally.  libxo can then interfaces with
1584these encoding modules using a simplistic API.  libxo processes all
1585functions calls, handles state transitions, performs all formatting,
1586and then passes the results as operations to a customized encoding
1587function, which implements specific encoding logic as required.  This
1588means your encoder doesn't need to detect errors with unbalanced
1589open/close operations but can rely on libxo to pass correct data.
1590
1591By making a simple API, libxo internals are not exposed, insulating the
1592encoder and the library from future or internal changes.
1593
1594The three elements of the API are:
1595
1596- loading
1597- initialization
1598- operations
1599
1600The following sections provide details about these topics.
1601
1602.. index:: CBOR
1603
1604libxo source contains an encoder for Concise Binary Object
1605Representation, aka CBOR (:RFC:`7049`), which can be used as an
1606example for the API for other encoders.
1607
1608Loading Encoders
1609~~~~~~~~~~~~~~~~
1610
1611Encoders can be registered statically or discovered dynamically.
1612Applications can choose to call the `xo_encoder_register` function
1613to explicitly register encoders, but more typically they are built as
1614shared libraries, placed in the libxo/extensions directory, and loaded
1615based on name.  libxo looks for a file with the name of the encoder
1616and an extension of ".enc".  This can be a file or a symlink to the
1617shared library file that supports the encoder::
1618
1619    % ls -1 lib/libxo/extensions/*.enc
1620    lib/libxo/extensions/cbor.enc
1621    lib/libxo/extensions/test.enc
1622
1623Encoder Initialization
1624~~~~~~~~~~~~~~~~~~~~~~
1625
1626Each encoder must export a symbol used to access the library, which
1627must have the following signature::
1628
1629    int xo_encoder_library_init (XO_ENCODER_INIT_ARGS);
1630
1631`XO_ENCODER_INIT_ARGS` is a macro defined in "xo_encoder.h" that defines
1632an argument called "arg", a pointer of the type
1633`xo_encoder_init_args_t`.  This structure contains two fields:
1634
1635- `xei_version` is the version number of the API as implemented
1636  within libxo.  This version is currently as 1 using
1637  `XO_ENCODER_VERSION`.  This number can be checked to ensure
1638  compatibility.  The working assumption is that all versions should
1639  be backward compatible, but each side may need to accurately know
1640  the version supported by the other side.  `xo_encoder_library_init`
1641  can optionally check this value, and must then set it to the version
1642  number used by the encoder, allowing libxo to detect version
1643  differences and react accordingly.  For example, if version 2 adds
1644  new operations, then libxo will know that an encoding library that
1645  set `xei_version` to 1 cannot be expected to handle those new
1646  operations.
1647
1648- xei_handler must be set to a pointer to a function of type
1649  `xo_encoder_func_t`, as defined in "xo_encoder.h".  This function
1650  takes a set of parameters:
1651  - xop is a pointer to the opaque `xo_handle_t` structure
1652  - op is an integer representing the current operation
1653  - name is a string whose meaning differs by operation
1654  - value is a string whose meaning differs by operation
1655  - private is an opaque structure provided by the encoder
1656
1657Additional arguments may be added in the future, so handler functions
1658should use the `XO_ENCODER_HANDLER_ARGS` macro.  An appropriate
1659"extern" declaration is provided to help catch errors.
1660
1661Once the encoder initialization function has completed processing, it
1662should return zero to indicate that no error has occurred.  A non-zero
1663return code will cause the handle initialization to fail.
1664
1665Operations
1666~~~~~~~~~~
1667
1668The encoder API defines a set of operations representing the
1669processing model of libxo.  Content is formatted within libxo, and
1670callbacks are made to the encoder's handler function when data is
1671ready to be processed:
1672
1673  ======================= =======================================
1674   Operation               Meaning  (Base function)
1675  ======================= =======================================
1676   XO_OP_CREATE            Called when the handle is created
1677   XO_OP_OPEN_CONTAINER    Container opened (xo_open_container)
1678   XO_OP_CLOSE_CONTAINER   Container closed (xo_close_container)
1679   XO_OP_OPEN_LIST         List opened (xo_open_list)
1680   XO_OP_CLOSE_LIST        List closed (xo_close_list)
1681   XO_OP_OPEN_LEAF_LIST    Leaf list opened (xo_open_leaf_list)
1682   XO_OP_CLOSE_LEAF_LIST   Leaf list closed (xo_close_leaf_list)
1683   XO_OP_OPEN_INSTANCE     Instance opened (xo_open_instance)
1684   XO_OP_CLOSE_INSTANCE    Instance closed (xo_close_instance)
1685   XO_OP_STRING            Field with Quoted UTF-8 string
1686   XO_OP_CONTENT           Field with content
1687   XO_OP_FINISH            Finish any pending output
1688   XO_OP_FLUSH             Flush any buffered output
1689   XO_OP_DESTROY           Clean up resources
1690   XO_OP_ATTRIBUTE         An attribute name/value pair
1691   XO_OP_VERSION           A version string
1692  ======================= =======================================
1693
1694For all the open and close operations, the name parameter holds the
1695name of the construct.  For string, content, and attribute operations,
1696the name parameter is the name of the field and the value parameter is
1697the value.  "string" are differentiated from "content" to allow differing
1698treatment of true, false, null, and numbers from real strings, though
1699content values are formatted as strings before the handler is called.
1700For version operations, the value parameter contains the version.
1701
1702All strings are encoded in UTF-8.
1703