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