From: José Bollo Date: Thu, 9 Jun 2016 12:22:22 +0000 (+0200) Subject: documentation: switch to pandoc X-Git-Tag: blowfish_2.0.1~34 X-Git-Url: https://gerrit.automotivelinux.org/gerrit/gitweb?a=commitdiff_plain;h=741d4e0505c588f38a64350c1d3c53c74f7ac22c;p=src%2Fapp-framework-binder.git documentation: switch to pandoc Change-Id: I60fcea9d370f5b98efa1e08632f5f9682741b8c1 Signed-off-by: José Bollo --- diff --git a/doc/FAQ.html b/doc/FAQ.html index 98337815..0cad0b5b 100644 --- a/doc/FAQ.html +++ b/doc/FAQ.html @@ -1,19 +1,31 @@ + - - + + + + + Frequently Asked Question about AFB-DAEMON + + + - -

Frequently Asked Question about AFB-DAEMON

- +
+

Frequently Asked Question about AFB-DAEMON

+

José Bollo

+

27 mai 2016

+
+ +

Frequently Asked Question about AFB-DAEMON

version: 1
 Date:    27 mai 2016
-Author:  José Bollo
-
- -

+Author: José Bollo diff --git a/doc/README.html b/doc/README.html index 0a7dffa8..a45c16e1 100644 --- a/doc/README.html +++ b/doc/README.html @@ -1,22 +1,28 @@ + - - + + + + + + + - -

Inititial Build

- -

mkdir build -cd build -cmake ..

- - -

Netbeans

- - -

Copy nbprojet at project base

- + +

Inititial Build

+

mkdir build cd build cmake ..

+

Netbeans

+

Copy nbprojet at project base

cp -r doc/nbproject.template ./nbproject

diff --git a/doc/afb-application-writing.html b/doc/afb-application-writing.html index 3023e2b0..b394e6b9 100644 --- a/doc/afb-application-writing.html +++ b/doc/afb-application-writing.html @@ -1,340 +1,188 @@ + - - + + + + + HOWTO WRITE an APPLICATION above AGL FRAMEWORK + + + - -

HOWTO WRITE an APPLICATION above AGL FRAMEWORK

- +
+

HOWTO WRITE an APPLICATION above AGL FRAMEWORK

+

José Bollo

+

09 juin 2016

+
+ +

HOWTO WRITE an APPLICATION above AGL FRAMEWORK

version: 1
 Date:    09 juin 2016
-Author:  José Bollo
-
- -

- - -

Programmation Languages for Applications

- - -

Writing an HTML5 application

- -

Developers of HTML5 applications (client side) can easily create -applications for AGL framework using their preferred -HTML5 framework.

- -

Developers may also take advantage of powerful server side plugins to improve -application behavior. Server side plugins return an application/json mine-type -and can be accessed though either HTTP or Websockets.

- +Author: José Bollo +

Programmation Languages for Applications

+

Writing an HTML5 application

+

Developers of HTML5 applications (client side) can easily create applications for AGL framework using their preferred HTML5 framework.

+

Developers may also take advantage of powerful server side plugins to improve application behavior. Server side plugins return an application/json mine-type and can be accessed though either HTTP or Websockets.

In a near future, JSON-RPC protocol should be added to complete current x-afb-json1 protocol.

-

Two examples of HTML5 applications are given:

- - - - -

Writing a Qt application

- +

Writing a Qt application

Writing Qt applications is also supported. Qt offers standard API to send request through HTTP or WebSockets.

-

It is also possible to write QML applications. A sample QML application [token-websock] is avaliable..

- - - - -

Writing “C” application

- +

Writing "C" application

C applications can use afb-daemon binder through a websocket connection.

- -

The library libafbwsc is provided for C clients that need -to connect with an afb-daemon binder.

- -

The program afb-client-demo is the C example that use -libafbwsc library. -Source code is available here -src/afb-client-demo.c.

- -

Current implementation relies on libsystemd and file descriptors. -This model might be review in the future to support secure sockets -and free the dependency with libsystemd.

- - -

Handling sessions within applications

- +

The library libafbwsc is provided for C clients that need to connect with an afb-daemon binder.

+

The program afb-client-demo is the C example that use libafbwsc library. Source code is available here src/afb-client-demo.c.

+

Current implementation relies on libsystemd and file descriptors. This model might be review in the future to support secure sockets and free the dependency with libsystemd.

+

Handling sessions within applications

Applications should understand sessions and tokens management when interacting with afb-daemon binder.

- -

Applications are communicating with their private binder(afb-daemon) using -a network connection or potentially any other connection channel. While current version -does not yet implement unix domain this feature might be added in a near future. -Developers need to be warn that HTTP protocol is a none connected protocol. This prevents -from using HTTP socket connection to authenticate clients.

- -

For this reason, the binder should authenticate the application -by using a shared secret. The secret is named “token” and the identification -of client is named “session”.

- -

The examples token-websock.qml and afb-client are demonstrating -how authentication and sessions are managed.

- - -

Handling sessions

- -

Plugins and other binder feature need to keep track of client -instances. This is especially important for plugins running as services -as they may typically have to keep each client’s data separated.

- -

For HTML5 applications, the web runtime handles the cookie of session -that the binder afb-daemon automatically sets.

- -

Session identifier can be set using the parameter -uuid or x-afb-uuid in URI requests. Within current version of the -framework session UUID is supported by both HTTP requests and websocket negotiation.

- - -

Exchanging tokens

- -

At application start, AGL framework communicates a shared secret to both binder -and client application. This initial secret is called the “initial token”.

- -

For each of its client application, the binder manages a current active -token for session management. This authentication token can be use to restrict -access to some plugin’s methods.

- -

The token must be included in URI request on HTTP or during websockets -connection using parameter token or x-afb-token.

- +

Applications are communicating with their private binder(afb-daemon) using a network connection or potentially any other connection channel. While current version does not yet implement unix domain this feature might be added in a near future. Developers need to be warn that HTTP protocol is a none connected protocol. This prevents from using HTTP socket connection to authenticate clients.

+

For this reason, the binder should authenticate the application by using a shared secret. The secret is named "token" and the identification of client is named "session".

+

The examples token-websock.qml and afb-client are demonstrating how authentication and sessions are managed.

+

Handling sessions

+

Plugins and other binder feature need to keep track of client instances. This is especially important for plugins running as services as they may typically have to keep each client's data separated.

+

For HTML5 applications, the web runtime handles the cookie of session that the binder afb-daemon automatically sets.

+

Session identifier can be set using the parameter uuid or x-afb-uuid in URI requests. Within current version of the framework session UUID is supported by both HTTP requests and websocket negotiation.

+

Exchanging tokens

+

At application start, AGL framework communicates a shared secret to both binder and client application. This initial secret is called the "initial token".

+

For each of its client application, the binder manages a current active token for session management. This authentication token can be use to restrict access to some plugin's methods.

+

The token must be included in URI request on HTTP or during websockets connection using parameter token or x-afb-token.

To ensure security, tokens must be refreshed periodically.

- - -

Example of session management

- +

Example of session management

In following examples, we suppose that afb-daemon is launched with something equivalent to:

- -
$ afb-daemon --port=1234 --token=123456 [...]
-
- +
$ afb-daemon --port=1234 --token=123456 [...]

making the expectation that AuthLogin plugin is requested as default.

- - -

Using curl

- +

Using curl

First, connects with the initial token, 123456:

-
$ curl http://localhost:1234/api/auth/connect?token=123456
 {
-  "jtype": "afb-reply",
-  "request": {
- "status": "success",
- "token": "0aef6841-2ddd-436d-b961-ae78da3b5c5f",
- "uuid": "850c4594-1be1-4e9b-9fcc-38cc3e6ff015"
+  "jtype": "afb-reply",
+  "request": {
+     "status": "success",
+     "token": "0aef6841-2ddd-436d-b961-ae78da3b5c5f",
+     "uuid": "850c4594-1be1-4e9b-9fcc-38cc3e6ff015"
   },
-  "response": {"token": "A New Token and Session Context Was Created"}
-}
-
- -

It returns an answer containing session UUID, 850c4594-1be1-4e9b-9fcc-38cc3e6ff015, -and a refreshed token, 850c4594-1be1-4e9b-9fcc-38cc3e6ff015.

- + "response": {"token": "A New Token and Session Context Was Created"} +} +

It returns an answer containing session UUID, 850c4594-1be1-4e9b-9fcc-38cc3e6ff015, and a refreshed token, 850c4594-1be1-4e9b-9fcc-38cc3e6ff015.

Check if session and token is valid:

- -
$ curl http://localhost:1234/api/auth/check?token=0aef6841-2ddd-436d-b961-ae78da3b5c5f&uuid=850c4594-1be1-4e9b-9fcc-38cc3e6ff015
+
$ curl http://localhost:1234/api/auth/check?token=0aef6841-2ddd-436d-b961-ae78da3b5c5f\&uuid=850c4594-1be1-4e9b-9fcc-38cc3e6ff015
 {
-  "jtype": "afb-reply",
-  "request": {"status":"success"},
-  "response": {"isvalid":true}
-}
-
- + "jtype": "afb-reply", + "request": {"status":"success"}, + "response": {"isvalid":true} +}

Refresh the token:

- -
$ curl http://localhost:1234/api/auth/refresh?token=0aef6841-2ddd-436d-b961-ae78da3b5c5f&uuid=850c4594-1be1-4e9b-9fcc-38cc3e6ff015
+
$ curl http://localhost:1234/api/auth/refresh?token=0aef6841-2ddd-436d-b961-ae78da3b5c5f\&uuid=850c4594-1be1-4e9b-9fcc-38cc3e6ff015
 {
-  "jtype": "afb-reply",
-  "request": {
- "status":"success",
- "token":"b8ec3ec3-6ffe-448c-9a6c-efda69ad7bd9"
+  "jtype": "afb-reply",
+  "request": {
+     "status":"success",
+     "token":"b8ec3ec3-6ffe-448c-9a6c-efda69ad7bd9"
   },
-  "response": {"token":"Token was refreshed"}
-}
-
- + "response": {"token":"Token was refreshed"} +}

Close the session:

- -
curl http://localhost:1234/api/auth/logout?token=b8ec3ec3-6ffe-448c-9a6c-efda69ad7bd9&uuid=850c4594-1be1-4e9b-9fcc-38cc3e6ff015
+
curl http://localhost:1234/api/auth/logout?token=b8ec3ec3-6ffe-448c-9a6c-efda69ad7bd9\&uuid=850c4594-1be1-4e9b-9fcc-38cc3e6ff015
 {
-  "jtype": "afb-reply",
-  "request": {"status": "success"},
-  "response": {"info":"Token and all resources are released"}
-}
-
- + "jtype": "afb-reply", + "request": {"status": "success"}, + "response": {"info":"Token and all resources are released"} +}

Checking on closed session for uuid should be refused:

- -
curl http://localhost:1234/api/auth/check?token=b8ec3ec3-6ffe-448c-9a6c-efda69ad7bd9&uuid=850c4594-1be1-4e9b-9fcc-38cc3e6ff015
+
curl http://localhost:1234/api/auth/check?token=b8ec3ec3-6ffe-448c-9a6c-efda69ad7bd9\&uuid=850c4594-1be1-4e9b-9fcc-38cc3e6ff015
 {
-  "jtype": "afb-reply",
-  "request": {
- "status": "failed",
- "info": "invalid token's identity"
+  "jtype": "afb-reply",
+  "request": {
+     "status": "failed",
+     "info": "invalid token's identity"
   }
-}
-
- - -

Using afb-client-demo

- +}
+

Using afb-client-demo

Here is an example of exchange using afb-client-demo:

-
$ afb-client-demo ws://localhost:1234/api?token=123456
 auth connect
-ON-REPLY 1:auth/connect: {"jtype":"afb-reply","request":{"status":"success",
-   "token":"63f71a29-8b52-4f9b-829f-b3028ba46b68","uuid":"5fcc3f3d-4b84-4fc7-ba66-2d8bd34ae7d1"},
-   "response":{"token":"A New Token and Session Context Was Created"}}
+ON-REPLY 1:auth/connect: {"jtype":"afb-reply","request":{"status":"success",
+   "token":"63f71a29-8b52-4f9b-829f-b3028ba46b68","uuid":"5fcc3f3d-4b84-4fc7-ba66-2d8bd34ae7d1"},
+   "response":{"token":"A New Token and Session Context Was Created"}}
 auth check
-ON-REPLY 2:auth/check: {"jtype":"afb-reply","request":{"status":"success"},"response":{"isvalid":true}}
+ON-REPLY 2:auth/check: {"jtype":"afb-reply","request":{"status":"success"},"response":{"isvalid":true}}
 auth refresh
-ON-REPLY 4:auth/refresh: {"jtype":"afb-reply","request":{"status":"success",
-   "token":"8b8ba8f4-1b0c-48fa-962d-4a00a8c9157e"},"response":{"token":"Token was refreshed"}}
+ON-REPLY 4:auth/refresh: {"jtype":"afb-reply","request":{"status":"success",
+   "token":"8b8ba8f4-1b0c-48fa-962d-4a00a8c9157e"},"response":{"token":"Token was refreshed"}}
 auth check
-ON-REPLY 5:auth/check: {"jtype":"afb-reply","request":{"status":"success"},"response":{"isvalid":true}}
+ON-REPLY 5:auth/check: {"jtype":"afb-reply","request":{"status":"success"},"response":{"isvalid":true}}
 auth refresh
-ON-REPLY 6:auth/refresh: {"jtype":"afb-reply","request":{"status":"success",
-   "token":"e83b36f8-d945-463d-b983-5d8ed73ba529"},"response":{"token":"Token was refreshed"}}
-
- +ON-REPLY 6:auth/refresh: {"jtype":"afb-reply","request":{"status":"success", + "token":"e83b36f8-d945-463d-b983-5d8ed73ba529"},"response":{"token":"Token was refreshed"}}

After closing connection, reconnect as here after:

- -
$ afb-client-demo ws://localhost:1234/api?token=e83b36f8-d945-463d-b983-5d8ed73ba529&uuid=5fcc3f3d-4b84-4fc7-ba66-2d8bd34ae7d1 auth check
-ON-REPLY 1:auth/check: {"jtype":"afb-reply","request":{"status":"success"},"response":{"isvalid":true}}
-
- +
$ afb-client-demo ws://localhost:1234/api?token=e83b36f8-d945-463d-b983-5d8ed73ba529\&uuid=5fcc3f3d-4b84-4fc7-ba66-2d8bd34ae7d1 auth check
+ON-REPLY 1:auth/check: {"jtype":"afb-reply","request":{"status":"success"},"response":{"isvalid":true}}

Same connection check using curl:

- -
$ curl http://localhost:1234/api/auth/check?token=e83b36f8-d945-463d-b983-5d8ed73ba529&uuid=5fcc3f3d-4b84-4fc7-ba66-2d8bd34ae7d1
-{"jtype":"afb-reply","request":{"status":"success"},"response":{"isvalid":true}}
-
- - -

Format of replies

- +
$ curl http://localhost:1234/api/auth/check?token=e83b36f8-d945-463d-b983-5d8ed73ba529\&uuid=5fcc3f3d-4b84-4fc7-ba66-2d8bd34ae7d1
+{"jtype":"afb-reply","request":{"status":"success"},"response":{"isvalid":true}}
+

Format of replies

Replies use javascript object returned as serialized JSON.

- -

This object contains at least 2 mandatory fields of name jtype and request -and one optional field of name response.

- - -

Field jtype

- -

The field jtype must have a value of type string equal to “afb-reply”.

- - -

Field request

- -

The field request must have a value of type object. This request object -has at least one field named status and four optional fields named -info, token, uuid, reqid.

- - -

Subfield request.status

- -

status must have a value of type string. This string is equal to “success” -only in case of success.

- - -

Subfield request.info

- +

This object contains at least 2 mandatory fields of name jtype and request and one optional field of name response.

+

Field jtype

+

The field jtype must have a value of type string equal to "afb-reply".

+

Field request

+

The field request must have a value of type object. This request object has at least one field named status and four optional fields named info, token, uuid, reqid.

+

Subfield request.status

+

status must have a value of type string. This string is equal to "success" only in case of success.

+

Subfield request.info

info is of type string and represent optional information added to the reply.

- - -

Subfield request.token

- -

token is of type string. It is sent either at session creation -or when the token is refreshed.

- - -

Subfield request.uuid

- +

Subfield request.token

+

token is of type string. It is sent either at session creation or when the token is refreshed.

+

Subfield request.uuid

uuid is of type string. It is sent at session creation.

- - -

Subfield request.reqid

- -

reqid is of type string. It is sent in response to HTTP requests -that added a parameter of name reqid or x-afb-reqid at request time. -Value returns in the reply has the exact same value as the one received in the request.

- - -

Field response

- +

Subfield request.reqid

+

reqid is of type string. It is sent in response to HTTP requests that added a parameter of name reqid or x-afb-reqid at request time. Value returns in the reply has the exact same value as the one received in the request.

+

Field response

This field response optionally contains an object returned when request succeeded.

- - -

Template

- +

Template

This is a template of replies:

-
{
-  "jtype": "afb-reply",
-  "request": {
-   "status": "success",
-   "info": "informationnal text",
-   "token": "e83b36f8-d945-463d-b983-5d8ed73ba52",
-   "uuid": "5fcc3f3d-4b84-4fc7-ba66-2d8bd34ae7d1",
-   "reqid": "application-generated-id-23456"
- },
-  "response": ....any response object....
-}
-
+ "jtype": "afb-reply", + "request": { + "status": "success", + "info": "informationnal text", + "token": "e83b36f8-d945-463d-b983-5d8ed73ba52", + "uuid": "5fcc3f3d-4b84-4fc7-ba66-2d8bd34ae7d1", + "reqid": "application-generated-id-23456" + }, + "response": ....any response object.... +} diff --git a/doc/afb-daemon-vocabulary.html b/doc/afb-daemon-vocabulary.html index fadd1dee..d2d4f512 100644 --- a/doc/afb-daemon-vocabulary.html +++ b/doc/afb-daemon-vocabulary.html @@ -1,131 +1,78 @@ + - - + + + + + Vocabulary for AFB-DAEMON + + + - -

Vocabulary for AFB-DAEMON

- +
+

Vocabulary for AFB-DAEMON

+

José Bollo

+

27 mai 2016

+
+ +

Vocabulary for AFB-DAEMON

version: 1
 Date:    27 mai 2016
-Author:  José Bollo
-
- -

- - -

Event

- -

Message with data propagated from the services to the client and not expecting -any reply.

- +Author: José Bollo +

Event

+

Message with data propagated from the services to the client and not expecting any reply.

The current implementation allows to widely broadcast events to all clients.

- - -

Level of assurance (LOA)

- -

This level that can be from 0 to 3 represent the level of -assurance that the services can expect from the session.

- -

The exact definition of the meaning of this levels and of -how to use it remains to be achived.

- - -

Plugin

- -

A shared library object intended to be plug to an afb-daemon instance -to implement an API.

- - -

Request

- -

A request is an invocation by a client to a method of a plugin using a message -transfered through some protocol: HTTP, WebSocket, DBUS… served by afb-daemon

- - -

Reply/Response

- +

Level of assurance (LOA)

+

This level that can be from 0 to 3 represent the level of assurance that the services can expect from the session.

+

The exact definition of the meaning of this levels and of how to use it remains to be achived.

+

Plugin

+

A shared library object intended to be plug to an afb-daemon instance to implement an API.

+

Request

+

A request is an invocation by a client to a method of a plugin using a message transfered through some protocol: HTTP, WebSocket, DBUS... served by afb-daemon

+

Reply/Response

This is a message sent to client as the result of the request.

- - -

Service

- -

Service are made of plugins runnning by their side on their binder. -It can serve many client. Each one being attached to one session.

- -

The framework establishes the connection between the services and -the clients. Using DBus currently.

- - -

Session

- -

A session is meant to be the unic context of an instance of client, -identifying that instance across requests.

- +

Service

+

Service are made of plugins runnning by their side on their binder. It can serve many client. Each one being attached to one session.

+

The framework establishes the connection between the services and the clients. Using DBus currently.

+

Session

+

A session is meant to be the unic context of an instance of client, identifying that instance across requests.

Each session has an identifier. Session identifier generated by afb-daemon are UUIDs.

- -

Internally, afb-daemon offers a mechanism to attach data to sessions. -When the session is closed or disappears, the data attached to that session -are freed.

- - -

Token

- +

Internally, afb-daemon offers a mechanism to attach data to sessions. When the session is closed or disappears, the data attached to that session are freed.

+

Token

The token is an identifier that the the client must give to be authentificated.

- -

At start, afb-daemon get an initial token. This initial token must be presented -incoming client to be authentificated.

- +

At start, afb-daemon get an initial token. This initial token must be presented incoming client to be authentificated.

A token is valid only for a period.

- -

The token must be renewed periodically. When the token is renewed, afb-daemon -sends the new token to the client.

- +

The token must be renewed periodically. When the token is renewed, afb-daemon sends the new token to the client.

Tokens generated by afb-daemon are UUIDs.

- - -

UUID

- +

UUID

It stand for Universal Unic IDentifier.

- -

Its is designed to create identifier in a way that avoid has much as possible conflicts. -It means that if two differents instance create a UUID, the probability that they create the same UUID is very low, near to zero.

- - -

x-afb-reqid

- -

Argument name that can be used with HTTP request. -When this argument is given, it is automatically added to the “request” object of the -answer.

- - -

x-afb-token

- -

Argument name for giving the token without ambiguity. -You can also use the name token but it may conflicts with other arguments.

- - -

x-afb-uuid

- -

Argument name for giving explicitely the session identifier without ambiguity. -You can also use the name uuid but it may conflicts with other arguments.

+

Its is designed to create identifier in a way that avoid has much as possible conflicts. It means that if two differents instance create a UUID, the probability that they create the same UUID is very low, near to zero.

+

x-afb-reqid

+

Argument name that can be used with HTTP request. When this argument is given, it is automatically added to the "request" object of the answer.

+

x-afb-token

+

Argument name for giving the token without ambiguity. You can also use the name token but it may conflicts with other arguments.

+

x-afb-uuid

+

Argument name for giving explicitely the session identifier without ambiguity. You can also use the name uuid but it may conflicts with other arguments.

diff --git a/doc/afb-overview.html b/doc/afb-overview.html index 839d606c..e8050f9a 100644 --- a/doc/afb-overview.html +++ b/doc/afb-overview.html @@ -1,50 +1,51 @@ + - - + + + + + Overview of AFB-DAEMON + + + - -

Overview of AFB-DAEMON

- +
+

Overview of AFB-DAEMON

+

José Bollo

+

30 mai 2016

+
+ +

Overview of AFB-DAEMON

version: 1
 Date:    30 mai 2016
-Author:  José Bollo
-
- -

- - -

Roles of afb-daemon

- -

The name afb-daemon stands for Application -Framework Binder Daemon. That is why afb-daemon -is also named the binder.

- -

Afb-daemon is in charge to bind one instance of -an application to the AGL framework and AGL system.

- -

On the following figure, you can use a typical use -of afb-daemon:

- -

Figure: binder afb-daemon, basis

- +Author: José Bollo +

Roles of afb-daemon

+

The name afb-daemon stands for Application Framework Binder Daemon. That is why afb-daemon is also named the binder.

+

Afb-daemon is in charge to bind one instance of an application to the AGL framework and AGL system.

+

On the following figure, you can use a typical use of afb-daemon:

+ +

+Figure: binder afb-daemon, basis +

+

. . . . . . . . . . . . . . . . . . . . . . . . . .
 .        Isolated security context                .
 .                                                 .
@@ -65,43 +66,24 @@ of afb-daemon:

. . . . . . . . . . . . | . . . . . . . . . . . . . | v - AGL SYSTEM -
- -

The application and its companion binder run in secured and isolated -environment set for them. Applications are intended to access to AGL -system through the binder.

- + AGL SYSTEM +

The application and its companion binder run in secured and isolated environment set for them. Applications are intended to access to AGL system through the binder.

The binder afb-daemon serves multiple purposes:

- -
    +
    1. It acts as a gateway for the application to access the system;

    2. It acts as an HTTP server for serving files to HTML5 applications;

    3. -
    4. It allows HTML5 applications to have native extensions subject -to security enforcement for accessing hardware ressources or -for speeding parts of algorithm.

    5. +
    6. It allows HTML5 applications to have native extensions subject to security enforcement for accessing hardware ressources or for speeding parts of algorithm.

    - - - -

    Use cases of the binder afb-daemon

    - -

    This section tries to give a better understanding of the binder -usage through several use cases.

    - - -

    Remotely running application

    - -

    One of the most interresting aspect of using the binder afb-daemon -is the ability to run applications remotely. This feature is -possible because the binder afb-daemon implements native web -protocols.

    - -

    So the figure binder, basis would become -when the application is run remotely:

    - -

    Figure: binder afb-daemon and remotely running application

    - +

    Use cases of the binder afb-daemon

    +

    This section tries to give a better understanding of the binder usage through several use cases.

    +

    Remotely running application

    +

    One of the most interresting aspect of using the binder afb-daemon is the ability to run applications remotely. This feature is possible because the binder afb-daemon implements native web protocols.

    +

    So the figure binder, basis would become when the application is run remotely:

    + +

    +Figure: binder afb-daemon and remotely running application +

    +

                 +------------------------------+
                  |                              |
                  |    A P P L I C A T I O N     |
    @@ -131,35 +113,22 @@ when the application is run remotely:

    . . . . . . . . . . . . . . | . . . . . . . . . . . . . . | v - AGL SYSTEM -
    - - -

    Adding native features to HTML5/QML applications

    - -

    Applications can provide with their packaged delivery a plugin. -That plugin will be instanciated for each application instance. -The methods of the plugin will be accessible by applications and -will be excuted within the security context.

    - - -

    Offering services to the system

    - -

    It is possible to run the binder afb-daemon as a daemon that provides the -API of its plugins.

    - + AGL SYSTEM +

    Adding native features to HTML5/QML applications

    +

    Applications can provide with their packaged delivery a plugin. That plugin will be instanciated for each application instance. The methods of the plugin will be accessible by applications and will be excuted within the security context.

    +

    Offering services to the system

    +

    It is possible to run the binder afb-daemon as a daemon that provides the API of its plugins.

    This will be used for:

    - -
      +
      1. offering common APIs

      2. -
      3. provide application’s services (services provided as application)

      4. +
      5. provide application's services (services provided as application)

      - -

      In that case, the figure showing the whole aspects is

      - -

      Figure: binder afb-daemon for services

      - + +

      +Figure: binder afb-daemon for services +

      +

      . . . . . . . . . . . . . . . . . . . . . . 
       .  Isolated security context application  . 
       .                                         . 
      @@ -195,176 +164,151 @@ API of its plugins.

      . +------------------------------------+ . . +------------------------------------+ . . . . . . Isolated security context B . . Isolated security context C . -. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . -
      - -

      For this case, the binder afb-daemon takes care to attribute one single session -context to each client instance. It allows plugins to store and retrieve data -associated to each of its client.

      - - -

      The plugins of the binder afb-daemon

      - -

      The binder can instanciate plugins. The primary use of plugins -is to add native methods that can be accessed by applications -written with any language through web technologies ala JSON RPC.

      - +. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . +

      For this case, the binder afb-daemon takes care to attribute one single session context to each client instance. It allows plugins to store and retrieve data associated to each of its client.

      +

      The plugins of the binder afb-daemon

      +

      The binder can instanciate plugins. The primary use of plugins is to add native methods that can be accessed by applications written with any language through web technologies ala JSON RPC.

      This simple idea is declined to serves multiple purposes:

      - -
        +
        1. add native feature to applications

        2. add common API available by any applications

        3. provide customers services

        - - -

        A specific document explains how to write an afb-daemon binder plugin: -HOWTO WRITE a PLUGIN for AFB-DAEMON

        - - -

        Launching the binder afb-daemon

        - +

        A specific document explains how to write an afb-daemon binder plugin: HOWTO WRITE a PLUGIN for AFB-DAEMON

        +

        Launching the binder afb-daemon

        The launch options for binder afb-daemon are:

        -
          --help
         
        -        Prints help with available options
        +    Prints help with available options
         
           --version
         
        -        Display version and copyright
        +    Display version and copyright
         
           --verbose
         
        -        Increases the verbosity, can be repeated
        +    Increases the verbosity, can be repeated
         
           --port=xxxx
         
        -        HTTP listening TCP port  [default 1234]
        +    HTTP listening TCP port  [default 1234]
         
           --rootdir=xxxx
         
        -        HTTP Root Directory [default $AFBDIR or else $HOME/.AFB]
        +    HTTP Root Directory [default $AFBDIR or else $HOME/.AFB]
         
           --rootbase=xxxx
         
        -        Angular Base Root URL [default /opa]
        +    Angular Base Root URL [default /opa]
         
        -        This is used for any application of kind OPA (one page application).
        -        When set, any missing document whose url has the form /opa/zzz
        -        is translated to /opa/#!zzz
        +    This is used for any application of kind OPA (one page application).
        +    When set, any missing document whose url has the form /opa/zzz
        +    is translated to /opa/#!zzz
         
           --rootapi=xxxx
         
        -        HTML Root API URL [default /api]
        +    HTML Root API URL [default /api]
         
        -        The plugins are available within that url.
        +    The plugins are available within that url.
         
           --alias=xxxx
         
        -        Maps a path located anywhere in the file system to the
        -        a subdirectory. The syntax for mapping a PATH to the
        -        subdirectory NAME is: --alias=/NAME:PATH.
        +    Maps a path located anywhere in the file system to the
        +    a subdirectory. The syntax for mapping a PATH to the
        +    subdirectory NAME is: --alias=/NAME:PATH.
         
        -        Example: --alias=/icons:/usr/share/icons maps the
        -        content of /usr/share/icons within the subpath /icons.
        +    Example: --alias=/icons:/usr/share/icons maps the
        +    content of /usr/share/icons within the subpath /icons.
         
        -        This option can be repeated.
        +    This option can be repeated.
         
           --apitimeout=xxxx
         
        -        Plugin API timeout in seconds [default 20]
        +    Plugin API timeout in seconds [default 20]
         
        -        Defines how many seconds maximum a method is allowed to run.
        -        0 means no limit.
        +    Defines how many seconds maximum a method is allowed to run.
        +    0 means no limit.
         
           --cntxtimeout=xxxx
         
        -        Client Session Timeout in seconds [default 3600]
        +    Client Session Timeout in seconds [default 3600]
         
           --cache-eol=xxxx
         
        -        Client cache end of live [default 100000 that is 27,7 hours]
        +    Client cache end of live [default 100000 that is 27,7 hours]
         
           --sessiondir=xxxx
         
        -        Sessions file path [default rootdir/sessions]
        +    Sessions file path [default rootdir/sessions]
         
           --session-max=xxxx
         
        -        Maximum count of simultaneous sessions [default 10]
        +    Maximum count of simultaneous sessions [default 10]
         
           --ldpaths=xxxx
         
        -        Load Plugins from given paths separated by colons
        -        as for dir1:dir2:plugin1.so:... [default = $libdir/afb]
        +    Load Plugins from given paths separated by colons
        +    as for dir1:dir2:plugin1.so:... [default = $libdir/afb]
         
        -        You can mix path to directories and to plugins.
        -        The sub-directories of the given directories are searched
        -        recursively.
        +    You can mix path to directories and to plugins.
        +    The sub-directories of the given directories are searched
        +    recursively.
         
        -        The plugins are the files terminated by '.so' (the extension
        -        so denotes shared object) that contain the public entry symbol.
        +    The plugins are the files terminated by '.so' (the extension
        +    so denotes shared object) that contain the public entry symbol.
         
           --plugin=xxxx
         
        -        Load the plugin of given path.
        +    Load the plugin of given path.
         
           --token=xxxx
         
        -        Initial Secret token to authenticate.
        +    Initial Secret token to authenticate.
         
        -        If not set, no client can authenticate.
        +    If not set, no client can authenticate.
         
        -        If set to the empty string, then any initial token is accepted.
        +    If set to the empty string, then any initial token is accepted.
         
           --mode=xxxx
         
        -        Set the mode: either local, remote or global.
        +    Set the mode: either local, remote or global.
         
        -        The mode indicate if the application is run locally on the host
        -        or remotely through network.
        +    The mode indicate if the application is run locally on the host
        +    or remotely through network.
         
           --readyfd=xxxx
         
        -        Set the #fd to signal when ready
        +    Set the #fd to signal when ready
         
        -        If set, the binder afb-daemon will write "READY=1\n" on the file
        -        descriptor whose number if given (/proc/self/fd/xxx).
        +    If set, the binder afb-daemon will write "READY=1\n" on the file
        +    descriptor whose number if given (/proc/self/fd/xxx).
         
           --dbus-client=xxxx
         
        -        Transparent binding to a binder afb-daemon service through dbus.
        +    Transparent binding to a binder afb-daemon service through dbus.
         
        -        It creates an API of name xxxx that is implemented remotely
        -        and queried via DBUS.
        +    It creates an API of name xxxx that is implemented remotely
        +    and queried via DBUS.
         
           --dbus-server=xxxx
         
        -        Provides a binder afb-daemon service through dbus.
        +    Provides a binder afb-daemon service through dbus.
         
        -        The name xxxx must be the name of an API defined by a plugin.
        -        This API is exported through DBUS.
        +    The name xxxx must be the name of an API defined by a plugin.
        +    This API is exported through DBUS.
         
           --foreground
         
        -        Get all in foreground mode (default)
        +    Get all in foreground mode (default)
         
           --daemon
         
        -        Get all in background mode
        -
        - - -

        Future development of afb-daemon

        - + Get all in background mode +

        Future development of afb-daemon

        • The binder afb-daemon would launch the applications directly.

        • -
        • The current setting of mode (local/remote/global) might be reworked to a -mechanism for querying configuration variables.

        • -
        • Implements “one-shot” initial token. It means that after its first -authenticated use, the initial token is removed and no client can connect -anymore.

        • +
        • The current setting of mode (local/remote/global) might be reworked to a mechanism for querying configuration variables.

        • +
        • Implements "one-shot" initial token. It means that after its first authenticated use, the initial token is removed and no client can connect anymore.

        • Creates some intrinsic APIs.

        • Make the service connection using WebSocket not DBUS.

        • Management of targetted events.

        • diff --git a/doc/afb-plugin-writing.html b/doc/afb-plugin-writing.html index 84a23573..eaa7a370 100644 --- a/doc/afb-plugin-writing.html +++ b/doc/afb-plugin-writing.html @@ -1,1255 +1,805 @@ + - - + + + + + HOWTO WRITE a PLUGIN for AFB-DAEMON + + + + - -

          HOWTO WRITE a PLUGIN for AFB-DAEMON

          - +
          +

          HOWTO WRITE a PLUGIN for AFB-DAEMON

          +

          José Bollo

          +

          30 mai 2016

          +
          + +

          HOWTO WRITE a PLUGIN for AFB-DAEMON

          version: 1
           Date:    30 mai 2016
          -Author:  José Bollo
          -
          - -

          - - -

          Summary

          - -

          Afb-daemon binders serve files through HTTP protocol -and offers to developers the capability to expose application API methods through -HTTP or WebSocket protocol.

          - -

          Binder plugins are used to add API to afb-daemon. -This part describes how to write a plugin for afb-daemon.

          - +Author: José Bollo +

          Summary

          +

          Afb-daemon binders serve files through HTTP protocol and offers to developers the capability to expose application API methods through HTTP or WebSocket protocol.

          +

          Binder plugins are used to add API to afb-daemon. This part describes how to write a plugin for afb-daemon.

          Excepting this summary, this document target developers.

          - -

          Before moving further through an example, here after -a short overview of binder plugins fundamentals.

          - - -

          Nature of a plugin

          - -

          A plugin is an independent piece of software. A plugin is self contain and exposes application logic as sharable library. -A plugin is intended to be dynamically loaded by afb-daemon to expose application API.

          - +

          Before moving further through an example, here after a short overview of binder plugins fundamentals.

          +

          Nature of a plugin

          +

          A plugin is an independent piece of software. A plugin is self contain and exposes application logic as sharable library. A plugin is intended to be dynamically loaded by afb-daemon to expose application API.

          Technically, a binder plugin does not reference and is not linked with any afb-daemon library.

          - - -

          Class of plugins

          - -

          Application binder supports two kinds of plugins: application plugins and service plugins. -Technically both class of plugin are equivalent are use the same coding convention. Only sharing mode and security context diverge.

          - - -

          Application-plugins

          - -

          Application-plugins implements the glue in between application’s UI and services. Every AGL application -has a corresponding binder that typically activates one or many plugins to interface the application logic with lower platform services. -When an application is started by the AGL application framework, a dedicate binder is started that loads/activates application plugin(s). -API expose by application-plugin are executed within corresponding application security context.

          - -

          Application plugins generally handle a unique context for a unique client. As the application framework start -a dedicated instance of afb_daemon for each AGL application, if a given plugin is used within multiple application each of those -application get a new and private instance of eventually “shared” plugin.

          - - -

          Service-plugins

          - -

          Service-plugins enable API activation within corresponding service security context and not within calling application context. -Service-plugins are intended to run as a unique instance. Service-plugins can be shared in between multiple clients.

          - +

          Class of plugins

          +

          Application binder supports two kinds of plugins: application plugins and service plugins. Technically both class of plugin are equivalent are use the same coding convention. Only sharing mode and security context diverge.

          +

          Application-plugins

          +

          Application-plugins implements the glue in between application's UI and services. Every AGL application has a corresponding binder that typically activates one or many plugins to interface the application logic with lower platform services. When an application is started by the AGL application framework, a dedicate binder is started that loads/activates application plugin(s). API expose by application-plugin are executed within corresponding application security context.

          +

          Application plugins generally handle a unique context for a unique client. As the application framework start a dedicated instance of afb_daemon for each AGL application, if a given plugin is used within multiple application each of those application get a new and private instance of eventually "shared" plugin.

          +

          Service-plugins

          +

          Service-plugins enable API activation within corresponding service security context and not within calling application context. Service-plugins are intended to run as a unique instance. Service-plugins can be shared in between multiple clients.

          Service-plugins can either be stateless or manage client context. When managing context each client get a private context.

          -

          Sharing may either be global to the platform (ie: GPS service) or dedicated to a given user (ie: user preferences)

          - - -

          Live cycle of plugins within afb-daemon

          - +

          Live cycle of plugins within afb-daemon

          Application and service plugins are loaded and activated each time a new afb-daemon is started.

          - -

          At launch time, every loaded plugin initialise itself. -If a single plugin initialisation fail corresponding instance of afb-daemon self aborts.

          - -

          Conversely, when a plugin initialisation succeeds, it should register -its unique name as well as the list of verbs attached to the methods it exposes.

          - -

          When initialised, on request from application clients to the right API/verb, plugin methods -are activated by the afb-daemon attached to the application or service.

          - -

          At exit time, no special action is enforced by afb-daemon. When a specific actions is required at afb-daemon stop, -developers should use ‘atexit/on_exit’ during plugin initialisation sequence to register a custom exit function.

          - - -

          Plugin Contend

          - -

          Afb-daemon’s plugin register two classes of objects: names and functions.

          - -

          Plugins declare categories of names: - - A unique plugin name to access all API expose by this plugin, - - One name for each methods/verbs provided by this plugin.

          - -

          Plugins declare two categories of functions: - - function use for the initialisation - - functions implementing exposed API methods

          - -

          Afb-daemon parses URI requests to extract the API(plugin name) and the VERB(method to activate). -As an example, URI foo/bar translates to plugin named foo and method named bar. -To serve such a request, afb-daemon looks for an active plugin named foo and then within this plugin for a method named bar. -When find afb-daemon calls corresponding method with attached parameter if any.

          - +

          At launch time, every loaded plugin initialise itself. If a single plugin initialisation fail corresponding instance of afb-daemon self aborts.

          +

          Conversely, when a plugin initialisation succeeds, it should register its unique name as well as the list of verbs attached to the methods it exposes.

          +

          When initialised, on request from application clients to the right API/verb, plugin methods are activated by the afb-daemon attached to the application or service.

          +

          At exit time, no special action is enforced by afb-daemon. When a specific actions is required at afb-daemon stop, developers should use 'atexit/on_exit' during plugin initialisation sequence to register a custom exit function.

          +

          Plugin Contend

          +

          Afb-daemon's plugin register two classes of objects: names and functions.

          +

          Plugins declare categories of names: - A unique plugin name to access all API expose by this plugin, - One name for each methods/verbs provided by this plugin.

          +

          Plugins declare two categories of functions: - function use for the initialisation - functions implementing exposed API methods

          +

          Afb-daemon parses URI requests to extract the API(plugin name) and the VERB(method to activate). As an example, URI foo/bar translates to plugin named foo and method named bar. To serve such a request, afb-daemon looks for an active plugin named foo and then within this plugin for a method named bar. When find afb-daemon calls corresponding method with attached parameter if any.

          Afb-daemon ignores letter case when parsing URI. Thus TicTacToe/Board and tictactoe/board are equivalent.

          - - -

          The name of the plugin

          - -

          The name of a given plugin is also known as the name -of the API prefix that defines the plugin.

          - +

          The name of the plugin

          +

          The name of a given plugin is also known as the name of the API prefix that defines the plugin.

          The name of a plugin SHOULD be unique within a given afb-daemon instance.

          - -

          For example, when a client of afb-daemon calls a URI named foo/bar. Afb-daemon -extracts the prefix foo and the suffix bar. foo must match a plugin name and bar a VERB attached to some method.

          - - -

          Names of methods

          - -

          Each plugin exposes a set of methods that can be called -by the clients of a given afb-daemon.

          - -

          VERB’s name attached to a given plugin (API) MUST be unique within a plugin.

          - -

          Plugins static declaration link VERBS to corresponding methods. -When clients emit requests on a given API/VERB corresponding method is called by afb-daemon.

          - - -

          Initialisation function

          - -

          Plugin’s initialisation function serves several purposes.

          - -
            -
          1. It allows afb-daemon to control plugin version depending on initialisation function name. -As today, the only supported initialisation function is pluginAfbV1Register. This identifies -version “one” of plugins.

          2. +

            For example, when a client of afb-daemon calls a URI named foo/bar. Afb-daemon extracts the prefix foo and the suffix bar. foo must match a plugin name and bar a VERB attached to some method.

            +

            Names of methods

            +

            Each plugin exposes a set of methods that can be called by the clients of a given afb-daemon.

            +

            VERB's name attached to a given plugin (API) MUST be unique within a plugin.

            +

            Plugins static declaration link VERBS to corresponding methods. When clients emit requests on a given API/VERB corresponding method is called by afb-daemon.

            +

            Initialisation function

            +

            Plugin's initialisation function serves several purposes.

            +
              +
            1. It allows afb-daemon to control plugin version depending on initialisation function name. As today, the only supported initialisation function is pluginAfbV1Register. This identifies version "one" of plugins.

            2. It allows plugins to initialise itself.

            3. It enables names declarations: descriptions, requirements and implementations of exposed API/VERB.

            - - - -

            Functions instantiation of API/VERBs

            - -

            When an API/VERB is called, afb-daemon constructs a request object. Then it -passes this request object to the implementation function corresponding to requested method, this -within attached API plugin.

            - -

            An implementation function receives a request object that -is used to: get arguments of the request, send -answer, store session data.

            - +

            Functions instantiation of API/VERBs

            +

            When an API/VERB is called, afb-daemon constructs a request object. Then it passes this request object to the implementation function corresponding to requested method, this within attached API plugin.

            +

            An implementation function receives a request object that is used to: get arguments of the request, send answer, store session data.

            A plugin MUST set an answer to every received requests.

            - -

            Nevertheless it is not mandatory to set the answer -before returning from API/VERB implementing function. -This behaviour is important for asynchronous actions.

            - -

            API/VERB implementation that set an answer before returning are called synchronous implementations. -Those that do not systematically set an answer before returning are called asynchronous implementations.

            - -

            Asynchronous implementations typically launch asynchronous actions. They record some context at -request time and provide answer to the request only at completion of asynchronous actions.

            - - -

            The Tic-Tac-Toe example

            - -

            This part explains how to write an afb-plugin. -For the sake of being practical it uses many -examples based on tic-tac-toe. -This plugin example is in plugins/samples/tic-tac-toe.c.

            - +

            Nevertheless it is not mandatory to set the answer before returning from API/VERB implementing function. This behaviour is important for asynchronous actions.

            +

            API/VERB implementation that set an answer before returning are called synchronous implementations. Those that do not systematically set an answer before returning are called asynchronous implementations.

            +

            Asynchronous implementations typically launch asynchronous actions. They record some context at request time and provide answer to the request only at completion of asynchronous actions.

            +

            The Tic-Tac-Toe example

            +

            This part explains how to write an afb-plugin. For the sake of being practical it uses many examples based on tic-tac-toe. This plugin example is in plugins/samples/tic-tac-toe.c.

            This plugin is named tictactoe.

            - - -

            Dependencies when compiling

            - -

            Afb-daemon provides a configuration file for pkg-config. -Typing the command

            - -
            pkg-config --cflags afb-daemon
            -
            - +

            Dependencies when compiling

            +

            Afb-daemon provides a configuration file for pkg-config. Typing the command

            +
            pkg-config --cflags afb-daemon

            Print flags use for compilation:

            -
            $ pkg-config --cflags afb-daemon
            --I/opt/local/include -I/usr/include/json-c 
            -
            - +-I/opt/local/include -I/usr/include/json-c

            For linking, you should use

            -
            $ pkg-config --libs afb-daemon
            --ljson-c
            -
            - -

            Afb-daemon automatically includes dependency to json-c. -This is activated through Requires keyword in pkg-config. -While almost every plugin replies on json-c this is not a must have dependency.

            - -

            Internally, afb-daemon relies on libsystemd for its event loop, as well -as for its binding to D-Bus. -Plugins developers are encouraged to leverage libsystemd when possible. -Nevertheless there is no hard dependency to libsystemd if ever -you rather not use it, feel free to do so.

            - -

            Afb-daemon plugin are fully self contain. They do not enforce dependency on any libraries from the application framework. -Afb-daemon dependencies requirer to run AGL plugins are given at runtime through pointers leveraging read-only -memory feature.

            - - -

            Header files to include

            - +-ljson-c +

            Afb-daemon automatically includes dependency to json-c. This is activated through Requires keyword in pkg-config. While almost every plugin replies on json-c this is not a must have dependency.

            +

            Internally, afb-daemon relies on libsystemd for its event loop, as well as for its binding to D-Bus. Plugins developers are encouraged to leverage libsystemd when possible. Nevertheless there is no hard dependency to libsystemd if ever you rather not use it, feel free to do so.

            +
            +

            Afb-daemon plugin are fully self contain. They do not enforce dependency on any libraries from the application framework. Afb-daemon dependencies requirer to run AGL plugins are given at runtime through pointers leveraging read-only memory feature.

            +
            +

            Header files to include

            Plugin tictactoe has following includes:

            - -
            #define _GNU_SOURCE
            -#include <stdio.h>
            -#include <string.h>
            -#include <json-c/json.h>
            -#include <afb/afb-plugin.h>
            -
            - -

            Header afb/afb-plugin.h is the only hard dependency, it includes all features -that a plugin MUST HAVE. Outside of includes used to support application logic, -common external headers used within plugins are:

            - +
            #define _GNU_SOURCE
            +#include <stdio.h>
            +#include <string.h>
            +#include <json-c/json.h>
            +#include <afb/afb-plugin.h>
            +

            Header afb/afb-plugin.h is the only hard dependency, it includes all features that a plugin MUST HAVE. Outside of includes used to support application logic, common external headers used within plugins are:

            • json-c/json.h: should be include to handle json objects;
            • systemd/sd-event.h: should be include to access event main loop;
            • systemd/sd-bus.h: should be include for dbus connections.
            - - -

            The tictactoe plugin does not leverage systemd features, also only json.h -is used on top of mandatory afb/afb-plugin.h.

            - -

            When including afb/afb-plugin.h, the macro _GNU_SOURCE MUST be -defined.

            - - -

            Choosing names

            - -

            Designers of plugins should define a unique name for every API plugin -as well as for methods VERBs. They should also define names for request -arguments passed as name/value pair in URI.

            - -

            While forging names, designers should respect few rules to -ensure that created names are valid and easy to use across platforms.

            - +

            The tictactoe plugin does not leverage systemd features, also only json.h is used on top of mandatory afb/afb-plugin.h.

            +

            When including afb/afb-plugin.h, the macro **_GNU_SOURCE** MUST be defined.

            +

            Choosing names

            +

            Designers of plugins should define a unique name for every API plugin as well as for methods VERBs. They should also define names for request arguments passed as name/value pair in URI.

            +

            While forging names, designers should respect few rules to ensure that created names are valid and easy to use across platforms.

            All names and strings are UTF-8 encoded.

            - - -

            Names for API (plugin)

            - -

            Plugin API name are checked. -All characters are authorised except:

            - +

            Names for API (plugin)

            +

            Plugin API name are checked. All characters are authorised except:

              -
            • the control characters (\u0000 .. \u001f)
            • -
            • the characters of the set { ‘ ’, ‘“’, ‘#’, ‘%’, ‘&’, -‘’‘, ’/‘, ’?‘, ’`‘, ’\x7f' }
            • +
            • the control characters (000 .. 01f)
            • +
            • the characters of the set { ' ', '"', '#', '%', '&', ''', '/', '?', '`', '7f' }
            - - -

            In other words the set of forbidden characters is -{ \u0000..\u0020, \u0022, \u0023, \u0025..\u0027, - \u002f, \u003f, \u0060, \u007f }.

            - -

            Afb-daemon makes no distinction between lower case -and upper case when searching for API/VERB.

            - - -

            Names for methods

            - +

            In other words the set of forbidden characters is { 000..020, 022, 023, 025..027, 02f, 03f, 060, 07f }.

            +

            Afb-daemon makes no distinction between lower case and upper case when searching for API/VERB.

            +

            Names for methods

            The names of methods VERBs are totally free and not checked.

            - -

            However, the validity rules for method’s VERB name are the -same as for Plugin API name except that the dot(.) character -is forbidden.

            - +

            However, the validity rules for method's VERB name are the same as for Plugin API name except that the dot(.) character is forbidden.

            Afb-daemon makes no case distinction when searching for an API by name.

            - - -

            Names for arguments

            - -

            Argument’s name are not restricted and can be everything you wish.

            - -

            Warning arguments search is case sensitive and “index” and “Index” -are not two different arguments.

            - - -

            Forging names widely available

            - -

            The key names of javascript object can be almost -anything using the arrayed notation:

            - -
            object[key] = value
            -
            - +

            Names for arguments

            +

            Argument's name are not restricted and can be everything you wish.

            +
            +

            Warning arguments search is case sensitive and "index" and "Index" are not two different arguments.

            +
            +

            Forging names widely available

            +

            The key names of javascript object can be almost anything using the arrayed notation:

            +
            object[key] = value

            Nevertheless this is not the case with javascript dot notation:

            - -
            object.key = value
            -
            - -

            Using the dot notation, the key must be a valid javascript -identifier and dash(-) as well as few other reserved characters cannot be used.

            - +
            object.key = value
            +

            Using the dot notation, the key must be a valid javascript identifier and dash(-) as well as few other reserved characters cannot be used.

            For this reason, we advise developper to chose name compatible with both javascript and HTML notation.

            - -

            It is a good practice, even for arguments not to rely on case sensitivity. -This may reduce headache strength at debug time, especially with interpreted language like -javascript that may not warn you that a variable was not defined.

            - - -

            Writing a synchronous method implementation

            - -

            The method tictactoe/board is a synchronous implementation. -Here is its listing:

            - -
            /*
            - * get the board
            - */
            -static void board(struct afb_req req)
            +

            It is a good practice, even for arguments not to rely on case sensitivity. This may reduce headache strength at debug time, especially with interpreted language like javascript that may not warn you that a variable was not defined.

            +

            Writing a synchronous method implementation

            +

            The method tictactoe/board is a synchronous implementation. Here is its listing:

            +
            /*
            + * get the board
            + */
            +static void board(struct afb_req req)
             {
            -        struct board *board;
            -        struct json_object *description;
            -
            -        /* retrieves the context for the session */
            -        board = board_of_req(req);
            -        INFO(afbitf, "method 'board' called for boardid %d", board->id);
            -
            -        /* describe the board */
            -        description = describe(board);
            -
            -        /* send the board's description */
            -        afb_req_success(req, description, NULL);
            -}
            -
            - -

            This example shows many aspects of a synchronous -method implementation. Let summarise it:

            - -
              -
            1. The function board_of_req retrieves the context stored -for the plugin: the board.

            2. -
            3. The macro INFO sends a message of kind INFO -to the logging system. The global variable named afbitf -used represents the interface to afb-daemon.

            4. -
            5. The function describe creates a json_object representing -the board.

            6. -
            7. The function afb_req_success sends the reply, attaching to -it the object description.

            8. + struct board *board; + struct json_object *description; + + /* retrieves the context for the session */ + board = board_of_req(req); + INFO(afbitf, "method 'board' called for boardid %d", board->id); + + /* describe the board */ + description = describe(board); + + /* send the board's description */ + afb_req_success(req, description, NULL); +}
            +

            This example shows many aspects of a synchronous method implementation. Let summarise it:

            +
              +
            1. The function board_of_req retrieves the context stored for the plugin: the board.

            2. +
            3. The macro INFO sends a message of kind INFO to the logging system. The global variable named afbitf used represents the interface to afb-daemon.

            4. +
            5. The function describe creates a json_object representing the board.

            6. +
            7. The function afb_req_success sends the reply, attaching to it the object description.

            - - - -

            The incoming request

            - -

            For any implementation, the request is received by a structure of type -struct afb_req.

            - -

            Note that this is a PLAIN structure, not a pointer to a structure.

            - +

            The incoming request

            +

            For any implementation, the request is received by a structure of type struct afb_req.

            +
            +

            Note that this is a PLAIN structure, not a pointer to a structure.

            +

            The definition of struct afb_req is:

            - -
            /*
            - * Describes the request by plugins from afb-daemon
            - */
            -struct afb_req {
            -        const struct afb_req_itf *itf;  /* the interfacing functions */
            -        void *closure;          /* the closure for functions */
            -};
            -
            - -

            It contains two pointers: first one itf, points to functions used -to handle internal request. Second one closure point onto function closure.

            - -

            The structure must never be used directly. -Instead developer should use the intended functions provided -by afb-daemon as described here after.

            - -

            req is used to get arguments of the request, to send -answer, to store session data.

            - -

            This object and its interface is defined and documented -in the file names afb/afb-req-itf.h

            - +
            /*
            + * Describes the request by plugins from afb-daemon
            + */
            +struct afb_req {
            +    const struct afb_req_itf *itf;  /* the interfacing functions */
            +    void *closure;          /* the closure for functions */
            +};
            +

            It contains two pointers: first one itf, points to functions used to handle internal request. Second one closure point onto function closure.

            +
            +

            The structure must never be used directly. Instead developer should use the intended functions provided by afb-daemon as described here after.

            +
            +

            req is used to get arguments of the request, to send answer, to store session data.

            +

            This object and its interface is defined and documented in the file names afb/afb-req-itf.h

            The above example uses twice req object request.

            -

            The first time, to retrieve the board attached to the session of the request.

            -

            The second time, to send the reply: an object that describes the current board.

            - - -

            Associating a client context to a session

            - -

            When tic-tac-toe plugin receives a request, it musts get -the board describing the game associated to the session.

            - -

            For a plugin, having data associated to a session is common. -This data is called “plugin context” for the session. -Within tic-tac-toe plugin the context is the board.

            - +

            Associating a client context to a session

            +

            When tic-tac-toe plugin receives a request, it musts get the board describing the game associated to the session.

            +

            For a plugin, having data associated to a session is common. This data is called "plugin context" for the session. Within tic-tac-toe plugin the context is the board.

            Requests afb_req offer four functions for storing and retrieving session associated context.

            -

            These functions are:

            -
              -
            • afb_req_context_get: -retrieves context data stored for current plugin.

            • -
            • afb_req_context_set: -store context data of current plugin.

            • -
            • afb_req_context: -if exist retrieves context data of current plugin. -if context does not yet exist, creates a new context and store it.

            • -
            • afb_req_context_clear: -reset the stored context data.

            • +
            • afb_req_context_get: retrieves context data stored for current plugin.

            • +
            • afb_req_context_set: store context data of current plugin.

            • +
            • afb_req_context: if exist retrieves context data of current plugin. if context does not yet exist, creates a new context and store it.

            • +
            • afb_req_context_clear: reset the stored context data.

            - - -

            The plugin tictactoe use a convenient function to retrieve -its context: the board. This function is board_of_req:

            - -
            /*
            - * retrieves the board of the request
            - */
            -static inline struct board *board_of_req(struct afb_req req)
            +

            The plugin tictactoe use a convenient function to retrieve its context: the board. This function is board_of_req:

            +
            /*
            + * retrieves the board of the request
            + */
            +static inline struct board *board_of_req(struct afb_req req)
             {
            -        return afb_req_context(req, (void*)get_new_board, (void*)release_board);
            -}
            -
            - -

            The function afb_req_context ensures an existing context -for the session of the request. -Its two last arguments are functions to allocate and free context. -Note function type casts to avoid compilation warnings.

            - + return afb_req_context(req, (void*)get_new_board, (void*)release_board); +}
            +

            The function afb_req_context ensures an existing context for the session of the request. Its two last arguments are functions to allocate and free context. Note function type casts to avoid compilation warnings.

            Here is the definition of the function afb_req_context

            - -
            /*
            - * Gets the pointer stored by the plugin for the session of 'req'.
            - * If the stored pointer is NULL, indicating that no pointer was
            - * already stored, afb_req_context creates a new context by calling
            - * the function 'create_context' and stores it with the freeing function
            - * 'free_context'.
            - */
            -static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*))
            +
            /*
            + * Gets the pointer stored by the plugin for the session of 'req'.
            + * If the stored pointer is NULL, indicating that no pointer was
            + * already stored, afb_req_context creates a new context by calling
            + * the function 'create_context' and stores it with the freeing function
            + * 'free_context'.
            + */
            +static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*))
             {
            -        void *result = afb_req_context_get(req);
            -        if (result == NULL) {
            -                result = create_context();
            -                afb_req_context_set(req, result, free_context);
            -        }
            -        return result;
            -}
            -
            - -

            The second argument if the function that creates the context. -For plugin tic-tac-toe (function get_new_board). -The function get_new_board creates a new board and set usage its count to 1. -The boards are checking usage count to free resources when not used.

            - -

            The third argument is a function that frees context resources. -For plugin tic-tac-toe (function release_board). -The function release_board decrease usage count of the board passed in argument. -When usage count falls to zero, data board are freed.

            - + void *result = afb_req_context_get(req); + if (result == NULL) { + result = create_context(); + afb_req_context_set(req, result, free_context); + } + return result; +}
            +

            The second argument if the function that creates the context. For plugin tic-tac-toe (function get_new_board). The function get_new_board creates a new board and set usage its count to 1. The boards are checking usage count to free resources when not used.

            +

            The third argument is a function that frees context resources. For plugin tic-tac-toe (function release_board). The function release_board decrease usage count of the board passed in argument. When usage count falls to zero, data board are freed.

            Definition of other functions dealing with contexts:

            - -
            /*
            - * Gets the pointer stored by the plugin for the session of 'req'.
            - * When the plugin has not yet recorded a pointer, NULL is returned.
            - */
            -void *afb_req_context_get(struct afb_req req);
            -
            -/*
            - * Stores for the plugin the pointer 'context' to the session of 'req'.
            - * The function 'free_context' will be called when the session is closed
            - * or if plugin stores an other pointer.
            - */
            -void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));
            -
            -/*
            - * Frees the pointer stored by the plugin for the session of 'req'
            - * and sets it to NULL.
            - *
            - * Shortcut for: afb_req_context_set(req, NULL, NULL)
            - */
            -static inline void afb_req_context_clear(struct afb_req req)
            +
            /*
            + * Gets the pointer stored by the plugin for the session of 'req'.
            + * When the plugin has not yet recorded a pointer, NULL is returned.
            + */
            +void *afb_req_context_get(struct afb_req req);
            +
            +/*
            + * Stores for the plugin the pointer 'context' to the session of 'req'.
            + * The function 'free_context' will be called when the session is closed
            + * or if plugin stores an other pointer.
            + */
            +void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));
            +
            +/*
            + * Frees the pointer stored by the plugin for the session of 'req'
            + * and sets it to NULL.
            + *
            + * Shortcut for: afb_req_context_set(req, NULL, NULL)
            + */
            +static inline void afb_req_context_clear(struct afb_req req)
             {
            -        afb_req_context_set(req, NULL, NULL);
            -}
            -
            - - -

            Sending reply to a request

            - + afb_req_context_set(req, NULL, NULL); +}
            +

            Sending reply to a request

            Two kinds of replies: successful or failure.

            - -

            Sending a reply to a request MUST be done once and only once.

            - -

            It exists two functions for “success” replies: afb_req_success and afb_req_success_f.

            - -
            /*
            - * Sends a reply of kind success to the request 'req'.
            - * The status of the reply is automatically set to "success".
            - * Its send the object 'obj' (can be NULL) with an
            - * informationnal comment 'info (can also be NULL).
            - *
            - * For conveniency, the function calls 'json_object_put' for 'obj'.
            - * Thus, in the case where 'obj' should remain available after
            - * the function returns, the function 'json_object_get' shall be used.
            - */
            -void afb_req_success(struct afb_req req, struct json_object *obj, const char *info);
            -
            -/*
            - * Same as 'afb_req_success' but the 'info' is a formatting
            - * string followed by arguments.
            - *
            - * For conveniency, the function calls 'json_object_put' for 'obj'.
            - * Thus, in the case where 'obj' should remain available after
            - * the function returns, the function 'json_object_get' shall be used.
            - */
            -void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
            -
            - -

            It exists two functions for “failure” replies: afb_req_fail and afb_req_fail_f.

            - -
            /*
            - * Sends a reply of kind failure to the request 'req'.
            - * The status of the reply is set to 'status' and an
            - * informational comment 'info' (can also be NULL) can be added.
            - *
            - * Note that calling afb_req_fail("success", info) is equivalent
            - * to call afb_req_success(NULL, info). Thus even if possible it
            - * is strongly recommended to NEVER use "success" for status.
            - *
            - * For conveniency, the function calls 'json_object_put' for 'obj'.
            - * Thus, in the case where 'obj' should remain available after
            - * the function returns, the function 'json_object_get' shall be used.
            - */
            -void afb_req_fail(struct afb_req req, const char *status, const char *info);
            -
            -/*
            - * Same as 'afb_req_fail' but the 'info' is a formatting
            - * string followed by arguments.
            - *
            - * For conveniency, the function calls 'json_object_put' for 'obj'.
            - * Thus, in the case where 'obj' should remain available after
            - * the function returns, the function 'json_object_get' shall be used.
            - */
            -void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
            -
            - -

            For conveniency, these functions automatically call json_object_put to release obj. -Because obj usage count is null after being passed to a reply function, it SHOULD not be used anymore. -If exceptionally obj needs to remain usable after reply function then using json_object_get on obj -to increase usage count and cancels the effect the json_object_put is possible.

            - - -

            Getting argument of invocation

            - -

            Many methods expect arguments. Afb-daemon’s plugins -retrieve arguments by name and not by position.

            - -

            Arguments are passed by requests through either HTTP -or WebSockets.

            - -

            For example, the method join of plugin tic-tac-toe -expects one argument: the boardid to join. Here is an extract:

            - -
            /*
            - * Join a board
            - */
            -static void join(struct afb_req req)
            +
            +

            Sending a reply to a request MUST be done once and only once.

            +
            +

            It exists two functions for "success" replies: afb_req_success and afb_req_success_f.

            +
            /*
            + * Sends a reply of kind success to the request 'req'.
            + * The status of the reply is automatically set to "success".
            + * Its send the object 'obj' (can be NULL) with an
            + * informationnal comment 'info (can also be NULL).
            + *
            + * For conveniency, the function calls 'json_object_put' for 'obj'.
            + * Thus, in the case where 'obj' should remain available after
            + * the function returns, the function 'json_object_get' shall be used.
            + */
            +void afb_req_success(struct afb_req req, struct json_object *obj, const char *info);
            +
            +/*
            + * Same as 'afb_req_success' but the 'info' is a formatting
            + * string followed by arguments.
            + *
            + * For conveniency, the function calls 'json_object_put' for 'obj'.
            + * Thus, in the case where 'obj' should remain available after
            + * the function returns, the function 'json_object_get' shall be used.
            + */
            +void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
            +

            It exists two functions for "failure" replies: afb_req_fail and afb_req_fail_f.

            +
            /*
            + * Sends a reply of kind failure to the request 'req'.
            + * The status of the reply is set to 'status' and an
            + * informational comment 'info' (can also be NULL) can be added.
            + *
            + * Note that calling afb_req_fail("success", info) is equivalent
            + * to call afb_req_success(NULL, info). Thus even if possible it
            + * is strongly recommended to NEVER use "success" for status.
            + *
            + * For conveniency, the function calls 'json_object_put' for 'obj'.
            + * Thus, in the case where 'obj' should remain available after
            + * the function returns, the function 'json_object_get' shall be used.
            + */
            +void afb_req_fail(struct afb_req req, const char *status, const char *info);
            +
            +/*
            + * Same as 'afb_req_fail' but the 'info' is a formatting
            + * string followed by arguments.
            + *
            + * For conveniency, the function calls 'json_object_put' for 'obj'.
            + * Thus, in the case where 'obj' should remain available after
            + * the function returns, the function 'json_object_get' shall be used.
            + */
            +void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
            +
            +

            For conveniency, these functions automatically call json_object_put to release obj. Because obj usage count is null after being passed to a reply function, it SHOULD not be used anymore. If exceptionally obj needs to remain usable after reply function then using json_object_get on obj to increase usage count and cancels the effect the json_object_put is possible.

            +
            +

            Getting argument of invocation

            +

            Many methods expect arguments. Afb-daemon's plugins retrieve arguments by name and not by position.

            +

            Arguments are passed by requests through either HTTP or WebSockets.

            +

            For example, the method join of plugin tic-tac-toe expects one argument: the boardid to join. Here is an extract:

            +
            /*
            + * Join a board
            + */
            +static void join(struct afb_req req)
             {
            -        struct board *board, *new_board;
            -        const char *id;
            -
            -        /* retrieves the context for the session */
            -        board = board_of_req(req);
            -        INFO(afbitf, "method 'join' called for boardid %d", board->id);
            -
            -        /* retrieves the argument */
            -        id = afb_req_value(req, "boardid");
            -        if (id == NULL)
            -                goto bad_request;
            -        ...
            -
            - -

            The function afb_req_value searches in the request req -for argument name passed in the second argument. When argument name -is not passed, afb_req_value returns NULL.

            - -

            The search is case sensitive and boardid is not equivalent to BoardId. -Nevertheless having argument names that only differ by name case is not a good idea.

            - - -

            Basic functions for querying arguments

            - + struct board *board, *new_board; + const char *id; + + /* retrieves the context for the session */ + board = board_of_req(req); + INFO(afbitf, "method 'join' called for boardid %d", board->id); + + /* retrieves the argument */ + id = afb_req_value(req, "boardid"); + if (id == NULL) + goto bad_request; + ...
            +

            The function afb_req_value searches in the request req for argument name passed in the second argument. When argument name is not passed, afb_req_value returns NULL.

            +
            +

            The search is case sensitive and boardid is not equivalent to BoardId. Nevertheless having argument names that only differ by name case is not a good idea.

            +
            +

            Basic functions for querying arguments

            The function afb_req_value is defined here after:

            - -
            /*
            - * Gets from the request 'req' the string value of the argument of 'name'.
            - * Returns NULL if when there is no argument of 'name'.
            - * Returns the value of the argument of 'name' otherwise.
            - *
            - * Shortcut for: afb_req_get(req, name).value
            - */
            -static inline const char *afb_req_value(struct afb_req req, const char *name)
            +
            /*
            + * Gets from the request 'req' the string value of the argument of 'name'.
            + * Returns NULL if when there is no argument of 'name'.
            + * Returns the value of the argument of 'name' otherwise.
            + *
            + * Shortcut for: afb_req_get(req, name).value
            + */
            +static inline const char *afb_req_value(struct afb_req req, const char *name)
             {
            -        return afb_req_get(req, name).value;
            -}
            -
            - -

            It is defined as a shortcut to call the function afb_req_get. -That function is defined here after:

            - -
            /*
            - * Gets from the request 'req' the argument of 'name'.
            - * Returns a PLAIN structure of type 'struct afb_arg'.
            - * When the argument of 'name' is not found, all fields of result are set to NULL.
            - * When the argument of 'name' is found, the fields are filled,
            - * in particular, the field 'result.name' is set to 'name'.
            - *
            - * There is a special name value: the empty string.
            - * The argument of name "" is defined only if the request was made using
            - * an HTTP POST of Content-Type "application/json". In that case, the
            - * argument of name "" receives the value of the body of the HTTP request.
            - */
            -struct afb_arg afb_req_get(struct afb_req req, const char *name);
            -
            - -

            That function takes 2 parameters: the request and the name -of the argument to retrieve. It returns a PLAIN structure of -type struct afb_arg.

            - -

            There is a special name that is defined when the request is -of type HTTP/POST with a Content-Type being application/json. -This name is “” (the empty string). In that case, the value -of this argument of empty name is the string received as a body -of the post and is supposed to be a JSON string.

            - + return afb_req_get(req, name).value; +}
            +

            It is defined as a shortcut to call the function afb_req_get. That function is defined here after:

            +
            /*
            + * Gets from the request 'req' the argument of 'name'.
            + * Returns a PLAIN structure of type 'struct afb_arg'.
            + * When the argument of 'name' is not found, all fields of result are set to NULL.
            + * When the argument of 'name' is found, the fields are filled,
            + * in particular, the field 'result.name' is set to 'name'.
            + *
            + * There is a special name value: the empty string.
            + * The argument of name "" is defined only if the request was made using
            + * an HTTP POST of Content-Type "application/json". In that case, the
            + * argument of name "" receives the value of the body of the HTTP request.
            + */
            +struct afb_arg afb_req_get(struct afb_req req, const char *name);
            +

            That function takes 2 parameters: the request and the name of the argument to retrieve. It returns a PLAIN structure of type struct afb_arg.

            +

            There is a special name that is defined when the request is of type HTTP/POST with a Content-Type being application/json. This name is "" (the empty string). In that case, the value of this argument of empty name is the string received as a body of the post and is supposed to be a JSON string.

            The definition of struct afb_arg is:

            - -
            /*
            - * Describes an argument (or parameter) of a request
            - */
            -struct afb_arg {
            -        const char *name;   /* name of the argument or NULL if invalid */
            -        const char *value;  /* string representation of the value of the argument */
            -                                /* original filename of the argument if path != NULL */
            -        const char *path;   /* if not NULL, path of the received file for the argument */
            -                                /* when the request is finalized this file is removed */
            -};
            -
            - -

            The structure returns the data arguments that are known for the -request. This data include a field named path. This path -can be accessed using the function afb_req_path defined here after:

            - -
            /*
            - * Gets from the request 'req' the path for file attached to the argument of 'name'.
            - * Returns NULL if when there is no argument of 'name' or when there is no file.
            - * Returns the path of the argument of 'name' otherwise.
            - *
            - * Shortcut for: afb_req_get(req, name).path
            - */
            -static inline const char *afb_req_path(struct afb_req req, const char *name)
            +
            /*
            + * Describes an argument (or parameter) of a request
            + */
            +struct afb_arg {
            +    const char *name;   /* name of the argument or NULL if invalid */
            +    const char *value;  /* string representation of the value of the argument */
            +                /* original filename of the argument if path != NULL */
            +    const char *path;   /* if not NULL, path of the received file for the argument */
            +                /* when the request is finalized this file is removed */
            +};
            +

            The structure returns the data arguments that are known for the request. This data include a field named path. This path can be accessed using the function afb_req_path defined here after:

            +
            /*
            + * Gets from the request 'req' the path for file attached to the argument of 'name'.
            + * Returns NULL if when there is no argument of 'name' or when there is no file.
            + * Returns the path of the argument of 'name' otherwise.
            + *
            + * Shortcut for: afb_req_get(req, name).path
            + */
            +static inline const char *afb_req_path(struct afb_req req, const char *name)
             {
            -        return afb_req_get(req, name).path;
            -}
            -
            - + return afb_req_get(req, name).path; +}

            The path is only defined for HTTP/POST requests that send file.

            - - -

            Arguments for received files

            - +

            Arguments for received files

            As it is explained above, clients can send files using HTTP/POST requests.

            - -

            Received files are attached to “file” argument name. For example, the -following HTTP fragment (from test/sample-post.html) -will send an HTTP/POST request to the method -post/upload-image with 2 arguments named file and -hidden.

            - -
            <h2>Sample Post File</h2>
            -<form enctype="multipart/form-data">
            -    <input type="file" name="file" />
            -    <input type="hidden" name="hidden" value="bollobollo" />
            -    <br>
            -    <button formmethod="POST" formaction="api/post/upload-image">Post File</button>
            -</form>
            -
            - +

            Received files are attached to "file" argument name. For example, the following HTTP fragment (from test/sample-post.html) will send an HTTP/POST request to the method post/upload-image with 2 arguments named file and hidden.

            +
            <h2>Sample Post File</h2>
            +<form enctype="multipart/form-data">
            +    <input type="file" name="file" />
            +    <input type="hidden" name="hidden" value="bollobollo" />
            +    <br>
            +    <button formmethod="POST" formaction="api/post/upload-image">Post File</button>
            +</form>

            Argument named file should have both its value and path defined.

            - -

            The value is the name of the file as it was set by the HTTP client. -Generally it is the filename on client side.

            - -

            The path is the effective path of saved file on the temporary local storage -area of the application. This is a randomly generated and unique filename. -It is not linked with the original filename as used on client side.

            - -

            After success the plugin can use the uploaded file directly from local storage path with no restriction: -read, write, remove, copy, rename… -Nevertheless when request reply is set and query terminated, the uploaded temporary file at -path is destroyed.

            - - -

            Arguments as a JSON object

            - -

            Plugins may also request every arguments of a given call as one single object. -This feature is provided by the function afb_req_json defined here after:

            - -
            /*
            - * Gets from the request 'req' the json object hashing the arguments.
            - * The returned object must not be released using 'json_object_put'.
            - */
            -struct json_object *afb_req_json(struct afb_req req);
            -
            - +

            The value is the name of the file as it was set by the HTTP client. Generally it is the filename on client side.

            +

            The path is the effective path of saved file on the temporary local storage area of the application. This is a randomly generated and unique filename. It is not linked with the original filename as used on client side.

            +

            After success the plugin can use the uploaded file directly from local storage path with no restriction: read, write, remove, copy, rename... Nevertheless when request reply is set and query terminated, the uploaded temporary file at path is destroyed.

            +

            Arguments as a JSON object

            +

            Plugins may also request every arguments of a given call as one single object. This feature is provided by the function afb_req_json defined here after:

            +
            /*
            + * Gets from the request 'req' the json object hashing the arguments.
            + * The returned object must not be released using 'json_object_put'.
            + */
            +struct json_object *afb_req_json(struct afb_req req);

            It returns a json object. This object depends on how the request was built:

            -
              -
            • For HTTP requests, this json object uses key names mapped on argument name. -Values are either string for common arguments or object ie: { “file”: “…”, “path”: “…” }

            • +
            • For HTTP requests, this json object uses key names mapped on argument name. Values are either string for common arguments or object ie: { "file": "...", "path": "..." }

            • For WebSockets requests, returned directly the object as provided by the client.

            - - -

            In fact, for Websockets requests, the function afb_req_value -can be seen as a shortcut to -json_object_get_string(json_object_object_get(afb_req_json(req), name))

            - - -

            Initialisation of the plugin and declaration of methods

            - -

            To be active, plugin’s methods should be declared to -afb-daemon. Furthermore, the plugin itself must be recorded.

            - -

            The registration mechanism is very basic: when afb-need starts, -it loads all plugins listed in: command line or configuration file.

            - +
            +

            In fact, for Websockets requests, the function afb_req_value can be seen as a shortcut to json_object_get_string(json_object_object_get(afb_req_json(req), name))

            +
            +

            Initialisation of the plugin and declaration of methods

            +

            To be active, plugin's methods should be declared to afb-daemon. Furthermore, the plugin itself must be recorded.

            +

            The registration mechanism is very basic: when afb-need starts, it loads all plugins listed in: command line or configuration file.

            Loading a plugin follows the following steps:

            - -
              +
              1. Afb-daemon loads the plugin with dlopen.

              2. -
              3. Afb-daemon searches for a symbol named pluginAfbV1Register using dlsym. -This symbol is assumed to be the exported initialisation function of the plugin.

              4. +
              5. Afb-daemon searches for a symbol named pluginAfbV1Register using dlsym. This symbol is assumed to be the exported initialisation function of the plugin.

              6. Afb-daemon builds an interface object for the plugin.

              7. -
              8. Afb-daemon calls the found function pluginAfbV1Register with interface pointer -as parameter.

              9. +
              10. Afb-daemon calls the found function pluginAfbV1Register with interface pointer as parameter.

              11. Function pluginAfbV1Register setups the plugin and initialises it.

              12. -
              13. Function pluginAfbV1Register returns the pointer to a structure -describing the plugin: version, name (prefix or API name), and list of methods.

              14. -
              15. Afb-daemon checks that the returned version and name can be managed. -If so, plugin and its methods are register to become usable as soon as -afb-daemon initialisation is finished.

              16. +
              17. Function pluginAfbV1Register returns the pointer to a structure describing the plugin: version, name (prefix or API name), and list of methods.

              18. +
              19. Afb-daemon checks that the returned version and name can be managed. If so, plugin and its methods are register to become usable as soon as afb-daemon initialisation is finished.

              - -

              Here after the code used for pluginAfbV1Register from plugin tic-tac-toe:

              - -
              /*
              - * activation function for registering the plugin called by afb-daemon
              - */
              -const struct AFB_plugin *pluginAfbV1Register(const struct AFB_interface *itf)
              +
              /*
              + * activation function for registering the plugin called by afb-daemon
              + */
              +const struct AFB_plugin *pluginAfbV1Register(const struct AFB_interface *itf)
               {
              -   afbitf = itf;         // records the interface for accessing afb-daemon
              -   return &plugin_description;  // returns the description of the plugin
              -}
              -
              - -

              It is a very minimal initialisation function because tic-tac-toe plugin doesn’t -have any application related initialisation step. It merely record daemon’s interface -and returns its description.

              - -

              The variable afbitf is a plugin global variable. It keeps the -interface to afb-daemon that should be used for logging and pushing events. -Here is its declaration:

              - -
              /*
              - * the interface to afb-daemon
              - */
              -const struct AFB_interface *afbitf;
              -
              - + afbitf = itf; // records the interface for accessing afb-daemon + return &plugin_description; // returns the description of the plugin +}
              +

              It is a very minimal initialisation function because tic-tac-toe plugin doesn't have any application related initialisation step. It merely record daemon's interface and returns its description.

              +

              The variable afbitf is a plugin global variable. It keeps the interface to afb-daemon that should be used for logging and pushing events. Here is its declaration:

              +
              /*
              + * the interface to afb-daemon
              + */
              +const struct AFB_interface *afbitf;

              The description of the plugin is defined here after.

              - -
              /*
              - * array of the methods exported to afb-daemon
              - */
              -static const struct AFB_method_desc_v1 plugin_methods[] = {
              -   /* VERB'S NAME     SESSION MANAGEMENT          FUNCTION TO CALL  SHORT DESCRIPTION */
              -   { .name= "new",   .session= AFB_SESSION_NONE, .callback= new,   .info= "Starts a new game" },
              -   { .name= "play",  .session= AFB_SESSION_NONE, .callback= play,  .info= "Asks the server to play" },
              -   { .name= "move",  .session= AFB_SESSION_NONE, .callback= move,  .info= "Tells the client move" },
              -   { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" },
              -   { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" },
              -   { .name= "join",  .session= AFB_SESSION_CHECK,.callback= join,  .info= "Join a board" },
              -   { .name= "undo",  .session= AFB_SESSION_NONE, .callback= undo,  .info= "Undo the last move" },
              -   { .name= "wait",  .session= AFB_SESSION_NONE, .callback= wait,  .info= "Wait for a change" },
              -   { .name= NULL } /* marker for end of the array */
              +
              /*
              + * array of the methods exported to afb-daemon
              + */
              +static const struct AFB_method_desc_v1 plugin_methods[] = {
              +   /* VERB'S NAME     SESSION MANAGEMENT          FUNCTION TO CALL  SHORT DESCRIPTION */
              +   { .name= "new",   .session= AFB_SESSION_NONE, .callback= new,   .info= "Starts a new game" },
              +   { .name= "play",  .session= AFB_SESSION_NONE, .callback= play,  .info= "Asks the server to play" },
              +   { .name= "move",  .session= AFB_SESSION_NONE, .callback= move,  .info= "Tells the client move" },
              +   { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" },
              +   { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" },
              +   { .name= "join",  .session= AFB_SESSION_CHECK,.callback= join,  .info= "Join a board" },
              +   { .name= "undo",  .session= AFB_SESSION_NONE, .callback= undo,  .info= "Undo the last move" },
              +   { .name= "wait",  .session= AFB_SESSION_NONE, .callback= wait,  .info= "Wait for a change" },
              +   { .name= NULL } /* marker for end of the array */
               };
               
              -/*
              - * description of the plugin for afb-daemon
              - */
              -static const struct AFB_plugin plugin_description =
              +/*
              + * description of the plugin for afb-daemon
              + */
              +static const struct AFB_plugin plugin_description =
               {
              -   /* description conforms to VERSION 1 */
              +   /* description conforms to VERSION 1 */
                  .type= AFB_PLUGIN_VERSION_1,
              -   .v1= {               /* fills the v1 field of the union when AFB_PLUGIN_VERSION_1 */
              -      .prefix= "tictactoe",     /* the API name (or plugin name or prefix) */
              -      .info= "Sample tac-tac-toe game", /* short description of of the plugin */
              -      .methods = plugin_methods     /* the array describing the methods of the API */
              +   .v1= {               /* fills the v1 field of the union when AFB_PLUGIN_VERSION_1 */
              +      .prefix= "tictactoe",     /* the API name (or plugin name or prefix) */
              +      .info= "Sample tac-tac-toe game", /* short description of of the plugin */
              +      .methods = plugin_methods     /* the array describing the methods of the API */
                  }
              -};
              -
              - -

              The structure plugin_description describes the plugin. -It declares the type and version of the plugin, its name, a short description -and its methods list.

              - +};
              +

              The structure plugin_description describes the plugin. It declares the type and version of the plugin, its name, a short description and its methods list.

              The list of methods is an array of structures describing the methods and terminated by a NULL marker.

              -

              In version one of afb-damon plugin, a method description contains 4 fields:

              -
              • the name of the method,

              • the session management flags,

              • the implementation function to be call for the method,

              • a short description.

              - -

              The structure describing methods is defined as follows:

              - -
              /*
              - * Description of one method of the API provided by the plugin
              - * This enumeration is valid for plugins of type 1
              - */
              -struct AFB_method_desc_v1
              +
              /*
              + * Description of one method of the API provided by the plugin
              + * This enumeration is valid for plugins of type 1
              + */
              +struct AFB_method_desc_v1
               {
              -       const char *name;                       /* name of the method */
              -       enum AFB_session_v1 session;            /* authorisation and session requirements of the method */
              -       void (*callback)(struct afb_req req);   /* callback function implementing the method */
              -       const char *info;                       /* textual description of the method */
              -};
              -
              - -

              For technical reasons, the enumeration enum AFB_session_v1 is not exactly an -enumeration but the wrapper of constant definitions that can be mixed using bitwise or -(the C operator |).

              - + const char *name; /* name of the method */ + enum AFB_session_v1 session; /* authorisation and session requirements of the method */ + void (*callback)(struct afb_req req); /* callback function implementing the method */ + const char *info; /* textual description of the method */ +};
              +

              For technical reasons, the enumeration enum AFB_session_v1 is not exactly an enumeration but the wrapper of constant definitions that can be mixed using bitwise or (the C operator |).

              The constants that can bit mixed are:

              - - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + +
              Constant name Meaning
              Constant nameMeaning
              AFB_SESSION_CREATE Equals to AFB_SESSION_LOA_EQ_0|AFB_SESSION_RENEW
              AFB_SESSION_CREATEEquals to AFB_SESSION_LOA_EQ_0
              AFB_SESSION_CLOSE Closes the session after the reply and set the LOA to 0
              AFB_SESSION_CLOSECloses the session after the reply and set the LOA to 0
              AFB_SESSION_RENEW Refreshes the token of authentification
              AFB_SESSION_RENEWRefreshes the token of authentification
              AFB_SESSION_CHECK Just requires the token authentification
              AFB_SESSION_CHECKJust requires the token authentification
              AFB_SESSION_LOA_LE_0 Requires the current LOA to be lesser then or equal to 0
              AFB_SESSION_LOA_LE_0Requires the current LOA to be lesser then or equal to 0
              AFB_SESSION_LOA_LE_1 Requires the current LOA to be lesser then or equal to 1
              AFB_SESSION_LOA_LE_1Requires the current LOA to be lesser then or equal to 1
              AFB_SESSION_LOA_LE_2 Requires the current LOA to be lesser then or equal to 2
              AFB_SESSION_LOA_LE_2Requires the current LOA to be lesser then or equal to 2
              AFB_SESSION_LOA_LE_3 Requires the current LOA to be lesser then or equal to 3
              AFB_SESSION_LOA_LE_3Requires the current LOA to be lesser then or equal to 3
              AFB_SESSION_LOA_GE_0 Requires the current LOA to be greater then or equal to 0
              AFB_SESSION_LOA_GE_0Requires the current LOA to be greater then or equal to 0
              AFB_SESSION_LOA_GE_1 Requires the current LOA to be greater then or equal to 1
              AFB_SESSION_LOA_GE_1Requires the current LOA to be greater then or equal to 1
              AFB_SESSION_LOA_GE_2 Requires the current LOA to be greater then or equal to 2
              AFB_SESSION_LOA_GE_2Requires the current LOA to be greater then or equal to 2
              AFB_SESSION_LOA_GE_3 Requires the current LOA to be greater then or equal to 3
              AFB_SESSION_LOA_GE_3Requires the current LOA to be greater then or equal to 3
              AFB_SESSION_LOA_EQ_0 Requires the current LOA to be equal to 0
              AFB_SESSION_LOA_EQ_0Requires the current LOA to be equal to 0
              AFB_SESSION_LOA_EQ_1 Requires the current LOA to be equal to 1
              AFB_SESSION_LOA_EQ_1Requires the current LOA to be equal to 1
              AFB_SESSION_LOA_EQ_2 Requires the current LOA to be equal to 2
              AFB_SESSION_LOA_EQ_2Requires the current LOA to be equal to 2
              AFB_SESSION_LOA_EQ_3 Requires the current LOA to be equal to 3
              AFB_SESSION_LOA_EQ_3Requires the current LOA to be equal to 3
              - - -

              If any of this flag is set, afb-daemon requires an authentication token -as if AFB_SESSION_CHECK flag was also set.

              - +

              If any of this flag is set, afb-daemon requires an authentication token as if AFB_SESSION_CHECK flag was also set.

              The special value AFB_SESSION_NONE is zero and can be used to bypass token check.

              - -

              Note that AFB_SESSION_CREATE and AFB_SESSION_CLOSE might be removed in later versions.

              - - -

              Sending messages to the log system

              - +
              +

              Note that AFB_SESSION_CREATE and AFB_SESSION_CLOSE might be removed in later versions.

              +
              +

              Sending messages to the log system

              Afb-daemon provides 4 levels of verbosity and 5 methods for logging messages.

              - -

              The verbosity is managed. Options allow the change the verbosity of afb-daemon -and the verbosity of the plugins can be set plugin by plugin.

              - -

              The methods for logging messages are defined as macros that test the -verbosity level and that call the real logging function only if the -message must be output. This avoid evaluation of arguments of the -formatting messages if the message must not be output.

              - - -

              Verbs for logging messages

              - +

              The verbosity is managed. Options allow the change the verbosity of afb-daemon and the verbosity of the plugins can be set plugin by plugin.

              +

              The methods for logging messages are defined as macros that test the verbosity level and that call the real logging function only if the message must be output. This avoid evaluation of arguments of the formatting messages if the message must not be output.

              +

              Verbs for logging messages

              The 5 logging methods are:

              - - - - - - + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
              Macro Verbosity Meaning syslog level
              MacroVerbosityMeaningsyslog level
              ERROR 0 Error conditions 3
              WARNING 1 Warning conditions 4
              NOTICE 1 Normal but significant condition 5
              INFO 2 Informational 6
              DEBUG 3 Debug-level messages 7
              ERROR0Error conditions3
              WARNING1Warning conditions4
              NOTICE1Normal but significant condition5
              INFO2Informational6
              DEBUG3Debug-level messages7
              - - -

              You can note that the 2 methods WARNING and INFO have the same level -of verbosity. But they don’t have the same syslog level. It means that -they are output with a different level on the logging system.

              - +

              You can note that the 2 methods WARNING and INFO have the same level of verbosity. But they don't have the same syslog level. It means that they are output with a different level on the logging system.

              All of these methods have the same signature:

              - -
              void ERROR(const struct AFB_interface *afbitf, const char *message, ...);
              -
              - -

              The first argument afbitf is the interface to afb daemon that the -plugin received at initialisation time when pluginAfbV1Register is called.

              - +
              void ERROR(const struct AFB_interface *afbitf, const char *message, ...);
              +

              The first argument afbitf is the interface to afb daemon that the plugin received at initialisation time when pluginAfbV1Register is called.

              The second argument message is a formatting string compatible with printf/sprintf.

              -

              The remaining arguments are arguments of the formating message like with printf.

              - - -

              Managing verbosity

              - -

              Depending on the level of verbosity, the messages are output or not. -The following table explains what messages will be output depending -ont the verbosity level.

              - +

              Managing verbosity

              +

              Depending on the level of verbosity, the messages are output or not. The following table explains what messages will be output depending ont the verbosity level.

              - - - + + + - - - + + + - - - + + + - - - + + + - - - + + +
              Level of verbosity Outputed macro
              Level of verbosityOutputed macro
              0 ERROR
              0ERROR
              1 ERROR + WARNING + NOTICE
              1ERROR + WARNING + NOTICE
              2 ERROR + WARNING + NOTICE + INFO
              2ERROR + WARNING + NOTICE + INFO
              3 ERROR + WARNING + NOTICE + INFO + DEBUG
              3ERROR + WARNING + NOTICE + INFO + DEBUG
              - - - -

              Output format and destination

              - -

              The syslog level is used for forging a prefix to the message. -The prefixes are:

              - +

              Output format and destination

              +

              The syslog level is used for forging a prefix to the message. The prefixes are:

              - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + +
              syslog level prefix
              syslog levelprefix
              0 <0> EMERGENCY
              0<0> EMERGENCY
              1 <1> ALERT
              1<1> ALERT
              2 <2> CRITICAL
              2<2> CRITICAL
              3 <3> ERROR
              3<3> ERROR
              4 <4> WARNING
              4<4> WARNING
              5 <5> NOTICE
              5<5> NOTICE
              6 <6> INFO
              6<6> INFO
              7 <7> DEBUG
              7<7> DEBUG
              - - -

              The message is pushed to standard error. -The final destination of the message depends on how systemd service -was configured through its variable StandardError. It can be -journal, syslog or kmsg. (See man sd-daemon).

              - - -

              Sending events

              - -

              Since version 0.5, plugins can broadcast events to any potential listener. -As today only unattended even are supported. Targeted events are expected for next -coming version.

              - -

              The plugin tic-tac-toe broadcasts events when the board changes. -This is done in the function changed:

              - -
              /*
              - * signals a change of the board
              - */
              -static void changed(struct board *board, const char *reason)
              +

              The message is pushed to standard error. The final destination of the message depends on how systemd service was configured through its variable StandardError. It can be journal, syslog or kmsg. (See man sd-daemon).

              +

              Sending events

              +

              Since version 0.5, plugins can broadcast events to any potential listener. As today only unattended even are supported. Targeted events are expected for next coming version.

              +

              The plugin tic-tac-toe broadcasts events when the board changes. This is done in the function changed:

              +
              /*
              + * signals a change of the board
              + */
              +static void changed(struct board *board, const char *reason)
               {
              -        ...
              -        struct json_object *description;
              +    ...
              +    struct json_object *description;
               
              -        /* get the description */
              -        description = describe(board);
              +    /* get the description */
              +    description = describe(board);
               
              -        ...
              -
              -        afb_daemon_broadcast_event(afbitf->daemon, reason, description);
              -}
              -
              + ... + afb_daemon_broadcast_event(afbitf->daemon, reason, description); +}

              The description of the changed board is pushed via the daemon interface.

              - -

              Within plugin tic-tac-toe, reason indicates the origin of -the change. In function afb_daemon_broadcast_event the second -parameter is the name of broadcasted event. The third argument is the -object that is transmitted with the event.

              - +

              Within plugin tic-tac-toe, reason indicates the origin of the change. In function afb_daemon_broadcast_event the second parameter is the name of broadcasted event. The third argument is the object that is transmitted with the event.

              Function afb_daemon_broadcast_event is defined here after:

              - -
              /*
              - * Broadcasts widely the event of 'name' with the data 'object'.
              - * 'object' can be NULL.
              - * 'daemon' MUST be the daemon given in interface when activating the plugin.
              - *
              - * For conveniency, the function calls 'json_object_put' for 'object'.
              - * Thus, in the case where 'object' should remain available after
              - * the function returns, the function 'json_object_get' shall be used.
              - */
              -void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
              -
              - -

              Be aware, as with reply functions object is automatically released using -json_object_put when using this function. Call json_object_get before -calling afb_daemon_broadcast_event to keep object available -after function returns.

              - -

              Event name received by listeners is prefixed with plugin name. -So when a change occurs after a move, the reason is move and every clients -receive an event tictactoe/move.

              - -

              Note that nothing is said about case sensitivity of event names. -However, the event is always prefixed with the name that the plugin -declared, with the same case, followed with a slash /. -Thus it is safe to compare event using a case sensitive comparison.

              - - -

              Writing an asynchronous method implementation

              - -

              The tic-tac-toe example allows two clients or more to share the same board. -This is implemented by the method join that illustrated partly how to -retrieve arguments.

              - -

              When two or more clients are sharing a same board, one of them can wait -until the state of the board changes, but this could also be implemented using -events because an even is generated each time the board changes.

              - -

              In this case, the reply to the wait is sent only when the board changes. -See the diagram below:

              - +
              /*
              + * Broadcasts widely the event of 'name' with the data 'object'.
              + * 'object' can be NULL.
              + * 'daemon' MUST be the daemon given in interface when activating the plugin.
              + *
              + * For conveniency, the function calls 'json_object_put' for 'object'.
              + * Thus, in the case where 'object' should remain available after
              + * the function returns, the function 'json_object_get' shall be used.
              + */
              +void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
              +
              +

              Be aware, as with reply functions object is automatically released using json_object_put when using this function. Call json_object_get before calling afb_daemon_broadcast_event to keep object available after function returns.

              +
              +

              Event name received by listeners is prefixed with plugin name. So when a change occurs after a move, the reason is move and every clients receive an event tictactoe/move.

              +
              +

              Note that nothing is said about case sensitivity of event names. However, the event is always prefixed with the name that the plugin declared, with the same case, followed with a slash /. Thus it is safe to compare event using a case sensitive comparison.

              +
              +

              Writing an asynchronous method implementation

              +

              The tic-tac-toe example allows two clients or more to share the same board. This is implemented by the method join that illustrated partly how to retrieve arguments.

              +

              When two or more clients are sharing a same board, one of them can wait until the state of the board changes, but this could also be implemented using events because an even is generated each time the board changes.

              +

              In this case, the reply to the wait is sent only when the board changes. See the diagram below:

              CLIENT A       CLIENT B         TIC-TAC-TOE
                  |              |                  |
                  +--------------|----------------->| wait . . . . . . . .
              @@ -1261,227 +811,141 @@ See the diagram below:

              | | | V . | |<-----------------+ success of move . | | | . - |<-------------|------------------+ success of wait < -
              - -

              Here, this is an invocation of the plugin by an other client that -unblock the suspended wait call. -Nevertheless in most case this should be a timer, a hardware event, a sync with -a concurrent process or thread, …

              - + |<-------------|------------------+ success of wait < +

              Here, this is an invocation of the plugin by an other client that unblock the suspended wait call. Nevertheless in most case this should be a timer, a hardware event, a sync with a concurrent process or thread, ...

              Common case of an asynchronous implementation.

              -

              Here is the listing of the function wait:

              - -
              static void wait(struct afb_req req)
              +
              static void wait(struct afb_req req)
               {
              -        struct board *board;
              -        struct waiter *waiter;
              -
              -        /* retrieves the context for the session */
              -        board = board_of_req(req);
              -        INFO(afbitf, "method 'wait' called for boardid %d", board->id);
              -
              -        /* creates the waiter and enqueues it */
              -        waiter = calloc(1, sizeof *waiter);
              -        waiter->req = req;
              -        waiter->next = board->waiters;
              -        afb_req_addref(req);
              -        board->waiters = waiter;
              -}
              -
              - -

              After retrieving the board, the function adds a new waiter to -waiters list and returns without setting a reply.

              - -

              Before returning, it increases req request’s reference count using afb_req_addref function.

              - -

              When a method returns without setting a reply, -it MUST increment request’s reference count -using afb_req_addref. If unpredictable behaviour may pop up.

              - -

              Later, when a board changes, it calls tic-tac-toe changed function -with reason of change in parameter.

              - + struct board *board; + struct waiter *waiter; + + /* retrieves the context for the session */ + board = board_of_req(req); + INFO(afbitf, "method 'wait' called for boardid %d", board->id); + + /* creates the waiter and enqueues it */ + waiter = calloc(1, sizeof *waiter); + waiter->req = req; + waiter->next = board->waiters; + afb_req_addref(req); + board->waiters = waiter; +}
              +

              After retrieving the board, the function adds a new waiter to waiters list and returns without setting a reply.

              +

              Before returning, it increases req request's reference count using afb_req_addref function.

              +
              +

              When a method returns without setting a reply, it MUST increment request's reference count using afb_req_addref. If unpredictable behaviour may pop up.

              +
              +

              Later, when a board changes, it calls tic-tac-toe changed function with reason of change in parameter.

              Here is the full listing of the function changed:

              - -
              /*
              - * signals a change of the board
              - */
              -static void changed(struct board *board, const char *reason)
              +
              /*
              + * signals a change of the board
              + */
              +static void changed(struct board *board, const char *reason)
               {
              -        struct waiter *waiter, *next;
              -        struct json_object *description;
              -
              -        /* get the description */
              -        description = describe(board);
              -
              -        waiter = board->waiters;
              -        board->waiters = NULL;
              -        while (waiter != NULL) {
              -                next = waiter->next;
              -                afb_req_success(waiter->req, json_object_get(description), reason);
              -                afb_req_unref(waiter->req);
              -                free(waiter);
              -                waiter = next;
              -        }
              -
              -        afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description);
              -}
              -
              - -

              The list of waiters is walked and a reply is sent to each waiter. -After sending the reply, the reference count of the request -is decremented using afb_req_unref to allow resources to be freed.

              - -

              The reference count MUST be decremented using afb_req_unref to free -resources and avoid memory leaks. -This usage count decrement should happen AFTER setting reply or -bad things may happen.

              - - -

              How to build a plugin

              - -

              Afb-daemon provides a pkg-config configuration file that can be -queried by providing afb-daemon in command line arguments. -This configuration file provides data that should be used -for plugins compilation. Examples:

              - -
              $ pkg-config --cflags afb-daemon
              -$ pkg-config --libs afb-daemon
              -
              - - -

              Example for cmake meta build system

              - + struct waiter *waiter, *next; + struct json_object *description; + + /* get the description */ + description = describe(board); + + waiter = board->waiters; + board->waiters = NULL; + while (waiter != NULL) { + next = waiter->next; + afb_req_success(waiter->req, json_object_get(description), reason); + afb_req_unref(waiter->req); + free(waiter); + waiter = next; + } + + afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description); +}
              +

              The list of waiters is walked and a reply is sent to each waiter. After sending the reply, the reference count of the request is decremented using afb_req_unref to allow resources to be freed.

              +
              +

              The reference count MUST be decremented using afb_req_unref to free resources and avoid memory leaks. This usage count decrement should happen AFTER setting reply or bad things may happen.

              +
              +

              How to build a plugin

              +

              Afb-daemon provides a pkg-config configuration file that can be queried by providing afb-daemon in command line arguments. This configuration file provides data that should be used for plugins compilation. Examples:

              +
              $ pkg-config --cflags afb-daemon
              +$ pkg-config --libs afb-daemon
              +

              Example for cmake meta build system

              This example is the extract for building the plugin afm-main using CMAKE.

              - -
              pkg_check_modules(afb afb-daemon)
              -if(afb_FOUND)
              -        message(STATUS "Creation afm-main-plugin for AFB-DAEMON")
              -        add_library(afm-main-plugin MODULE afm-main-plugin.c)
              -        target_compile_options(afm-main-plugin PRIVATE ${afb_CFLAGS})
              -        target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
              -        target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
              -        set_target_properties(afm-main-plugin PROPERTIES
              -                PREFIX ""
              -                LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
              -        )
              -        install(TARGETS afm-main-plugin LIBRARY DESTINATION ${plugin_dir})
              -else()
              -        message(STATUS "Not creating the plugin for AFB-DAEMON")
              -endif()
              -
              - +
              pkg_check_modules(afb afb-daemon)
              +if(afb_FOUND)
              +    message(STATUS "Creation afm-main-plugin for AFB-DAEMON")
              +    add_library(afm-main-plugin MODULE afm-main-plugin.c)
              +    target_compile_options(afm-main-plugin PRIVATE ${afb_CFLAGS})
              +    target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
              +    target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
              +    set_target_properties(afm-main-plugin PROPERTIES
              +        PREFIX ""
              +        LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
              +    )
              +    install(TARGETS afm-main-plugin LIBRARY DESTINATION ${plugin_dir})
              +else()
              +    message(STATUS "Not creating the plugin for AFB-DAEMON")
              +endif()

              Let now describe some of these lines.

              - -
              pkg_check_modules(afb afb-daemon)
              -
              - -

              This first lines searches to the pkg-config configuration file for -afb-daemon. Resulting data are stored in the following variables:

              - +
              pkg_check_modules(afb afb-daemon)
              +

              This first lines searches to the pkg-config configuration file for afb-daemon. Resulting data are stored in the following variables:

              - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + +
              Variable Meaning
              VariableMeaning
              afb_FOUND Set to 1 if afb-daemon plugin development files exist
              afb_FOUNDSet to 1 if afb-daemon plugin development files exist
              afb_LIBRARIES Only the libraries (w/o the ‘-l’) for compiling afb-daemon plugins
              afb_LIBRARIESOnly the libraries (w/o the '-l') for compiling afb-daemon plugins
              afb_LIBRARY_DIRS The paths of the libraries (w/o the ‘-L’) for compiling afb-daemon plugins
              afb_LIBRARY_DIRSThe paths of the libraries (w/o the '-L') for compiling afb-daemon plugins
              afb_LDFLAGS All required linker flags for compiling afb-daemon plugins
              afb_LDFLAGSAll required linker flags for compiling afb-daemon plugins
              afb_INCLUDE_DIRS The ‘-I’ preprocessor flags (w/o the ‘-I’) for compiling afb-daemon plugins
              afb_INCLUDE_DIRSThe '-I' preprocessor flags (w/o the '-I') for compiling afb-daemon plugins
              afb_CFLAGS All required cflags for compiling afb-daemon plugins
              afb_CFLAGSAll required cflags for compiling afb-daemon plugins
              - - -

              If development files are found, the plugin can be added to the set of -target to build.

              - -
              add_library(afm-main-plugin MODULE afm-main-plugin.c)
              -
              - -

              This line asks to create a shared library having a single -source file named afm-main-plugin.c to be compiled. -The default name of the created shared object is -libafm-main-plugin.so.

              - -
              set_target_properties(afm-main-plugin PROPERTIES
              -        PREFIX ""
              -        LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
              -)
              -
              - +

              If development files are found, the plugin can be added to the set of target to build.

              +
              add_library(afm-main-plugin MODULE afm-main-plugin.c)
              +

              This line asks to create a shared library having a single source file named afm-main-plugin.c to be compiled. The default name of the created shared object is libafm-main-plugin.so.

              +
              set_target_properties(afm-main-plugin PROPERTIES
              +    PREFIX ""
              +    LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
              +)

              This lines are doing two things:

              - -
                -
              1. It renames the built library from libafm-main-plugin.so to afm-main-plugin.so -by removing the implicitly added prefix lib. This step is not mandatory -because afb-daemon doesn’t check names of files at load time. -The only filename convention used by afb-daemon relates to .so termination. -*.so pattern is used when afb-daemon automatically discovers plugin from a directory hierarchy.

              2. -
              3. It applies a version script at link time to only export the reserved name -pluginAfbV1Register for registration entry point. By default, when building -a shared library linker exports all the public symbols (C functions that are not static).

              4. +
                  +
                1. It renames the built library from libafm-main-plugin.so to afm-main-plugin.so by removing the implicitly added prefix lib. This step is not mandatory because afb-daemon doesn't check names of files at load time. The only filename convention used by afb-daemon relates to .so termination. *.so pattern is used when afb-daemon automatically discovers plugin from a directory hierarchy.

                2. +
                3. It applies a version script at link time to only export the reserved name pluginAfbV1Register for registration entry point. By default, when building a shared library linker exports all the public symbols (C functions that are not static).

                - -

                Next line are:

                - -
                target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
                -target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
                -
                - -

                As you can see it uses the variables computed by pkg_check_modules(afb afb-daemon) -to configure the compiler and the linker.

                - - -

                Exporting the function pluginAfbV1Register

                - -

                The function pluginAfbV1Register MUST be exported. This can be achieved -using a version script at link time. Here after is a version script used for -tic-tac-toe (plugins/samples/export.map).

                - -
                { global: pluginAfbV1Register; local: *; };
                -
                - -

                This sample version script -exports as global the symbol pluginAfbV1Register and hides any -other symbols.

                - -

                This version script is added to the link options using the -option –version-script=export.map is given directly to the -linker or using the option -Wl,–version-script=export.map -when the option is given to the C compiler.

                - - -

                Building within yocto

                - +
                target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
                +target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
                +

                As you can see it uses the variables computed by pkg_check_modules(afb afb-daemon) to configure the compiler and the linker.

                +

                Exporting the function pluginAfbV1Register

                +

                The function pluginAfbV1Register MUST be exported. This can be achieved using a version script at link time. Here after is a version script used for tic-tac-toe (plugins/samples/export.map).

                +
                { global: pluginAfbV1Register; local: *; };
                +

                This sample version script exports as global the symbol pluginAfbV1Register and hides any other symbols.

                +

                This version script is added to the link options using the option --version-script=export.map is given directly to the linker or using the option -Wl,--version-script=export.map when the option is given to the C compiler.

                +

                Building within yocto

                Adding a dependency to afb-daemon is enough. See below:

                - -
                DEPENDS += " afb-daemon "
                -
                +
                DEPENDS += " afb-daemon "
                diff --git a/doc/afb-plugin-writing.md b/doc/afb-plugin-writing.md index f5966092..bc43e4e4 100644 --- a/doc/afb-plugin-writing.md +++ b/doc/afb-plugin-writing.md @@ -189,11 +189,13 @@ Header files to include Plugin *tictactoe* has following includes: - #define _GNU_SOURCE - #include - #include - #include - #include +```C +#define _GNU_SOURCE +#include +#include +#include +#include +``` Header *afb/afb-plugin.h* is the only hard dependency, it includes all features that a plugin MUST HAVE. Outside of includes used to support application logic, @@ -280,24 +282,26 @@ Writing a synchronous method implementation The method **tictactoe/board** is a synchronous implementation. Here is its listing: - /* - * get the board - */ - static void board(struct afb_req req) - { - struct board *board; - struct json_object *description; +```C +/* + * get the board + */ +static void board(struct afb_req req) +{ + struct board *board; + struct json_object *description; - /* retrieves the context for the session */ - board = board_of_req(req); - INFO(afbitf, "method 'board' called for boardid %d", board->id); + /* retrieves the context for the session */ + board = board_of_req(req); + INFO(afbitf, "method 'board' called for boardid %d", board->id); - /* describe the board */ - description = describe(board); + /* describe the board */ + description = describe(board); - /* send the board's description */ - afb_req_success(req, description, NULL); - } + /* send the board's description */ + afb_req_success(req, description, NULL); +} +``` This example shows many aspects of a synchronous method implementation. Let summarise it: @@ -324,13 +328,15 @@ For any implementation, the request is received by a structure of type The definition of **struct afb_req** is: - /* - * Describes the request by plugins from afb-daemon - */ - struct afb_req { - const struct afb_req_itf *itf; /* the interfacing functions */ - void *closure; /* the closure for functions */ - }; +```C +/* + * Describes the request by plugins from afb-daemon + */ +struct afb_req { + const struct afb_req_itf *itf; /* the interfacing functions */ + void *closure; /* the closure for functions */ +}; +``` It contains two pointers: first one *itf*, points to functions used to handle internal request. Second one *closure* point onto function closure. @@ -380,13 +386,15 @@ These functions are: The plugin *tictactoe* use a convenient function to retrieve its context: the board. This function is *board_of_req*: - /* - * retrieves the board of the request - */ - static inline struct board *board_of_req(struct afb_req req) - { - return afb_req_context(req, (void*)get_new_board, (void*)release_board); - } +```C +/* + * retrieves the board of the request + */ +static inline struct board *board_of_req(struct afb_req req) +{ + return afb_req_context(req, (void*)get_new_board, (void*)release_board); +} +``` The function **afb_req_context** ensures an existing context for the session of the request. @@ -395,22 +403,24 @@ Note function type casts to avoid compilation warnings. Here is the definition of the function **afb_req_context** - /* - * Gets the pointer stored by the plugin for the session of 'req'. - * If the stored pointer is NULL, indicating that no pointer was - * already stored, afb_req_context creates a new context by calling - * the function 'create_context' and stores it with the freeing function - * 'free_context'. - */ - static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*)) - { - void *result = afb_req_context_get(req); - if (result == NULL) { - result = create_context(); - afb_req_context_set(req, result, free_context); - } - return result; +```C +/* + * Gets the pointer stored by the plugin for the session of 'req'. + * If the stored pointer is NULL, indicating that no pointer was + * already stored, afb_req_context creates a new context by calling + * the function 'create_context' and stores it with the freeing function + * 'free_context'. + */ +static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*)) +{ + void *result = afb_req_context_get(req); + if (result == NULL) { + result = create_context(); + afb_req_context_set(req, result, free_context); } + return result; +} +``` The second argument if the function that creates the context. For plugin *tic-tac-toe* (function **get_new_board**). @@ -424,29 +434,31 @@ When usage count falls to zero, data board are freed. Definition of other functions dealing with contexts: - /* - * Gets the pointer stored by the plugin for the session of 'req'. - * When the plugin has not yet recorded a pointer, NULL is returned. - */ - void *afb_req_context_get(struct afb_req req); - - /* - * Stores for the plugin the pointer 'context' to the session of 'req'. - * The function 'free_context' will be called when the session is closed - * or if plugin stores an other pointer. - */ - void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*)); - - /* - * Frees the pointer stored by the plugin for the session of 'req' - * and sets it to NULL. - * - * Shortcut for: afb_req_context_set(req, NULL, NULL) - */ - static inline void afb_req_context_clear(struct afb_req req) - { - afb_req_context_set(req, NULL, NULL); - } +```C +/* + * Gets the pointer stored by the plugin for the session of 'req'. + * When the plugin has not yet recorded a pointer, NULL is returned. + */ +void *afb_req_context_get(struct afb_req req); + +/* + * Stores for the plugin the pointer 'context' to the session of 'req'. + * The function 'free_context' will be called when the session is closed + * or if plugin stores an other pointer. + */ +void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*)); + +/* + * Frees the pointer stored by the plugin for the session of 'req' + * and sets it to NULL. + * + * Shortcut for: afb_req_context_set(req, NULL, NULL) + */ +static inline void afb_req_context_clear(struct afb_req req) +{ + afb_req_context_set(req, NULL, NULL); +} +``` ### Sending reply to a request @@ -456,54 +468,58 @@ Two kinds of replies: successful or failure. It exists two functions for "success" replies: **afb_req_success** and **afb_req_success_f**. - /* - * Sends a reply of kind success to the request 'req'. - * The status of the reply is automatically set to "success". - * Its send the object 'obj' (can be NULL) with an - * informationnal comment 'info (can also be NULL). - * - * For conveniency, the function calls 'json_object_put' for 'obj'. - * Thus, in the case where 'obj' should remain available after - * the function returns, the function 'json_object_get' shall be used. - */ - void afb_req_success(struct afb_req req, struct json_object *obj, const char *info); - - /* - * Same as 'afb_req_success' but the 'info' is a formatting - * string followed by arguments. - * - * For conveniency, the function calls 'json_object_put' for 'obj'. - * Thus, in the case where 'obj' should remain available after - * the function returns, the function 'json_object_get' shall be used. - */ - void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...); +```C +/* + * Sends a reply of kind success to the request 'req'. + * The status of the reply is automatically set to "success". + * Its send the object 'obj' (can be NULL) with an + * informationnal comment 'info (can also be NULL). + * + * For conveniency, the function calls 'json_object_put' for 'obj'. + * Thus, in the case where 'obj' should remain available after + * the function returns, the function 'json_object_get' shall be used. + */ +void afb_req_success(struct afb_req req, struct json_object *obj, const char *info); + +/* + * Same as 'afb_req_success' but the 'info' is a formatting + * string followed by arguments. + * + * For conveniency, the function calls 'json_object_put' for 'obj'. + * Thus, in the case where 'obj' should remain available after + * the function returns, the function 'json_object_get' shall be used. + */ +void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...); +``` It exists two functions for "failure" replies: **afb_req_fail** and **afb_req_fail_f**. - /* - * Sends a reply of kind failure to the request 'req'. - * The status of the reply is set to 'status' and an - * informational comment 'info' (can also be NULL) can be added. - * - * Note that calling afb_req_fail("success", info) is equivalent - * to call afb_req_success(NULL, info). Thus even if possible it - * is strongly recommended to NEVER use "success" for status. - * - * For conveniency, the function calls 'json_object_put' for 'obj'. - * Thus, in the case where 'obj' should remain available after - * the function returns, the function 'json_object_get' shall be used. - */ - void afb_req_fail(struct afb_req req, const char *status, const char *info); - - /* - * Same as 'afb_req_fail' but the 'info' is a formatting - * string followed by arguments. - * - * For conveniency, the function calls 'json_object_put' for 'obj'. - * Thus, in the case where 'obj' should remain available after - * the function returns, the function 'json_object_get' shall be used. - */ - void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...); +```C +/* + * Sends a reply of kind failure to the request 'req'. + * The status of the reply is set to 'status' and an + * informational comment 'info' (can also be NULL) can be added. + * + * Note that calling afb_req_fail("success", info) is equivalent + * to call afb_req_success(NULL, info). Thus even if possible it + * is strongly recommended to NEVER use "success" for status. + * + * For conveniency, the function calls 'json_object_put' for 'obj'. + * Thus, in the case where 'obj' should remain available after + * the function returns, the function 'json_object_get' shall be used. + */ +void afb_req_fail(struct afb_req req, const char *status, const char *info); + +/* + * Same as 'afb_req_fail' but the 'info' is a formatting + * string followed by arguments. + * + * For conveniency, the function calls 'json_object_put' for 'obj'. + * Thus, in the case where 'obj' should remain available after + * the function returns, the function 'json_object_get' shall be used. + */ +void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...); +``` > For conveniency, these functions automatically call **json_object_put** to release **obj**. > Because **obj** usage count is null after being passed to a reply function, it SHOULD not be used anymore. @@ -522,23 +538,25 @@ or WebSockets. For example, the method **join** of plugin **tic-tac-toe** expects one argument: the *boardid* to join. Here is an extract: - /* - * Join a board - */ - static void join(struct afb_req req) - { - struct board *board, *new_board; - const char *id; - - /* retrieves the context for the session */ - board = board_of_req(req); - INFO(afbitf, "method 'join' called for boardid %d", board->id); - - /* retrieves the argument */ - id = afb_req_value(req, "boardid"); - if (id == NULL) - goto bad_request; - ... +```C +/* + * Join a board + */ +static void join(struct afb_req req) +{ + struct board *board, *new_board; + const char *id; + + /* retrieves the context for the session */ + board = board_of_req(req); + INFO(afbitf, "method 'join' called for boardid %d", board->id); + + /* retrieves the argument */ + id = afb_req_value(req, "boardid"); + if (id == NULL) + goto bad_request; + ... +``` The function **afb_req_value** searches in the request *req* for argument name passed in the second argument. When argument name @@ -551,34 +569,38 @@ is not passed, **afb_req_value** returns NULL. The function **afb_req_value** is defined here after: - /* - * Gets from the request 'req' the string value of the argument of 'name'. - * Returns NULL if when there is no argument of 'name'. - * Returns the value of the argument of 'name' otherwise. - * - * Shortcut for: afb_req_get(req, name).value - */ - static inline const char *afb_req_value(struct afb_req req, const char *name) - { - return afb_req_get(req, name).value; - } +```C +/* + * Gets from the request 'req' the string value of the argument of 'name'. + * Returns NULL if when there is no argument of 'name'. + * Returns the value of the argument of 'name' otherwise. + * + * Shortcut for: afb_req_get(req, name).value + */ +static inline const char *afb_req_value(struct afb_req req, const char *name) +{ + return afb_req_get(req, name).value; +} +``` It is defined as a shortcut to call the function **afb_req_get**. That function is defined here after: - /* - * Gets from the request 'req' the argument of 'name'. - * Returns a PLAIN structure of type 'struct afb_arg'. - * When the argument of 'name' is not found, all fields of result are set to NULL. - * When the argument of 'name' is found, the fields are filled, - * in particular, the field 'result.name' is set to 'name'. - * - * There is a special name value: the empty string. - * The argument of name "" is defined only if the request was made using - * an HTTP POST of Content-Type "application/json". In that case, the - * argument of name "" receives the value of the body of the HTTP request. - */ - struct afb_arg afb_req_get(struct afb_req req, const char *name); +```C +/* + * Gets from the request 'req' the argument of 'name'. + * Returns a PLAIN structure of type 'struct afb_arg'. + * When the argument of 'name' is not found, all fields of result are set to NULL. + * When the argument of 'name' is found, the fields are filled, + * in particular, the field 'result.name' is set to 'name'. + * + * There is a special name value: the empty string. + * The argument of name "" is defined only if the request was made using + * an HTTP POST of Content-Type "application/json". In that case, the + * argument of name "" receives the value of the body of the HTTP request. + */ +struct afb_arg afb_req_get(struct afb_req req, const char *name); +``` That function takes 2 parameters: the request and the name of the argument to retrieve. It returns a PLAIN structure of @@ -592,32 +614,36 @@ of the post and is supposed to be a JSON string. The definition of **struct afb_arg** is: - /* - * Describes an argument (or parameter) of a request - */ - struct afb_arg { - const char *name; /* name of the argument or NULL if invalid */ - const char *value; /* string representation of the value of the argument */ - /* original filename of the argument if path != NULL */ - const char *path; /* if not NULL, path of the received file for the argument */ - /* when the request is finalized this file is removed */ - }; +```C +/* + * Describes an argument (or parameter) of a request + */ +struct afb_arg { + const char *name; /* name of the argument or NULL if invalid */ + const char *value; /* string representation of the value of the argument */ + /* original filename of the argument if path != NULL */ + const char *path; /* if not NULL, path of the received file for the argument */ + /* when the request is finalized this file is removed */ +}; +``` The structure returns the data arguments that are known for the request. This data include a field named **path**. This **path** can be accessed using the function **afb_req_path** defined here after: - /* - * Gets from the request 'req' the path for file attached to the argument of 'name'. - * Returns NULL if when there is no argument of 'name' or when there is no file. - * Returns the path of the argument of 'name' otherwise. - * - * Shortcut for: afb_req_get(req, name).path - */ - static inline const char *afb_req_path(struct afb_req req, const char *name) - { - return afb_req_get(req, name).path; - } +```C +/* + * Gets from the request 'req' the path for file attached to the argument of 'name'. + * Returns NULL if when there is no argument of 'name' or when there is no file. + * Returns the path of the argument of 'name' otherwise. + * + * Shortcut for: afb_req_get(req, name).path + */ +static inline const char *afb_req_path(struct afb_req req, const char *name) +{ + return afb_req_get(req, name).path; +} +``` The path is only defined for HTTP/POST requests that send file. @@ -631,13 +657,15 @@ will send an HTTP/POST request to the method **post/upload-image** with 2 arguments named *file* and *hidden*. -

                Sample Post File

                -
                - - -
                - -
                +```html +

                Sample Post File

                +
                + + +
                + +
                +``` Argument named **file** should have both its value and path defined. @@ -658,11 +686,13 @@ path is destroyed. Plugins may also request every arguments of a given call as one single object. This feature is provided by the function **afb_req_json** defined here after: - /* - * Gets from the request 'req' the json object hashing the arguments. - * The returned object must not be released using 'json_object_put'. - */ - struct json_object *afb_req_json(struct afb_req req); +```C +/* + * Gets from the request 'req' the json object hashing the arguments. + * The returned object must not be released using 'json_object_put'. + */ +struct json_object *afb_req_json(struct afb_req req); +``` It returns a json object. This object depends on how the request was built: @@ -707,14 +737,16 @@ afb-daemon initialisation is finished. Here after the code used for **pluginAfbV1Register** from plugin *tic-tac-toe*: - /* - * activation function for registering the plugin called by afb-daemon - */ - const struct AFB_plugin *pluginAfbV1Register(const struct AFB_interface *itf) - { - afbitf = itf; // records the interface for accessing afb-daemon - return &plugin_description; // returns the description of the plugin - } +```C +/* + * activation function for registering the plugin called by afb-daemon + */ +const struct AFB_plugin *pluginAfbV1Register(const struct AFB_interface *itf) +{ + afbitf = itf; // records the interface for accessing afb-daemon + return &plugin_description; // returns the description of the plugin +} +``` It is a very minimal initialisation function because *tic-tac-toe* plugin doesn't have any application related initialisation step. It merely record daemon's interface @@ -724,42 +756,46 @@ The variable **afbitf** is a plugin global variable. It keeps the interface to afb-daemon that should be used for logging and pushing events. Here is its declaration: - /* - * the interface to afb-daemon - */ - const struct AFB_interface *afbitf; +```C +/* + * the interface to afb-daemon + */ +const struct AFB_interface *afbitf; +``` The description of the plugin is defined here after. - /* - * array of the methods exported to afb-daemon - */ - static const struct AFB_method_desc_v1 plugin_methods[] = { - /* VERB'S NAME SESSION MANAGEMENT FUNCTION TO CALL SHORT DESCRIPTION */ - { .name= "new", .session= AFB_SESSION_NONE, .callback= new, .info= "Starts a new game" }, - { .name= "play", .session= AFB_SESSION_NONE, .callback= play, .info= "Asks the server to play" }, - { .name= "move", .session= AFB_SESSION_NONE, .callback= move, .info= "Tells the client move" }, - { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" }, - { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" }, - { .name= "join", .session= AFB_SESSION_CHECK,.callback= join, .info= "Join a board" }, - { .name= "undo", .session= AFB_SESSION_NONE, .callback= undo, .info= "Undo the last move" }, - { .name= "wait", .session= AFB_SESSION_NONE, .callback= wait, .info= "Wait for a change" }, - { .name= NULL } /* marker for end of the array */ - }; - - /* - * description of the plugin for afb-daemon - */ - static const struct AFB_plugin plugin_description = - { - /* description conforms to VERSION 1 */ - .type= AFB_PLUGIN_VERSION_1, - .v1= { /* fills the v1 field of the union when AFB_PLUGIN_VERSION_1 */ - .prefix= "tictactoe", /* the API name (or plugin name or prefix) */ - .info= "Sample tac-tac-toe game", /* short description of of the plugin */ - .methods = plugin_methods /* the array describing the methods of the API */ - } - }; +```C +/* + * array of the methods exported to afb-daemon + */ +static const struct AFB_method_desc_v1 plugin_methods[] = { + /* VERB'S NAME SESSION MANAGEMENT FUNCTION TO CALL SHORT DESCRIPTION */ + { .name= "new", .session= AFB_SESSION_NONE, .callback= new, .info= "Starts a new game" }, + { .name= "play", .session= AFB_SESSION_NONE, .callback= play, .info= "Asks the server to play" }, + { .name= "move", .session= AFB_SESSION_NONE, .callback= move, .info= "Tells the client move" }, + { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" }, + { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" }, + { .name= "join", .session= AFB_SESSION_CHECK,.callback= join, .info= "Join a board" }, + { .name= "undo", .session= AFB_SESSION_NONE, .callback= undo, .info= "Undo the last move" }, + { .name= "wait", .session= AFB_SESSION_NONE, .callback= wait, .info= "Wait for a change" }, + { .name= NULL } /* marker for end of the array */ +}; + +/* + * description of the plugin for afb-daemon + */ +static const struct AFB_plugin plugin_description = +{ + /* description conforms to VERSION 1 */ + .type= AFB_PLUGIN_VERSION_1, + .v1= { /* fills the v1 field of the union when AFB_PLUGIN_VERSION_1 */ + .prefix= "tictactoe", /* the API name (or plugin name or prefix) */ + .info= "Sample tac-tac-toe game", /* short description of of the plugin */ + .methods = plugin_methods /* the array describing the methods of the API */ + } +}; +``` The structure **plugin_description** describes the plugin. It declares the type and version of the plugin, its name, a short description @@ -779,17 +815,19 @@ In version one of afb-damon plugin, a method description contains 4 fields: The structure describing methods is defined as follows: - /* - * Description of one method of the API provided by the plugin - * This enumeration is valid for plugins of type 1 - */ - struct AFB_method_desc_v1 - { - const char *name; /* name of the method */ - enum AFB_session_v1 session; /* authorisation and session requirements of the method */ - void (*callback)(struct afb_req req); /* callback function implementing the method */ - const char *info; /* textual description of the method */ - }; +```C +/* + * Description of one method of the API provided by the plugin + * This enumeration is valid for plugins of type 1 + */ +struct AFB_method_desc_v1 +{ + const char *name; /* name of the method */ + enum AFB_session_v1 session; /* authorisation and session requirements of the method */ + void (*callback)(struct afb_req req); /* callback function implementing the method */ + const char *info; /* textual description of the method */ +}; +``` For technical reasons, the enumeration **enum AFB_session_v1** is not exactly an enumeration but the wrapper of constant definitions that can be mixed using bitwise or @@ -854,7 +892,9 @@ they are output with a different level on the logging system. All of these methods have the same signature: - void ERROR(const struct AFB_interface *afbitf, const char *message, ...); +```C +void ERROR(const struct AFB_interface *afbitf, const char *message, ...); +``` The first argument **afbitf** is the interface to afb daemon that the plugin received at initialisation time when **pluginAfbV1Register** is called. @@ -871,10 +911,10 @@ ont the verbosity level. Level of verbosity | Outputed macro :-----------------:|-------------------------- - 0 | ERROR - 1 | ERROR + WARNING + NOTICE - 2 | ERROR + WARNING + NOTICE + INFO - 3 | ERROR + WARNING + NOTICE + INFO + DEBUG +0 | ERROR +1 | ERROR + WARNING + NOTICE +2 | ERROR + WARNING + NOTICE + INFO +3 | ERROR + WARNING + NOTICE + INFO + DEBUG ### Output format and destination @@ -883,14 +923,14 @@ The prefixes are: syslog level | prefix :-----------:|--------------- - 0 | <0> EMERGENCY - 1 | <1> ALERT - 2 | <2> CRITICAL - 3 | <3> ERROR - 4 | <4> WARNING - 5 | <5> NOTICE - 6 | <6> INFO - 7 | <7> DEBUG +0 | <0> EMERGENCY +1 | <1> ALERT +2 | <2> CRITICAL +3 | <3> ERROR +4 | <4> WARNING +5 | <5> NOTICE +6 | <6> INFO +7 | <7> DEBUG The message is pushed to standard error. @@ -908,21 +948,23 @@ coming version. The plugin *tic-tac-toe* broadcasts events when the board changes. This is done in the function **changed**: - /* - * signals a change of the board - */ - static void changed(struct board *board, const char *reason) - { - ... - struct json_object *description; +```C +/* + * signals a change of the board + */ +static void changed(struct board *board, const char *reason) +{ + ... + struct json_object *description; - /* get the description */ - description = describe(board); + /* get the description */ + description = describe(board); - ... + ... - afb_daemon_broadcast_event(afbitf->daemon, reason, description); - } + afb_daemon_broadcast_event(afbitf->daemon, reason, description); +} +``` The description of the changed board is pushed via the daemon interface. @@ -933,16 +975,18 @@ object that is transmitted with the event. Function **afb_daemon_broadcast_event** is defined here after: - /* - * Broadcasts widely the event of 'name' with the data 'object'. - * 'object' can be NULL. - * 'daemon' MUST be the daemon given in interface when activating the plugin. - * - * For conveniency, the function calls 'json_object_put' for 'object'. - * Thus, in the case where 'object' should remain available after - * the function returns, the function 'json_object_get' shall be used. - */ - void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object); +```C +/* + * Broadcasts widely the event of 'name' with the data 'object'. + * 'object' can be NULL. + * 'daemon' MUST be the daemon given in interface when activating the plugin. + * + * For conveniency, the function calls 'json_object_put' for 'object'. + * Thus, in the case where 'object' should remain available after + * the function returns, the function 'json_object_get' shall be used. + */ +void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object); +``` > Be aware, as with reply functions **object** is automatically released using > **json_object_put** when using this function. Call **json_object_get** before @@ -996,22 +1040,24 @@ Common case of an asynchronous implementation. Here is the listing of the function **wait**: - static void wait(struct afb_req req) - { - struct board *board; - struct waiter *waiter; - - /* retrieves the context for the session */ - board = board_of_req(req); - INFO(afbitf, "method 'wait' called for boardid %d", board->id); - - /* creates the waiter and enqueues it */ - waiter = calloc(1, sizeof *waiter); - waiter->req = req; - waiter->next = board->waiters; - afb_req_addref(req); - board->waiters = waiter; - } +```C +static void wait(struct afb_req req) +{ + struct board *board; + struct waiter *waiter; + + /* retrieves the context for the session */ + board = board_of_req(req); + INFO(afbitf, "method 'wait' called for boardid %d", board->id); + + /* creates the waiter and enqueues it */ + waiter = calloc(1, sizeof *waiter); + waiter->req = req; + waiter->next = board->waiters; + afb_req_addref(req); + board->waiters = waiter; +} +``` After retrieving the board, the function adds a new waiter to waiters list and returns without setting a reply. @@ -1027,30 +1073,32 @@ with reason of change in parameter. Here is the full listing of the function **changed**: - /* - * signals a change of the board - */ - static void changed(struct board *board, const char *reason) - { - struct waiter *waiter, *next; - struct json_object *description; - - /* get the description */ - description = describe(board); - - waiter = board->waiters; - board->waiters = NULL; - while (waiter != NULL) { - next = waiter->next; - afb_req_success(waiter->req, json_object_get(description), reason); - afb_req_unref(waiter->req); - free(waiter); - waiter = next; - } - - afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description); +```C +/* + * signals a change of the board + */ +static void changed(struct board *board, const char *reason) +{ + struct waiter *waiter, *next; + struct json_object *description; + + /* get the description */ + description = describe(board); + + waiter = board->waiters; + board->waiters = NULL; + while (waiter != NULL) { + next = waiter->next; + afb_req_success(waiter->req, json_object_get(description), reason); + afb_req_unref(waiter->req); + free(waiter); + waiter = next; } + afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description); +} +``` + The list of waiters is walked and a reply is sent to each waiter. After sending the reply, the reference count of the request is decremented using **afb_req_unref** to allow resources to be freed. @@ -1068,32 +1116,38 @@ queried by providing **afb-daemon** in command line arguments. This configuration file provides data that should be used for plugins compilation. Examples: - $ pkg-config --cflags afb-daemon - $ pkg-config --libs afb-daemon +```bash +$ pkg-config --cflags afb-daemon +$ pkg-config --libs afb-daemon +``` ### Example for cmake meta build system This example is the extract for building the plugin *afm-main* using *CMAKE*. - pkg_check_modules(afb afb-daemon) - if(afb_FOUND) - message(STATUS "Creation afm-main-plugin for AFB-DAEMON") - add_library(afm-main-plugin MODULE afm-main-plugin.c) - target_compile_options(afm-main-plugin PRIVATE ${afb_CFLAGS}) - target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS}) - target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES}) - set_target_properties(afm-main-plugin PROPERTIES - PREFIX "" - LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map" - ) - install(TARGETS afm-main-plugin LIBRARY DESTINATION ${plugin_dir}) - else() - message(STATUS "Not creating the plugin for AFB-DAEMON") - endif() +```cmake +pkg_check_modules(afb afb-daemon) +if(afb_FOUND) + message(STATUS "Creation afm-main-plugin for AFB-DAEMON") + add_library(afm-main-plugin MODULE afm-main-plugin.c) + target_compile_options(afm-main-plugin PRIVATE ${afb_CFLAGS}) + target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS}) + target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES}) + set_target_properties(afm-main-plugin PROPERTIES + PREFIX "" + LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map" + ) + install(TARGETS afm-main-plugin LIBRARY DESTINATION ${plugin_dir}) +else() + message(STATUS "Not creating the plugin for AFB-DAEMON") +endif() +``` Let now describe some of these lines. - pkg_check_modules(afb afb-daemon) +```cmake +pkg_check_modules(afb afb-daemon) +``` This first lines searches to the *pkg-config* configuration file for **afb-daemon**. Resulting data are stored in the following variables: @@ -1110,17 +1164,21 @@ afb_CFLAGS | All required cflags for compiling afb-daemon plugins If development files are found, the plugin can be added to the set of target to build. - add_library(afm-main-plugin MODULE afm-main-plugin.c) +```cmake +add_library(afm-main-plugin MODULE afm-main-plugin.c) +``` This line asks to create a shared library having a single source file named afm-main-plugin.c to be compiled. The default name of the created shared object is **libafm-main-plugin.so**. - set_target_properties(afm-main-plugin PROPERTIES - PREFIX "" - LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map" - ) +```cmake +set_target_properties(afm-main-plugin PROPERTIES + PREFIX "" + LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map" +) +``` This lines are doing two things: @@ -1136,8 +1194,10 @@ a shared library linker exports all the public symbols (C functions that are not Next line are: - target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS}) - target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES}) +```cmake +target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS}) +target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES}) +``` As you can see it uses the variables computed by ***pkg_check_modules(afb afb-daemon)*** to configure the compiler and the linker. diff --git a/doc/afb-plugins-overview.html b/doc/afb-plugins-overview.html index 4fdb72f4..6c1506ad 100644 --- a/doc/afb-plugins-overview.html +++ b/doc/afb-plugins-overview.html @@ -1,22 +1,38 @@ + - - + + + + + + + - -

                Overview of plugins shipped with AFB-Daemon

                - + +

                Overview of plugins shipped with AFB-Daemon

                Version: 1
                 Date:    09 juin 2016
                -Author:  Manuel Bachmann
                -
                - - -

                List of plugins

                - +Author: Manuel Bachmann +

                List of plugins

                Here are the plugins shipped in the source tree:

                -
                • Hello World
                • Authentication
                • @@ -25,22 +41,12 @@ Author: Manuel Bachmann
                • Radio (1 backend: RTLSDR RTL2832U)
                • Media (1 backend: Rygel UPnP)
                - -

                All plugins may not be built, depending on the development libraries present on the system at build time.

                - - -

                Detail of plugins

                - - -

                Hello World

                - +

                Detail of plugins

                +

                Hello World

                A sample Hello World plugin for demonstration and learning purposes.

                - -

                This plugin provides a few unauthenticated requests, all beginning with “ping”, to demonstrate basic binder capabilities.

                - +

                This plugin provides a few unauthenticated requests, all beginning with "ping", to demonstrate basic binder capabilities.

                Verbs:

                -
                • ping: returns a success response
                • pingfail: returns a failure response
                • @@ -49,21 +55,12 @@ Author: Manuel Bachmann
                • pingJson: returns a success response, with a complex JSON response field
                • pingevent: broadcasts a global event
                - -


                - - -

                Authentication

                - +

                Authentication

                An sample Authentication plugin for demonstration purposes.

                - -

                This plugin provides a few requests to demonstrate the binder’s token-based security mechanism.

                - -

                Calling “connect” with a security token will initiate a session, calling “refresh” will issue a new token and invalidate the previous one, calling “logout” will invalidate all tokens and close the session.

                - +

                This plugin provides a few requests to demonstrate the binder's token-based security mechanism.

                +

                Calling "connect" with a security token will initiate a session, calling "refresh" will issue a new token and invalidate the previous one, calling "logout" will invalidate all tokens and close the session.

                Verbs:

                -
                • ping: returns a success response
                • connect: creates a session and returns a new token
                • @@ -71,19 +68,11 @@ Author: Manuel Bachmann
                • check: verifies the passed token is valid
                • logout: closes the session
                - -


                - - -

                Tic Tac Toe

                - +

                Tic Tac Toe

                A sample Tic Tac Toe game plugin.

                -

                This plugin provides an interactive Tic Tac Toe game where the binder returns the grid as a JSON response.

                -

                Verbs:

                -
                • new: starts a new game
                • play: asks the server to play
                • @@ -94,57 +83,34 @@ Author: Manuel Bachmann
                • undo: undo the last move
                • wait: wait for a move
                - -


                - - -

                Audio

                - +

                Audio

                A sample Audio plugin with 2 backends:

                -
                • ALSA (mandatory)
                • PulseAudio (optional)
                - - -

                This plugin is able to initialize a specific soundcard, define volume levels, channels (mono/stereo…), mute sound, and play a 22,050 Hz PCM stream.

                - +

                This plugin is able to initialize a specific soundcard, define volume levels, channels (mono/stereo...), mute sound, and play a 22,050 Hz PCM stream.

                Verbs:

                -
                • ping: returns a success response
                • -
                • init: initializes backend, on the “default” sound card
                • +
                • init: initializes backend, on the "default" sound card
                • volume: gets or sets volume, in % (0-100)
                • channels: gets or sets channels count (1-8)
                • mute: gets or sets the mute status (on-off)
                • play: gets or sets the playing status (on-off)
                - -

                (if PulseAudio development libraries are not found at build time, only ALSA will be available)

                -

                (if a PulseAudio server is not found at runtime, the plugin will dynamically fall back to ALSA)

                -

                (a specifc backend can be forced by using this syntax before running afb-daemon : $ export AFB_AUDIO_OUTPUT=Alsa)

                -


                - - -

                Radio

                - +

                Radio

                A sample AM/FM Radio plugin with 1 backend:

                -
                • RTLSDR - Realtek RTL2832U dongles (mandatory)
                - -

                This plugin is able to initialize specific RTL2832U dongles, switch between AM/FM modes, define frequency, mute sound, and play sound (if combining with the audio plugin).

                -

                Verbs:

                -
                • ping: returns a success response
                • init: initializes backend, looking for plugged-in devices
                • @@ -154,54 +120,32 @@ Author: Manuel Bachmann
                • mute: sets device mute status (on-off)
                • play: sets device playing status (on-off)
                - -

                (if rtlsdr development libraries are not found at build time, this plugin will not be built)

                -


                - - -

                Media

                - +

                Media

                A sample Media Server plugin with 1 backend:

                -
                • Rygel
                - -

                This plugin is able to detect a local Rygel UPnP media server, list audio files, select an audio file for playback, play/pause/seek in this file, upload an audio file to the server.

                -

                Verbs:

                -
                • ping: returns a success response
                • init: initializes backend, looking for an active local UPnP server
                • list: returns list of audio files, as a JSON structure
                • -
                • select: select an audio files, by index number (001-…)
                • +
                • select: select an audio files, by index number (001-...)
                • play: plays the currently selected audio file
                • stop: stops the currently selected audio file
                • pause: pauses the currently selected audio file
                • seek: seeks in the currently selected audio file, in seconds
                • upload: uploads an audio file, with a POST request
                - -

                (if GUPnP/GSSDP development libraries are not fund at build time, this plugin will not be built)

                -


                -
                -


                -

                Sample command-line applications: afb-client-demo (built by default)

                - -

                Sample HTML5 applications: -test/*.html, -afb-client, -afb-radio

                - +

                Sample HTML5 applications: **test/*.html, afb-client, afb-radio**

                Sample Qt/QML applications: test/token-websock.qml

                diff --git a/doc/afb-tests-overview.html b/doc/afb-tests-overview.html index ce1cba44..f663a75f 100644 --- a/doc/afb-tests-overview.html +++ b/doc/afb-tests-overview.html @@ -1,106 +1,77 @@ + - - + + + + + Overview of tests shipped with AFB-Daemon + + + - -

                Overview of tests shipped with AFB-Daemon

                - +
                +

                Overview of tests shipped with AFB-Daemon

                +

                Manuel Bachmann

                +

                30 mai 2016

                +
                + +

                Overview of tests shipped with AFB-Daemon

                Version: 1
                 Date:    30 mai 2016
                -Author:  Manuel Bachmann
                -
                - - -

                List of tests

                - +Author: Manuel Bachmann +

                List of tests

                Here are the tests shipped in the source tree:

                -
                • afb-client-demo (command-line WebSockets)

                • token-websock.qml (Qt/QML WebSockets)

                • -
                • *.html (HTML5/JS HTTP-REST & WebSockets)

                • +
                • *.html (HTML5/JS HTTP-REST & WebSockets)

                - - - -

                Detail of tests

                - - -

                afb-client-demo (command-line WebSockets)

                - -

                This clients interactively calls plugins APIs from the command line, using the binder -WebSockets facility.

                - +

                Detail of tests

                +

                afb-client-demo (command-line WebSockets)

                +

                This clients interactively calls plugins APIs from the command line, using the binder WebSockets facility.

                If afb-daemon has been launched with the following parameters:

                - -
                $ afb-daemon --port=1234 --token=123456 [...]
                -
                - +
                $ afb-daemon --port=1234 --token=123456 [...]

                Then run the client with :

                - -
                afb-client-demo ws://localhost:1234/api?token=123456 [<api> <verb> [<json-data>]]
                -
                - +
                afb-client-demo ws://localhost:1234/api?token=123456 [<api> <verb> [<json-data>]]

                For instance, to initialize the Audio plugin from the command line :

                - -
                afb-client-demo ws://localhost:1234/api?token=123456
                -
                - -

                The command doesn’t return. You should type requests of type [<json-data>]. -So, try:

                - +
                afb-client-demo ws://localhost:1234/api?token=123456
                +

                The command doesn't return. You should type requests of type []. So, try:

                auth connect
                -hello pingjson true
                -
                - +hello pingjson true


                - - -

                token-websock.qml (Qt/QML WebSockets)

                - +

                token-websock.qml (Qt/QML WebSockets)

                If afb-daemon has been launched with the following parameters:

                - -
                $ afb-daemon --port=1234 --token=123456 [...]
                -
                - +
                $ afb-daemon --port=1234 --token=123456 [...]

                and Qt5 is installed.

                -

                For installing Qt5 on Ubuntu 16.04:

                - -
                $ apt-get install qmlscene qml-module-qtwebsockets qml-module-qtquick-controls
                -
                - +
                $ apt-get install qmlscene qml-module-qtwebsockets qml-module-qtquick-controls

                For installing Qt5 on Fedora 23 :

                - -
                $ dnf install qt5-qtdeclarative-devel qt5-qtwebsockets-devel qt5-qtquickcontrols
                -
                - +
                $ dnf install qt5-qtdeclarative-devel qt5-qtwebsockets-devel qt5-qtquickcontrols

                Then run the client with :

                - -
                qmlscene test/token-websock.qml
                -
                - -

                and interactively press the buttons, “Connect”, “Refresh”, “Logout”.

                - +
                qmlscene test/token-websock.qml
                +

                and interactively press the buttons, "Connect", "Refresh", "Logout".


                - - -

                *.html (HTML5/JS HTTP-REST & WebSockets)

                - +

                *.html (HTML5/JS HTTP-REST & WebSockets)

                If afb-daemon has been launched with the following parameters:

                - -
                $ afb-daemon --port=1234 --rootdir=$PWD/test [...]
                -
                - -

                (“$PWD/test” being the “test” subdirectory of the source tree)_

                - +
                $ afb-daemon --port=1234 --rootdir=$PWD/test [...]
                +

                ("$PWD/test" being the "test" subdirectory of the source tree)_

                Then open your preferred Web browser, connect to the following URL:

                - -
                http://localhost:1234
                -
                - +
                http://localhost:1234

                and interactively run the various tests.

                diff --git a/doc/afb-tests-overview.md b/doc/afb-tests-overview.md index 98d971fc..272d98af 100644 --- a/doc/afb-tests-overview.md +++ b/doc/afb-tests-overview.md @@ -1,10 +1,12 @@ -# Overview of tests shipped with AFB-Daemon +Overview of tests shipped with AFB-Daemon +========================================= Version: 1 Date: 30 mai 2016 Author: Manuel Bachmann -## List of tests +List of tests +------------- Here are the tests shipped in the source tree: @@ -15,7 +17,8 @@ Here are the tests shipped in the source tree: * ***.html** (HTML5/JS HTTP-REST & WebSockets) -## Detail of tests +Detail of tests +--------------- ### afb-client-demo (command-line WebSockets) diff --git a/doc/updt.sh b/doc/updt.sh index 1c9d023e..e6b721d6 100755 --- a/doc/updt.sh +++ b/doc/updt.sh @@ -1,19 +1,15 @@ #!/bin/bash -# the HTML template -main=' - - - - - -GENERATED-MARKDOWN-HERE - -' - -# substitute the pattern $1 by the content of the file $2 -subst() { - awk -v pat="$1" -v rep="$(sed 's:\\:\\\\:g' $2)" '{gsub(pat,rep);gsub(pat,"\\&");print}' +meta() { + awk ' + NR == 1 { t = $0; next } + NR == 2 && $1 ~ "======" { next } + NR == 2 { exit } + $1 == "Date:" { d = $2; for(i = 3 ; i <= NF ; i++) d = d " " $i; next } + $1 == "Author:" { a = $2; for(i = 3 ; i <= NF ; i++) a = a " " $i; next } + $1 == "version" || $1 == "Version" {next} + /^[ \t]*$/ { printf "%% %s\n%% %s\n%% %s\n", t, a, d; exit } + ' "$1" } # update the date field of file $1 @@ -29,14 +25,8 @@ updadate() { mkhtml() { local x=$1 local h=${x%%.md}.html - expand -i $x | sed 's:^ : :' > $h.pre - markdown -f toc,autolink $h.pre > $h.toc.no - markdown -Tf toc,autolink $h.pre > $h.toc.yes - head --bytes=-$(stat -c %s $h.toc.no) $h.toc.yes > $h.toc - echo "$main" | - subst GENERATED-MARKDOWN-HERE $h.toc.no | - subst TABLE-OF-CONTENT-HERE $h.toc > $h - rm $h.* + { meta "$x"; sed 's/TABLE-OF-CONTENT-HERE//' "$x"; } | + pandoc --css doc.css -f markdown -t html5 --toc > "$h" } # apply