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