Merge "Auto generate cover from book.json fields."
[src/app-framework-binder.git] / docs / afb-binding-references.md
1 Binding Reference
2 =================
3
4 Structure for declaring binding
5 -------------------------------
6
7 ### struct afb_binding_v2
8
9 The main structure, of type **afb_binding_v2**, for describing the binding
10 must be exported under the name **afbBindingV2**.
11
12 This structure is defined as below.
13
14 ```C
15 /*
16  * Description of the bindings of type version 2
17  */
18 struct afb_binding_v2
19 {
20         const char *api;                        /* api name for the binding */
21         const char *specification;              /* textual openAPIv3 specification of the binding */
22         const struct afb_verb_v2 *verbs;        /* array of descriptions of verbs terminated by a NULL name */
23         int (*preinit)();                       /* callback at load of the binding */
24         int (*init)();                          /* callback for starting the service */
25         void (*onevent)(const char *event, struct json_object *object); /* callback for handling events */
26         unsigned noconcurrency: 1;              /* avoids concurrent requests to verbs */
27 };
28 ```
29
30 ### struct afb_verb_v2
31
32 Each verb is described with a structure of type **afb_verb_v2**
33 defined below:
34
35 ```C
36 /*
37  * Description of one verb of the API provided by the binding
38  * This enumeration is valid for bindings of type version 2
39  */
40 struct afb_verb_v2
41 {
42         const char *verb;                       /* name of the verb */
43         void (*callback)(struct afb_req req);   /* callback function implementing the verb */
44         const struct afb_auth *auth;                /* required authorization */
45         uint32_t session;                       /* authorization and session requirements of the verb */
46 };
47 ```
48
49 The session flags is an or of the constant defined below:
50
51   - AFB_SESSION_NONE : no flag, synonym to 0
52   - AFB_SESSION_LOA_0 : Requires the LOA to be 0 or more, synonym to 0 or AFB_SESSION_NONE
53   - AFB_SESSION_LOA_1 : Requires the LOA to be 1 or more
54   - AFB_SESSION_LOA_2 : Requires the LOA to be 2 or more
55   - AFB_SESSION_LOA_3 : Requires the LOA to be 3 or more
56   - AFB_SESSION_CHECK : Requires the token to be set and valid
57   - AFB_SESSION_REFRESH : Implies a token refresh
58   - AFB_SESSION_CLOSE : Implies cloing the session
59
60 The LOA is set binding by binding using the function **afb_req_session_set_LOA**.
61
62 ### struct afb_auth and enum afb_auth_type
63
64 The structure **afb_auth** is used within verb description to
65 set security requirements. The interpretation of the structure
66 depends on the value of the field **type**.
67
68 ```C
69 struct afb_auth
70 {
71         const enum afb_auth_type type;
72         union {
73                 const char *text;
74                 const unsigned loa;
75                 const struct afb_auth *first;
76         };
77         const struct afb_auth *next;
78 };
79 ```
80 The possible values for **type** is defined here:
81
82 ```C
83 /*
84  * Enum for Session/Token/Assurance middleware.
85  */
86 enum afb_auth_type
87 {
88         afb_auth_No = 0,        /** never authorized, no data */
89         afb_auth_Token,         /** authorized if token valid, no data */
90         afb_auth_LOA,           /** authorized if LOA greater than data 'loa' */
91         afb_auth_Permission,    /** authorized if permission 'text' is granted */
92         afb_auth_Or,            /** authorized if 'first' or 'next' is authorized */
93         afb_auth_And,           /** authorized if 'first' and 'next' are authorized */
94         afb_auth_Not,           /** authorized if 'first' is not authorized */
95         afb_auth_Yes            /** always authorized, no data */
96 };
97 ```
98
99 Example:
100
101 ```C
102 static const struct afb_auth _afb_auths_v2_monitor[] = {
103         { .type = afb_auth_Permission, .text = "urn:AGL:permission:monitor:public:set" },
104         { .type = afb_auth_Permission, .text = "urn:AGL:permission:monitor:public:get" },
105         { .type = afb_auth_Or, .first = &_afb_auths_v2_monitor[1], .next = &_afb_auths_v2_monitor[0] }
106 };
107 ```
108
109 Functions of class afb_daemon...
110 -------------------------
111
112 The 3 following functions are linked to libsystemd.
113 They allow use of **sd_event** features and access
114 to **sd_bus** features.
115
116 ```C
117 /*
118  * Retrieves the common systemd's event loop of AFB
119  */
120 struct sd_event *afb_daemon_get_event_loop();
121
122 /*
123  * Retrieves the common systemd's user/session d-bus of AFB
124  */
125 struct sd_bus *afb_daemon_get_user_bus();
126
127 /*
128  * Retrieves the common systemd's system d-bus of AFB
129  */
130 struct sd_bus *afb_daemon_get_system_bus();
131 ```
132
133 The 2 following functions are linked to event management.
134 Broadcasting an event send it to any possible listener.
135
136 ```C
137 /*
138  * Broadcasts widely the event of 'name' with the data 'object'.
139  * 'object' can be NULL.
140  *
141  * For convenience, the function calls 'json_object_put' for 'object'.
142  * Thus, in the case where 'object' should remain available after
143  * the function returns, the function 'json_object_get' shall be used.
144  *
145  * Returns the count of clients that received the event.
146  */
147 int afb_daemon_broadcast_event(const char *name, struct json_object *object);
148
149 /*
150  * Creates an event of 'name' and returns it.
151  *
152  * See afb_event_is_valid to check if there is an error.
153  */
154 struct afb_event afb_daemon_make_event(const char *name);
155 ```
156
157 The following function is used by logging macros and should normally
158 not be used. Instead, you should use the macros
159 **AFB\_ERROR**, **AFB\_WARNING**, **AFB\_NOTICE**,
160 **AFB\_INFO**, **AFB\_DEBUG**
161
162 ```C
163 /*
164  * Send a message described by 'fmt' and following parameters
165  * to the journal for the verbosity 'level'.
166  *
167  * 'file', 'line' and 'func' are indicators of position of the code in source files
168  * (see macros __FILE__, __LINE__ and __func__).
169  *
170  * 'level' is defined by syslog standard:
171  *      EMERGENCY         0        System is unusable
172  *      ALERT             1        Action must be taken immediately
173  *      CRITICAL          2        Critical conditions
174  *      ERROR             3        Error conditions
175  *      WARNING           4        Warning conditions
176  *      NOTICE            5        Normal but significant condition
177  *      INFO              6        Informational
178  *      DEBUG             7        Debug-level messages
179  */
180 void afb_daemon_verbose(int level, const char *file, int line, const char * func, const char *fmt, ...);
181 ```
182
183 The 2 following functions MUST be used to access data of the bindings.
184
185 ```C
186 /*
187  * Get the root directory file descriptor. This file descriptor can
188  * be used with functions 'openat', 'fstatat', ...
189  */
190 int afb_daemon_rootdir_get_fd();
191
192 /*
193  * Opens 'filename' within the root directory with 'flags' (see function openat)
194  * using the 'locale' definition (example: "jp,en-US") that can be NULL.
195  * Returns the file descriptor or -1 in case of error.
196  */
197 int afb_daemon_rootdir_open_locale(const char *filename, int flags, const char *locale);
198 ```
199
200 The following function is used to queue jobs.
201
202 ```C
203 /*
204  * Queue the job defined by 'callback' and 'argument' for being executed asynchronously
205  * in this thread (later) or in an other thread.
206  * If 'group' is not NUL, the jobs queued with a same value (as the pointer value 'group')
207  * are executed in sequence in the order of there submission.
208  * If 'timeout' is not 0, it represent the maximum execution time for the job in seconds.
209  * At first, the job is called with 0 as signum and the given argument.
210  * The job is executed with the monitoring of its time and some signals like SIGSEGV and
211  * SIGFPE. When a such signal is catched, the job is terminated and re-executed but with
212  * signum being the signal number (SIGALRM when timeout expired).
213  *
214  * Returns 0 in case of success or -1 in case of error.
215  */
216 int afb_daemon_queue_job(void (*callback)(int signum, void *arg), void *argument, void *group, int timeout)
217 ```
218
219 The following function must be used when a binding depends on other
220 bindings at its initialization.
221
222 ```C
223 /*
224  * Tells that it requires the API of "name" to exist
225  * and if 'initialized' is not null to be initialized.
226  * Returns 0 in case of success or -1 in case of error.
227  */
228 int afb_daemon_require_api(const char *name, int initialized)
229 ```
230
231 Functions of class afb_service...
232 -------------------------
233
234 The following functions allow services to call verbs of other
235 bindings for themselves.
236
237 ```C
238 /**
239  * Calls the 'verb' of the 'api' with the arguments 'args' and 'verb' in the name of the binding.
240  * The result of the call is delivered to the 'callback' function with the 'callback_closure'.
241  *
242  * For convenience, the function calls 'json_object_put' for 'args'.
243  * Thus, in the case where 'args' should remain available after
244  * the function returns, the function 'json_object_get' shall be used.
245  *
246  * The 'callback' receives 3 arguments:
247  *  1. 'closure' the user defined closure pointer 'callback_closure',
248  *  2. 'iserror' a boolean status being true (not null) when an error occured,
249  *  2. 'result' the resulting data as a JSON object.
250  *
251  * @param api      The api name of the method to call
252  * @param verb     The verb name of the method to call
253  * @param args     The arguments to pass to the method
254  * @param callback The to call on completion
255  * @param callback_closure The closure to pass to the callback
256  *
257  * @see also 'afb_req_subcall'
258  */
259 void afb_service_call(
260         const char *api,
261         const char *verb,
262         struct json_object *args,
263         void (*callback)(void*closure, int iserror, struct json_object *result),
264         void *callback_closure);
265
266 /**
267  * Calls the 'verb' of the 'api' with the arguments 'args' and 'verb' in the name of the binding.
268  * 'result' will receive the response.
269  *
270  * For convenience, the function calls 'json_object_put' for 'args'.
271  * Thus, in the case where 'args' should remain available after
272  * the function returns, the function 'json_object_get' shall be used.
273  *
274  * @param api      The api name of the method to call
275  * @param verb     The verb name of the method to call
276  * @param args     The arguments to pass to the method
277  * @param result   Where to store the result - should call json_object_put on it -
278  *
279  * @returns 1 in case of success or 0 in case of error.
280  *
281  * @see also 'afb_req_subcall'
282  */
283 int afb_service_call_sync(
284         const char *api,
285         const char *verb,
286         struct json_object *args,
287         struct json_object **result);
288 ```
289
290 Functions of class afb_event...
291 -------------------------
292
293 This function checks whether the event is valid. It must be used
294 when creating events.
295
296 ```C
297 /*
298  * Checks wether the 'event' is valid or not.
299  *
300  * Returns 0 if not valid or 1 if valid.
301  */
302 int afb_event_is_valid(struct afb_event event);
303 ```
304
305 The two following functions are used to broadcast or push
306 event with its data.
307
308 ```C
309 /*
310  * Broadcasts widely the 'event' with the data 'object'.
311  * 'object' can be NULL.
312  *
313  * For convenience, the function calls 'json_object_put' for 'object'.
314  * Thus, in the case where 'object' should remain available after
315  * the function returns, the function 'json_object_get' shall be used.
316  *
317  * Returns the count of clients that received the event.
318  */
319 int afb_event_broadcast(struct afb_event event, struct json_object *object);
320
321 /*
322  * Pushes the 'event' with the data 'object' to its observers.
323  * 'object' can be NULL.
324  *
325  * For convenience, the function calls 'json_object_put' for 'object'.
326  * Thus, in the case where 'object' should remain available after
327  * the function returns, the function 'json_object_get' shall be used.
328  *
329  * Returns the count of clients that received the event.
330  */
331 int afb_event_push(struct afb_event event, struct json_object *object);
332 ```
333
334 The following function destiys the event.
335
336 ```C
337 /*
338  * Drops the data associated to the 'event'
339  * After calling this function, the event
340  * MUST NOT BE USED ANYMORE.
341  */
342 void afb_event_drop(struct afb_event event);
343 ```
344
345 This function allows to retrieve the exact name of the event.
346
347 ```C
348 /*
349  * Gets the name associated to the 'event'.
350  */
351 const char *afb_event_name(struct afb_event event);
352 ```
353
354 Functions of class afb_req...
355 -------------------------
356
357 This function checks the validity of the **req**.
358
359 ```C
360 /*
361  * Checks wether the request 'req' is valid or not.
362  *
363  * Returns 0 if not valid or 1 if valid.
364  */
365 int afb_req_is_valid(struct afb_req req);
366 ```
367
368 The following functions retrieves parameters of the request.
369
370 ```C
371 /*
372  * Gets from the request 'req' the argument of 'name'.
373  * Returns a PLAIN structure of type 'struct afb_arg'.
374  * When the argument of 'name' is not found, all fields of result are set to NULL.
375  * When the argument of 'name' is found, the fields are filled,
376  * in particular, the field 'result.name' is set to 'name'.
377  *
378  * There is a special name value: the empty string.
379  * The argument of name "" is defined only if the request was made using
380  * an HTTP POST of Content-Type "application/json". In that case, the
381  * argument of name "" receives the value of the body of the HTTP request.
382  */
383 struct afb_arg afb_req_get(struct afb_req req, const char *name);
384
385 /*
386  * Gets from the request 'req' the string value of the argument of 'name'.
387  * Returns NULL if when there is no argument of 'name'.
388  * Returns the value of the argument of 'name' otherwise.
389  *
390  * Shortcut for: afb_req_get(req, name).value
391  */
392 const char *afb_req_value(struct afb_req req, const char *name);
393
394 /*
395  * Gets from the request 'req' the path for file attached to the argument of 'name'.
396  * Returns NULL if when there is no argument of 'name' or when there is no file.
397  * Returns the path of the argument of 'name' otherwise.
398  *
399  * Shortcut for: afb_req_get(req, name).path
400  */
401 const char *afb_req_path(struct afb_req req, const char *name);
402
403 /*
404  * Gets from the request 'req' the json object hashing the arguments.
405  * The returned object must not be released using 'json_object_put'.
406  */
407 struct json_object *afb_req_json(struct afb_req req);
408 ```
409
410 The following functions emit the reply to the request.
411
412 ```C
413 /*
414  * Sends a reply of kind success to the request 'req'.
415  * The status of the reply is automatically set to "success".
416  * Its send the object 'obj' (can be NULL) with an
417  * informationnal comment 'info (can also be NULL).
418  *
419  * For convenience, the function calls 'json_object_put' for 'obj'.
420  * Thus, in the case where 'obj' should remain available after
421  * the function returns, the function 'json_object_get' shall be used.
422  */
423 void afb_req_success(struct afb_req req, struct json_object *obj, const char *info);
424
425 /*
426  * Same as 'afb_req_success' but the 'info' is a formatting
427  * string followed by arguments.
428  *
429  * For convenience, the function calls 'json_object_put' for 'obj'.
430  * Thus, in the case where 'obj' should remain available after
431  * the function returns, the function 'json_object_get' shall be used.
432  */
433 void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
434
435 /*
436  * Same as 'afb_req_success_f' but the arguments to the format 'info'
437  * are given as a variable argument list instance.
438  *
439  * For convenience, the function calls 'json_object_put' for 'obj'.
440  * Thus, in the case where 'obj' should remain available after
441  * the function returns, the function 'json_object_get' shall be used.
442  */
443 void afb_req_success_v(struct afb_req req, struct json_object *obj, const char *info, va_list args);
444
445 /*
446  * Sends a reply of kind failure to the request 'req'.
447  * The status of the reply is set to 'status' and an
448  * informationnal comment 'info' (can also be NULL) can be added.
449  *
450  * Note that calling afb_req_fail("success", info) is equivalent
451  * to call afb_req_success(NULL, info). Thus even if possible it
452  * is strongly recommended to NEVER use "success" for status.
453  */
454 void afb_req_fail(struct afb_req req, const char *status, const char *info);
455
456 /*
457  * Same as 'afb_req_fail' but the 'info' is a formatting
458  * string followed by arguments.
459  */
460 void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
461
462 /*
463  * Same as 'afb_req_fail_f' but the arguments to the format 'info'
464  * are given as a variable argument list instance.
465  */
466 void afb_req_fail_v(struct afb_req req, const char *status, const char *info, va_list args);
467 ```
468
469 The following functions handle the session data.
470
471 ```C
472 /*
473  * Gets the pointer stored by the binding for the session of 'req'.
474  * When the binding has not yet recorded a pointer, NULL is returned.
475  */
476 void *afb_req_context_get(struct afb_req req);
477
478 /*
479  * Stores for the binding the pointer 'context' to the session of 'req'.
480  * The function 'free_context' will be called when the session is closed
481  * or if binding stores an other pointer.
482  */
483 void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));
484
485 /*
486  * Gets the pointer stored by the binding for the session of 'req'.
487  * If the stored pointer is NULL, indicating that no pointer was
488  * already stored, afb_req_context creates a new context by calling
489  * the function 'create_context' and stores it with the freeing function
490  * 'free_context'.
491  */
492 void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*));
493
494 /*
495  * Frees the pointer stored by the binding for the session of 'req'
496  * and sets it to NULL.
497  *
498  * Shortcut for: afb_req_context_set(req, NULL, NULL)
499  */
500 void afb_req_context_clear(struct afb_req req);
501
502 /*
503  * Closes the session associated with 'req'
504  * and delete all associated contexts.
505  */
506 void afb_req_session_close(struct afb_req req);
507
508 /*
509  * Sets the level of assurance of the session of 'req'
510  * to 'level'. The effect of this function is subject of
511  * security policies.
512  * Returns 1 on success or 0 if failed.
513  */
514 int afb_req_session_set_LOA(struct afb_req req, unsigned level);
515 ```
516
517
518 The 4 following functions must be used for asynchronous handling requests.
519
520 ```C
521 /*
522  * Adds one to the count of references of 'req'.
523  * This function MUST be called by asynchronous implementations
524  * of verbs if no reply was sent before returning.
525  */
526 void afb_req_addref(struct afb_req req);
527
528 /*
529  * Substracts one to the count of references of 'req'.
530  * This function MUST be called by asynchronous implementations
531  * of verbs after sending the asynchronous reply.
532  */
533 void afb_req_unref(struct afb_req req);
534
535 /*
536  * Stores 'req' on heap for asynchronous use.
537  * Returns a handler to the stored 'req' or NULL on memory depletion.
538  * The count of reference to 'req' is incremented on success
539  * (see afb_req_addref).
540  */
541 struct afb_stored_req *afb_req_store(struct afb_req req);
542
543 /*
544  * Retrieves the afb_req stored at 'sreq'.
545  * Returns the stored request.
546  * The count of reference is UNCHANGED, thus, the
547  * function 'afb_req_unref' should be called on the result
548  * after that the asynchronous reply if sent.
549  */
550 struct afb_req afb_req_unstore(struct afb_stored_req *sreq);
551 ```
552
553 The two following functions are used to associate client with events
554 (subscription).
555
556 ```C
557 /*
558  * Establishes for the client link identified by 'req' a subscription
559  * to the 'event'.
560  * Returns 0 in case of successful subscription or -1 in case of error.
561  */
562 int afb_req_subscribe(struct afb_req req, struct afb_event event);
563
564 /*
565  * Revokes the subscription established to the 'event' for the client
566  * link identified by 'req'.
567  * Returns 0 in case of successful subscription or -1 in case of error.
568  */
569 int afb_req_unsubscribe(struct afb_req req, struct afb_event event);
570 ```
571
572 The following functions must be used to make request in the name of the
573 client (with its permissions).
574
575 ```C
576 /*
577  * Makes a call to the method of name 'api' / 'verb' with the object 'args'.
578  * This call is made in the context of the request 'req'.
579  * On completion, the function 'callback' is invoked with the
580  * 'closure' given at call and two other parameters: 'iserror' and 'result'.
581  * 'iserror' is a boolean that indicates if the reply is an error reply.
582  * 'result' is the json object of the reply, you must not call json_object_put
583  * on the result.
584  *
585  * For convenience, the function calls 'json_object_put' for 'args'.
586  * Thus, in the case where 'args' should remain available after
587  * the function returns, the function 'json_object_get' shall be used.
588  */
589 void afb_req_subcall(
590                 struct afb_req req,
591                 const char *api,
592                 const char *verb,
593                 struct json_object *args,
594                 void (*callback)(void *closure, int iserror, struct json_object *result),
595                 void *closure);
596
597 /*
598  * Makes a call to the method of name 'api' / 'verb' with the object 'args'.
599  * This call is made in the context of the request 'req'.
600  * This call is synchronous, it waits untill completion of the request.
601  * It returns 0 on an error answer and returns 1 when no error was detected.
602  * The object pointed by 'result' is filled and must be released by the caller
603  * after its use by calling 'json_object_put'.
604  *
605  * For convenience, the function calls 'json_object_put' for 'args'.
606  * Thus, in the case where 'args' should remain available after
607  * the function returns, the function 'json_object_get' shall be used.
608  */
609 int afb_req_subcall_sync(
610                 struct afb_req req,
611                 const char *api,
612                 const char *verb,
613                 struct json_object *args,
614                 struct json_object **result);
615 ```
616
617 The following function is used by logging macros and should normally
618 not be used. Instead, you should use the macros
619 **AFB_REQ_ERROR**, **AFB_REQ_WARNING**, **AFB_REQ_NOTICE**,
620 **AFB_REQ_INFO**, **AFB_REQ_DEBUG**
621
622 ```C
623 /*
624  * Send associated to 'req' a message described by 'fmt' and following parameters
625  * to the journal for the verbosity 'level'.
626  *
627  * 'file', 'line' and 'func' are indicators of position of the code in source files
628  * (see macros __FILE__, __LINE__ and __func__).
629  *
630  * 'level' is defined by syslog standard:
631  *      EMERGENCY         0        System is unusable
632  *      ALERT             1        Action must be taken immediately
633  *      CRITICAL          2        Critical conditions
634  *      ERROR             3        Error conditions
635  *      WARNING           4        Warning conditions
636  *      NOTICE            5        Normal but significant condition
637  *      INFO              6        Informational
638  *      DEBUG             7        Debug-level messages
639  */
640 void afb_req_verbose(struct afb_req req, int level, const char *file, int line, const char * func, const char *fmt, ...);
641 ```
642
643 Logging macros
644 --------------
645
646 The following macros must be used for logging:
647
648 ```C
649 AFB_ERROR(fmt,...)
650 AFB_WARNING(fmt,...)
651 AFB_NOTICE(fmt,...)
652 AFB_INFO(fmt,...)
653 AFB_DEBUG(fmt,...)
654 ```
655
656 The following macros can be used for logging in the context
657 of a request **req** of type **afb_req**:
658
659 ```C
660 AFB_REQ_ERROR(req,fmt,...)
661 AFB_REQ_WARNING(req,fmt,...)
662 AFB_REQ_NOTICE(req,fmt,...)
663 AFB_REQ_INFO(req,fmt,...)
664 AFB_REQ_DEBUG(req,fmt,...)
665 ```
666
667 By default, the logging macros add file, line and function
668 indication.