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