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