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