afb-apiset: Fix start of apis
[src/app-framework-binder.git] / old-docs / afb-bindings-writing.md
1
2 How to write a binding for AFB-DAEMON
3 ===================================
4
5 Summary
6 -------
7
8 The afb-daemon binders serve files through HTTP protocol and offers to
9 developers the capability to offer application API methods through HTTP or
10 WebSocket protocol.
11
12 The bindings are used to add API to ***afb-daemon***.
13 This part describes how to write a binding for***afb-daemon***.
14
15 Excepting this summary, this document target developers.
16
17 Before moving further through an example, here after
18 a short overview of binder bindings fundamentals.
19
20 ### Nature of a binding
21
22 A binding is an independent piece of software. A binding is self contain and
23 exposes application logic as sharable library. A binding is intended to be
24 dynamically loaded by ***afb-daemon*** to expose application API.
25
26 Technically, a binder binding does not reference and is not linked with any
27 ***afb-daemon*** library.
28
29 ### Class of bindings
30
31 Application binder supports two kinds of bindings: application bindings and
32 service bindings. Technically both class of binding are equivalent and use the
33 same coding convention. Only sharing mode and security context diverge.
34
35 #### Application-bindings
36
37 Application-bindings implements the glue in between application's UI and
38 services. Every AGL application has a corresponding binder that typically
39 activates one or many bindings to interface the application logic with lower
40 platform services. When an application is started by the AGL application
41 framework, a dedicate binder is started that loads/activates application
42 binding(s). API expose by application-binding are executed within corresponding
43 application security context.
44
45 Application bindings generally handle a unique context for a unique client. As
46 the application framework start a dedicated instance of afb_daemon for each AGL
47 application, if a given binding is used within multiple application each of
48 those application get a new and private instance of eventually "shared" binding.
49
50 #### Service-bindings
51
52 Service-bindings enable API activation within corresponding service security
53 context and not within calling application context. Service-bindings are
54 intended to run as a unique instance. Service-bindings can be shared in between
55 multiple clients.
56
57 Service-bindings can either be stateless or manage client context. When managing
58 context each client get a private context. Sharing may either be global to the
59 platform (ie: GPS service) or dedicated to a given user (ie: user preferences)
60
61 ### Live cycle of bindings within ***afb-daemon***
62
63 Application and service bindings are loaded and activated each time a new
64 ***afb-daemon*** is started.
65
66 At launch time, every loaded binding initialise itself. If a single binding
67 initialisation fails the corresponding instance of ***afb-daemon*** aborts.
68
69 Conversely, when a binding initialisation succeeds, it should register its
70 unique name as well as the list of verbs (methods name from binder point of
71 view) attached to the methods it exposes.
72
73 When initialised, on request from application clients to the right API/verbs
74 binding methods are activated by the ***afb-daemon*** attached to the
75 application or service.
76
77 At exit time, no special action is enforced by ***afb-daemon***. When a specific
78 actions is required at afb-daemon stop, developers should use 'atexit/on_exit'
79 during binding initialisation sequence to register a custom exit function.
80
81 ### Binding Content
82
83 Afb-daemon's bindings register two classes of objects: names and functions.
84
85 Bindings declare categories of names:
86  - A unique binding name to access all API exposed by this binding,
87  - One name for each methods/verbs provided by this binding.
88
89 Bindings declare two categories of functions:
90  - function used for initialisation
91  - functions implementing the exposed API methods
92
93 Afb-daemon parses URI requests to extract the API(binding name) and the
94 VERB(method to activate). As an example, URI **foo/bar** translates to binding
95 named **foo** and method named **bar**. To serve such a request,
96 ***afb-daemon*** looks for an active binding named **foo** and then within this
97 binding for a method named **bar**. When found ***afb-daemon*** calls
98 the corresponding method with an attached parameter if any.
99
100 Afb-daemon is case-insensitive when parsing URI. Thus **TicTacToe/Board** and
101 **tictactoe/board** are equivalent.
102
103 #### The name of the binding
104
105 The name of a given binding is also known as the name
106 of the API prefix that defines the binding.
107
108 The name of a binding SHOULD be unique within a given ***afb-daemon*** instance.
109
110 For example, when a client of ***afb-daemon*** calls a URI named **foo/bar**.
111 Afb-daemon extracts the prefix **foo** and the suffix **bar**. **foo** must
112 match a binding name and **bar** has to match a VERB attached to some method.
113
114 #### Names of methods
115
116 Each binding exposes a set of methods that can be called by the clients of a
117 given ***afb-daemon***.
118
119 VERB's name attached to a given binding (API) MUST be unique within a binding.
120
121 Bindings static declaration link VERBS to the corresponding methods.
122 When clients emit requests on a given API/VERB corresponding method is called
123 by ***afb-daemon***.
124
125 #### Initialisation function
126
127 Binding's initialisation function serves several purposes.
128
129 1. It allows ***afb-daemon*** to control the binding version depending on
130 the initialisation of function name. As today, the only supported initialisation
131 function is **afbBindingV1Register**. This identifies version "one" of bindings.
132
133 2. It allows bindings to initialise itself.
134
135 3. It enables names declarations: descriptions, requirements and implementations
136 of exposed API/VERB.
137
138 #### Functions instantiation of API/VERBs
139
140 When an API/VERB is called, ***afb-daemon*** constructs a request object. Then
141 it passes this request object to the implementation function corresponding to
142 requested method, this within attached API binding.
143
144 An implementation function receives a request object used to: get
145 the arguments of the request, send an answer, store session data.
146
147 A binding MUST set an answer to every received requests.
148
149 Nevertheless, there are two implementations, *synchronous* and *asynchronous*.
150 API/VERB implementation that set an answer before returning are called
151 *synchronous implementations*. Those that do not systematically set an answer
152 before returning are called *asynchronous implementations*.
153
154 Asynchronous implementations typically launch asynchronous actions. They record
155 some context at request time and provide an answer to the request only at
156 completion of asynchronous actions.
157
158 The Tic-Tac-Toe example
159 -----------------------
160
161 This part explains how to write an afb-binding. For the sake of being practical
162 it uses many examples based on tic-tac-toe. This binding example is in
163 *bindings/samples/tic-tac-toe.c*.
164
165 This binding is named ***tictactoe***.
166
167 Dependencies when compiling
168 ---------------------------
169
170 Afb-daemon provides a configuration file for *pkg-config*.
171 Typing the command
172
173         pkg-config --cflags afb-daemon
174
175 Print flags use for compilation:
176
177         $ pkg-config --cflags afb-daemon
178         -I/opt/local/include -I/usr/include/json-c
179
180 For linking, you should use
181
182         $ pkg-config --libs afb-daemon
183         -ljson-c
184
185 Afb-daemon automatically includes the dependency to json-c.
186 This is activated through **Requires** keyword in pkg-config.
187 While almost every binding replies on **json-c** this is not a must have
188 dependency.
189
190 Internally, ***afb-daemon*** relies on **libsystemd** for its event loop, as
191 well as for its binding to D-Bus. Bindings developers are encouraged to leverage
192 **libsystemd** when possible. Nevertheless there is no hard dependency to
193 **libsystemd** if you do not want to use it, feel free to do so.
194
195 > Afb-daemon bindings are fully self contained. They do not enforce dependency
196 on any libraries from the application framework.
197 > Afb-daemon dependencies requirer to run AGL bindings are given at runtime
198 through pointers leveraging read-only
199 > memory feature.
200
201 Header files to include
202 -----------------------
203
204 Binding *tictactoe* has following includes:
205
206 ```C
207 #define _GNU_SOURCE
208 #include <stdio.h>
209 #include <string.h>
210 #include <json-c/json.h>
211 #include <afb/afb-binding.h>
212 ```
213
214 Header *afb/afb-binding.h* is the only hard dependency, it includes all features
215 that a binding MUST HAVE. Outside of includes used to support application logic,
216 common external headers used within bindings are:
217
218 - *json-c/json.h*: should be include to handle json objects;
219 - *systemd/sd-event.h*: should be include to access event main loop;
220 - *systemd/sd-bus.h*: should be include for dbus connections.
221
222 The *tictactoe* binding does not leverage systemd features, also only json.h
223 is used on top of mandatory afb/afb-binding.h.
224
225 When including *afb/afb-binding.h*, the macro **_GNU_SOURCE** MUST be
226 defined.
227
228 Choosing names
229 --------------
230
231 Designers of bindings should define a unique name for every API binding
232 as well as for methods VERBs. They should also define names for request
233 arguments passed as name/value pair in URI.
234
235 While forging names, designers should respect few rules to
236 ensure that created names are valid and easy to use across platforms.
237
238 All names and strings are UTF-8 encoded.
239
240 ### Names for API (binding)
241
242 Binding API name are checked.
243 All characters are authorised except:
244
245 - the control characters (\u0000 .. \u001f)
246 - the characters of the set { ' ', '"', '#', '%', '&',
247   '\'', '/', '?', '`', '\x7f' }
248
249 In other words the set of forbidden characters is
250 { \u0000..\u0020, \u0022, \u0023, \u0025..\u0027,
251   \u002f, \u003f, \u0060, \u007f }.
252
253 Afb-daemon makes no distinction between lower case
254 and upper case when searching for API/VERB.
255
256 ### Names for methods
257
258 The names of methods VERBs are totally free and not checked.
259
260 However, the validity rules for method's VERB name are the
261 same as for Binding API name except that the dot(.) character
262 is forbidden.
263
264 Afb-daemon makes no case distinction when searching for an API by name.
265
266 ### Names for arguments
267
268 Argument's name are not restricted and can be everything you wish.
269
270 > Warning arguments search is case sensitive and "index" and "Index"
271 > are not two different arguments.
272
273 ### Forging names widely available
274
275 The key names of javascript object can be almost
276 anything using the arrayed notation:
277
278         object[key] = value
279
280 Nevertheless this is not the case with javascript dot notation:
281
282         object.key = value
283
284 Using the dot notation, the key must be a valid javascript
285 identifier and dash(-) as well as few other reserved characters cannot be used.
286
287 For this reason, we advise developers to chose name compatible with both
288 javascript and HTML notation.
289
290 It is a good practice, even for arguments not to rely on case sensitivity.
291 This may reduce headache strength at debug time, especially with interpreted
292 language like javascript that may not warn you that a variable was not defined.
293
294 Declaration of methods and initialisation of the bindings
295 ---------------------------------------------------------
296
297 ### Declaration of methods
298
299 To be active, binding's methods should be declared to
300 ***afb-daemon***. Furthermore, the binding itself must be recorded.
301
302 The registration mechanism is very basic: when ***afb-daemon*** starts,
303 it loads all bindings listed in: command line or configuration file.
304
305 Loading a binding follows the following steps:
306
307 1. Afb-daemon loads the binding with *dlopen*.
308
309 2. Afb-daemon searches for a symbol named **afbBindingV1Register** using *dlsym*.
310 This symbol is assumed to be the exported initialisation function of the binding.
311
312 3. Afb-daemon builds an interface object for the binding.
313
314 4. Afb-daemon calls the found function **afbBindingV1Register** with interface pointer
315 as parameter.
316
317 5. Function **afbBindingV1Register** setups the binding and initialises it.
318
319 6. Function **afbBindingV1Register** returns the pointer to a structure
320 describing the binding: version, name (prefix or API name), and list of methods.
321
322 7. Afb-daemon checks that the returned version and name can be managed.
323 If so, binding and its methods are register to become usable as soon as
324 ***afb-daemon*** initialisation is finished.
325
326 ### Initialisation of bindings
327
328 The bindings initialisation is the final step made at the end of declaration of
329 methods. This will initialize the binding and make its ***afb-daemon***'s
330 interface fully functional.
331
332 So, afb-daemon binder call **afbBindingV1ServiceInit** as final step to a
333 binding. This will allows the binding to call features in its name and as saw in
334 [Binder events guide](afb-events-guide.md) you can create an event only at this
335 moment and not before. Before that it will fail because afb-daemon doesn't know
336 the binding name.
337
338 **afbBindingV1ServiceInit** is defined as below:
339
340 ```C
341 /*
342  * When a binding have an exported implementation of the
343  * function 'afbBindingV1ServiceInit', defined below,
344  * the framework calls it for initialising the service after
345  * registration of all bindings.
346  *
347  * The object 'service' should be recorded. It has functions that
348  * allows the binding to call features with its own personality.
349  *
350  * The function should return 0 in case of success or, else, should return
351  * a negative value.
352  */
353 extern int afbBindingV1ServiceInit(struct afb_service service);
354 ```
355
356 ### Application binding example: tic-tac-toe
357
358 If we continue our tic-tac-toe example, here after the code used for
359 **afbBindingV1Register** implementation from binding *tic-tac-toe*:
360
361 ```C
362 /*
363  * activation function for registering the binding called by afb-daemon
364  */
365 const struct afb_binding *afbBindingV1Register(const struct afb_binding_interface *itf)
366 {
367    afbitf = itf;         // records the interface for accessing afb-daemon
368    return &binding_description;  // returns the description of the binding
369 }
370 ```
371
372 It is a very minimal initialisation function because *tic-tac-toe* binding doesn't
373 have any application related initialisation step. It merely record daemon's interface
374 and returns its description.
375
376 The variable **afbitf** is a binding global variable. It keeps the
377 interface to ***afb-daemon*** that should be used for logging and pushing events.
378 Here is its declaration:
379
380 ```C
381 /*
382  * the interface to afb-daemon
383  */
384 const struct afb_binding_interface *afbitf;
385 ```
386
387 The description of the binding is defined here after.
388
389 ```C
390 /*
391  * array of the methods exported to afb-daemon
392  */
393 static const struct afb_verb_desc_v1 binding_methods[] = {
394    /* VERB'S NAME     SESSION MANAGEMENT          FUNCTION TO CALL  SHORT DESCRIPTION */
395    { .name= "new",   .session= AFB_SESSION_NONE, .callback= new,   .info= "Starts a new game" },
396    { .name= "play",  .session= AFB_SESSION_NONE, .callback= play,  .info= "Asks the server to play" },
397    { .name= "move",  .session= AFB_SESSION_NONE, .callback= move,  .info= "Tells the client move" },
398    { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" },
399    { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" },
400    { .name= "join",  .session= AFB_SESSION_CHECK,.callback= join,  .info= "Join a board" },
401    { .name= "undo",  .session= AFB_SESSION_NONE, .callback= undo,  .info= "Undo the last move" },
402    { .name= "wait",  .session= AFB_SESSION_NONE, .callback= wait,  .info= "Wait for a change" },
403    { .name= NULL } /* marker for end of the array */
404 };
405
406 /*
407  * description of the binding for afb-daemon
408  */
409 static const struct afb_binding binding_description =
410 {
411    /* description conforms to VERSION 1 */
412    .type= AFB_BINDING_VERSION_1,
413    .v1= {                               /* fills the v1 field of the union when AFB_BINDING_VERSION_1 */
414       .prefix= "tictactoe",             /* the API name (or binding name or prefix) */
415       .info= "Sample tac-tac-toe game", /* short description of of the binding */
416       .methods = binding_methods                /* the array describing the methods of the API */
417    }
418 };
419 ```
420
421 The structure **binding_description** describes the binding.
422 It declares the type and version of the binding, its name, a short description
423 and its methods list.
424
425 The list of methods is an array of structures describing the methods and terminated by a NULL marker.
426
427 In version one of afb-damon binding, a method description contains 4 fields:
428
429 - the name of the method,
430
431 - the session management flags,
432
433 - the implementation function to be call for the method,
434
435 - a short description.
436
437 The structure describing methods is defined as follows:
438
439 ```C
440 /*
441  * Description of one method of the API provided by the binding
442  * This enumeration is valid for bindings of type 1
443  */
444 struct afb_verb_desc_v1
445 {
446        const char *name;                       /* name of the method */
447        enum AFB_session_v1 session;            /* authorisation and session requirements of the method */
448        void (*callback)(struct afb_req req);   /* callback function implementing the method */
449        const char *info;                       /* textual description of the method */
450 };
451 ```
452
453 For technical reasons, the enumeration **enum AFB_session_v1** is not exactly an
454 enumeration but the wrapper of constant definitions that can be mixed using bitwise or
455 (the C operator |).
456
457 The constants that can bit mixed are:
458
459 Constant name            | Meaning
460 -------------------------|-------------------------------------------------------------
461 **AFB_SESSION_CREATE**   | Equals to AFB_SESSION_LOA_EQ_0|AFB_SESSION_RENEW
462 **AFB_SESSION_CLOSE**    | Closes the session after the reply and set the LOA to 0
463 **AFB_SESSION_RENEW**    | Refreshes the token of authentification
464 **AFB_SESSION_CHECK**    | Just requires the token authentification
465 **AFB_SESSION_LOA_LE_0** | Requires the current LOA to be lesser then or equal to 0
466 **AFB_SESSION_LOA_LE_1** | Requires the current LOA to be lesser then or equal to 1
467 **AFB_SESSION_LOA_LE_2** | Requires the current LOA to be lesser then or equal to 2
468 **AFB_SESSION_LOA_LE_3** | Requires the current LOA to be lesser then or equal to 3
469 **AFB_SESSION_LOA_GE_0** | Requires the current LOA to be greater then or equal to 0
470 **AFB_SESSION_LOA_GE_1** | Requires the current LOA to be greater then or equal to 1
471 **AFB_SESSION_LOA_GE_2** | Requires the current LOA to be greater then or equal to 2
472 **AFB_SESSION_LOA_GE_3** | Requires the current LOA to be greater then or equal to 3
473 **AFB_SESSION_LOA_EQ_0** | Requires the current LOA to be equal to 0
474 **AFB_SESSION_LOA_EQ_1** | Requires the current LOA to be equal to 1
475 **AFB_SESSION_LOA_EQ_2** | Requires the current LOA to be equal to 2
476 **AFB_SESSION_LOA_EQ_3** | Requires the current LOA to be equal to 3
477
478 If any of this flag is set, ***afb-daemon*** requires an authentication token
479 as if **AFB_SESSION_CHECK** flag was also set.
480
481 The special value **AFB_SESSION_NONE** is zero and can be used to bypass token check.
482
483 > Note that **AFB_SESSION_CREATE** and **AFB_SESSION_CLOSE** might be removed in later versions.
484
485 Sending messages to the log system
486 ----------------------------------
487
488 Afb-daemon provides 4 levels of verbosity and 5 methods for logging messages.
489
490 The verbosity is managed. Options allow the change the verbosity of ***afb-daemon***
491 and the verbosity of the bindings can be set binding by binding.
492
493 The methods for logging messages are defined as macros that test the
494 verbosity level and that call the real logging function only if the
495 message must be output. This avoid evaluation of arguments of the
496 formatting messages if the message must not be output.
497
498 ### Verbs for logging messages
499
500 The 5 logging methods are:
501
502 Macro   | Verbosity | Meaning                           | syslog level
503 --------|:---------:|-----------------------------------|:-----------:
504 ERROR   |     0     | Error conditions                  |     3
505 WARNING |     1     | Warning conditions                |     4
506 NOTICE  |     1     | Normal but significant condition  |     5
507 INFO    |     2     | Informational                     |     6
508 DEBUG   |     3     | Debug-level messages              |     7
509
510 You can note that the 2 methods **WARNING** and **NOTICE** have the same level
511 of verbosity. But they don't have the same *syslog level*. It means that
512 they are output with a different level on the logging system.
513
514 All of these methods have the same signature:
515
516 ```C
517 void ERROR(const struct afb_binding_interface *afbitf, const char *message, ...);
518 ```
519
520 The first argument **afbitf** is the interface to afb daemon that the
521 binding received at initialisation time when **afbBindingV1Register** is called.
522
523 The second argument **message** is a formatting string compatible with printf/sprintf.
524
525 The remaining arguments are arguments of the formating message like with printf.
526
527 ### Managing verbosity
528
529 Depending on the level of verbosity, the messages are output or not.
530 The following table explains what messages will be output depending
531 ont the verbosity level.
532
533 Level of verbosity | Outputed macro
534 :-----------------:|--------------------------
535 0                  | ERROR
536 1                  | ERROR + WARNING + NOTICE
537 2                  | ERROR + WARNING + NOTICE + INFO
538 3                  | ERROR + WARNING + NOTICE + INFO + DEBUG
539
540 ### Output format and destination
541
542 The syslog level is used for forging a prefix to the message.
543 The prefixes are:
544
545 syslog level | prefix
546 :-----------:|---------------
547 0            | <0> EMERGENCY
548 1            | <1> ALERT
549 2            | <2> CRITICAL
550 3            | <3> ERROR
551 4            | <4> WARNING
552 5            | <5> NOTICE
553 6            | <6> INFO
554 7            | <7> DEBUG
555
556
557 The message is pushed to standard error.
558 The final destination of the message depends on how systemd service
559 was configured through its variable **StandardError**. It can be
560 journal, syslog or kmsg. (See man sd-daemon).
561
562 Sending events
563 --------------
564
565 Specific documentation exists about [sending events](afb-events-guide.md).
566
567 The binding *tic-tac-toe* broadcasts events when the board changes. This is done
568 in the function ***changed***:
569
570 ```C
571 /*
572  * signals a change of the board
573  */
574 static void changed(struct board *board, const char *reason)
575 {
576         ...
577         struct json_object *description;
578
579         /* get the description */
580         description = describe(board);
581
582         ...
583
584         afb_daemon_broadcast_event(afbitf->daemon, reason, description);
585 }
586 ```
587
588 The description of the changed board is pushed via the daemon interface.
589
590 Within binding *tic-tac-toe*, *reason* indicates the origin of
591 the change. In function **afb_daemon_broadcast_event** the second
592 parameter is the name of broadcasted event. The third argument is the
593 object that is transmitted with the event.
594
595 Function **afb_daemon_broadcast_event** is defined here after:
596
597 ```C
598 /*
599  * Broadcasts widely the event of 'name' with the data 'object'.
600  * 'object' can be NULL.
601  * 'daemon' MUST be the daemon given in interface when activating the binding.
602  *
603  * For convenience, the function calls 'json_object_put' for 'object'.
604  * Thus, in the case where 'object' should remain available after
605  * the function returns, the function 'json_object_get' shall be used.
606  */
607 void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
608 ```
609
610 > Be aware, as with reply functions **object** is automatically released using
611 > **json_object_put** when using this function. Call **json_object_get** before
612 > calling **afb_daemon_broadcast_event** to keep **object** available
613 > after function returns.
614
615 Event name received by listeners is prefixed with binding name.
616 So when a change occurs after a move, the reason is **move** and every clients
617 receive an event **tictactoe/move**.
618
619 > Note that nothing is said about case sensitivity of event names.
620 > However, the event is always prefixed with the name that the binding
621 > declared, with the same case, followed with a slash /.
622 > Thus it is safe to compare event using a case sensitive comparison.
623
624 Writing a synchronous method implementation
625 -----------------------------------------
626
627 The method **tictactoe/board** is a synchronous implementation.
628 Here is its listing:
629
630 ```C
631 /*
632  * get the board
633  */
634 static void board(struct afb_req req)
635 {
636         struct board *board;
637         struct json_object *description;
638
639         /* retrieves the context for the session */
640         board = board_of_req(req);
641         INFO(afbitf, "method 'board' called for boardid %d", board->id);
642
643         /* describe the board */
644         description = describe(board);
645
646         /* send the board's description */
647         afb_req_success(req, description, NULL);
648 }
649 ```
650
651 This example shows many aspects of a synchronous
652 method implementation. Let summarise it:
653
654 1. The function **board_of_req** retrieves the context stored
655 for the binding: the board.
656
657 2. The macro **INFO** sends a message of kind *INFO*
658 to the logging system. The global variable named **afbitf**
659 used represents the interface to ***afb-daemon***.
660
661 3. The function **describe** creates a json_object representing
662 the board.
663
664 4. The function **afb_req_success** sends the reply, attaching to
665 it the object *description*.
666
667 ### The incoming request
668
669 For any implementation, the request is received by a structure of type
670 **struct afb_req**.
671
672 > Note that this is a PLAIN structure, not a pointer to a structure.
673
674 The definition of **struct afb_req** is:
675
676 ```C
677 /*
678  * Describes the request by bindings from afb-daemon
679  */
680 struct afb_req {
681         const struct afb_req_itf *itf;  /* the interfacing functions */
682         void *closure;                  /* the closure for functions */
683 };
684 ```
685
686 It contains two pointers: first one *itf*, points to functions used
687 to handle internal request. Second one *closure* point onto function closure.
688
689 > The structure must never be used directly.
690 > Instead developer should use the intended functions provided
691 > by ***afb-daemon*** as described here after.
692
693 *req* is used to get arguments of the request, to send
694 answer, to store session data.
695
696 This object and its interface is defined and documented
697 in the file names *afb/afb-req-itf.h*
698
699 The above example uses twice *req* object request.
700
701 The first time, to retrieve the board attached to the session of the request.
702
703 The second time, to send the reply: an object that describes the current board.
704
705 ### Associating a client context to a session
706
707 When *tic-tac-toe* binding receives a request, it musts get
708 the board describing the game associated to the session.
709
710 For a binding, having data associated to a session is common.
711 This data is called "binding context" for the session.
712 Within *tic-tac-toe* binding the context is the board.
713
714 Requests *afb_req* offer four functions for storing and retrieving session
715 associated context.
716
717 These functions are:
718
719 - **afb_req_context_get**:
720   retrieves context data stored for current binding.
721
722 - **afb_req_context_set**:
723   store context data of current binding.
724
725 - **afb_req_context**:
726   if exist retrieves context data of current binding.
727   if context does not yet exist, creates a new context and store it.
728
729 - **afb_req_context_clear**:
730   reset the stored context data.
731
732 The binding *tictactoe* use a convenient function to retrieve
733 its context: the board. This function is *board_of_req*:
734
735 ```C
736 /*
737  * retrieves the board of the request
738  */
739 static inline struct board *board_of_req(struct afb_req req)
740 {
741         return afb_req_context(req, (void*)get_new_board, (void*)release_board);
742 }
743 ```
744
745 The function **afb_req_context** ensures an existing context
746 for the session of the request.
747 Its two last arguments are functions to allocate and free context.
748 Note function type casts to avoid compilation warnings.
749
750 Here is the definition of the function **afb_req_context**
751
752 ```C
753 /*
754  * Gets the pointer stored by the binding for the session of 'req'.
755  * If the stored pointer is NULL, indicating that no pointer was
756  * already stored, afb_req_context creates a new context by calling
757  * the function 'create_context' and stores it with the freeing function
758  * 'free_context'.
759  */
760 static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*))
761 {
762         void *result = afb_req_context_get(req);
763         if (result == NULL) {
764                 result = create_context();
765                 afb_req_context_set(req, result, free_context);
766         }
767         return result;
768 }
769 ```
770
771 The second argument if the function that creates the context.
772 For binding *tic-tac-toe* (function **get_new_board**).
773 The function **get_new_board** creates a new board and set usage its count to 1.
774 The boards are checking usage count to free resources when not used.
775
776 The third argument is a function that frees context resources.
777 For binding *tic-tac-toe* (function **release_board**).
778 The function **release_board** decrease usage count of the board passed in
779 argument. When usage count falls to zero, data board are freed.
780
781 Definition of other functions dealing with contexts:
782
783 ```C
784 /*
785  * Gets the pointer stored by the binding for the session of 'req'.
786  * When the binding has not yet recorded a pointer, NULL is returned.
787  */
788 void *afb_req_context_get(struct afb_req req);
789
790 /*
791  * Stores for the binding the pointer 'context' to the session of 'req'.
792  * The function 'free_context' will be called when the session is closed
793  * or if binding stores an other pointer.
794  */
795 void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));
796
797 /*
798  * Frees the pointer stored by the binding for the session of 'req'
799  * and sets it to NULL.
800  *
801  * Shortcut for: afb_req_context_set(req, NULL, NULL)
802  */
803 static inline void afb_req_context_clear(struct afb_req req)
804 {
805         afb_req_context_set(req, NULL, NULL);
806 }
807 ```
808
809 ### Sending reply to a request
810
811 Two kinds of replies: successful or failure.
812
813 > Sending a reply to a request MUST be done once and only once.
814
815 It exists two functions for "success" replies: **afb_req_success** and **afb_req_success_f**.
816
817 ```C
818 /*
819  * Sends a reply of kind success to the request 'req'.
820  * The status of the reply is automatically set to "success".
821  * Its send the object 'obj' (can be NULL) with an
822  * informationnal comment 'info (can also be NULL).
823  *
824  * For convenience, the function calls 'json_object_put' for 'obj'.
825  * Thus, in the case where 'obj' should remain available after
826  * the function returns, the function 'json_object_get' shall be used.
827  */
828 void afb_req_success(struct afb_req req, struct json_object *obj, const char *info);
829
830 /*
831  * Same as 'afb_req_success' but the 'info' is a formatting
832  * string followed by arguments.
833  *
834  * For convenience, the function calls 'json_object_put' for 'obj'.
835  * Thus, in the case where 'obj' should remain available after
836  * the function returns, the function 'json_object_get' shall be used.
837  */
838 void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
839 ```
840
841 It exists two functions for "failure" replies: **afb_req_fail** and **afb_req_fail_f**.
842
843 ```C
844 /*
845  * Sends a reply of kind failure to the request 'req'.
846  * The status of the reply is set to 'status' and an
847  * informational comment 'info' (can also be NULL) can be added.
848  *
849  * Note that calling afb_req_fail("success", info) is equivalent
850  * to call afb_req_success(NULL, info). Thus even if possible it
851  * is strongly recommended to NEVER use "success" for status.
852  *
853  * For convenience, the function calls 'json_object_put' for 'obj'.
854  * Thus, in the case where 'obj' should remain available after
855  * the function returns, the function 'json_object_get' shall be used.
856  */
857 void afb_req_fail(struct afb_req req, const char *status, const char *info);
858
859 /*
860  * Same as 'afb_req_fail' but the 'info' is a formatting
861  * string followed by arguments.
862  *
863  * For convenience, the function calls 'json_object_put' for 'obj'.
864  * Thus, in the case where 'obj' should remain available after
865  * the function returns, the function 'json_object_get' shall be used.
866  */
867 void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
868 ```
869
870 > For convenience, these functions automatically call **json_object_put** to release **obj**.
871 > Because **obj** usage count is null after being passed to a reply function, it SHOULD not be used anymore.
872 > If exceptionally **obj** needs to remain usable after reply function then using **json_object_get** on **obj**
873 > to increase usage count and cancels the effect the **json_object_put** is possible.
874
875 Getting argument of invocation
876 ------------------------------
877
878 Many methods expect arguments. Afb-daemon's bindings
879 retrieve arguments by name and not by position.
880
881 Arguments are passed by requests through either HTTP
882 or WebSockets.
883
884 For example, the method **join** of binding **tic-tac-toe**
885 expects one argument: the *boardid* to join. Here is an extract:
886
887 ```C
888 /*
889  * Join a board
890  */
891 static void join(struct afb_req req)
892 {
893         struct board *board, *new_board;
894         const char *id;
895
896         /* retrieves the context for the session */
897         board = board_of_req(req);
898         INFO(afbitf, "method 'join' called for boardid %d", board->id);
899
900         /* retrieves the argument */
901         id = afb_req_value(req, "boardid");
902         if (id == NULL)
903                 goto bad_request;
904         ...
905 ```
906
907 The function **afb_req_value** searches in the request *req*
908 for argument name passed in the second argument. When argument name
909 is not passed, **afb_req_value** returns NULL.
910
911 > The search is case sensitive and *boardid* is not equivalent to *BoardId*.
912 > Nevertheless having argument names that only differ by name case is not a good idea.
913
914 ### Basic functions for querying arguments
915
916 The function **afb_req_value** is defined here after:
917
918 ```C
919 /*
920  * Gets from the request 'req' the string value of the argument of 'name'.
921  * Returns NULL if when there is no argument of 'name'.
922  * Returns the value of the argument of 'name' otherwise.
923  *
924  * Shortcut for: afb_req_get(req, name).value
925  */
926 static inline const char *afb_req_value(struct afb_req req, const char *name)
927 {
928         return afb_req_get(req, name).value;
929 }
930 ```
931
932 It is defined as a shortcut to call the function **afb_req_get**.
933 That function is defined here after:
934
935 ```C
936 /*
937  * Gets from the request 'req' the argument of 'name'.
938  * Returns a PLAIN structure of type 'struct afb_arg'.
939  * When the argument of 'name' is not found, all fields of result are set to NULL.
940  * When the argument of 'name' is found, the fields are filled,
941  * in particular, the field 'result.name' is set to 'name'.
942  *
943  * There is a special name value: the empty string.
944  * The argument of name "" is defined only if the request was made using
945  * an HTTP POST of Content-Type "application/json". In that case, the
946  * argument of name "" receives the value of the body of the HTTP request.
947  */
948 struct afb_arg afb_req_get(struct afb_req req, const char *name);
949 ```
950
951 That function takes 2 parameters: the request and the name
952 of the argument to retrieve. It returns a PLAIN structure of
953 type **struct afb_arg**.
954
955 There is a special name that is defined when the request is
956 of type HTTP/POST with a Content-Type being application/json.
957 This name is **""** (the empty string). In that case, the value
958 of this argument of empty name is the string received as a body
959 of the post and is supposed to be a JSON string.
960
961 The definition of **struct afb_arg** is:
962
963 ```C
964 /*
965  * Describes an argument (or parameter) of a request
966  */
967 struct afb_arg {
968         const char *name;       /* name of the argument or NULL if invalid */
969         const char *value;      /* string representation of the value of the argument */
970                                 /* original filename of the argument if path != NULL */
971         const char *path;       /* if not NULL, path of the received file for the argument */
972                                 /* when the request is finalized this file is removed */
973 };
974 ```
975
976 The structure returns the data arguments that are known for the
977 request. This data include a field named **path**. This **path**
978 can be accessed using the function **afb_req_path** defined here after:
979
980 ```C
981 /*
982  * Gets from the request 'req' the path for file attached to the argument of 'name'.
983  * Returns NULL if when there is no argument of 'name' or when there is no file.
984  * Returns the path of the argument of 'name' otherwise.
985  *
986  * Shortcut for: afb_req_get(req, name).path
987  */
988 static inline const char *afb_req_path(struct afb_req req, const char *name)
989 {
990         return afb_req_get(req, name).path;
991 }
992 ```
993
994 The path is only defined for HTTP/POST requests that send file.
995
996 ### Arguments for received files
997
998 As it is explained above, clients can send files using HTTP/POST requests.
999
1000 Received files are attached to "file" argument name. For example, the
1001 following HTTP fragment (from test/sample-post.html)
1002 will send an HTTP/POST request to the method
1003 **post/upload-image** with 2 arguments named *file* and
1004 *hidden*.
1005
1006 ```html
1007 <h2>Sample Post File</h2>
1008 <form enctype="multipart/form-data">
1009     <input type="file" name="file" />
1010     <input type="hidden" name="hidden" value="bollobollo" />
1011     <br>
1012     <button formmethod="POST" formaction="api/post/upload-image">Post File</button>
1013 </form>
1014 ```
1015
1016 Argument named **file** should have both its value and path defined.
1017
1018 The value is the name of the file as it was set by the HTTP client.
1019 Generally it is the filename on client side.
1020
1021 The path is the effective path of saved file on the temporary local storage
1022 area of the application. This is a randomly generated and unique filename.
1023 It is not linked with the original filename as used on client side.
1024
1025 After success the binding can use the uploaded file directly from local storage path with no restriction:
1026 read, write, remove, copy, rename...
1027 Nevertheless when request reply is set and query terminated, the uploaded temporary file at
1028 path is destroyed.
1029
1030 ### Arguments as a JSON object
1031
1032 Bindings may also request every arguments of a given call as one single object.
1033 This feature is provided by the function **afb_req_json** defined here after:
1034
1035 ```C
1036 /*
1037  * Gets from the request 'req' the json object hashing the arguments.
1038  * The returned object must not be released using 'json_object_put'.
1039  */
1040 struct json_object *afb_req_json(struct afb_req req);
1041 ```
1042
1043 It returns a json object. This object depends on how the request was built:
1044
1045 - For HTTP requests, this json object uses key names mapped on argument name.
1046 Values are either string for common arguments or object ie: { "file": "...", "path": "..." }
1047
1048 - For WebSockets requests, returned directly the object as provided by the client.
1049
1050 > In fact, for Websockets requests, the function **afb_req_value**
1051 > can be seen as a shortcut to
1052 > ***json_object_get_string(json_object_object_get(afb_req_json(req), name))***
1053
1054
1055 Writing an asynchronous method implementation
1056 -------------------------------------------
1057
1058 The *tic-tac-toe* example allows two clients or more to share the same board.
1059 This is implemented by the method **join** that illustrated partly how to
1060 retrieve arguments.
1061
1062 When two or more clients are sharing a same board, one of them can wait
1063 until the state of the board changes, but this could also be implemented using
1064 events because an event is generated each time the board changes.
1065
1066 In this case, the reply to the wait is sent only when the board changes.
1067 See the diagram below:
1068
1069 ![tic-tac-toe_diagram][tic-tac-toe_diagram]
1070
1071 Here, this is an invocation of the binding by an other client that
1072 unblock the suspended *wait* call.
1073 Nevertheless in most case this should be a timer, a hardware event, a sync with
1074 a concurrent process or thread, ...
1075
1076 Common case of an asynchronous implementation.
1077
1078 Here is the listing of the function **wait**:
1079
1080 ```C
1081 static void wait(struct afb_req req)
1082 {
1083         struct board *board;
1084         struct waiter *waiter;
1085
1086         /* retrieves the context for the session */
1087         board = board_of_req(req);
1088         INFO(afbitf, "method 'wait' called for boardid %d", board->id);
1089
1090         /* creates the waiter and enqueues it */
1091         waiter = calloc(1, sizeof *waiter);
1092         waiter->req = req;
1093         waiter->next = board->waiters;
1094         afb_req_addref(req);
1095         board->waiters = waiter;
1096 }
1097 ```
1098
1099 After retrieving the board, the function adds a new waiter to
1100 waiters list and returns without setting a reply.
1101
1102 Before returning, it increases **req** request's reference count using **afb_req_addref** function.
1103
1104 > When a method returns without setting a reply,
1105 > it **MUST** increment request's reference count
1106 > using **afb_req_addref**. If unpredictable behaviour may pop up.
1107
1108 Later, when a board changes, it calls *tic-tac-toe* **changed** function
1109 with reason of change in parameter.
1110
1111 Here is the full listing of the function **changed**:
1112
1113 ```C
1114 /*
1115  * signals a change of the board
1116  */
1117 static void changed(struct board *board, const char *reason)
1118 {
1119         struct waiter *waiter, *next;
1120         struct json_object *description;
1121
1122         /* get the description */
1123         description = describe(board);
1124
1125         waiter = board->waiters;
1126         board->waiters = NULL;
1127         while (waiter != NULL) {
1128                 next = waiter->next;
1129                 afb_req_success(waiter->req, json_object_get(description), reason);
1130                 afb_req_unref(waiter->req);
1131                 free(waiter);
1132                 waiter = next;
1133         }
1134
1135         afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description);
1136 }
1137 ```
1138
1139 The list of waiters is walked and a reply is sent to each waiter.
1140 After sending the reply, the reference count of the request
1141 is decremented using **afb_req_unref** to allow resources to be freed.
1142
1143 > The reference count **MUST** be decremented using **afb_req_unref** to free
1144 > resources and avoid memory leaks.
1145 > This usage count decrement should happen **AFTER** setting reply or
1146 > bad things may happen.
1147
1148 Sending messages to the log system
1149 ----------------------------------
1150
1151 Afb-daemon provides 4 levels of verbosity and 5 methods for logging messages.
1152
1153 The verbosity is managed. Options allow the change the verbosity of ***afb-daemon***
1154 and the verbosity of the bindings can be set binding by binding.
1155
1156 The methods for logging messages are defined as macros that test the
1157 verbosity level and that call the real logging function only if the
1158 message must be output. This avoid evaluation of arguments of the
1159 formatting messages if the message must not be output.
1160
1161 ### Verbs for logging messages
1162
1163 The 5 logging methods are:
1164
1165 Macro   | Verbosity | Meaning                           | syslog level
1166 --------|:---------:|-----------------------------------|:-----------:
1167 ERROR   |     0     | Error conditions                  |     3
1168 WARNING |     1     | Warning conditions                |     4
1169 NOTICE  |     1     | Normal but significant condition  |     5
1170 INFO    |     2     | Informational                     |     6
1171 DEBUG   |     3     | Debug-level messages              |     7
1172
1173 You can note that the 2 methods **WARNING** and **NOTICE** have the same level
1174 of verbosity. But they don't have the same *syslog level*. It means that
1175 they are output with a different level on the logging system.
1176
1177 All of these methods have the same signature:
1178
1179 ```C
1180 void ERROR(const struct afb_binding_interface *afbitf, const char *message, ...);
1181 ```
1182
1183 The first argument **afbitf** is the interface to afb daemon that the
1184 binding received at initialisation time when **afbBindingV1Register** is called.
1185
1186 The second argument **message** is a formatting string compatible with printf/sprintf.
1187
1188 The remaining arguments are arguments of the formating message like with printf.
1189
1190 ### Managing verbosity
1191
1192 Depending on the level of verbosity, the messages are output or not.
1193 The following table explains what messages will be output depending
1194 ont the verbosity level.
1195
1196 Level of verbosity | Outputed macro
1197 :-----------------:|--------------------------
1198 0                  | ERROR
1199 1                  | ERROR + WARNING + NOTICE
1200 2                  | ERROR + WARNING + NOTICE + INFO
1201 3                  | ERROR + WARNING + NOTICE + INFO + DEBUG
1202
1203 ### Output format and destination
1204
1205 The syslog level is used for forging a prefix to the message.
1206 The prefixes are:
1207
1208 syslog level | prefix
1209 :-----------:|---------------
1210 0            | <0> EMERGENCY
1211 1            | <1> ALERT
1212 2            | <2> CRITICAL
1213 3            | <3> ERROR
1214 4            | <4> WARNING
1215 5            | <5> NOTICE
1216 6            | <6> INFO
1217 7            | <7> DEBUG
1218
1219
1220 The message is pushed to standard error.
1221 The final destination of the message depends on how systemd service
1222 was configured through its variable **StandardError**. It can be
1223 journal, syslog or kmsg. (See man sd-daemon).
1224
1225 Sending events
1226 --------------
1227
1228 Since version 0.5, bindings can broadcast events to any potential listener.
1229 As today only unattended events are supported. Targeted events are expected for
1230 next coming version.
1231
1232 The binding *tic-tac-toe* broadcasts events when the board changes.
1233 This is done in the function **changed**:
1234
1235 ```C
1236 /*
1237  * signals a change of the board
1238  */
1239 static void changed(struct board *board, const char *reason)
1240 {
1241         ...
1242         struct json_object *description;
1243
1244         /* get the description */
1245         description = describe(board);
1246
1247         ...
1248
1249         afb_daemon_broadcast_event(afbitf->daemon, reason, description);
1250 }
1251 ```
1252
1253 The description of the changed board is pushed via the daemon interface.
1254
1255 Within binding *tic-tac-toe*, *reason* indicates the origin of
1256 the change. In function **afb_daemon_broadcast_event** the second
1257 parameter is the name of broadcasted event. The third argument is the
1258 object that is transmitted with the event.
1259
1260 Function **afb_daemon_broadcast_event** is defined here after:
1261
1262 ```C
1263 /*
1264  * Broadcasts widely the event of 'name' with the data 'object'.
1265  * 'object' can be NULL.
1266  * 'daemon' MUST be the daemon given in interface when activating the binding.
1267  *
1268  * For convenience, the function calls 'json_object_put' for 'object'.
1269  * Thus, in the case where 'object' should remain available after
1270  * the function returns, the function 'json_object_get' shall be used.
1271  */
1272 void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
1273 ```
1274
1275 > Be aware, as with reply functions **object** is automatically released using
1276 > **json_object_put** when using this function. Call **json_object_get** before
1277 > calling **afb_daemon_broadcast_event** to keep **object** available
1278 > after function returns.
1279
1280 Event name received by listeners is prefixed with binding name.
1281 So when a change occurs after a move, the reason is **move** and every clients
1282 receive an event **tictactoe/move**.
1283
1284 > Note that nothing is said about case sensitivity of event names.
1285 > However, the event is always prefixed with the name that the binding
1286 > declared, with the same case, followed with a slash /.
1287 > Thus it is safe to compare event using a case sensitive comparison.
1288
1289 How to build a binding
1290 ---------------------
1291
1292 Afb-daemon provides a *pkg-config* configuration file that can be
1293 queried by providing ***afb-daemon*** in command line arguments.
1294 This configuration file provides data that should be used
1295 for bindings compilation. Examples:
1296
1297 ```bash
1298 $ pkg-config --cflags afb-daemon
1299 $ pkg-config --libs afb-daemon
1300 ```
1301
1302 ### Example for cmake meta build system
1303
1304 This example is the extract for building the binding *afm-main* using *CMAKE*.
1305
1306 ```cmake
1307 pkg_check_modules(afb afb-daemon)
1308 if(afb_FOUND)
1309         message(STATUS "Creation afm-main-binding for AFB-DAEMON")
1310         add_library(afm-main-binding MODULE afm-main-binding.c)
1311         target_compile_options(afm-main-binding PRIVATE ${afb_CFLAGS})
1312         target_include_directories(afm-main-binding PRIVATE ${afb_INCLUDE_DIRS})
1313         target_link_libraries(afm-main-binding utils ${afb_LIBRARIES})
1314         set_target_properties(afm-main-binding PROPERTIES
1315                 PREFIX ""
1316                 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-binding.export-map"
1317         )
1318         install(TARGETS afm-main-binding LIBRARY DESTINATION ${binding_dir})
1319 else()
1320         message(STATUS "Not creating the binding for AFB-DAEMON")
1321 endif()
1322 ```
1323
1324 Let now describe some of these lines.
1325
1326 ```cmake
1327 pkg_check_modules(afb afb-daemon)
1328 ```
1329
1330 This first lines searches to the *pkg-config* configuration file for
1331 **afb-daemon**. Resulting data are stored in the following variables:
1332
1333 Variable          | Meaning
1334 ------------------|------------------------------------------------
1335 afb_FOUND         | Set to 1 if afb-daemon binding development files exist
1336 afb_LIBRARIES     | Only the libraries (w/o the '-l') for compiling afb-daemon bindings
1337 afb_LIBRARY_DIRS  | The paths of the libraries (w/o the '-L') for compiling afb-daemon bindings
1338 afb_LDFLAGS       | All required linker flags for compiling afb-daemon bindings
1339 afb_INCLUDE_DIRS  | The '-I' preprocessor flags (w/o the '-I') for compiling afb-daemon bindings
1340 afb_CFLAGS        | All required cflags for compiling afb-daemon bindings
1341
1342 If development files are found, the binding can be added to the set of
1343 target to build.
1344
1345 ```cmake
1346 add_library(afm-main-binding MODULE afm-main-binding.c)
1347 ```
1348
1349 This line asks to create a shared library having a single
1350 source file named afm-main-binding.c to be compiled.
1351 The default name of the created shared object is
1352 **libafm-main-binding.so**.
1353
1354 ```cmake
1355 set_target_properties(afm-main-binding PROPERTIES
1356         PREFIX ""
1357         LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-binding.export-map"
1358 )
1359 ```
1360
1361 This lines are doing two things:
1362
1363 1. It renames the built library from **libafm-main-binding.so** to **afm-main-binding.so**
1364 by removing the implicitly added prefix *lib*. This step is not mandatory
1365 because afb-daemon doesn't check names of files at load time.
1366 The only filename convention used by afb-daemon relates to **.so** termination.
1367 *.so pattern is used when afb-daemon automatically discovers binding from a directory hierarchy.
1368
1369 2. It applies a version script at link time to only export the reserved name
1370 **afbBindingV1Register** for registration entry point. By default, when building
1371 a shared library linker exports all the public symbols (C functions that are not **static**).
1372
1373 Next line are:
1374
1375 ```cmake
1376 target_include_directories(afm-main-binding PRIVATE ${afb_INCLUDE_DIRS})
1377 target_link_libraries(afm-main-binding utils ${afb_LIBRARIES})
1378 ```
1379
1380 As you can see it uses the variables computed by ***pkg_check_modules(afb afb-daemon)***
1381 to configure the compiler and the linker.
1382
1383 ### Exporting the function afbBindingV1Register
1384
1385 The function **afbBindingV1Register** MUST be exported. This can be achieved
1386 using a version script at link time. Here after is a version script used for
1387 *tic-tac-toe* (bindings/samples/export.map).
1388
1389         { global: afbBindingV1Register; local: *; };
1390
1391 This sample [version script](https://sourceware.org/binutils/docs-2.26/ld/VERSION.html#VERSION)
1392 exports as global the symbol *afbBindingV1Register* and hides any
1393 other symbols.
1394
1395 This version script is added to the link options using the
1396 option **--version-script=export.map** is given directly to the
1397 linker or using the option **-Wl,--version-script=export.map**
1398 when the option is given to the C compiler.
1399
1400 ### Building within yocto
1401
1402 Adding a dependency to afb-daemon is enough. See below:
1403
1404         DEPENDS += " afb-daemon "
1405
1406
1407 [tic-tac-toe_diagram]: pictures/tic-tac-toe.svg