7861021bbf5423f9af80bd0f25512f253becb8b0
[src/app-framework-binder.git] / doc / afb-plugin-writing.md
1 HOWTO WRITE a PLUGIN for AFB-DAEMON
2 ===================================
3     version: 1
4     Date:    27 mai 2016
5     Author:  José Bollo
6
7 TABLE-OF-CONTENT-HERE
8
9 Summary
10 -------
11
12 The binder afb-daemon serves files through
13 the HTTP protocol and offers access to API's through
14 HTTP or WebSocket protocol.
15
16 The plugins are used to add API's to afb-daemon.
17 This part describes how to write a plugin for afb-daemon.
18 Excepting this summary, this part is intended to be read
19 by developpers.
20
21 Before going into details, through a tiny example,
22 a short overview plugins basis is needed.
23
24 ### Nature of a plugin
25
26 A plugin is a separate piece of code made of a shared library.
27 The plugin is loaded and activated by afb-daemon when afb-daemon
28 starts.
29
30 Technically, a plugin is not linked to any library of afb-daemon.
31
32 ### Kinds of plugins
33
34 There is two kinds of plugins: application plugins and service
35 plugins.
36
37 #### Application plugins
38
39 Application plugins are intended to be instanciated for each
40 application: when an application using that plugin is started,
41 its binder starts a new instance of the plugin.
42
43 It means that the application plugins mainly have only one
44 context to manage for one client.
45
46 #### Service plugins
47
48 Service plugins are intended to be instanciated only one time
49 only and connected to many clients.
50
51 So either it does not manage context at all or otherwise,
52 if it manages context, it should be able to manage one context
53 per client.
54
55 In details, it may be useful to have service plugins at a user
56 level.
57  
58 ### Live cycle of a plugin within afb-daemon
59
60 The plugins are loaded and activated when afb-daemon starts.
61
62 At start, the plugin initialise itself.
63 If it fails to initialise then afb-daemon stops.
64
65 Conversely, if it success to initialize, it must declare
66 a name, that must be unique, and a list of API's verbs.
67
68 When initialized, the functions implementing the API's verbs
69 of the plugin are activated on call.
70
71 At the end, nothing special is done by afb-daemon.
72 Consequently, developpers of plugins should use 'atexit'
73 or 'on_exit' during initialisation if they need to
74 perform specific actions when stopping.
75
76 ### Content of a plugin
77
78 For afb-daemon, a plugin contains 2 different
79 things: names and functions.
80
81 There is two kind of names:
82  - the name of the plugin,
83  - the names of the verbs.
84
85 There is two kind of functions:
86  - the initialisation function
87  - functions implementing verbs
88
89 Afb-daemon translates the name of the method that is
90 invoked to a pair of API and verb names. For example,
91 the method named **foo/bar** translated to the API
92 name **foo** and the verb name **bar**.
93 To serve it, afb-daemon search the plugin that record
94 the name **foo** and if it also recorded the verb **bar**,
95 it calls the implementation function declared for this verb.
96
97 Afb-daemon make no distinction between lower case
98 and upper case when searching for a method.
99 Thus, The names **TicTacToe/Board** and **tictactoe/borad**
100 are equals.
101
102 #### The name of the plugin
103
104 The name of the plugin is also known as the name
105 of the API that defines the plugin.
106
107 This name is also known as the prefix.
108
109 The name of a plugin MUST be unique within afb-daemon.
110
111 For example, when a client of afb-daemon
112 calls a method named **foo/bar**. Afb-daemon
113 extracts the prefix **foo** and the suffix **bar**.
114 **foo** is the API name and must match a plugin name,
115 the plugin that implements the verb **bar**.
116
117 #### Names of verbs
118
119 Each plugin exposes a set of verbs that can be called
120 by client of afb-daemon.
121
122 The name of a verb MUST be unique within a plugin.
123
124 Plugins link verbs to functions that are called
125 when clients emit requests for that verb.
126
127 For example, when a client of afb-daemon
128 calls a method named **foo/bar**.
129
130 #### The initialisation function
131
132 The initialisation function serves several purposes.
133
134 1. It allows afb-daemon to check the version
135 of the plugin using the name of the initialisation
136 functions that it found. Currently, the initialisation
137 function is named **pluginAfbV1Register**. It identifies
138 the first version of plugins.
139
140 2. It allows the plugin to initialise itself.
141
142 3. It serves to the plugin to declare names, descriptions,
143 requirements and implmentations of the verbs that it exposes.
144
145 #### Functions implementing verbs
146
147 When a method is called, afb-daemon constructs a request
148 object and pass it to the implementation function for verb
149 within the plugin of the API.
150
151 An implementation function receives a request object that
152 is used to get arguments of the request, to send
153 answer, to store session data.
154
155 A plugin MUST send an answer to the request.
156
157 But it is not mandatory to send the answer
158 before to return from the implementing function.
159 This behaviour is important for implementing
160 asynchronous actions.
161
162 Implementation functions that always reply to the request
163 before returning are named *synchronous implementations*.
164 Those that don't always reply to the request before
165 returning are named *asynchronous implementations*.
166
167 Asynchronous implementations typically initiate an
168 asynchronous action and record to send the reply
169 on completion of this action.
170
171 The Tic-Tac-Toe example
172 -----------------------
173
174 This part explains how to write an afb-plugin.
175 For the sake of being practical we will use many
176 examples from the tic-tac-toe example.
177 This plugin example is in *plugins/samples/tic-tac-toe.c*.
178
179 This plugin is named ***tictactoe***.
180
181 Dependencies when compiling
182 ---------------------------
183
184 Afb-daemon provides a configuration file for *pkg-config*.
185 Typing the command
186
187         pkg-config --cflags afb-daemon
188
189 will print the flags to use for compiling, like this:
190
191         $ pkg-config --cflags afb-daemon
192         -I/opt/local/include -I/usr/include/json-c 
193
194 For linking, you should use
195
196         $ pkg-config --libs afb-daemon
197         -ljson-c
198
199 As you see, afb-daemon automatically includes dependency to json-c.
200 This is done through the **Requires** keyword of pkg-config
201 because almost all plugin will use **json-c**.
202
203 If this behaviour is a problem, let us know.
204
205 Internally, afb-daemon uses **libsystemd** for its event loop
206 and for its binding to D-Bus.
207 Plugins developpers are encouraged to also use this library.
208 But it is a matter of choice.
209 Thus there is no dependency to **libsystemd**.
210
211 > Afb-daemon provides no library for plugins.
212 > The functions that the plugin need to have are given
213 > to the plugin at runtime through pointer using read-only
214 > memory.
215
216 Header files to include
217 -----------------------
218
219 The plugin *tictactoe* has the following lines for its includes:
220
221         #define _GNU_SOURCE
222         #include <stdio.h>
223         #include <string.h>
224         #include <json-c/json.h>
225         #include <afb/afb-plugin.h>
226
227 The header *afb/afb-plugin.h* includes all the features that a plugin
228 needs except two foreign header that must be included by the plugin
229 if it needs it:
230
231 - *json-c/json.h*: this header must be include to handle json objects;
232 - *systemd/sd-event.h*: this must be include to access the main loop;
233 - *systemd/sd-bus.h*: this may be include to use dbus connections.
234
235 The *tictactoe* plugin does not use systemd features so it is not included.
236
237 When including *afb/afb-plugin.h*, the macro **_GNU_SOURCE** must be
238 defined.
239
240 Choosing names
241 --------------
242
243 The designer of a plugin must defines names for its plugin
244 (or its API) and for the verbs of its API. He also
245 must defines names for arguments given by name.
246
247 While forging names, the designer should take into account
248 the rules for making valid names and some rules that make
249 the names easy to use across plaforms.
250
251 The names and strings used ALL are UTF-8 encoded.
252
253 ### Names for API (plugin)
254
255 The names of the API are checked.
256 All characters are authorised except:
257
258 - the control characters (\u0000 .. \u001f)
259 - the characters of the set { ' ', '"', '#', '%', '&',
260   '\'', '/', '?', '`', '\x7f' }
261
262 In other words the set of forbidden characters is
263 { \u0000..\u0020, \u0022, \u0023, \u0025..\u0027,
264   \u002f, \u003f, \u0060, \u007f }.
265
266 Afb-daemon make no distinction between lower case
267 and upper case when searching for an API by its name.
268
269 ### Names for verbs
270
271 The names of the verbs are not checked.
272
273 However, the validity rules for verb's names are the
274 same as for API's names except that the dot (.) character
275 is forbidden.
276
277 Afb-daemon make no distinction between lower case
278 and upper case when searching for an API by its name.
279
280 ### Names for arguments
281
282 The names for arguments are not restricted and can be
283 anything.
284
285 The arguments are searched with the case sensitive
286 string comparison. Thus the names "index" and "Index"
287 are not the same.
288
289 ### Forging names widely available
290
291 The key names of javascript object can be almost
292 anything using the arrayed notation:
293
294         object[key] = value
295
296 That is not the case with the dot notation:
297
298         object.key = value
299
300 Using the dot notation, the key must be a valid javascript
301 identifier.
302
303 For this reason, the chosen names should better be
304 valid javascript identifier.
305
306 It is also a good practice, even for arguments, to not
307 rely on the case sensitivity and to avoid the use of
308 names different only by the case.
309
310 Writing a synchronous verb implementation
311 -----------------------------------------
312
313 The verb **tictactoe/board** is a synchronous implementation.
314 Here is its listing:
315
316         /*
317          * get the board
318          */
319         static void board(struct afb_req req)
320         {
321                 struct board *board;
322                 struct json_object *description;
323
324                 /* retrieves the context for the session */
325                 board = board_of_req(req);
326                 INFO(afbitf, "method 'board' called for boardid %d", board->id);
327
328                 /* describe the board */
329                 description = describe(board);
330
331                 /* send the board's description */
332                 afb_req_success(req, description, NULL);
333         }
334
335 This examples show many aspects of writing a synchronous
336 verb implementation. Let summarize it:
337
338 1. The function **board_of_req** retrieves the context stored
339 for the plugin: the board.
340
341 2. The macro **INFO** sends a message of kind *INFO*
342 to the logging system. The global variable named **afbitf**
343 used represents the interface to afb-daemon.
344
345 3. The function **describe** creates a json_object representing
346 the board.
347
348 4. The function **afb_req_success** sends the reply, attaching to
349 it the object *description*.
350
351 ### The incoming request
352
353 For any implementation, the request is received by a structure of type
354 **struct afb_req**.
355
356 > Note that this is a PLAIN structure, not a pointer to a structure.
357
358 The definition of **struct afb_req** is:
359
360         /*
361          * Describes the request by plugins from afb-daemon
362          */
363         struct afb_req {
364                 const struct afb_req_itf *itf;  /* the interfacing functions */
365                 void *closure;                  /* the closure for functions */
366         };
367
368 It contains two pointers: one, *itf*, points to the functions needed
369 to handle the internal request represented by the second pointer, *closure*.
370
371 > The structure must never be used directly.
372 > Insted, use the intended functions provided
373 > by afb-daemon and described here.
374
375 *req* is used to get arguments of the request, to send
376 answer, to store session data.
377
378 This object and its interface is defined and documented
379 in the file names *afb/afb-req-itf.h*
380
381 The above example uses 2 times the request object *req*.
382
383 The first time, it is used for retrieving the board attached to
384 the session of the request.
385
386 The second time, it is used to send the reply: an object that
387 describes the current board.
388
389 ### Associating a context to the session
390
391 When the plugin *tic-tac-toe* receives a request, it musts regain
392 the board that describes the game associated to the session.
393
394 For a plugin, having data associated to a session is a common case.
395 This data is called the context of the plugin for the session.
396 For the plugin *tic-tac-toe*, the context is the board.
397
398 The requests *afb_req* offer four functions for
399 storing and retrieving the context associated to the session.
400
401 These functions are:
402
403 - **afb_req_context_get**:
404   retrieves the context data stored for the plugin.
405
406 - **afb_req_context_set**:
407   store the context data of the plugin.
408
409 - **afb_req_context**:
410   retrieves the context data of the plugin,
411   if needed, creates the context and store it.
412
413 - **afb_req_context_clear**:
414   reset the stored data.
415
416 The plugin *tictactoe* use a convenient function to retrieve
417 its context: the board. This function is *board_of_req*:
418
419         /*
420          * retrieves the board of the request
421          */
422         static inline struct board *board_of_req(struct afb_req req)
423         {
424                 return afb_req_context(req, (void*)get_new_board, (void*)release_board);
425         }
426
427 The function **afb_req_context** ensure an existing context
428 for the session of the request.
429 Its two last arguments are functions. Here, the casts are required
430 to avoid a warning when compiling.
431
432 Here is the definition of the function **afb_req_context**
433
434         /*
435          * Gets the pointer stored by the plugin for the session of 'req'.
436          * If the stored pointer is NULL, indicating that no pointer was
437          * already stored, afb_req_context creates a new context by calling
438          * the function 'create_context' and stores it with the freeing function
439          * 'free_context'.
440          */
441         static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*))
442         {
443                 void *result = afb_req_context_get(req);
444                 if (result == NULL) {
445                         result = create_context();
446                         afb_req_context_set(req, result, free_context);
447                 }
448                 return result;
449         }
450
451 The second argument if the function that creates the context.
452 For the plugin *tic-tac-toe* it is the function **get_new_board**.
453 The function **get_new_board** creates a new board and set its
454 count of use to 1. The boards are counting their count of use
455 to free there ressources when no more used.
456
457 The third argument if the function that frees the context.
458 For the plugin *tic-tac-toe* it is the function **release_board**.
459 The function **release_board** decrease the the count of use of
460 the board given as argument. If the use count decrease to zero,
461 the board data are freed.
462
463 The definition of the other functions for dealing with contexts are:
464
465         /*
466          * Gets the pointer stored by the plugin for the session of 'req'.
467          * When the plugin has not yet recorded a pointer, NULL is returned.
468          */
469         void *afb_req_context_get(struct afb_req req);
470
471         /*
472          * Stores for the plugin the pointer 'context' to the session of 'req'.
473          * The function 'free_context' will be called when the session is closed
474          * or if plugin stores an other pointer.
475          */
476         void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));
477
478         /*
479          * Frees the pointer stored by the plugin for the session of 'req'
480          * and sets it to NULL.
481          *
482          * Shortcut for: afb_req_context_set(req, NULL, NULL)
483          */
484         static inline void afb_req_context_clear(struct afb_req req)
485         {
486                 afb_req_context_set(req, NULL, NULL);
487         }
488
489 ### Sending the reply to a request
490
491 Two kinds of replies can be made: successful replies and
492 failure replies.
493
494 > Sending a reply to a request must be done at most one time.
495
496 The two functions to send a reply of kind "success" are
497 **afb_req_success** and **afb_req_success_f**.
498
499         /*
500          * Sends a reply of kind success to the request 'req'.
501          * The status of the reply is automatically set to "success".
502          * Its send the object 'obj' (can be NULL) with an
503          * informationnal comment 'info (can also be NULL).
504          */
505         void afb_req_success(struct afb_req req, struct json_object *obj, const char *info);
506
507         /*
508          * Same as 'afb_req_success' but the 'info' is a formatting
509          * string followed by arguments.
510          */
511         void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
512
513 The two functions to send a reply of kind "failure" are
514 **afb_req_fail** and **afb_req_fail_f**.
515
516         /*
517          * Sends a reply of kind failure to the request 'req'.
518          * The status of the reply is set to 'status' and an
519          * informationnal comment 'info' (can also be NULL) can be added.
520          *
521          * Note that calling afb_req_fail("success", info) is equivalent
522          * to call afb_req_success(NULL, info). Thus even if possible it
523          * is strongly recommanded to NEVER use "success" for status.
524          */
525         void afb_req_fail(struct afb_req req, const char *status, const char *info);
526
527         /*
528          * Same as 'afb_req_fail' but the 'info' is a formatting
529          * string followed by arguments.
530          */
531         void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
532
533 Getting argument of invocation
534 ------------------------------
535
536 Many verbs expect arguments. Afb-daemon let plugins
537 retrieve their arguments by name not by position.
538
539 Arguments are given by the requests either through HTTP
540 or through WebSockets.
541
542 For example, the verb **join** of the plugin **tic-tac-toe**
543 expects one argument: the *boardid* to join. Here is an extract:
544
545         /*
546          * Join a board
547          */
548         static void join(struct afb_req req)
549         {
550                 struct board *board, *new_board;
551                 const char *id;
552
553                 /* retrieves the context for the session */
554                 board = board_of_req(req);
555                 INFO(afbitf, "method 'join' called for boardid %d", board->id);
556
557                 /* retrieves the argument */
558                 id = afb_req_value(req, "boardid");
559                 if (id == NULL)
560                         goto bad_request;
561                 ...
562
563 The function **afb_req_value** search in the request *req*
564 for an argument whose name is given. When no argument of the
565 given name was passed, **afb_req_value** returns NULL.
566
567 > The search is case sensitive. So the name *boardid* is not the
568 > same name than *BoardId*. But this must not be assumed so two
569 > expected names of argument should not differ only by case.
570
571 ### Basic functions for querying arguments
572
573 The function **afb_req_value** is defined as below:
574
575         /*
576          * Gets from the request 'req' the string value of the argument of 'name'.
577          * Returns NULL if when there is no argument of 'name'.
578          * Returns the value of the argument of 'name' otherwise.
579          *
580          * Shortcut for: afb_req_get(req, name).value
581          */
582         static inline const char *afb_req_value(struct afb_req req, const char *name)
583         {
584                 return afb_req_get(req, name).value;
585         }
586
587 It is defined as a shortcut to call the function **afb_req_get**.
588 That function is defined as below:
589
590         /*
591          * Gets from the request 'req' the argument of 'name'.
592          * Returns a PLAIN structure of type 'struct afb_arg'.
593          * When the argument of 'name' is not found, all fields of result are set to NULL.
594          * When the argument of 'name' is found, the fields are filled,
595          * in particular, the field 'result.name' is set to 'name'.
596          *
597          * There is a special name value: the empty string.
598          * The argument of name "" is defined only if the request was made using
599          * an HTTP POST of Content-Type "application/json". In that case, the
600          * argument of name "" receives the value of the body of the HTTP request.
601          */
602         struct afb_arg afb_req_get(struct afb_req req, const char *name);
603
604 That function takes 2 parameters: the request and the name
605 of the argument to retrieve. It returns a PLAIN structure of
606 type **struct afb_arg**.
607
608 There is a special name that is defined when the request is
609 of type HTTP/POST with a Content-Type being application/json.
610 This name is **""** (the empty string). In that case, the value
611 of this argument of empty name is the string received as a body
612 of the post and is supposed to be a JSON string.
613
614 The definition of **struct afb_arg** is:
615
616         /*
617          * Describes an argument (or parameter) of a request
618          */
619         struct afb_arg {
620                 const char *name;       /* name of the argument or NULL if invalid */
621                 const char *value;      /* string representation of the value of the argument */
622                                         /* original filename of the argument if path != NULL */
623                 const char *path;       /* if not NULL, path of the received file for the argument */
624                                         /* when the request is finalized this file is removed */
625         };
626
627 The structure returns the data arguments that are known for the
628 request. This data include a field named **path**. This **path**
629 can be accessed using the function **afb_req_path** defined as
630 below:
631
632         /*
633          * Gets from the request 'req' the path for file attached to the argument of 'name'.
634          * Returns NULL if when there is no argument of 'name' or when there is no file.
635          * Returns the path of the argument of 'name' otherwise.
636          *
637          * Shortcut for: afb_req_get(req, name).path
638          */
639         static inline const char *afb_req_path(struct afb_req req, const char *name)
640         {
641                 return afb_req_get(req, name).path;
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 just above, clients can send files using
649 HTTP/POST requests.
650
651 Received files are attached to a arguments. For example, the
652 following HTTP fragment (from test/sample-post.html)
653 will send an HTTP/POST request to the method
654 **post/upload-image** with 2 arguments named *file* and
655 *hidden*.
656
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 In that case, the argument named **file** has its value and its
666 path defined and not NULL.
667
668 The value is the name of the file as it was
669 set by the HTTP client and is generally the filename on the
670 client side.
671
672 The path is the path of the file saved on the temporary local storage
673 area of the application. This is a randomly generated and unic filename
674 not linked in any way with the original filename on the client.
675
676 The plugin can use the file at the given path the way that it wants:
677 read, write, remove, copy, rename...
678 But when the reply is sent and the query is terminated, the file at
679 this path is destroyed if it still exist.
680
681 ### Arguments as a JSON object
682
683 Plugins can get all the arguments as one single object.
684 This feature is provided by the function **afb_req_json**
685 that is defined as below:
686
687         /*
688          * Gets from the request 'req' the json object hashing the arguments.
689          * The returned object must not be released using 'json_object_put'.
690          */
691         struct json_object *afb_req_json(struct afb_req req);
692
693 It returns a json object. This object depends on how the request was
694 made:
695
696 - For HTTP requests, this is an object whose keys are the names of the
697 arguments and whose values are either a string for common arguments or
698 an object like { "file": "...", "path": "..." }
699
700 - For WebSockets requests, the returned object is the object
701 given by the client transparently transported.
702
703 > In fact, for Websockets requests, the function **afb_req_value**
704 > can be seen as a shortcut to
705 > ***json_object_get_string(json_object_object_get(afb_req_json(req), name))***
706
707 Initialisation of the plugin and declaration of verbs
708 -----------------------------------------------------
709
710 To be active, the verbs of the plugin should be declared to
711 afb-daemon. And even more, the plugin itself must be recorded.
712
713 The mechanism for doing this is very simple: when afb-need starts,
714 it loads the plugins that are listed in its argument or configuration.
715
716 Loading a plugin follows the following steps:
717
718 1. It loads the plugin using *dlopen*.
719
720 2. It searchs for the symbol named **pluginAfbV1Register** using *dlsym*.
721 This symbol is assumed to be the exported initialisation function of the plugin.
722
723 3. It build an interface object for the plugin.
724
725 4. It calls the found function **pluginAfbV1Register** and pass it the pointer
726 to its interface.
727
728 5. The function **pluginAfbV1Register** setup the plugin, initialize it.
729
730 6. The function **pluginAfbV1Register** returns the pointer to a structure
731 that describes the plugin: its version, its name (prefix or API name), and the
732 list of its verbs.
733
734 7. Afb-daemon checks that the returned version and name can be managed.
735 If it can manage it, the plugin and its verbs are recorded and can be used
736 when afb-daemon finishes it initialisation.
737
738 Here is the listing of the function **pluginAfbV1Register** of the plugin
739 *tic-tac-toe*:
740
741         /*
742          * activation function for registering the plugin called by afb-daemon
743          */
744         const struct AFB_plugin *pluginAfbV1Register(const struct AFB_interface *itf)
745         {
746            afbitf = itf;         // records the interface for accessing afb-daemon
747            return &plugin_description;  // returns the description of the plugin
748         }
749
750 This is a very small function because the *tic-tac-toe* plugin doesn't have initialisation step.
751 It merely record the daemon's interface and returns its descritption.
752
753 The variable **afbitf** is a variable global to the plugin. It records the
754 interface to afb-daemon and is used for logging and pushing events.
755 Here is its declaration:
756
757         /*
758          * the interface to afb-daemon
759          */
760         const struct AFB_interface *afbitf;
761
762 The description of the plugin is defined as below.
763
764         /*
765          * array of the verbs exported to afb-daemon
766          */
767         static const struct AFB_verb_desc_v1 plugin_verbs[] = {
768            /* VERB'S NAME     SESSION MANAGEMENT          FUNCTION TO CALL  SHORT DESCRIPTION */
769            { .name= "new",   .session= AFB_SESSION_NONE, .callback= new,   .info= "Starts a new game" },
770            { .name= "play",  .session= AFB_SESSION_NONE, .callback= play,  .info= "Asks the server to play" },
771            { .name= "move",  .session= AFB_SESSION_NONE, .callback= move,  .info= "Tells the client move" },
772            { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" },
773            { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" },
774            { .name= "join",  .session= AFB_SESSION_CHECK,.callback= join,  .info= "Join a board" },
775            { .name= "undo",  .session= AFB_SESSION_NONE, .callback= undo,  .info= "Undo the last move" },
776            { .name= "wait",  .session= AFB_SESSION_NONE, .callback= wait,  .info= "Wait for a change" },
777            { .name= NULL } /* marker for end of the array */
778         };
779
780         /*
781          * description of the plugin for afb-daemon
782          */
783         static const struct AFB_plugin plugin_description =
784         {
785            /* description conforms to VERSION 1 */
786            .type= AFB_PLUGIN_VERSION_1,
787            .v1= {                               /* fills the v1 field of the union when AFB_PLUGIN_VERSION_1 */
788               .prefix= "tictactoe",             /* the API name (or plugin name or prefix) */
789               .info= "Sample tac-tac-toe game", /* short description of of the plugin */
790               .verbs = plugin_verbs             /* the array describing the verbs of the API */
791            }
792         };
793
794 The structure **plugin_description** describes the plugin.
795 It declares the type and version of the plugin, its name, a description
796 and a list of its verbs.
797
798 The list of verbs is an array of structures describing the verbs and terminated by a marker:
799 a verb whose name is NULL.
800
801 The description of the verbs for this version is made of 4 fields:
802
803 - the name of the verbs,
804
805 - the session management flags,
806
807 - the implementation function to be call for the verb,
808
809 - a short description.
810
811 The structure describing verbs is defined as follows:
812
813         /*
814          * Description of one verb of the API provided by the plugin
815          * This enumeration is valid for plugins of type 1
816          */
817         struct AFB_verb_desc_v1
818         {
819                const char *name;                       /* name of the verb */
820                enum AFB_session_v1 session;            /* authorisation and session requirements of the verb */
821                void (*callback)(struct afb_req req);   /* callback function implementing the verb */
822                const char *info;                       /* textual description of the verb */
823         };
824
825 For technical reasons, the enumeration **enum AFB_session_v1** is not exactly an
826 enumeration but the wrapper of constant definitions that can be mixed using bitwise or
827 (the C operator |).
828
829 The constants that can bit mixed are:
830
831 Constant name            | Meaning
832 -------------------------|-------------------------------------------------------------
833 **AFB_SESSION_CREATE**   | Equals to AFB_SESSION_LOA_EQ_0|AFB_SESSION_RENEW
834 **AFB_SESSION_CLOSE**    | Closes the session after the reply and set the LOA to 0
835 **AFB_SESSION_RENEW**    | Refreshes the token of authentification
836 **AFB_SESSION_CHECK**    | Just requires the token authentification
837 **AFB_SESSION_LOA_LE_0** | Requires the current LOA to be lesser then or equal to 0
838 **AFB_SESSION_LOA_LE_1** | Requires the current LOA to be lesser then or equal to 1
839 **AFB_SESSION_LOA_LE_2** | Requires the current LOA to be lesser then or equal to 2
840 **AFB_SESSION_LOA_LE_3** | Requires the current LOA to be lesser then or equal to 3
841 **AFB_SESSION_LOA_GE_0** | Requires the current LOA to be greater then or equal to 0
842 **AFB_SESSION_LOA_GE_1** | Requires the current LOA to be greater then or equal to 1
843 **AFB_SESSION_LOA_GE_2** | Requires the current LOA to be greater then or equal to 2
844 **AFB_SESSION_LOA_GE_3** | Requires the current LOA to be greater then or equal to 3
845 **AFB_SESSION_LOA_EQ_0** | Requires the current LOA to be equal to 0
846 **AFB_SESSION_LOA_EQ_1** | Requires the current LOA to be equal to 1
847 **AFB_SESSION_LOA_EQ_2** | Requires the current LOA to be equal to 2
848 **AFB_SESSION_LOA_EQ_3** | Requires the current LOA to be equal to 3
849
850 If any of this flags is set, afb-daemon requires the token authentification
851 as if the flag **AFB_SESSION_CHECK** had been set.
852
853 The special value **AFB_SESSION_NONE** is zero and can be used to avoid any check.
854
855 > Note that **AFB_SESSION_CREATE** and **AFB_SESSION_CLOSE** might be removed in later versions.
856
857 Sending messages to the log system
858 ----------------------------------
859
860 Afb-daemon provides 4 levels of verbosity and 5 verbs for logging messages.
861
862 The verbosity is managed. Options allow the change the verbosity of afb-daemon
863 and the verbosity of the plugins can be set plugin by plugin.
864
865 The verbs for logging messages are defined as macros that test the
866 verbosity level and that call the real logging function only if the
867 message must be output. This avoid evaluation of arguments of the
868 formatting messages if the message must not be output.
869
870 ### Verbs for logging messages
871
872 The 5 logging verbs are:
873
874 Macro   | Verbosity | Meaning                           | syslog level
875 --------|:---------:|-----------------------------------|:-----------:
876 ERROR   |     0     | Error conditions                  |     3
877 WARNING |     1     | Warning conditions                |     4
878 NOTICE  |     1     | Normal but significant condition  |     5
879 INFO    |     2     | Informational                     |     6
880 DEBUG   |     3     | Debug-level messages              |     7
881
882 You can note that the 2 verbs **WARNING** and **INFO** have the same level
883 of verbosity. But they don't have the same *syslog level*. It means that
884 they are output with a different level on the logging system.
885
886 All of these verbs have the same signature:
887
888         void ERROR(const struct AFB_interface *afbitf, const char *message, ...);
889
890 The first argument **afbitf** is the interface to afb daemon that the
891 plugin received at its initialisation when **pluginAfbV1Register** was called.
892
893 The second argument **message** is a formatting string compatible with printf/sprintf.
894
895 The remaining arguments are arguments of the formating message like for printf.
896
897 ### Managing verbosity
898
899 Depending on the level of verbosity, the messages are output or not.
900 The following table explains what messages will be output depending
901 ont the verbosity level.
902
903 Level of verbosity | Outputed macro
904 :-----------------:|--------------------------
905         0          | ERROR
906         1          | ERROR + WARNING + NOTICE
907         2          | ERROR + WARNING + NOTICE + INFO
908         3          | ERROR + WARNING + NOTICE + INFO + DEBUG
909
910 ### Output format and destination
911
912 The syslog level is used for forging a prefix to the message.
913 The prefixes are:
914
915 syslog level | prefix
916 :-----------:|---------------
917       0      | <0> EMERGENCY
918       1      | <1> ALERT
919       2      | <2> CRITICAL
920       3      | <3> ERROR
921       4      | <4> WARNING
922       5      | <5> NOTICE
923       6      | <6> INFO
924       7      | <7> DEBUG
925
926
927 The message is issued to the standard error.
928 The final destination of the message depends on how the systemd service
929 was configured through the variable **StandardError**: It can be
930 journal, syslog or kmsg. (See man sd-daemon).
931
932 Sending events
933 --------------
934
935 Since version 0.5, plugins can broadcast events to any potential listener.
936 This kind of bradcast is not targeted. Event targeted will come in a future
937 version of afb-daemon.
938
939 The plugin *tic-tac-toe* broadcasts events when the board changes.
940 This is done in the function **changed**:
941
942         /*
943          * signals a change of the board
944          */
945         static void changed(struct board *board, const char *reason)
946         {
947                 ...
948                 struct json_object *description;
949
950                 /* get the description */
951                 description = describe(board);
952
953                 ...
954
955                 afb_daemon_broadcast_event(afbitf->daemon, reason, description);
956         }
957
958 The description of the changed board is pushed via the daemon interface.
959
960 Within the plugin *tic-tac-toe*, the *reason* indicates the origin of
961 the change. For the function **afb_daemon_broadcast_event**, the second
962 parameter is the name of the broadcasted event. The third argument is the
963 object that is transmitted with the event.
964
965 The function **afb_daemon_broadcast_event** is defined as below:
966
967         /*
968          * Broadcasts widely the event of 'name' with the data 'object'.
969          * 'object' can be NULL.
970          * 'daemon' MUST be the daemon given in interface when activating the plugin.
971          */
972         void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
973
974 In fact the event name received by the listener is prefixed with
975 the name of the plugin. So when the change occurs after a move, the
976 reason is **move** and then the clients receive the event **tictactoe/move**.
977
978 > Note that nothing is said about the case sensitivity of event names.
979 > However, the event is always prefixed with the name that the plugin
980 > declared, with the same case, followed with a slash /.
981 > Thus it is safe to compare event using a case sensitive comparison.
982
983
984 Writing an asynchronous verb implementation
985 -------------------------------------------
986
987 /*
988  * signals a change of the board
989  */
990 static void changed(struct board *board, const char *reason)
991 {
992         struct waiter *waiter, *next;
993         struct json_object *description;
994
995         /* get the description */
996         description = describe(board);
997
998         waiter = board->waiters;
999         board->waiters = NULL;
1000         while (waiter != NULL) {
1001                 next = waiter->next;
1002                 afb_req_success(waiter->req, json_object_get(description), reason);
1003                 afb_req_unref(waiter->req);
1004                 free(waiter);
1005                 waiter = next;
1006         }
1007
1008         afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description);
1009 }
1010
1011 How to build a plugin
1012 ---------------------
1013
1014 Afb-daemon provides a *pkg-config* configuration file that can be
1015 queried by the name **afb-daemon**.
1016 This configuration file provides data that should be used
1017 for compiling plugins. Examples:
1018
1019         $ pkg-config --cflags afb-daemon
1020         $ pkg-config --libs afb-daemon
1021
1022 ### Example for cmake meta build system
1023
1024 This example is the extract for building the plugin *afm-main* using *CMAKE*.
1025
1026         pkg_check_modules(afb afb-daemon)
1027         if(afb_FOUND)
1028                 message(STATUS "Creation afm-main-plugin for AFB-DAEMON")
1029                 add_library(afm-main-plugin MODULE afm-main-plugin.c)
1030                 target_compile_options(afm-main-plugin PRIVATE ${afb_CFLAGS})
1031                 target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
1032                 target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
1033                 set_target_properties(afm-main-plugin PROPERTIES
1034                         PREFIX ""
1035                         LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
1036                 )
1037                 install(TARGETS afm-main-plugin LIBRARY DESTINATION ${plugin_dir})
1038         else()
1039                 message(STATUS "Not creating the plugin for AFB-DAEMON")
1040         endif()
1041
1042 Let now describe some of these lines.
1043
1044         pkg_check_modules(afb afb-daemon)
1045
1046 This first lines searches to the *pkg-config* configuration file for
1047 **afb-daemon**. Resulting data are stored in the following variables:
1048
1049 Variable          | Meaning
1050 ------------------|------------------------------------------------
1051 afb_FOUND         | Set to 1 if afb-daemon plugin development files exist
1052 afb_LIBRARIES     | Only the libraries (w/o the '-l') for compiling afb-daemon plugins
1053 afb_LIBRARY_DIRS  | The paths of the libraries (w/o the '-L') for compiling afb-daemon plugins
1054 afb_LDFLAGS       | All required linker flags for compiling afb-daemon plugins
1055 afb_INCLUDE_DIRS  | The '-I' preprocessor flags (w/o the '-I') for compiling afb-daemon plugins
1056 afb_CFLAGS        | All required cflags for compiling afb-daemon plugins
1057
1058 If development files are found, the plugin can be added to the set of
1059 target to build.
1060
1061         add_library(afm-main-plugin MODULE afm-main-plugin.c)
1062
1063 This line asks to create a shared library having only the
1064 source file afm-main-plugin.c (that is compiled).
1065 The default name of the created shared object is
1066 **libafm-main-plugin.so**.
1067
1068         set_target_properties(afm-main-plugin PROPERTIES
1069                 PREFIX ""
1070                 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
1071         )
1072
1073 This lines are doing two things:
1074
1075 1. It renames the built library from **libafm-main-plugin.so** to **afm-main-plugin.so**
1076 by removing the implicitely added prefix *lib*. This step is not mandatory
1077 at all because afb-daemon doesn't check names of files when loading it.
1078 The only convention that use afb-daemon is that extension is **.so**
1079 but this convention is used only when afb-daemon discovers plugin
1080 from a directory hierarchy.
1081
1082 2. It applies a version script at link to only export the conventional name
1083 of the entry point: **pluginAfbV1Register**. See below. By default, the linker
1084 that creates the shared object exports all the public symbols (C functions that
1085 are not **static**).
1086
1087 Next line are:
1088
1089         target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
1090         target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
1091
1092 As you can see it uses the variables computed by ***pkg_check_modules(afb afb-daemon)***
1093 to configure the compiler and the linker.
1094
1095 ### Exporting the function pluginAfbV1Register
1096
1097 The function **pluginAfbV1Register** must be exported. This can be achieved
1098 using a version script when linking. Here is the version script that is
1099 used for *tic-tac-toe* (plugins/samples/export.map).
1100
1101         { global: pluginAfbV1Register; local: *; };
1102
1103 This sample [version script](https://sourceware.org/binutils/docs-2.26/ld/VERSION.html#VERSION)
1104 exports as global the symbol *pluginAfbV1Register* and hides any
1105 other symbols.
1106
1107 This version script is added to the link options using the
1108 option **--version-script=export.map** is given directly to the
1109 linker or using th option **-Wl,--version-script=export.map**
1110 when the option is given to the C compiler.
1111
1112 ### Building within yocto
1113
1114 Adding a dependency to afb-daemon is enough. See below:
1115
1116         DEPENDS += " afb-daemon "
1117