2 HOWTO WRITE a BINDING for AFB-DAEMON
3 ===================================
8 Afb-daemon binders serve files through HTTP protocol
9 and offers to developers the capability to expose application API methods through
10 HTTP or WebSocket protocol.
12 Binder bindings are used to add API to afb-daemon.
13 This part describes how to write a binding for afb-daemon.
15 Excepting this summary, this document target developers.
17 Before moving further through an example, here after
18 a short overview of binder bindings fundamentals.
20 ### Nature of a binding
22 A binding is an independent piece of software. A binding is self contain and exposes application logic as sharable library.
23 A binding is intended to be dynamically loaded by afb-daemon to expose application API.
25 Technically, a binder binding does not reference and is not linked with any afb-daemon library.
29 Application binder supports two kinds of bindings: application bindings and service bindings.
30 Technically both class of binding are equivalent are use the same coding convention. Only sharing mode and security context diverge.
32 #### Application-bindings
34 Application-bindings implements the glue in between application's UI and services. Every AGL application
35 has a corresponding binder that typically activates one or many bindings to interface the application logic with lower platform services.
36 When an application is started by the AGL application framework, a dedicate binder is started that loads/activates application binding(s).
37 API expose by application-binding are executed within corresponding application security context.
39 Application bindings generally handle a unique context for a unique client. As the application framework start
40 a dedicated instance of afb_daemon for each AGL application, if a given binding is used within multiple application each of those
41 application get a new and private instance of eventually "shared" binding.
45 Service-bindings enable API activation within corresponding service security context and not within calling application context.
46 Service-bindings are intended to run as a unique instance. Service-bindings can be shared in between multiple clients.
48 Service-bindings can either be stateless or manage client context. When managing context each client get a private context.
50 Sharing may either be global to the platform (ie: GPS service) or dedicated to a given user (ie: user preferences)
52 ### Live cycle of bindings within afb-daemon
54 Application and service bindings are loaded and activated each time a new afb-daemon is started.
56 At launch time, every loaded binding initialise itself.
57 If a single binding initialisation fail corresponding instance of afb-daemon self aborts.
59 Conversely, when a binding initialisation succeeds, it should register
60 its unique name as well as the list of verbs attached to the methods it exposes.
62 When initialised, on request from application clients to the right API/verb, binding methods
63 are activated by the afb-daemon attached to the application or service.
65 At exit time, no special action is enforced by afb-daemon. When a specific actions is required at afb-daemon stop,
66 developers should use 'atexit/on_exit' during binding initialisation sequence to register a custom exit function.
70 Afb-daemon's binding register two classes of objects: names and functions.
72 Bindings declare categories of names:
73 - A unique binding name to access all API expose by this binding,
74 - One name for each methods/verbs provided by this binding.
76 Bindings declare two categories of functions:
77 - function use for the initialisation
78 - functions implementing exposed API methods
80 Afb-daemon parses URI requests to extract the API(binding name) and the VERB(method to activate).
81 As an example, URI **foo/bar** translates to binding named **foo** and method named **bar**.
82 To serve such a request, afb-daemon looks for an active binding named **foo** and then within this binding for a method named **bar**.
83 When find afb-daemon calls corresponding method with attached parameter if any.
85 Afb-daemon ignores letter case when parsing URI. Thus **TicTacToe/Board** and **tictactoe/board** are equivalent.
87 #### The name of the binding
89 The name of a given binding is also known as the name
90 of the API prefix that defines the binding.
92 The name of a binding SHOULD be unique within a given afb-daemon instance.
94 For example, when a client of afb-daemon calls a URI named **foo/bar**. Afb-daemon
95 extracts the prefix **foo** and the suffix **bar**. **foo** must match a binding name and **bar** a VERB attached to some method.
99 Each binding exposes a set of methods that can be called
100 by the clients of a given afb-daemon.
102 VERB's name attached to a given binding (API) MUST be unique within a binding.
104 Bindings static declaration link VERBS to corresponding methods.
105 When clients emit requests on a given API/VERB corresponding method is called by afb-daemon.
107 #### Initialisation function
109 Binding's initialisation function serves several purposes.
111 1. It allows afb-daemon to control binding version depending on initialisation function name.
112 As today, the only supported initialisation function is **afbBindingV1Register**. This identifies
113 version "one" of bindings.
115 2. It allows bindings to initialise itself.
117 3. It enables names declarations: descriptions, requirements and implementations of exposed API/VERB.
119 #### Functions instantiation of API/VERBs
121 When an API/VERB is called, afb-daemon constructs a request object. Then it
122 passes this request object to the implementation function corresponding to requested method, this
123 within attached API binding.
125 An implementation function receives a request object that
126 is used to: get arguments of the request, send
127 answer, store session data.
129 A binding MUST set an answer to every received requests.
131 Nevertheless it is not mandatory to set the answer
132 before returning from API/VERB implementing function.
133 This behaviour is important for asynchronous actions.
135 API/VERB implementation that set an answer before returning are called *synchronous implementations*.
136 Those that do not systematically set an answer before returning are called *asynchronous implementations*.
138 Asynchronous implementations typically launch asynchronous actions. They record some context at
139 request time and provide answer to the request only at completion of asynchronous actions.
141 The Tic-Tac-Toe example
142 -----------------------
144 This part explains how to write an afb-binding.
145 For the sake of being practical it uses many
146 examples based on tic-tac-toe.
147 This binding example is in *bindings/samples/tic-tac-toe.c*.
149 This binding is named ***tictactoe***.
151 Dependencies when compiling
152 ---------------------------
154 Afb-daemon provides a configuration file for *pkg-config*.
157 pkg-config --cflags afb-daemon
159 Print flags use for compilation:
161 $ pkg-config --cflags afb-daemon
162 -I/opt/local/include -I/usr/include/json-c
164 For linking, you should use
166 $ pkg-config --libs afb-daemon
169 Afb-daemon automatically includes dependency to json-c.
170 This is activated through **Requires** keyword in pkg-config.
171 While almost every binding replies on **json-c** this is not a must have dependency.
173 Internally, afb-daemon relies on **libsystemd** for its event loop, as well
174 as for its binding to D-Bus.
175 Bindings developers are encouraged to leverage **libsystemd** when possible.
176 Nevertheless there is no hard dependency to **libsystemd** if ever
177 you rather not use it, feel free to do so.
179 > Afb-daemon binding are fully self contain. They do not enforce dependency on any libraries from the application framework.
180 > Afb-daemon dependencies requirer to run AGL bindings are given at runtime through pointers leveraging read-only
183 Header files to include
184 -----------------------
186 Binding *tictactoe* has following includes:
192 #include <json-c/json.h>
193 #include <afb/afb-binding.h>
196 Header *afb/afb-binding.h* is the only hard dependency, it includes all features
197 that a binding MUST HAVE. Outside of includes used to support application logic,
198 common external headers used within bindings are:
200 - *json-c/json.h*: should be include to handle json objects;
201 - *systemd/sd-event.h*: should be include to access event main loop;
202 - *systemd/sd-bus.h*: should be include for dbus connections.
204 The *tictactoe* binding does not leverage systemd features, also only json.h
205 is used on top of mandatory afb/afb-binding.h.
207 When including *afb/afb-binding.h*, the macro **_GNU_SOURCE** MUST be
213 Designers of bindings should define a unique name for every API binding
214 as well as for methods VERBs. They should also define names for request
215 arguments passed as name/value pair in URI.
217 While forging names, designers should respect few rules to
218 ensure that created names are valid and easy to use across platforms.
220 All names and strings are UTF-8 encoded.
222 ### Names for API (binding)
224 Binding API name are checked.
225 All characters are authorised except:
227 - the control characters (\u0000 .. \u001f)
228 - the characters of the set { ' ', '"', '#', '%', '&',
229 '\'', '/', '?', '`', '\x7f' }
231 In other words the set of forbidden characters is
232 { \u0000..\u0020, \u0022, \u0023, \u0025..\u0027,
233 \u002f, \u003f, \u0060, \u007f }.
235 Afb-daemon makes no distinction between lower case
236 and upper case when searching for API/VERB.
238 ### Names for methods
240 The names of methods VERBs are totally free and not checked.
242 However, the validity rules for method's VERB name are the
243 same as for Binding API name except that the dot(.) character
246 Afb-daemon makes no case distinction when searching for an API by name.
248 ### Names for arguments
250 Argument's name are not restricted and can be everything you wish.
252 > Warning arguments search is case sensitive and "index" and "Index"
253 > are not two different arguments.
255 ### Forging names widely available
257 The key names of javascript object can be almost
258 anything using the arrayed notation:
262 Nevertheless this is not the case with javascript dot notation:
266 Using the dot notation, the key must be a valid javascript
267 identifier and dash(-) as well as few other reserved characters cannot be used.
269 For this reason, we advise developper to chose name compatible with both javascript and HTML notation.
271 It is a good practice, even for arguments not to rely on case sensitivity.
272 This may reduce headache strength at debug time, especially with interpreted language like
273 javascript that may not warn you that a variable was not defined.
275 Writing a synchronous method implementation
276 -----------------------------------------
278 The method **tictactoe/board** is a synchronous implementation.
285 static void board(struct afb_req req)
288 struct json_object *description;
290 /* retrieves the context for the session */
291 board = board_of_req(req);
292 INFO(afbitf, "method 'board' called for boardid %d", board->id);
294 /* describe the board */
295 description = describe(board);
297 /* send the board's description */
298 afb_req_success(req, description, NULL);
302 This example shows many aspects of a synchronous
303 method implementation. Let summarise it:
305 1. The function **board_of_req** retrieves the context stored
306 for the binding: the board.
308 2. The macro **INFO** sends a message of kind *INFO*
309 to the logging system. The global variable named **afbitf**
310 used represents the interface to afb-daemon.
312 3. The function **describe** creates a json_object representing
315 4. The function **afb_req_success** sends the reply, attaching to
316 it the object *description*.
318 ### The incoming request
320 For any implementation, the request is received by a structure of type
323 > Note that this is a PLAIN structure, not a pointer to a structure.
325 The definition of **struct afb_req** is:
329 * Describes the request by bindings from afb-daemon
332 const struct afb_req_itf *itf; /* the interfacing functions */
333 void *closure; /* the closure for functions */
337 It contains two pointers: first one *itf*, points to functions used
338 to handle internal request. Second one *closure* point onto function closure.
340 > The structure must never be used directly.
341 > Instead developer should use the intended functions provided
342 > by afb-daemon as described here after.
344 *req* is used to get arguments of the request, to send
345 answer, to store session data.
347 This object and its interface is defined and documented
348 in the file names *afb/afb-req-itf.h*
350 The above example uses twice *req* object request.
352 The first time, to retrieve the board attached to the session of the request.
354 The second time, to send the reply: an object that describes the current board.
356 ### Associating a client context to a session
358 When *tic-tac-toe* binding receives a request, it musts get
359 the board describing the game associated to the session.
361 For a binding, having data associated to a session is common.
362 This data is called "binding context" for the session.
363 Within *tic-tac-toe* binding the context is the board.
365 Requests *afb_req* offer four functions for storing and retrieving session associated context.
369 - **afb_req_context_get**:
370 retrieves context data stored for current binding.
372 - **afb_req_context_set**:
373 store context data of current binding.
375 - **afb_req_context**:
376 if exist retrieves context data of current binding.
377 if context does not yet exist, creates a new context and store it.
379 - **afb_req_context_clear**:
380 reset the stored context data.
382 The binding *tictactoe* use a convenient function to retrieve
383 its context: the board. This function is *board_of_req*:
387 * retrieves the board of the request
389 static inline struct board *board_of_req(struct afb_req req)
391 return afb_req_context(req, (void*)get_new_board, (void*)release_board);
395 The function **afb_req_context** ensures an existing context
396 for the session of the request.
397 Its two last arguments are functions to allocate and free context.
398 Note function type casts to avoid compilation warnings.
400 Here is the definition of the function **afb_req_context**
404 * Gets the pointer stored by the binding for the session of 'req'.
405 * If the stored pointer is NULL, indicating that no pointer was
406 * already stored, afb_req_context creates a new context by calling
407 * the function 'create_context' and stores it with the freeing function
410 static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*))
412 void *result = afb_req_context_get(req);
413 if (result == NULL) {
414 result = create_context();
415 afb_req_context_set(req, result, free_context);
421 The second argument if the function that creates the context.
422 For binding *tic-tac-toe* (function **get_new_board**).
423 The function **get_new_board** creates a new board and set usage its count to 1.
424 The boards are checking usage count to free resources when not used.
426 The third argument is a function that frees context resources.
427 For binding *tic-tac-toe* (function **release_board**).
428 The function **release_board** decrease usage count of the board passed in argument.
429 When usage count falls to zero, data board are freed.
431 Definition of other functions dealing with contexts:
435 * Gets the pointer stored by the binding for the session of 'req'.
436 * When the binding has not yet recorded a pointer, NULL is returned.
438 void *afb_req_context_get(struct afb_req req);
441 * Stores for the binding the pointer 'context' to the session of 'req'.
442 * The function 'free_context' will be called when the session is closed
443 * or if binding stores an other pointer.
445 void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));
448 * Frees the pointer stored by the binding for the session of 'req'
449 * and sets it to NULL.
451 * Shortcut for: afb_req_context_set(req, NULL, NULL)
453 static inline void afb_req_context_clear(struct afb_req req)
455 afb_req_context_set(req, NULL, NULL);
459 ### Sending reply to a request
461 Two kinds of replies: successful or failure.
463 > Sending a reply to a request MUST be done once and only once.
465 It exists two functions for "success" replies: **afb_req_success** and **afb_req_success_f**.
469 * Sends a reply of kind success to the request 'req'.
470 * The status of the reply is automatically set to "success".
471 * Its send the object 'obj' (can be NULL) with an
472 * informationnal comment 'info (can also be NULL).
474 * For convenience, the function calls 'json_object_put' for 'obj'.
475 * Thus, in the case where 'obj' should remain available after
476 * the function returns, the function 'json_object_get' shall be used.
478 void afb_req_success(struct afb_req req, struct json_object *obj, const char *info);
481 * Same as 'afb_req_success' but the 'info' is a formatting
482 * string followed by arguments.
484 * For convenience, the function calls 'json_object_put' for 'obj'.
485 * Thus, in the case where 'obj' should remain available after
486 * the function returns, the function 'json_object_get' shall be used.
488 void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
491 It exists two functions for "failure" replies: **afb_req_fail** and **afb_req_fail_f**.
495 * Sends a reply of kind failure to the request 'req'.
496 * The status of the reply is set to 'status' and an
497 * informational comment 'info' (can also be NULL) can be added.
499 * Note that calling afb_req_fail("success", info) is equivalent
500 * to call afb_req_success(NULL, info). Thus even if possible it
501 * is strongly recommended to NEVER use "success" for status.
503 * For convenience, the function calls 'json_object_put' for 'obj'.
504 * Thus, in the case where 'obj' should remain available after
505 * the function returns, the function 'json_object_get' shall be used.
507 void afb_req_fail(struct afb_req req, const char *status, const char *info);
510 * Same as 'afb_req_fail' but the 'info' is a formatting
511 * string followed by arguments.
513 * For convenience, the function calls 'json_object_put' for 'obj'.
514 * Thus, in the case where 'obj' should remain available after
515 * the function returns, the function 'json_object_get' shall be used.
517 void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
520 > For convenience, these functions automatically call **json_object_put** to release **obj**.
521 > Because **obj** usage count is null after being passed to a reply function, it SHOULD not be used anymore.
522 > If exceptionally **obj** needs to remain usable after reply function then using **json_object_get** on **obj**
523 > to increase usage count and cancels the effect the **json_object_put** is possible.
525 Getting argument of invocation
526 ------------------------------
528 Many methods expect arguments. Afb-daemon's bindings
529 retrieve arguments by name and not by position.
531 Arguments are passed by requests through either HTTP
534 For example, the method **join** of binding **tic-tac-toe**
535 expects one argument: the *boardid* to join. Here is an extract:
541 static void join(struct afb_req req)
543 struct board *board, *new_board;
546 /* retrieves the context for the session */
547 board = board_of_req(req);
548 INFO(afbitf, "method 'join' called for boardid %d", board->id);
550 /* retrieves the argument */
551 id = afb_req_value(req, "boardid");
557 The function **afb_req_value** searches in the request *req*
558 for argument name passed in the second argument. When argument name
559 is not passed, **afb_req_value** returns NULL.
561 > The search is case sensitive and *boardid* is not equivalent to *BoardId*.
562 > Nevertheless having argument names that only differ by name case is not a good idea.
564 ### Basic functions for querying arguments
566 The function **afb_req_value** is defined here after:
570 * Gets from the request 'req' the string value of the argument of 'name'.
571 * Returns NULL if when there is no argument of 'name'.
572 * Returns the value of the argument of 'name' otherwise.
574 * Shortcut for: afb_req_get(req, name).value
576 static inline const char *afb_req_value(struct afb_req req, const char *name)
578 return afb_req_get(req, name).value;
582 It is defined as a shortcut to call the function **afb_req_get**.
583 That function is defined here after:
587 * Gets from the request 'req' the argument of 'name'.
588 * Returns a PLAIN structure of type 'struct afb_arg'.
589 * When the argument of 'name' is not found, all fields of result are set to NULL.
590 * When the argument of 'name' is found, the fields are filled,
591 * in particular, the field 'result.name' is set to 'name'.
593 * There is a special name value: the empty string.
594 * The argument of name "" is defined only if the request was made using
595 * an HTTP POST of Content-Type "application/json". In that case, the
596 * argument of name "" receives the value of the body of the HTTP request.
598 struct afb_arg afb_req_get(struct afb_req req, const char *name);
601 That function takes 2 parameters: the request and the name
602 of the argument to retrieve. It returns a PLAIN structure of
603 type **struct afb_arg**.
605 There is a special name that is defined when the request is
606 of type HTTP/POST with a Content-Type being application/json.
607 This name is **""** (the empty string). In that case, the value
608 of this argument of empty name is the string received as a body
609 of the post and is supposed to be a JSON string.
611 The definition of **struct afb_arg** is:
615 * Describes an argument (or parameter) of a request
618 const char *name; /* name of the argument or NULL if invalid */
619 const char *value; /* string representation of the value of the argument */
620 /* original filename of the argument if path != NULL */
621 const char *path; /* if not NULL, path of the received file for the argument */
622 /* when the request is finalized this file is removed */
626 The structure returns the data arguments that are known for the
627 request. This data include a field named **path**. This **path**
628 can be accessed using the function **afb_req_path** defined here after:
632 * Gets from the request 'req' the path for file attached to the argument of 'name'.
633 * Returns NULL if when there is no argument of 'name' or when there is no file.
634 * Returns the path of the argument of 'name' otherwise.
636 * Shortcut for: afb_req_get(req, name).path
638 static inline const char *afb_req_path(struct afb_req req, const char *name)
640 return afb_req_get(req, name).path;
644 The path is only defined for HTTP/POST requests that send file.
646 ### Arguments for received files
648 As it is explained above, clients can send files using HTTP/POST requests.
650 Received files are attached to "file" argument name. For example, the
651 following HTTP fragment (from test/sample-post.html)
652 will send an HTTP/POST request to the method
653 **post/upload-image** with 2 arguments named *file* and
657 <h2>Sample Post File</h2>
658 <form enctype="multipart/form-data">
659 <input type="file" name="file" />
660 <input type="hidden" name="hidden" value="bollobollo" />
662 <button formmethod="POST" formaction="api/post/upload-image">Post File</button>
666 Argument named **file** should have both its value and path defined.
668 The value is the name of the file as it was set by the HTTP client.
669 Generally it is the filename on client side.
671 The path is the effective path of saved file on the temporary local storage
672 area of the application. This is a randomly generated and unique filename.
673 It is not linked with the original filename as used on client side.
675 After success the binding can use the uploaded file directly from local storage path with no restriction:
676 read, write, remove, copy, rename...
677 Nevertheless when request reply is set and query terminated, the uploaded temporary file at
680 ### Arguments as a JSON object
682 Bindings may also request every arguments of a given call as one single object.
683 This feature is provided by the function **afb_req_json** defined here after:
687 * Gets from the request 'req' the json object hashing the arguments.
688 * The returned object must not be released using 'json_object_put'.
690 struct json_object *afb_req_json(struct afb_req req);
693 It returns a json object. This object depends on how the request was built:
695 - For HTTP requests, this json object uses key names mapped on argument name.
696 Values are either string for common arguments or object ie: { "file": "...", "path": "..." }
698 - For WebSockets requests, returned directly the object as provided by the client.
700 > In fact, for Websockets requests, the function **afb_req_value**
701 > can be seen as a shortcut to
702 > ***json_object_get_string(json_object_object_get(afb_req_json(req), name))***
704 Initialisation of the binding and declaration of methods
705 -----------------------------------------------------
707 To be active, binding's methods should be declared to
708 afb-daemon. Furthermore, the binding itself must be recorded.
710 The registration mechanism is very basic: when afb-need starts,
711 it loads all bindings listed in: command line or configuration file.
713 Loading a binding follows the following steps:
715 1. Afb-daemon loads the binding with *dlopen*.
717 2. Afb-daemon searches for a symbol named **afbBindingV1Register** using *dlsym*.
718 This symbol is assumed to be the exported initialisation function of the binding.
720 3. Afb-daemon builds an interface object for the binding.
722 4. Afb-daemon calls the found function **afbBindingV1Register** with interface pointer
725 5. Function **afbBindingV1Register** setups the binding and initialises it.
727 6. Function **afbBindingV1Register** returns the pointer to a structure
728 describing the binding: version, name (prefix or API name), and list of methods.
730 7. Afb-daemon checks that the returned version and name can be managed.
731 If so, binding and its methods are register to become usable as soon as
732 afb-daemon initialisation is finished.
734 Here after the code used for **afbBindingV1Register** from binding *tic-tac-toe*:
738 * activation function for registering the binding called by afb-daemon
740 const struct afb_binding *afbBindingV1Register(const struct afb_binding_interface *itf)
742 afbitf = itf; // records the interface for accessing afb-daemon
743 return &binding_description; // returns the description of the binding
747 It is a very minimal initialisation function because *tic-tac-toe* binding doesn't
748 have any application related initialisation step. It merely record daemon's interface
749 and returns its description.
751 The variable **afbitf** is a binding global variable. It keeps the
752 interface to afb-daemon that should be used for logging and pushing events.
753 Here is its declaration:
757 * the interface to afb-daemon
759 const struct afb_binding_interface *afbitf;
762 The description of the binding is defined here after.
766 * array of the methods exported to afb-daemon
768 static const struct afb_verb_desc_v1 binding_methods[] = {
769 /* VERB'S NAME SESSION MANAGEMENT FUNCTION TO CALL SHORT DESCRIPTION */
770 { .name= "new", .session= AFB_SESSION_NONE, .callback= new, .info= "Starts a new game" },
771 { .name= "play", .session= AFB_SESSION_NONE, .callback= play, .info= "Asks the server to play" },
772 { .name= "move", .session= AFB_SESSION_NONE, .callback= move, .info= "Tells the client move" },
773 { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" },
774 { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" },
775 { .name= "join", .session= AFB_SESSION_CHECK,.callback= join, .info= "Join a board" },
776 { .name= "undo", .session= AFB_SESSION_NONE, .callback= undo, .info= "Undo the last move" },
777 { .name= "wait", .session= AFB_SESSION_NONE, .callback= wait, .info= "Wait for a change" },
778 { .name= NULL } /* marker for end of the array */
782 * description of the binding for afb-daemon
784 static const struct afb_binding binding_description =
786 /* description conforms to VERSION 1 */
787 .type= AFB_BINDING_VERSION_1,
788 .v1= { /* fills the v1 field of the union when AFB_BINDING_VERSION_1 */
789 .prefix= "tictactoe", /* the API name (or binding name or prefix) */
790 .info= "Sample tac-tac-toe game", /* short description of of the binding */
791 .methods = binding_methods /* the array describing the methods of the API */
796 The structure **binding_description** describes the binding.
797 It declares the type and version of the binding, its name, a short description
798 and its methods list.
800 The list of methods is an array of structures describing the methods and terminated by a NULL marker.
802 In version one of afb-damon binding, a method description contains 4 fields:
804 - the name of the method,
806 - the session management flags,
808 - the implementation function to be call for the method,
810 - a short description.
812 The structure describing methods is defined as follows:
816 * Description of one method of the API provided by the binding
817 * This enumeration is valid for bindings of type 1
819 struct afb_verb_desc_v1
821 const char *name; /* name of the method */
822 enum AFB_session_v1 session; /* authorisation and session requirements of the method */
823 void (*callback)(struct afb_req req); /* callback function implementing the method */
824 const char *info; /* textual description of the method */
828 For technical reasons, the enumeration **enum AFB_session_v1** is not exactly an
829 enumeration but the wrapper of constant definitions that can be mixed using bitwise or
832 The constants that can bit mixed are:
834 Constant name | Meaning
835 -------------------------|-------------------------------------------------------------
836 **AFB_SESSION_CREATE** | Equals to AFB_SESSION_LOA_EQ_0|AFB_SESSION_RENEW
837 **AFB_SESSION_CLOSE** | Closes the session after the reply and set the LOA to 0
838 **AFB_SESSION_RENEW** | Refreshes the token of authentification
839 **AFB_SESSION_CHECK** | Just requires the token authentification
840 **AFB_SESSION_LOA_LE_0** | Requires the current LOA to be lesser then or equal to 0
841 **AFB_SESSION_LOA_LE_1** | Requires the current LOA to be lesser then or equal to 1
842 **AFB_SESSION_LOA_LE_2** | Requires the current LOA to be lesser then or equal to 2
843 **AFB_SESSION_LOA_LE_3** | Requires the current LOA to be lesser then or equal to 3
844 **AFB_SESSION_LOA_GE_0** | Requires the current LOA to be greater then or equal to 0
845 **AFB_SESSION_LOA_GE_1** | Requires the current LOA to be greater then or equal to 1
846 **AFB_SESSION_LOA_GE_2** | Requires the current LOA to be greater then or equal to 2
847 **AFB_SESSION_LOA_GE_3** | Requires the current LOA to be greater then or equal to 3
848 **AFB_SESSION_LOA_EQ_0** | Requires the current LOA to be equal to 0
849 **AFB_SESSION_LOA_EQ_1** | Requires the current LOA to be equal to 1
850 **AFB_SESSION_LOA_EQ_2** | Requires the current LOA to be equal to 2
851 **AFB_SESSION_LOA_EQ_3** | Requires the current LOA to be equal to 3
853 If any of this flag is set, afb-daemon requires an authentication token
854 as if **AFB_SESSION_CHECK** flag was also set.
856 The special value **AFB_SESSION_NONE** is zero and can be used to bypass token check.
858 > Note that **AFB_SESSION_CREATE** and **AFB_SESSION_CLOSE** might be removed in later versions.
860 Sending messages to the log system
861 ----------------------------------
863 Afb-daemon provides 4 levels of verbosity and 5 methods for logging messages.
865 The verbosity is managed. Options allow the change the verbosity of afb-daemon
866 and the verbosity of the bindings can be set binding by binding.
868 The methods for logging messages are defined as macros that test the
869 verbosity level and that call the real logging function only if the
870 message must be output. This avoid evaluation of arguments of the
871 formatting messages if the message must not be output.
873 ### Verbs for logging messages
875 The 5 logging methods are:
877 Macro | Verbosity | Meaning | syslog level
878 --------|:---------:|-----------------------------------|:-----------:
879 ERROR | 0 | Error conditions | 3
880 WARNING | 1 | Warning conditions | 4
881 NOTICE | 1 | Normal but significant condition | 5
882 INFO | 2 | Informational | 6
883 DEBUG | 3 | Debug-level messages | 7
885 You can note that the 2 methods **WARNING** and **INFO** have the same level
886 of verbosity. But they don't have the same *syslog level*. It means that
887 they are output with a different level on the logging system.
889 All of these methods have the same signature:
892 void ERROR(const struct afb_binding_interface *afbitf, const char *message, ...);
895 The first argument **afbitf** is the interface to afb daemon that the
896 binding received at initialisation time when **afbBindingV1Register** is called.
898 The second argument **message** is a formatting string compatible with printf/sprintf.
900 The remaining arguments are arguments of the formating message like with printf.
902 ### Managing verbosity
904 Depending on the level of verbosity, the messages are output or not.
905 The following table explains what messages will be output depending
906 ont the verbosity level.
908 Level of verbosity | Outputed macro
909 :-----------------:|--------------------------
911 1 | ERROR + WARNING + NOTICE
912 2 | ERROR + WARNING + NOTICE + INFO
913 3 | ERROR + WARNING + NOTICE + INFO + DEBUG
915 ### Output format and destination
917 The syslog level is used for forging a prefix to the message.
920 syslog level | prefix
921 :-----------:|---------------
932 The message is pushed to standard error.
933 The final destination of the message depends on how systemd service
934 was configured through its variable **StandardError**. It can be
935 journal, syslog or kmsg. (See man sd-daemon).
940 Since version 0.5, bindings can broadcast events to any potential listener.
941 As today only unattended even are supported. Targeted events are expected for next
944 The binding *tic-tac-toe* broadcasts events when the board changes.
945 This is done in the function **changed**:
949 * signals a change of the board
951 static void changed(struct board *board, const char *reason)
954 struct json_object *description;
956 /* get the description */
957 description = describe(board);
961 afb_daemon_broadcast_event(afbitf->daemon, reason, description);
965 The description of the changed board is pushed via the daemon interface.
967 Within binding *tic-tac-toe*, *reason* indicates the origin of
968 the change. In function **afb_daemon_broadcast_event** the second
969 parameter is the name of broadcasted event. The third argument is the
970 object that is transmitted with the event.
972 Function **afb_daemon_broadcast_event** is defined here after:
976 * Broadcasts widely the event of 'name' with the data 'object'.
977 * 'object' can be NULL.
978 * 'daemon' MUST be the daemon given in interface when activating the binding.
980 * For convenience, the function calls 'json_object_put' for 'object'.
981 * Thus, in the case where 'object' should remain available after
982 * the function returns, the function 'json_object_get' shall be used.
984 void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
987 > Be aware, as with reply functions **object** is automatically released using
988 > **json_object_put** when using this function. Call **json_object_get** before
989 > calling **afb_daemon_broadcast_event** to keep **object** available
990 > after function returns.
992 Event name received by listeners is prefixed with binding name.
993 So when a change occurs after a move, the reason is **move** and every clients
994 receive an event **tictactoe/move**.
996 > Note that nothing is said about case sensitivity of event names.
997 > However, the event is always prefixed with the name that the binding
998 > declared, with the same case, followed with a slash /.
999 > Thus it is safe to compare event using a case sensitive comparison.
1003 Writing an asynchronous method implementation
1004 -------------------------------------------
1006 The *tic-tac-toe* example allows two clients or more to share the same board.
1007 This is implemented by the method **join** that illustrated partly how to
1010 When two or more clients are sharing a same board, one of them can wait
1011 until the state of the board changes, but this could also be implemented using
1012 events because an even is generated each time the board changes.
1014 In this case, the reply to the wait is sent only when the board changes.
1015 See the diagram below:
1017 CLIENT A CLIENT B TIC-TAC-TOE
1019 +--------------|----------------->| wait . . . . . . . .
1024 | +----------------->| move . . . .
1026 | |<-----------------+ success of move .
1028 |<-------------|------------------+ success of wait <
1030 Here, this is an invocation of the binding by an other client that
1031 unblock the suspended *wait* call.
1032 Nevertheless in most case this should be a timer, a hardware event, a sync with
1033 a concurrent process or thread, ...
1035 Common case of an asynchronous implementation.
1037 Here is the listing of the function **wait**:
1040 static void wait(struct afb_req req)
1042 struct board *board;
1043 struct waiter *waiter;
1045 /* retrieves the context for the session */
1046 board = board_of_req(req);
1047 INFO(afbitf, "method 'wait' called for boardid %d", board->id);
1049 /* creates the waiter and enqueues it */
1050 waiter = calloc(1, sizeof *waiter);
1052 waiter->next = board->waiters;
1053 afb_req_addref(req);
1054 board->waiters = waiter;
1058 After retrieving the board, the function adds a new waiter to
1059 waiters list and returns without setting a reply.
1061 Before returning, it increases **req** request's reference count using **afb_req_addref** function.
1063 > When a method returns without setting a reply,
1064 > it **MUST** increment request's reference count
1065 > using **afb_req_addref**. If unpredictable behaviour may pop up.
1067 Later, when a board changes, it calls *tic-tac-toe* **changed** function
1068 with reason of change in parameter.
1070 Here is the full listing of the function **changed**:
1074 * signals a change of the board
1076 static void changed(struct board *board, const char *reason)
1078 struct waiter *waiter, *next;
1079 struct json_object *description;
1081 /* get the description */
1082 description = describe(board);
1084 waiter = board->waiters;
1085 board->waiters = NULL;
1086 while (waiter != NULL) {
1087 next = waiter->next;
1088 afb_req_success(waiter->req, json_object_get(description), reason);
1089 afb_req_unref(waiter->req);
1094 afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description);
1098 The list of waiters is walked and a reply is sent to each waiter.
1099 After sending the reply, the reference count of the request
1100 is decremented using **afb_req_unref** to allow resources to be freed.
1102 > The reference count **MUST** be decremented using **afb_req_unref** to free
1103 > resources and avoid memory leaks.
1104 > This usage count decrement should happen **AFTER** setting reply or
1105 > bad things may happen.
1107 How to build a binding
1108 ---------------------
1110 Afb-daemon provides a *pkg-config* configuration file that can be
1111 queried by providing **afb-daemon** in command line arguments.
1112 This configuration file provides data that should be used
1113 for bindings compilation. Examples:
1116 $ pkg-config --cflags afb-daemon
1117 $ pkg-config --libs afb-daemon
1120 ### Example for cmake meta build system
1122 This example is the extract for building the binding *afm-main* using *CMAKE*.
1125 pkg_check_modules(afb afb-daemon)
1127 message(STATUS "Creation afm-main-binding for AFB-DAEMON")
1128 add_library(afm-main-binding MODULE afm-main-binding.c)
1129 target_compile_options(afm-main-binding PRIVATE ${afb_CFLAGS})
1130 target_include_directories(afm-main-binding PRIVATE ${afb_INCLUDE_DIRS})
1131 target_link_libraries(afm-main-binding utils ${afb_LIBRARIES})
1132 set_target_properties(afm-main-binding PROPERTIES
1134 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-binding.export-map"
1136 install(TARGETS afm-main-binding LIBRARY DESTINATION ${binding_dir})
1138 message(STATUS "Not creating the binding for AFB-DAEMON")
1142 Let now describe some of these lines.
1145 pkg_check_modules(afb afb-daemon)
1148 This first lines searches to the *pkg-config* configuration file for
1149 **afb-daemon**. Resulting data are stored in the following variables:
1152 ------------------|------------------------------------------------
1153 afb_FOUND | Set to 1 if afb-daemon binding development files exist
1154 afb_LIBRARIES | Only the libraries (w/o the '-l') for compiling afb-daemon bindings
1155 afb_LIBRARY_DIRS | The paths of the libraries (w/o the '-L') for compiling afb-daemon bindings
1156 afb_LDFLAGS | All required linker flags for compiling afb-daemon bindings
1157 afb_INCLUDE_DIRS | The '-I' preprocessor flags (w/o the '-I') for compiling afb-daemon bindings
1158 afb_CFLAGS | All required cflags for compiling afb-daemon bindings
1160 If development files are found, the binding can be added to the set of
1164 add_library(afm-main-binding MODULE afm-main-binding.c)
1167 This line asks to create a shared library having a single
1168 source file named afm-main-binding.c to be compiled.
1169 The default name of the created shared object is
1170 **libafm-main-binding.so**.
1173 set_target_properties(afm-main-binding PROPERTIES
1175 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-binding.export-map"
1179 This lines are doing two things:
1181 1. It renames the built library from **libafm-main-binding.so** to **afm-main-binding.so**
1182 by removing the implicitly added prefix *lib*. This step is not mandatory
1183 because afb-daemon doesn't check names of files at load time.
1184 The only filename convention used by afb-daemon relates to **.so** termination.
1185 *.so pattern is used when afb-daemon automatically discovers binding from a directory hierarchy.
1187 2. It applies a version script at link time to only export the reserved name
1188 **afbBindingV1Register** for registration entry point. By default, when building
1189 a shared library linker exports all the public symbols (C functions that are not **static**).
1194 target_include_directories(afm-main-binding PRIVATE ${afb_INCLUDE_DIRS})
1195 target_link_libraries(afm-main-binding utils ${afb_LIBRARIES})
1198 As you can see it uses the variables computed by ***pkg_check_modules(afb afb-daemon)***
1199 to configure the compiler and the linker.
1201 ### Exporting the function afbBindingV1Register
1203 The function **afbBindingV1Register** MUST be exported. This can be achieved
1204 using a version script at link time. Here after is a version script used for
1205 *tic-tac-toe* (bindings/samples/export.map).
1207 { global: afbBindingV1Register; local: *; };
1209 This sample [version script](https://sourceware.org/binutils/docs-2.26/ld/VERSION.html#VERSION)
1210 exports as global the symbol *afbBindingV1Register* and hides any
1213 This version script is added to the link options using the
1214 option **--version-script=export.map** is given directly to the
1215 linker or using the option **-Wl,--version-script=export.map**
1216 when the option is given to the C compiler.
1218 ### Building within yocto
1220 Adding a dependency to afb-daemon is enough. See below:
1222 DEPENDS += " afb-daemon "