2 How to write a binding for AFB-DAEMON
3 ===================================
8 The afb-daemon binders serve files through HTTP protocol and offers to
9 developers the capability to offer application API methods through HTTP or
12 The 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
23 exposes application logic as sharable library. A binding is intended to be
24 dynamically loaded by ***afb-daemon*** to expose application API.
26 Technically, a binder binding does not reference and is not linked with any
27 ***afb-daemon*** library.
31 Application binder supports two kinds of bindings: application bindings and
32 service bindings. Technically both class of binding are equivalent and use the
33 same coding convention. Only sharing mode and security context diverge.
35 #### Application-bindings
37 Application-bindings implements the glue in between application's UI and
38 services. Every AGL application has a corresponding binder that typically
39 activates one or many bindings to interface the application logic with lower
40 platform services. When an application is started by the AGL application
41 framework, a dedicate binder is started that loads/activates application
42 binding(s). API expose by application-binding are executed within corresponding
43 application security context.
45 Application bindings generally handle a unique context for a unique client. As
46 the application framework start a dedicated instance of afb_daemon for each AGL
47 application, if a given binding is used within multiple application each of
48 those application get a new and private instance of eventually "shared" binding.
52 Service-bindings enable API activation within corresponding service security
53 context and not within calling application context. Service-bindings are
54 intended to run as a unique instance. Service-bindings can be shared in between
57 Service-bindings can either be stateless or manage client context. When managing
58 context each client get a private context. Sharing may either be global to the
59 platform (ie: GPS service) or dedicated to a given user (ie: user preferences)
61 ### Live cycle of bindings within ***afb-daemon***
63 Application and service bindings are loaded and activated each time a new
64 ***afb-daemon*** is started.
66 At launch time, every loaded binding initialise itself. If a single binding
67 initialisation fails the corresponding instance of ***afb-daemon*** aborts.
69 Conversely, when a binding initialisation succeeds, it should register its
70 unique name as well as the list of verbs (methods name from binder point of
71 view) attached to the methods it exposes.
73 When initialised, on request from application clients to the right API/verbs
74 binding methods are activated by the ***afb-daemon*** attached to the
75 application or service.
77 At exit time, no special action is enforced by ***afb-daemon***. When a specific
78 actions is required at afb-daemon stop, developers should use 'atexit/on_exit'
79 during binding initialisation sequence to register a custom exit function.
83 Afb-daemon's bindings register two classes of objects: names and functions.
85 Bindings declare categories of names:
86 - A unique binding name to access all API exposed by this binding,
87 - One name for each methods/verbs provided by this binding.
89 Bindings declare two categories of functions:
90 - function used for initialisation
91 - functions implementing the exposed API methods
93 Afb-daemon parses URI requests to extract the API(binding name) and the
94 VERB(method to activate). As an example, URI **foo/bar** translates to binding
95 named **foo** and method named **bar**. To serve such a request,
96 ***afb-daemon*** looks for an active binding named **foo** and then within this
97 binding for a method named **bar**. When found ***afb-daemon*** calls
98 the corresponding method with an attached parameter if any.
100 Afb-daemon is case-insensitive when parsing URI. Thus **TicTacToe/Board** and
101 **tictactoe/board** are equivalent.
103 #### The name of the binding
105 The name of a given binding is also known as the name
106 of the API prefix that defines the binding.
108 The name of a binding SHOULD be unique within a given ***afb-daemon*** instance.
110 For example, when a client of ***afb-daemon*** calls a URI named **foo/bar**.
111 Afb-daemon extracts the prefix **foo** and the suffix **bar**. **foo** must
112 match a binding name and **bar** has to match a VERB attached to some method.
114 #### Names of methods
116 Each binding exposes a set of methods that can be called by the clients of a
117 given ***afb-daemon***.
119 VERB's name attached to a given binding (API) MUST be unique within a binding.
121 Bindings static declaration link VERBS to the corresponding methods.
122 When clients emit requests on a given API/VERB corresponding method is called
125 #### Initialisation function
127 Binding's initialisation function serves several purposes.
129 1. It allows ***afb-daemon*** to control the binding version depending on
130 the initialisation of function name. As today, the only supported initialisation
131 function is **afbBindingV1Register**. This identifies version "one" of bindings.
133 2. It allows bindings to initialise itself.
135 3. It enables names declarations: descriptions, requirements and implementations
138 #### Functions instantiation of API/VERBs
140 When an API/VERB is called, ***afb-daemon*** constructs a request object. Then
141 it passes this request object to the implementation function corresponding to
142 requested method, this within attached API binding.
144 An implementation function receives a request object used to: get
145 the arguments of the request, send an answer, store session data.
147 A binding MUST set an answer to every received requests.
149 Nevertheless, there are two implementations, *synchronous* and *asynchronous*.
150 API/VERB implementation that set an answer before returning are called
151 *synchronous implementations*. Those that do not systematically set an answer
152 before returning are called *asynchronous implementations*.
154 Asynchronous implementations typically launch asynchronous actions. They record
155 some context at request time and provide an answer to the request only at
156 completion of asynchronous actions.
158 The Tic-Tac-Toe example
159 -----------------------
161 This part explains how to write an afb-binding. For the sake of being practical
162 it uses many examples based on tic-tac-toe. This binding example is in
163 *bindings/samples/tic-tac-toe.c*.
165 This binding is named ***tictactoe***.
167 Dependencies when compiling
168 ---------------------------
170 Afb-daemon provides a configuration file for *pkg-config*.
173 pkg-config --cflags afb-daemon
175 Print flags use for compilation:
177 $ pkg-config --cflags afb-daemon
178 -I/opt/local/include -I/usr/include/json-c
180 For linking, you should use
182 $ pkg-config --libs afb-daemon
185 Afb-daemon automatically includes the dependency to json-c.
186 This is activated through **Requires** keyword in pkg-config.
187 While almost every binding replies on **json-c** this is not a must have
190 Internally, ***afb-daemon*** relies on **libsystemd** for its event loop, as
191 well as for its binding to D-Bus. Bindings developers are encouraged to leverage
192 **libsystemd** when possible. Nevertheless there is no hard dependency to
193 **libsystemd** if you do not want to use it, feel free to do so.
195 > Afb-daemon bindings are fully self contained. They do not enforce dependency
196 on any libraries from the application framework.
197 > Afb-daemon dependencies requirer to run AGL bindings are given at runtime
198 through pointers leveraging read-only
201 Header files to include
202 -----------------------
204 Binding *tictactoe* has following includes:
210 #include <json-c/json.h>
211 #include <afb/afb-binding.h>
214 Header *afb/afb-binding.h* is the only hard dependency, it includes all features
215 that a binding MUST HAVE. Outside of includes used to support application logic,
216 common external headers used within bindings are:
218 - *json-c/json.h*: should be include to handle json objects;
219 - *systemd/sd-event.h*: should be include to access event main loop;
220 - *systemd/sd-bus.h*: should be include for dbus connections.
222 The *tictactoe* binding does not leverage systemd features, also only json.h
223 is used on top of mandatory afb/afb-binding.h.
225 When including *afb/afb-binding.h*, the macro **_GNU_SOURCE** MUST be
231 Designers of bindings should define a unique name for every API binding
232 as well as for methods VERBs. They should also define names for request
233 arguments passed as name/value pair in URI.
235 While forging names, designers should respect few rules to
236 ensure that created names are valid and easy to use across platforms.
238 All names and strings are UTF-8 encoded.
240 ### Names for API (binding)
242 Binding API name are checked.
243 All characters are authorised except:
245 - the control characters (\u0000 .. \u001f)
246 - the characters of the set { ' ', '"', '#', '%', '&',
247 '\'', '/', '?', '`', '\x7f' }
249 In other words the set of forbidden characters is
250 { \u0000..\u0020, \u0022, \u0023, \u0025..\u0027,
251 \u002f, \u003f, \u0060, \u007f }.
253 Afb-daemon makes no distinction between lower case
254 and upper case when searching for API/VERB.
256 ### Names for methods
258 The names of methods VERBs are totally free and not checked.
260 However, the validity rules for method's VERB name are the
261 same as for Binding API name except that the dot(.) character
264 Afb-daemon makes no case distinction when searching for an API by name.
266 ### Names for arguments
268 Argument's name are not restricted and can be everything you wish.
270 > Warning arguments search is case sensitive and "index" and "Index"
271 > are not two different arguments.
273 ### Forging names widely available
275 The key names of javascript object can be almost
276 anything using the arrayed notation:
280 Nevertheless this is not the case with javascript dot notation:
284 Using the dot notation, the key must be a valid javascript
285 identifier and dash(-) as well as few other reserved characters cannot be used.
287 For this reason, we advise developers to chose name compatible with both
288 javascript and HTML notation.
290 It is a good practice, even for arguments not to rely on case sensitivity.
291 This may reduce headache strength at debug time, especially with interpreted
292 language like javascript that may not warn you that a variable was not defined.
294 Declaration of methods and initialisation of the bindings
295 ---------------------------------------------------------
297 ### Declaration of methods
299 To be active, binding's methods should be declared to
300 ***afb-daemon***. Furthermore, the binding itself must be recorded.
302 The registration mechanism is very basic: when ***afb-daemon*** starts,
303 it loads all bindings listed in: command line or configuration file.
305 Loading a binding follows the following steps:
307 1. Afb-daemon loads the binding with *dlopen*.
309 2. Afb-daemon searches for a symbol named **afbBindingV1Register** using *dlsym*.
310 This symbol is assumed to be the exported initialisation function of the binding.
312 3. Afb-daemon builds an interface object for the binding.
314 4. Afb-daemon calls the found function **afbBindingV1Register** with interface pointer
317 5. Function **afbBindingV1Register** setups the binding and initialises it.
319 6. Function **afbBindingV1Register** returns the pointer to a structure
320 describing the binding: version, name (prefix or API name), and list of methods.
322 7. Afb-daemon checks that the returned version and name can be managed.
323 If so, binding and its methods are register to become usable as soon as
324 ***afb-daemon*** initialisation is finished.
326 ### Initialisation of bindings
328 The bindings initialisation is the final step made at the end of declaration of
329 methods. This will initialize the binding and make its ***afb-daemon***'s
330 interface fully functional.
332 So, afb-daemon binder call **afbBindingV1ServiceInit** as final step to a
333 binding. This will allows the binding to call features in its name and as saw in
334 [Binder events guide](afb-events-guide.md) you can create an event only at this
335 moment and not before. Before that it will fail because afb-daemon doesn't know
338 **afbBindingV1ServiceInit** is defined as below:
342 * When a binding have an exported implementation of the
343 * function 'afbBindingV1ServiceInit', defined below,
344 * the framework calls it for initialising the service after
345 * registration of all bindings.
347 * The object 'service' should be recorded. It has functions that
348 * allows the binding to call features with its own personality.
350 * The function should return 0 in case of success or, else, should return
353 extern int afbBindingV1ServiceInit(struct afb_service service);
356 ### Application binding example: tic-tac-toe
358 If we continue our tic-tac-toe example, here after the code used for
359 **afbBindingV1Register** implementation from binding *tic-tac-toe*:
363 * activation function for registering the binding called by afb-daemon
365 const struct afb_binding *afbBindingV1Register(const struct afb_binding_interface *itf)
367 afbitf = itf; // records the interface for accessing afb-daemon
368 return &binding_description; // returns the description of the binding
372 It is a very minimal initialisation function because *tic-tac-toe* binding doesn't
373 have any application related initialisation step. It merely record daemon's interface
374 and returns its description.
376 The variable **afbitf** is a binding global variable. It keeps the
377 interface to ***afb-daemon*** that should be used for logging and pushing events.
378 Here is its declaration:
382 * the interface to afb-daemon
384 const struct afb_binding_interface *afbitf;
387 The description of the binding is defined here after.
391 * array of the methods exported to afb-daemon
393 static const struct afb_verb_desc_v1 binding_methods[] = {
394 /* VERB'S NAME SESSION MANAGEMENT FUNCTION TO CALL SHORT DESCRIPTION */
395 { .name= "new", .session= AFB_SESSION_NONE, .callback= new, .info= "Starts a new game" },
396 { .name= "play", .session= AFB_SESSION_NONE, .callback= play, .info= "Asks the server to play" },
397 { .name= "move", .session= AFB_SESSION_NONE, .callback= move, .info= "Tells the client move" },
398 { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" },
399 { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" },
400 { .name= "join", .session= AFB_SESSION_CHECK,.callback= join, .info= "Join a board" },
401 { .name= "undo", .session= AFB_SESSION_NONE, .callback= undo, .info= "Undo the last move" },
402 { .name= "wait", .session= AFB_SESSION_NONE, .callback= wait, .info= "Wait for a change" },
403 { .name= NULL } /* marker for end of the array */
407 * description of the binding for afb-daemon
409 static const struct afb_binding binding_description =
411 /* description conforms to VERSION 1 */
412 .type= AFB_BINDING_VERSION_1,
413 .v1= { /* fills the v1 field of the union when AFB_BINDING_VERSION_1 */
414 .prefix= "tictactoe", /* the API name (or binding name or prefix) */
415 .info= "Sample tac-tac-toe game", /* short description of of the binding */
416 .methods = binding_methods /* the array describing the methods of the API */
421 The structure **binding_description** describes the binding.
422 It declares the type and version of the binding, its name, a short description
423 and its methods list.
425 The list of methods is an array of structures describing the methods and terminated by a NULL marker.
427 In version one of afb-damon binding, a method description contains 4 fields:
429 - the name of the method,
431 - the session management flags,
433 - the implementation function to be call for the method,
435 - a short description.
437 The structure describing methods is defined as follows:
441 * Description of one method of the API provided by the binding
442 * This enumeration is valid for bindings of type 1
444 struct afb_verb_desc_v1
446 const char *name; /* name of the method */
447 enum AFB_session_v1 session; /* authorisation and session requirements of the method */
448 void (*callback)(struct afb_req req); /* callback function implementing the method */
449 const char *info; /* textual description of the method */
453 For technical reasons, the enumeration **enum AFB_session_v1** is not exactly an
454 enumeration but the wrapper of constant definitions that can be mixed using bitwise or
457 The constants that can bit mixed are:
459 Constant name | Meaning
460 -------------------------|-------------------------------------------------------------
461 **AFB_SESSION_CREATE** | Equals to AFB_SESSION_LOA_EQ_0|AFB_SESSION_RENEW
462 **AFB_SESSION_CLOSE** | Closes the session after the reply and set the LOA to 0
463 **AFB_SESSION_RENEW** | Refreshes the token of authentification
464 **AFB_SESSION_CHECK** | Just requires the token authentification
465 **AFB_SESSION_LOA_LE_0** | Requires the current LOA to be lesser then or equal to 0
466 **AFB_SESSION_LOA_LE_1** | Requires the current LOA to be lesser then or equal to 1
467 **AFB_SESSION_LOA_LE_2** | Requires the current LOA to be lesser then or equal to 2
468 **AFB_SESSION_LOA_LE_3** | Requires the current LOA to be lesser then or equal to 3
469 **AFB_SESSION_LOA_GE_0** | Requires the current LOA to be greater then or equal to 0
470 **AFB_SESSION_LOA_GE_1** | Requires the current LOA to be greater then or equal to 1
471 **AFB_SESSION_LOA_GE_2** | Requires the current LOA to be greater then or equal to 2
472 **AFB_SESSION_LOA_GE_3** | Requires the current LOA to be greater then or equal to 3
473 **AFB_SESSION_LOA_EQ_0** | Requires the current LOA to be equal to 0
474 **AFB_SESSION_LOA_EQ_1** | Requires the current LOA to be equal to 1
475 **AFB_SESSION_LOA_EQ_2** | Requires the current LOA to be equal to 2
476 **AFB_SESSION_LOA_EQ_3** | Requires the current LOA to be equal to 3
478 If any of this flag is set, ***afb-daemon*** requires an authentication token
479 as if **AFB_SESSION_CHECK** flag was also set.
481 The special value **AFB_SESSION_NONE** is zero and can be used to bypass token check.
483 > Note that **AFB_SESSION_CREATE** and **AFB_SESSION_CLOSE** might be removed in later versions.
485 Sending messages to the log system
486 ----------------------------------
488 Afb-daemon provides 4 levels of verbosity and 5 methods for logging messages.
490 The verbosity is managed. Options allow the change the verbosity of ***afb-daemon***
491 and the verbosity of the bindings can be set binding by binding.
493 The methods for logging messages are defined as macros that test the
494 verbosity level and that call the real logging function only if the
495 message must be output. This avoid evaluation of arguments of the
496 formatting messages if the message must not be output.
498 ### Verbs for logging messages
500 The 5 logging methods are:
502 Macro | Verbosity | Meaning | syslog level
503 --------|:---------:|-----------------------------------|:-----------:
504 ERROR | 0 | Error conditions | 3
505 WARNING | 1 | Warning conditions | 4
506 NOTICE | 1 | Normal but significant condition | 5
507 INFO | 2 | Informational | 6
508 DEBUG | 3 | Debug-level messages | 7
510 You can note that the 2 methods **WARNING** and **NOTICE** have the same level
511 of verbosity. But they don't have the same *syslog level*. It means that
512 they are output with a different level on the logging system.
514 All of these methods have the same signature:
517 void ERROR(const struct afb_binding_interface *afbitf, const char *message, ...);
520 The first argument **afbitf** is the interface to afb daemon that the
521 binding received at initialisation time when **afbBindingV1Register** is called.
523 The second argument **message** is a formatting string compatible with printf/sprintf.
525 The remaining arguments are arguments of the formating message like with printf.
527 ### Managing verbosity
529 Depending on the level of verbosity, the messages are output or not.
530 The following table explains what messages will be output depending
531 ont the verbosity level.
533 Level of verbosity | Outputed macro
534 :-----------------:|--------------------------
536 1 | ERROR + WARNING + NOTICE
537 2 | ERROR + WARNING + NOTICE + INFO
538 3 | ERROR + WARNING + NOTICE + INFO + DEBUG
540 ### Output format and destination
542 The syslog level is used for forging a prefix to the message.
545 syslog level | prefix
546 :-----------:|---------------
557 The message is pushed to standard error.
558 The final destination of the message depends on how systemd service
559 was configured through its variable **StandardError**. It can be
560 journal, syslog or kmsg. (See man sd-daemon).
565 Specific documentation exists about [sending events](afb-events-guide.md).
567 The binding *tic-tac-toe* broadcasts events when the board changes. This is done
568 in the function ***changed***:
572 * signals a change of the board
574 static void changed(struct board *board, const char *reason)
577 struct json_object *description;
579 /* get the description */
580 description = describe(board);
584 afb_daemon_broadcast_event(afbitf->daemon, reason, description);
588 The description of the changed board is pushed via the daemon interface.
590 Within binding *tic-tac-toe*, *reason* indicates the origin of
591 the change. In function **afb_daemon_broadcast_event** the second
592 parameter is the name of broadcasted event. The third argument is the
593 object that is transmitted with the event.
595 Function **afb_daemon_broadcast_event** is defined here after:
599 * Broadcasts widely the event of 'name' with the data 'object'.
600 * 'object' can be NULL.
601 * 'daemon' MUST be the daemon given in interface when activating the binding.
603 * For convenience, the function calls 'json_object_put' for 'object'.
604 * Thus, in the case where 'object' should remain available after
605 * the function returns, the function 'json_object_get' shall be used.
607 void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
610 > Be aware, as with reply functions **object** is automatically released using
611 > **json_object_put** when using this function. Call **json_object_get** before
612 > calling **afb_daemon_broadcast_event** to keep **object** available
613 > after function returns.
615 Event name received by listeners is prefixed with binding name.
616 So when a change occurs after a move, the reason is **move** and every clients
617 receive an event **tictactoe/move**.
619 > Note that nothing is said about case sensitivity of event names.
620 > However, the event is always prefixed with the name that the binding
621 > declared, with the same case, followed with a slash /.
622 > Thus it is safe to compare event using a case sensitive comparison.
624 Writing a synchronous method implementation
625 -----------------------------------------
627 The method **tictactoe/board** is a synchronous implementation.
634 static void board(struct afb_req req)
637 struct json_object *description;
639 /* retrieves the context for the session */
640 board = board_of_req(req);
641 INFO(afbitf, "method 'board' called for boardid %d", board->id);
643 /* describe the board */
644 description = describe(board);
646 /* send the board's description */
647 afb_req_success(req, description, NULL);
651 This example shows many aspects of a synchronous
652 method implementation. Let summarise it:
654 1. The function **board_of_req** retrieves the context stored
655 for the binding: the board.
657 2. The macro **INFO** sends a message of kind *INFO*
658 to the logging system. The global variable named **afbitf**
659 used represents the interface to ***afb-daemon***.
661 3. The function **describe** creates a json_object representing
664 4. The function **afb_req_success** sends the reply, attaching to
665 it the object *description*.
667 ### The incoming request
669 For any implementation, the request is received by a structure of type
672 > Note that this is a PLAIN structure, not a pointer to a structure.
674 The definition of **struct afb_req** is:
678 * Describes the request by bindings from afb-daemon
681 const struct afb_req_itf *itf; /* the interfacing functions */
682 void *closure; /* the closure for functions */
686 It contains two pointers: first one *itf*, points to functions used
687 to handle internal request. Second one *closure* point onto function closure.
689 > The structure must never be used directly.
690 > Instead developer should use the intended functions provided
691 > by ***afb-daemon*** as described here after.
693 *req* is used to get arguments of the request, to send
694 answer, to store session data.
696 This object and its interface is defined and documented
697 in the file names *afb/afb-req-itf.h*
699 The above example uses twice *req* object request.
701 The first time, to retrieve the board attached to the session of the request.
703 The second time, to send the reply: an object that describes the current board.
705 ### Associating a client context to a session
707 When *tic-tac-toe* binding receives a request, it musts get
708 the board describing the game associated to the session.
710 For a binding, having data associated to a session is common.
711 This data is called "binding context" for the session.
712 Within *tic-tac-toe* binding the context is the board.
714 Requests *afb_req* offer four functions for storing and retrieving session
719 - **afb_req_context_get**:
720 retrieves context data stored for current binding.
722 - **afb_req_context_set**:
723 store context data of current binding.
725 - **afb_req_context**:
726 if exist retrieves context data of current binding.
727 if context does not yet exist, creates a new context and store it.
729 - **afb_req_context_clear**:
730 reset the stored context data.
732 The binding *tictactoe* use a convenient function to retrieve
733 its context: the board. This function is *board_of_req*:
737 * retrieves the board of the request
739 static inline struct board *board_of_req(struct afb_req req)
741 return afb_req_context(req, (void*)get_new_board, (void*)release_board);
745 The function **afb_req_context** ensures an existing context
746 for the session of the request.
747 Its two last arguments are functions to allocate and free context.
748 Note function type casts to avoid compilation warnings.
750 Here is the definition of the function **afb_req_context**
754 * Gets the pointer stored by the binding for the session of 'req'.
755 * If the stored pointer is NULL, indicating that no pointer was
756 * already stored, afb_req_context creates a new context by calling
757 * the function 'create_context' and stores it with the freeing function
760 static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*))
762 void *result = afb_req_context_get(req);
763 if (result == NULL) {
764 result = create_context();
765 afb_req_context_set(req, result, free_context);
771 The second argument if the function that creates the context.
772 For binding *tic-tac-toe* (function **get_new_board**).
773 The function **get_new_board** creates a new board and set usage its count to 1.
774 The boards are checking usage count to free resources when not used.
776 The third argument is a function that frees context resources.
777 For binding *tic-tac-toe* (function **release_board**).
778 The function **release_board** decrease usage count of the board passed in
779 argument. When usage count falls to zero, data board are freed.
781 Definition of other functions dealing with contexts:
785 * Gets the pointer stored by the binding for the session of 'req'.
786 * When the binding has not yet recorded a pointer, NULL is returned.
788 void *afb_req_context_get(struct afb_req req);
791 * Stores for the binding the pointer 'context' to the session of 'req'.
792 * The function 'free_context' will be called when the session is closed
793 * or if binding stores an other pointer.
795 void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));
798 * Frees the pointer stored by the binding for the session of 'req'
799 * and sets it to NULL.
801 * Shortcut for: afb_req_context_set(req, NULL, NULL)
803 static inline void afb_req_context_clear(struct afb_req req)
805 afb_req_context_set(req, NULL, NULL);
809 ### Sending reply to a request
811 Two kinds of replies: successful or failure.
813 > Sending a reply to a request MUST be done once and only once.
815 It exists two functions for "success" replies: **afb_req_success** and **afb_req_success_f**.
819 * Sends a reply of kind success to the request 'req'.
820 * The status of the reply is automatically set to "success".
821 * Its send the object 'obj' (can be NULL) with an
822 * informationnal comment 'info (can also be NULL).
824 * For convenience, the function calls 'json_object_put' for 'obj'.
825 * Thus, in the case where 'obj' should remain available after
826 * the function returns, the function 'json_object_get' shall be used.
828 void afb_req_success(struct afb_req req, struct json_object *obj, const char *info);
831 * Same as 'afb_req_success' but the 'info' is a formatting
832 * string followed by arguments.
834 * For convenience, the function calls 'json_object_put' for 'obj'.
835 * Thus, in the case where 'obj' should remain available after
836 * the function returns, the function 'json_object_get' shall be used.
838 void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
841 It exists two functions for "failure" replies: **afb_req_fail** and **afb_req_fail_f**.
845 * Sends a reply of kind failure to the request 'req'.
846 * The status of the reply is set to 'status' and an
847 * informational comment 'info' (can also be NULL) can be added.
849 * Note that calling afb_req_fail("success", info) is equivalent
850 * to call afb_req_success(NULL, info). Thus even if possible it
851 * is strongly recommended to NEVER use "success" for status.
853 * For convenience, the function calls 'json_object_put' for 'obj'.
854 * Thus, in the case where 'obj' should remain available after
855 * the function returns, the function 'json_object_get' shall be used.
857 void afb_req_fail(struct afb_req req, const char *status, const char *info);
860 * Same as 'afb_req_fail' but the 'info' is a formatting
861 * string followed by arguments.
863 * For convenience, the function calls 'json_object_put' for 'obj'.
864 * Thus, in the case where 'obj' should remain available after
865 * the function returns, the function 'json_object_get' shall be used.
867 void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
870 > For convenience, these functions automatically call **json_object_put** to release **obj**.
871 > Because **obj** usage count is null after being passed to a reply function, it SHOULD not be used anymore.
872 > If exceptionally **obj** needs to remain usable after reply function then using **json_object_get** on **obj**
873 > to increase usage count and cancels the effect the **json_object_put** is possible.
875 Getting argument of invocation
876 ------------------------------
878 Many methods expect arguments. Afb-daemon's bindings
879 retrieve arguments by name and not by position.
881 Arguments are passed by requests through either HTTP
884 For example, the method **join** of binding **tic-tac-toe**
885 expects one argument: the *boardid* to join. Here is an extract:
891 static void join(struct afb_req req)
893 struct board *board, *new_board;
896 /* retrieves the context for the session */
897 board = board_of_req(req);
898 INFO(afbitf, "method 'join' called for boardid %d", board->id);
900 /* retrieves the argument */
901 id = afb_req_value(req, "boardid");
907 The function **afb_req_value** searches in the request *req*
908 for argument name passed in the second argument. When argument name
909 is not passed, **afb_req_value** returns NULL.
911 > The search is case sensitive and *boardid* is not equivalent to *BoardId*.
912 > Nevertheless having argument names that only differ by name case is not a good idea.
914 ### Basic functions for querying arguments
916 The function **afb_req_value** is defined here after:
920 * Gets from the request 'req' the string value of the argument of 'name'.
921 * Returns NULL if when there is no argument of 'name'.
922 * Returns the value of the argument of 'name' otherwise.
924 * Shortcut for: afb_req_get(req, name).value
926 static inline const char *afb_req_value(struct afb_req req, const char *name)
928 return afb_req_get(req, name).value;
932 It is defined as a shortcut to call the function **afb_req_get**.
933 That function is defined here after:
937 * Gets from the request 'req' the argument of 'name'.
938 * Returns a PLAIN structure of type 'struct afb_arg'.
939 * When the argument of 'name' is not found, all fields of result are set to NULL.
940 * When the argument of 'name' is found, the fields are filled,
941 * in particular, the field 'result.name' is set to 'name'.
943 * There is a special name value: the empty string.
944 * The argument of name "" is defined only if the request was made using
945 * an HTTP POST of Content-Type "application/json". In that case, the
946 * argument of name "" receives the value of the body of the HTTP request.
948 struct afb_arg afb_req_get(struct afb_req req, const char *name);
951 That function takes 2 parameters: the request and the name
952 of the argument to retrieve. It returns a PLAIN structure of
953 type **struct afb_arg**.
955 There is a special name that is defined when the request is
956 of type HTTP/POST with a Content-Type being application/json.
957 This name is **""** (the empty string). In that case, the value
958 of this argument of empty name is the string received as a body
959 of the post and is supposed to be a JSON string.
961 The definition of **struct afb_arg** is:
965 * Describes an argument (or parameter) of a request
968 const char *name; /* name of the argument or NULL if invalid */
969 const char *value; /* string representation of the value of the argument */
970 /* original filename of the argument if path != NULL */
971 const char *path; /* if not NULL, path of the received file for the argument */
972 /* when the request is finalized this file is removed */
976 The structure returns the data arguments that are known for the
977 request. This data include a field named **path**. This **path**
978 can be accessed using the function **afb_req_path** defined here after:
982 * Gets from the request 'req' the path for file attached to the argument of 'name'.
983 * Returns NULL if when there is no argument of 'name' or when there is no file.
984 * Returns the path of the argument of 'name' otherwise.
986 * Shortcut for: afb_req_get(req, name).path
988 static inline const char *afb_req_path(struct afb_req req, const char *name)
990 return afb_req_get(req, name).path;
994 The path is only defined for HTTP/POST requests that send file.
996 ### Arguments for received files
998 As it is explained above, clients can send files using HTTP/POST requests.
1000 Received files are attached to "file" argument name. For example, the
1001 following HTTP fragment (from test/sample-post.html)
1002 will send an HTTP/POST request to the method
1003 **post/upload-image** with 2 arguments named *file* and
1007 <h2>Sample Post File</h2>
1008 <form enctype="multipart/form-data">
1009 <input type="file" name="file" />
1010 <input type="hidden" name="hidden" value="bollobollo" />
1012 <button formmethod="POST" formaction="api/post/upload-image">Post File</button>
1016 Argument named **file** should have both its value and path defined.
1018 The value is the name of the file as it was set by the HTTP client.
1019 Generally it is the filename on client side.
1021 The path is the effective path of saved file on the temporary local storage
1022 area of the application. This is a randomly generated and unique filename.
1023 It is not linked with the original filename as used on client side.
1025 After success the binding can use the uploaded file directly from local storage path with no restriction:
1026 read, write, remove, copy, rename...
1027 Nevertheless when request reply is set and query terminated, the uploaded temporary file at
1030 ### Arguments as a JSON object
1032 Bindings may also request every arguments of a given call as one single object.
1033 This feature is provided by the function **afb_req_json** defined here after:
1037 * Gets from the request 'req' the json object hashing the arguments.
1038 * The returned object must not be released using 'json_object_put'.
1040 struct json_object *afb_req_json(struct afb_req req);
1043 It returns a json object. This object depends on how the request was built:
1045 - For HTTP requests, this json object uses key names mapped on argument name.
1046 Values are either string for common arguments or object ie: { "file": "...", "path": "..." }
1048 - For WebSockets requests, returned directly the object as provided by the client.
1050 > In fact, for Websockets requests, the function **afb_req_value**
1051 > can be seen as a shortcut to
1052 > ***json_object_get_string(json_object_object_get(afb_req_json(req), name))***
1055 Writing an asynchronous method implementation
1056 -------------------------------------------
1058 The *tic-tac-toe* example allows two clients or more to share the same board.
1059 This is implemented by the method **join** that illustrated partly how to
1062 When two or more clients are sharing a same board, one of them can wait
1063 until the state of the board changes, but this could also be implemented using
1064 events because an event is generated each time the board changes.
1066 In this case, the reply to the wait is sent only when the board changes.
1067 See the diagram below:
1069 ![tic-tac-toe_diagram][tic-tac-toe_diagram]
1071 Here, this is an invocation of the binding by an other client that
1072 unblock the suspended *wait* call.
1073 Nevertheless in most case this should be a timer, a hardware event, a sync with
1074 a concurrent process or thread, ...
1076 Common case of an asynchronous implementation.
1078 Here is the listing of the function **wait**:
1081 static void wait(struct afb_req req)
1083 struct board *board;
1084 struct waiter *waiter;
1086 /* retrieves the context for the session */
1087 board = board_of_req(req);
1088 INFO(afbitf, "method 'wait' called for boardid %d", board->id);
1090 /* creates the waiter and enqueues it */
1091 waiter = calloc(1, sizeof *waiter);
1093 waiter->next = board->waiters;
1094 afb_req_addref(req);
1095 board->waiters = waiter;
1099 After retrieving the board, the function adds a new waiter to
1100 waiters list and returns without setting a reply.
1102 Before returning, it increases **req** request's reference count using **afb_req_addref** function.
1104 > When a method returns without setting a reply,
1105 > it **MUST** increment request's reference count
1106 > using **afb_req_addref**. If unpredictable behaviour may pop up.
1108 Later, when a board changes, it calls *tic-tac-toe* **changed** function
1109 with reason of change in parameter.
1111 Here is the full listing of the function **changed**:
1115 * signals a change of the board
1117 static void changed(struct board *board, const char *reason)
1119 struct waiter *waiter, *next;
1120 struct json_object *description;
1122 /* get the description */
1123 description = describe(board);
1125 waiter = board->waiters;
1126 board->waiters = NULL;
1127 while (waiter != NULL) {
1128 next = waiter->next;
1129 afb_req_success(waiter->req, json_object_get(description), reason);
1130 afb_req_unref(waiter->req);
1135 afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description);
1139 The list of waiters is walked and a reply is sent to each waiter.
1140 After sending the reply, the reference count of the request
1141 is decremented using **afb_req_unref** to allow resources to be freed.
1143 > The reference count **MUST** be decremented using **afb_req_unref** to free
1144 > resources and avoid memory leaks.
1145 > This usage count decrement should happen **AFTER** setting reply or
1146 > bad things may happen.
1148 Sending messages to the log system
1149 ----------------------------------
1151 Afb-daemon provides 4 levels of verbosity and 5 methods for logging messages.
1153 The verbosity is managed. Options allow the change the verbosity of ***afb-daemon***
1154 and the verbosity of the bindings can be set binding by binding.
1156 The methods for logging messages are defined as macros that test the
1157 verbosity level and that call the real logging function only if the
1158 message must be output. This avoid evaluation of arguments of the
1159 formatting messages if the message must not be output.
1161 ### Verbs for logging messages
1163 The 5 logging methods are:
1165 Macro | Verbosity | Meaning | syslog level
1166 --------|:---------:|-----------------------------------|:-----------:
1167 ERROR | 0 | Error conditions | 3
1168 WARNING | 1 | Warning conditions | 4
1169 NOTICE | 1 | Normal but significant condition | 5
1170 INFO | 2 | Informational | 6
1171 DEBUG | 3 | Debug-level messages | 7
1173 You can note that the 2 methods **WARNING** and **NOTICE** have the same level
1174 of verbosity. But they don't have the same *syslog level*. It means that
1175 they are output with a different level on the logging system.
1177 All of these methods have the same signature:
1180 void ERROR(const struct afb_binding_interface *afbitf, const char *message, ...);
1183 The first argument **afbitf** is the interface to afb daemon that the
1184 binding received at initialisation time when **afbBindingV1Register** is called.
1186 The second argument **message** is a formatting string compatible with printf/sprintf.
1188 The remaining arguments are arguments of the formating message like with printf.
1190 ### Managing verbosity
1192 Depending on the level of verbosity, the messages are output or not.
1193 The following table explains what messages will be output depending
1194 ont the verbosity level.
1196 Level of verbosity | Outputed macro
1197 :-----------------:|--------------------------
1199 1 | ERROR + WARNING + NOTICE
1200 2 | ERROR + WARNING + NOTICE + INFO
1201 3 | ERROR + WARNING + NOTICE + INFO + DEBUG
1203 ### Output format and destination
1205 The syslog level is used for forging a prefix to the message.
1208 syslog level | prefix
1209 :-----------:|---------------
1220 The message is pushed to standard error.
1221 The final destination of the message depends on how systemd service
1222 was configured through its variable **StandardError**. It can be
1223 journal, syslog or kmsg. (See man sd-daemon).
1228 Since version 0.5, bindings can broadcast events to any potential listener.
1229 As today only unattended events are supported. Targeted events are expected for
1230 next coming version.
1232 The binding *tic-tac-toe* broadcasts events when the board changes.
1233 This is done in the function **changed**:
1237 * signals a change of the board
1239 static void changed(struct board *board, const char *reason)
1242 struct json_object *description;
1244 /* get the description */
1245 description = describe(board);
1249 afb_daemon_broadcast_event(afbitf->daemon, reason, description);
1253 The description of the changed board is pushed via the daemon interface.
1255 Within binding *tic-tac-toe*, *reason* indicates the origin of
1256 the change. In function **afb_daemon_broadcast_event** the second
1257 parameter is the name of broadcasted event. The third argument is the
1258 object that is transmitted with the event.
1260 Function **afb_daemon_broadcast_event** is defined here after:
1264 * Broadcasts widely the event of 'name' with the data 'object'.
1265 * 'object' can be NULL.
1266 * 'daemon' MUST be the daemon given in interface when activating the binding.
1268 * For convenience, the function calls 'json_object_put' for 'object'.
1269 * Thus, in the case where 'object' should remain available after
1270 * the function returns, the function 'json_object_get' shall be used.
1272 void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
1275 > Be aware, as with reply functions **object** is automatically released using
1276 > **json_object_put** when using this function. Call **json_object_get** before
1277 > calling **afb_daemon_broadcast_event** to keep **object** available
1278 > after function returns.
1280 Event name received by listeners is prefixed with binding name.
1281 So when a change occurs after a move, the reason is **move** and every clients
1282 receive an event **tictactoe/move**.
1284 > Note that nothing is said about case sensitivity of event names.
1285 > However, the event is always prefixed with the name that the binding
1286 > declared, with the same case, followed with a slash /.
1287 > Thus it is safe to compare event using a case sensitive comparison.
1289 How to build a binding
1290 ---------------------
1292 Afb-daemon provides a *pkg-config* configuration file that can be
1293 queried by providing ***afb-daemon*** in command line arguments.
1294 This configuration file provides data that should be used
1295 for bindings compilation. Examples:
1298 $ pkg-config --cflags afb-daemon
1299 $ pkg-config --libs afb-daemon
1302 ### Example for cmake meta build system
1304 This example is the extract for building the binding *afm-main* using *CMAKE*.
1307 pkg_check_modules(afb afb-daemon)
1309 message(STATUS "Creation afm-main-binding for AFB-DAEMON")
1310 add_library(afm-main-binding MODULE afm-main-binding.c)
1311 target_compile_options(afm-main-binding PRIVATE ${afb_CFLAGS})
1312 target_include_directories(afm-main-binding PRIVATE ${afb_INCLUDE_DIRS})
1313 target_link_libraries(afm-main-binding utils ${afb_LIBRARIES})
1314 set_target_properties(afm-main-binding PROPERTIES
1316 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-binding.export-map"
1318 install(TARGETS afm-main-binding LIBRARY DESTINATION ${binding_dir})
1320 message(STATUS "Not creating the binding for AFB-DAEMON")
1324 Let now describe some of these lines.
1327 pkg_check_modules(afb afb-daemon)
1330 This first lines searches to the *pkg-config* configuration file for
1331 **afb-daemon**. Resulting data are stored in the following variables:
1334 ------------------|------------------------------------------------
1335 afb_FOUND | Set to 1 if afb-daemon binding development files exist
1336 afb_LIBRARIES | Only the libraries (w/o the '-l') for compiling afb-daemon bindings
1337 afb_LIBRARY_DIRS | The paths of the libraries (w/o the '-L') for compiling afb-daemon bindings
1338 afb_LDFLAGS | All required linker flags for compiling afb-daemon bindings
1339 afb_INCLUDE_DIRS | The '-I' preprocessor flags (w/o the '-I') for compiling afb-daemon bindings
1340 afb_CFLAGS | All required cflags for compiling afb-daemon bindings
1342 If development files are found, the binding can be added to the set of
1346 add_library(afm-main-binding MODULE afm-main-binding.c)
1349 This line asks to create a shared library having a single
1350 source file named afm-main-binding.c to be compiled.
1351 The default name of the created shared object is
1352 **libafm-main-binding.so**.
1355 set_target_properties(afm-main-binding PROPERTIES
1357 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-binding.export-map"
1361 This lines are doing two things:
1363 1. It renames the built library from **libafm-main-binding.so** to **afm-main-binding.so**
1364 by removing the implicitly added prefix *lib*. This step is not mandatory
1365 because afb-daemon doesn't check names of files at load time.
1366 The only filename convention used by afb-daemon relates to **.so** termination.
1367 *.so pattern is used when afb-daemon automatically discovers binding from a directory hierarchy.
1369 2. It applies a version script at link time to only export the reserved name
1370 **afbBindingV1Register** for registration entry point. By default, when building
1371 a shared library linker exports all the public symbols (C functions that are not **static**).
1376 target_include_directories(afm-main-binding PRIVATE ${afb_INCLUDE_DIRS})
1377 target_link_libraries(afm-main-binding utils ${afb_LIBRARIES})
1380 As you can see it uses the variables computed by ***pkg_check_modules(afb afb-daemon)***
1381 to configure the compiler and the linker.
1383 ### Exporting the function afbBindingV1Register
1385 The function **afbBindingV1Register** MUST be exported. This can be achieved
1386 using a version script at link time. Here after is a version script used for
1387 *tic-tac-toe* (bindings/samples/export.map).
1389 { global: afbBindingV1Register; local: *; };
1391 This sample [version script](https://sourceware.org/binutils/docs-2.26/ld/VERSION.html#VERSION)
1392 exports as global the symbol *afbBindingV1Register* and hides any
1395 This version script is added to the link options using the
1396 option **--version-script=export.map** is given directly to the
1397 linker or using the option **-Wl,--version-script=export.map**
1398 when the option is given to the C compiler.
1400 ### Building within yocto
1402 Adding a dependency to afb-daemon is enough. See below:
1404 DEPENDS += " afb-daemon "
1407 [tic-tac-toe_diagram]: pictures/tic-tac-toe.svg