summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorFulup Ar Foll <fulup@iot.bzh>2017-11-01 19:22:36 +0100
committerFulup Ar Foll <fulup@iot.bzh>2017-11-01 19:22:36 +0100
commitfb2566c629de780c8ddc88058c864ea08436d1de (patch)
tree7cba08126f8fd0a11102bbd506eaf70a67022b1f
parentbc799a90ab7cc23dbe7286eb38d64af545de417c (diff)
Move to support Audio-4a High Level API
-rw-r--r--alsa-hook/CMakeLists.txt (renamed from hook-plugin/CMakeLists.txt)20
-rw-r--r--alsa-hook/PolicyAlsaHook.c640
-rw-r--r--alsa-hook/README.md211
-rw-r--r--conf.d/cmake/config.cmake2
-rw-r--r--hook-plugin/PolicyHookTcp.c560
-rw-r--r--hook-plugin/PolicyHookUnix.c562
-rw-r--r--hook-plugin/README.md121
-rw-r--r--nbproject/configurations.xml149
8 files changed, 936 insertions, 1329 deletions
diff --git a/hook-plugin/CMakeLists.txt b/alsa-hook/CMakeLists.txt
index 197fb4c..5f3cc6d 100644
--- a/hook-plugin/CMakeLists.txt
+++ b/alsa-hook/CMakeLists.txt
@@ -19,10 +19,10 @@
# Activate ALSA dynamic build build mode get resolve "snd_dlsym_start"
add_compile_options(-DPIC)
-PROJECT_TARGET_ADD(policy_hook_tcp)
+PROJECT_TARGET_ADD(policy_alsa_hook)
# Define targets
- ADD_LIBRARY(${TARGET_NAME} MODULE PolicyHookTcp.c)
+ ADD_LIBRARY(${TARGET_NAME} MODULE PolicyAlsaHook.c)
# Alsa Plugin properties
SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES
@@ -36,19 +36,3 @@ PROJECT_TARGET_ADD(policy_hook_tcp)
)
install(TARGETS ${TARGET_NAME} LIBRARY DESTINATION lib)
-PROJECT_TARGET_ADD(policy_hook_unix)
-
- # Define targets
- ADD_LIBRARY(${TARGET_NAME} MODULE PolicyHookUnix.c)
-
- # Alsa Plugin properties
- SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES
- PREFIX ""
- OUTPUT_NAME ${TARGET_NAME}
- )
-
- # Library dependencies (include updates automatically)
- TARGET_LINK_LIBRARIES(${TARGET_NAME}
- ${link_libraries}
- )
- install(TARGETS ${TARGET_NAME} LIBRARY DESTINATION lib)
diff --git a/alsa-hook/PolicyAlsaHook.c b/alsa-hook/PolicyAlsaHook.c
new file mode 100644
index 0000000..5e63825
--- /dev/null
+++ b/alsa-hook/PolicyAlsaHook.c
@@ -0,0 +1,640 @@
+/*
+ * Copyright (C) 2016 "IoT.bzh"
+ * Author Fulup Ar Foll <fulup@iot.bzh>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * AfbCallBack (snd_ctl_hal_t *handle, int numid, void **response);
+ * AlsaHookInit is mandatory and called with numid=0
+ *
+ * Syntax in .asoundrc file
+ * CrlLabel { cb MyFunctionName name "My_Second_Control" }
+ *
+ * Testing:
+ * aplay -DAlsaHook /usr/share/sounds/alsa/test.wav
+ *
+ * References:
+ * https://www.spinics.net/lists/alsa-devel/msg54235.html
+ * https://github.com/shivdasgujare/utilities/blob/master/nexuss/alsa-scenario-hook/src/alsa-wrapper.c
+ */
+
+#define _GNU_SOURCE
+#include <stdio.h>
+#include <alloca.h>
+
+#include <alsa/asoundlib.h>
+#include <alsa/conf.h>
+#include <alsa/pcm.h>
+
+#include <systemd/sd-event.h>
+#include <json-c/json.h>
+
+#include "afb/afb-wsj1.h"
+#include "afb/afb-ws-client.h"
+#include "afb/afb-proto-ws.h"
+
+#include <pthread.h>
+#include <semaphore.h>
+
+#define PLUGIN_ENTRY_POINT AlsaInstallHook
+ // Fulup Note: What ever you may find on Internet you should use
+ // SND_CONFIG_DLSYM_VERSION_HOOK and not SND_CONFIG_DLSYM_VERSION_HOOK
+ SND_DLSYM_BUILD_VERSION(PLUGIN_ENTRY_POINT, SND_PCM_DLSYM_VERSION)
+
+// this should be more than enough
+#define MAX_API_CALL 10
+#define MAX_EVT_CALL 10
+
+// timeout in ms
+#define REQUEST_DEFAULT_TIMEOUT 500
+#ifndef MAINLOOP_WATCHDOG
+#define MAINLOOP_WATCHDOG 100000
+#endif
+
+// closing message is added to query when PCM is closed
+#define CLOSING_MSG ",\"source\":-1}"
+
+// Currently not implemented
+#define UNUSED_ARG(x) UNUSED_ ## x __attribute__((__unused__))
+
+typedef struct {
+ const char *apiverb;
+ json_object *queryJ;
+ sd_event_source *evtSource;
+ char *callIdTag;
+ void *afbClient;
+} afbRequestT;
+
+typedef struct {
+ const char *search;
+ const char *value;
+ int signal;
+} afbEventT;
+
+typedef struct {
+ char *name;
+ const char *api;
+ char *uid;
+ snd_pcm_t *pcm;
+ const char *uri;
+ struct afb_proto_ws *pws;
+ sd_event *sdLoop;
+ int verbose;
+ int synchronous;
+ sem_t semaphore;
+ long timeout;
+ int count;
+ int error;
+ afbRequestT **request;
+ afbRequestT **release;
+ afbEventT **event;
+} afbClientT;
+
+
+static void *LoopInThread(void *handle) {
+ afbClientT *afbClient = (afbClientT*) handle;
+ int count=0;
+ int watchdog= MAINLOOP_WATCHDOG *1000;
+
+ /* loop until end */
+ for (;;) {
+
+ if (afbClient->verbose) printf("ON-MAINLOOP ping=%d\n", count++);
+ sd_event_run(afbClient->sdLoop, watchdog);
+ }
+
+ return NULL;
+}
+
+// lost connect with the AudioDaemon
+static void OnHangupCB(void *handle) {
+
+ afbClientT *afbClient = (afbClientT*) handle;
+ SNDERR("(Hoops) Lost Connection to %s", afbClient->uri);
+
+ // try to close PCM when impossible terminate client
+ int err = snd_pcm_close (afbClient->pcm);
+ if (err) exit(1);
+}
+
+typedef enum {
+ HOOK_INSTALL,
+ HOOK_CLOSE,
+} hookActionT;
+
+void OnEventCB(void *handle, const char *event, int evtid, struct json_object *dataJ) {
+ afbClientT *afbClient = (afbClientT*) handle;
+ afbEventT **afbEvent = afbClient->event;
+ json_object *tmpJ;
+ int done;
+
+ // if no event handler just ignore events
+ if (!afbEvent) goto OnErrorExit;
+
+ if (afbClient->verbose) printf("ON-EVENT processing signal event=%s search=%s\n", event, json_object_get_string(dataJ));
+
+ // loop on event/signal mapping table
+ for (int index=0; afbEvent[index]!= NULL; index++) {
+ done = json_object_object_get_ex(dataJ,afbEvent[index]->search, &tmpJ);
+ if (done) {
+ const char *value=json_object_get_string(tmpJ);
+ if (!strcmp(afbEvent[index]->value, value)) {
+ if (afbEvent[index]->signal)
+ if (afbClient->verbose) printf("ON-EVENT search=%s value=%s signal=%d\n", afbEvent[index]->search, value, afbEvent[index]->signal);
+ if (afbEvent[index]->signal) kill (getpid(), afbEvent[index]->signal);
+ }
+ }
+ }
+
+ return;
+
+OnErrorExit:
+ if (afbClient->verbose) SNDERR("ON-EVENT Fail/Ignored %s(%s)\n", event, json_object_get_string(dataJ));
+ return;
+}
+
+static void OnSuccessCB(void* UNUSED_ARG(ctx) , void* handle, json_object* responseJ, const char* info) {
+
+ afbRequestT *afbRequest= (afbRequestT*)handle;
+ afbClientT *afbClient=(afbClientT*)afbRequest->afbClient;
+
+ if (afbClient->verbose) printf("OnSuccessCB callid='%s' response='%s' info='%s'\n", afbRequest->callIdTag, json_object_get_string(responseJ), info);
+
+ // Cancel timeout for this request
+ sd_event_source_unref(afbRequest->evtSource);
+ free(afbRequest->callIdTag);
+
+ // When not more waiting call release semaphore
+ afbClient->count--;
+ if (afbClient->synchronous) {
+ if (afbClient->verbose) printf("OnSuccessCB One Request Done\n");
+ sem_post (&afbClient->semaphore);
+ afbClient->error=0;
+ } else if (afbClient->count == 0) {
+ if (afbClient->verbose) printf("OnSuccessCB No More Waiting Request\n");
+ sem_post (&afbClient->semaphore);
+ }
+}
+
+static void OnFailureCB(void* UNUSED_ARG(ctx), void* handle, const char *status, const char *info) {
+
+ afbRequestT *afbRequest= (afbRequestT*)handle;
+ afbClientT *afbClient=(afbClientT*)afbRequest->afbClient;
+
+ if (afbClient->verbose) printf("OnFailureCB callid='%s' status='%s' info='%s'\n", afbRequest->callIdTag, status, info);
+
+ // Cancel timeout for this request
+ sd_event_source_unref(afbRequest->evtSource);
+ free(afbRequest->callIdTag);
+
+ afbClient->error=1;
+ sem_post (&afbClient->semaphore);
+}
+
+
+/* the callback interface for pws */
+static struct afb_proto_ws_client_itf itf = {
+ .on_reply_success = OnSuccessCB,
+ .on_reply_fail = OnFailureCB,
+ .on_event_create = NULL,
+ .on_event_remove = NULL,
+ .on_event_subscribe = NULL,
+ .on_event_unsubscribe = NULL,
+ .on_event_push = OnEventCB,
+ .on_event_broadcast = NULL,
+ .on_subcall = NULL,
+};
+
+int OnTimeoutCB (sd_event_source* source, uint64_t timer, void* handle) {
+ afbClientT *afbClient= (afbClientT*)handle;
+
+ SNDERR("\nON-TIMEOUT Call Request Fail URI=%s\n", afbClient->uri);
+
+ // Close PCM and release waiting client
+ afbClient->error=1;
+ sem_post (&afbClient->semaphore);
+
+ return 0;
+}
+
+// Call AGL binder asynchronously by with a timeout
+static int CallWithTimeout(afbClientT *afbClient, afbRequestT *afbRequest, int count) {
+ uint64_t usec;
+ int err;
+
+ // create a unique tag for request
+ (void) asprintf(&afbRequest->callIdTag, "%d:%s", count, afbRequest->apiverb);
+
+ // create a timer with ~250us accuracy
+ sd_event_now(afbClient->sdLoop, CLOCK_MONOTONIC, &usec);
+ sd_event_add_time(afbClient->sdLoop, &afbRequest->evtSource, CLOCK_MONOTONIC, usec+afbClient->timeout*1000, 250, OnTimeoutCB, afbClient);
+
+ // release action is optional
+ if (afbRequest->apiverb) {
+ if (afbClient->verbose) printf("CALL-REQUEST verb=%s tag=%s\n", afbRequest->apiverb, afbRequest->callIdTag);
+ err = afb_proto_ws_client_call(afbClient->pws, afbRequest->apiverb, afbRequest->queryJ, afbClient->uid, afbRequest);
+ if (err < 0 ) goto OnErrorExit;
+ }
+
+ // save client handle in request
+ afbRequest->afbClient = afbClient;
+ afbClient->count ++;
+
+ // in synchronous mode we wait for CB to return
+ if (afbClient->synchronous) sem_wait(&afbClient->semaphore);
+
+ return 0;
+
+OnErrorExit:
+ fprintf(stderr, "LaunchCallRequest: Fail call %s//%s&%s", afbClient->uri, afbRequest->apiverb, json_object_get_string(afbRequest->queryJ));
+ return 1;
+}
+
+static int LaunchCallRequest(afbClientT *afbClient, hookActionT action) {
+
+ pthread_t tid;
+ int err, idx;
+
+ switch (action) {
+ case HOOK_INSTALL: {
+
+ // init waiting counting semaphore
+ if (sem_init(&afbClient->semaphore, 1, 0) == -1) {
+ fprintf(stderr, "LaunchCallRequest: Fail Semaphore Init: %s\n", afbClient->uri);
+ }
+
+ // Create a main loop
+ err = sd_event_default(&afbClient->sdLoop);
+ if (err < 0) {
+ fprintf(stderr, "LaunchCallRequest: Connection to default event loop failed: %s\n", strerror(-err));
+ goto OnErrorExit;
+ }
+
+ // start a thread with a mainloop to monitor Audio-Agent
+ err = pthread_create(&tid, NULL, &LoopInThread, afbClient);
+ if (err) goto OnErrorExit;
+
+ afbClient->pws = afb_ws_client_connect_api(afbClient->sdLoop, afbClient->uri, &itf, afbClient);
+ if (afbClient->pws == NULL) {
+ fprintf(stderr, "LaunchCallRequest: Connection to %s failed\n", afbClient->uri);
+ goto OnErrorExit;
+ }
+
+ // register hanghup callback
+ afb_proto_ws_on_hangup(afbClient->pws, OnHangupCB);
+
+
+ // If no request exit now
+ if (!afbClient->release) {
+ fprintf(stderr, "LaunchCallRequest: HOOK_INSTALL:fatal mandatory request call missing in asoundrc\n");
+ goto OnErrorExit;;
+ }
+
+ // send call request to audio-agent asynchronously (respond with thread mainloop context)
+ for (idx = 0; afbClient->request[idx] != NULL; idx++) {
+ err = CallWithTimeout(afbClient, afbClient->request[idx], idx);
+ if (err) goto OnErrorExit;
+ }
+ // launch counter to keep track of waiting request call
+ afbClient->count=idx;
+ break;
+ }
+
+ case HOOK_CLOSE: {
+
+ // If no request exit now
+ if (!afbClient->release) {
+ if (afbClient->verbose) printf("LaunchCallRequest:optional HOOK_CLOSE no release control call\n");
+ break;
+ }
+
+ // send call request to audio-agent asynchronously (respond with thread mainloop context)
+ for (idx = 0; afbClient->release[idx] != NULL; idx++) {
+ err = CallWithTimeout(afbClient, afbClient->release[idx], idx);
+ if (err) goto OnErrorExit;
+ }
+ // launch counter to keep track of waiting request call
+ afbClient->count=idx;
+ break;
+ }
+
+ default:
+ fprintf(stderr, "LaunchCallRequest (hoops): Unknown action");
+ goto OnErrorExit;
+ }
+
+ return 0;
+
+OnErrorExit:
+ return -1;
+}
+
+static int AlsaCloseHook(snd_pcm_hook_t *hook) {
+
+ afbClientT *afbClient = (afbClientT*) snd_pcm_hook_get_private (hook);
+
+ // launch call request and create a waiting mainloop thread
+ int err = LaunchCallRequest(afbClient, HOOK_CLOSE);
+ if (err < 0) {
+ fprintf (stderr, "PCM Fail to Enter Mainloop\n");
+ goto OnErrorExit;
+ }
+
+ // wait for all call request to return
+ if (!afbClient->synchronous) sem_wait(&afbClient->semaphore);
+ if (afbClient->error) {
+ fprintf (stderr, "AlsaCloseHook: Notice exit before audio-4a response\n");
+ goto OnErrorExit;
+ }
+
+ if (afbClient->verbose) fprintf(stdout, "\nAlsaHook Close Success PCM=%s URI=%s\n", snd_pcm_name(afbClient->pcm), afbClient->uri);
+ return 0;
+
+OnErrorExit:
+ fprintf(stderr, "\nAlsaPcmHook Plugin Close Fail PCM=%s\n", snd_pcm_name(afbClient->pcm));
+ return 0;
+}
+
+// Get an asoundrc compound and return it as a JSON object
+static json_object* AlsaGetJson (snd_config_t *ctlconfig, const char *id, const char*label) {
+
+ json_object *queryJ;
+ snd_config_type_t ctype;
+ char* query;
+
+ // each control is a sting that contain a json object
+ ctype = snd_config_get_type(ctlconfig);
+ snd_config_get_string(ctlconfig, (const char**) &query);
+ if (ctype != SND_CONFIG_TYPE_STRING) {
+ SNDERR("Invalid signal number for %s value=%s", label, query);
+ goto OnErrorExit;
+ }
+
+ // cleanup string for json_tokener
+ for (int idx = 0; query[idx] != '\0'; idx++) {
+ if (query[idx] == '\'') query[idx] = '"';
+ }
+ queryJ = json_tokener_parse(query);
+ if (!queryJ) {
+ SNDERR("Not a valid Json object control='%s' query='%s'", id, query);
+ goto OnErrorExit;
+ }
+
+ return queryJ;
+
+OnErrorExit:
+ return NULL;
+}
+
+static int AlsaGetActions (snd_config_t *node, afbRequestT **afbRequest, const char*id) {
+ const char *callConf, *apiverb;
+ snd_config_type_t ctype;
+ snd_config_iterator_t currentCall, follow;
+ int callCount=0;
+
+ ctype = snd_config_get_type(node);
+ if (ctype != SND_CONFIG_TYPE_COMPOUND) {
+ snd_config_get_string(node, &callConf);
+ SNDERR("Invalid compound type for %s", callConf);
+ goto OnErrorExit;
+ }
+
+
+ // loop on each call
+ snd_config_for_each(currentCall, follow, node) {
+ snd_config_t *ctlconfig = snd_config_iterator_entry(currentCall);
+
+ // ignore empty line
+ if (snd_config_get_id(ctlconfig, &apiverb) < 0) continue;
+
+ // allocate an empty call request
+ afbRequest[callCount] = calloc(1, sizeof (afbRequestT));
+ afbRequest[callCount]->apiverb=strdup(apiverb);
+ afbRequest[callCount]->queryJ= AlsaGetJson(ctlconfig, id, apiverb);
+ if (!afbRequest[callCount]->queryJ) goto OnErrorExit;
+
+ // move to next call if any
+ callCount ++;
+ if (callCount == MAX_EVT_CALL) {
+ SNDERR("Too Many call MAX_EVT_CALL=%d", MAX_EVT_CALL);
+ goto OnErrorExit;
+ }
+ afbRequest[callCount]=NULL; // afbEvent array is NULL terminated
+ }
+
+ return 0;
+
+OnErrorExit:
+ return 1;
+}
+
+static int AlsaGetEvents (snd_config_t *node, afbEventT **afbEvent, const char*id) {
+
+ const char *confEvents, *evtpattern;
+ snd_config_type_t ctype;
+ snd_config_iterator_t currentEvt, follow;
+ snd_config_t *itemConf;
+ int callCount=0;
+ int err;
+
+ ctype = snd_config_get_type(node);
+ if (ctype != SND_CONFIG_TYPE_COMPOUND) {
+ snd_config_get_string(node, &confEvents);
+ SNDERR("Invalid compound type for %s", confEvents);
+ goto OnErrorExit;
+ }
+
+ // loop on each call
+ snd_config_for_each(currentEvt, follow, node) {
+ snd_config_t *ctlconfig = snd_config_iterator_entry(currentEvt);
+
+ // ignore empty line
+ if (snd_config_get_id(ctlconfig, &evtpattern) < 0) continue;
+
+ // allocate an empty call request
+ afbEvent[callCount] = calloc(1, sizeof (afbEventT));
+
+ // extract signal num from config label
+ for (int idx=0; evtpattern[idx] != '\0'; idx++) {
+ if (evtpattern[idx]=='-' && evtpattern[idx+1] != '\0') {
+ int done= sscanf (&evtpattern[idx+1], "%d",&afbEvent[callCount]->signal);
+ if (done != 1) {
+ SNDERR("Invalid Signal '%s' definition should be something like Sig-xx", evtpattern);
+ goto OnErrorExit;
+ }
+ break;
+ }
+ }
+
+ // extract signal key value search pattern
+ ctype = snd_config_get_type(ctlconfig);
+ if (ctype != SND_CONFIG_TYPE_COMPOUND) {
+ snd_config_get_string(ctlconfig, &confEvents);
+ SNDERR("Invalid event search pattern for %s value=%s", evtpattern, confEvents);
+ goto OnErrorExit;
+ }
+
+ // pattern should have a search
+ err = snd_config_search(ctlconfig, "search", &itemConf);
+ if (!err) {
+ const char *search;
+ if (snd_config_get_string(itemConf, &search) < 0) {
+ SNDERR("Invalid event/signal 'search' should be a string %s", confEvents);
+ goto OnErrorExit;
+ }
+ afbEvent[callCount]->search=strdup(search);
+ } else {
+ SNDERR("Missing 'search' from event/signal 'search' from signal definition %s", confEvents);
+ goto OnErrorExit;
+ }
+
+ // pattern should have a value
+ err = snd_config_search(ctlconfig, "value", &itemConf);
+ if (!err) {
+ const char *value;
+ if (snd_config_get_string(itemConf, &value) < 0) {
+ SNDERR("Invalid event/signal 'value' should be a string %s", confEvents);
+ goto OnErrorExit;
+ }
+ afbEvent[callCount]->value=strdup(value);
+ } else {
+ SNDERR("Missing 'value' from event/signal 'value' from signal definition %s", confEvents);
+ goto OnErrorExit;
+ }
+
+
+ // move to next call if any
+ callCount ++;
+ if (callCount == MAX_EVT_CALL) {
+ SNDERR("Too Many call MAX_EVT_CALL=%d", MAX_EVT_CALL);
+ goto OnErrorExit;
+ }
+ afbEvent[callCount]=NULL; // afbEvent array is NULL terminated
+ }
+ return 0;
+
+OnErrorExit:
+ return 1;
+}
+
+// Function call when Plugin PCM is OPEN
+int PLUGIN_ENTRY_POINT (snd_pcm_t *pcm, snd_config_t *conf) {
+ snd_pcm_hook_t *h_close = NULL;
+ snd_config_iterator_t it, next;
+ afbClientT *afbClient = malloc(sizeof (afbClientT));
+ int err;
+
+ // start populating client handle
+ afbClient->pcm = pcm;
+ afbClient->name= strdup(snd_pcm_name(pcm));
+ afbClient->verbose = 0;
+ (void) asprintf(&afbClient->uid, "alsa-hook-pid:%d", getpid());
+
+
+ // Get PCM arguments from asoundrc
+ snd_config_for_each(it, next, conf) {
+ snd_config_t *node = snd_config_iterator_entry(it);
+ const char *id;
+
+ // ignore comment en empty lines
+ if (snd_config_get_id(node, &id) < 0) continue;
+ if (strcmp(id, "comment") == 0 || strcmp(id, "hint") == 0) continue;
+
+ if (strcmp(id, "uri") == 0) {
+ const char *uri;
+ if (snd_config_get_string(node, &uri) < 0) {
+ SNDERR("Invalid String for %s", id);
+ goto OnErrorExit;
+ }
+ afbClient->uri=strdup(uri);
+ continue;
+ }
+
+ if (strcmp(id, "verbose") == 0) {
+ afbClient->verbose= snd_config_get_bool(node);
+ if (afbClient->verbose < 0) {
+ SNDERR("Invalid Boolean for %s", id);
+ goto OnErrorExit;
+ }
+ continue;
+ }
+
+ if (strcmp(id, "synchronous") == 0) {
+ afbClient->synchronous= snd_config_get_bool(node);
+ if (afbClient->synchronous < 0) {
+ SNDERR("Invalid Boolean for %s", id);
+ goto OnErrorExit;
+ }
+ continue;
+ }
+
+ if (strcmp(id, "timeout") == 0) {
+ if (snd_config_get_integer(node, &afbClient->timeout) < 0) {
+ SNDERR("Invalid timeout Integer %s", id);
+ goto OnErrorExit;
+ }
+ continue;
+ }
+
+ if (strcmp(id, "request") == 0) {
+ afbClient->request = malloc(MAX_API_CALL * sizeof(afbRequestT*));;
+ int err= AlsaGetActions(node, afbClient->request , id);
+ if (err) goto OnErrorExit;
+ continue;
+ }
+
+ if (strcmp(id, "release") == 0) {
+ afbClient->release = malloc(MAX_API_CALL * sizeof(afbRequestT*));;
+ int err= AlsaGetActions(node, afbClient->release, id);
+ if (err) goto OnErrorExit;
+ continue;
+ }
+
+ if (strcmp(id, "events") == 0) {
+ afbClient->event= malloc(MAX_API_CALL * sizeof(afbRequestT*));;
+ int err= AlsaGetEvents(node, afbClient->event, id);
+ if (err) goto OnErrorExit;
+ continue;
+ }
+ }
+
+ if (afbClient->verbose) fprintf(stdout, "\nAlsaHook Install Start PCM=%s URI=%s\n", snd_pcm_name(afbClient->pcm), afbClient->uri);
+
+ err = snd_pcm_hook_add(&h_close, afbClient->pcm, SND_PCM_HOOK_TYPE_CLOSE, AlsaCloseHook, afbClient);
+ if (err < 0) goto OnErrorExit;
+
+ // launch call request and create a waiting mainloop thread
+ err = LaunchCallRequest(afbClient, HOOK_INSTALL);
+ if (err < 0) {
+ fprintf (stderr, "PCM Fail to Enter Mainloop\n");
+ goto OnErrorExit;
+ }
+
+ // wait for all call request to return
+ if (!afbClient->synchronous) sem_wait(&afbClient->semaphore);
+ if (afbClient->error) {
+ fprintf (stderr, "PCM Authorisation Deny from AAAA Controller (AGL Advanced Audio Agent)\n");
+ goto OnErrorExit;
+ }
+
+ if (afbClient->verbose) fprintf(stdout, "\nAlsaHook Install Success PCM=%s URI=%s\n", afbClient->name, afbClient->uri);
+ return 0;
+
+OnErrorExit:
+ fprintf(stderr, "\nAlsaPcmHook Plugin Policy Control Fail PCM=%s\n", afbClient->name);
+ if (h_close)
+ snd_pcm_hook_remove(h_close);
+
+ return -EINVAL;
+}
+
diff --git a/alsa-hook/README.md b/alsa-hook/README.md
new file mode 100644
index 0000000..a51ec19
--- /dev/null
+++ b/alsa-hook/README.md
@@ -0,0 +1,211 @@
+Alsa-Hook-Plugin
+
+Object: Provide a Hook on Alsa PCM to check permission again AGL Advance Audio Agent
+Status: Release Candidate
+Author: Fulup Ar Foll fulup@iot.bzh
+Date : August-2017
+ References: https://www.spinics.net/lists/alsa-devel/msg54235.html
+
+
+## Functionalities:
+ - Execute a set of unix/ws RPC request again AGL binders to allow/deny access
+ - Keep websocket open in an idependant thread in order to monitor event received from AGL audio agent
+
+## Installation
+ - Alsaplugins are typically search in /usr/share/alsa-lib. Nevertheless a full path might be given
+ - This plugin implement a hook on a slave PCM. Typically this slave PCM is a dedicated virtual channel (eg: navigation, emergency,...)
+ - Config should be place in ~/.asoundrc (see config sample in PROJECT_ROOT/conf.d/alsa)
+
+## Test
+ - Install a full .asoundrc from conf.d/project/alsa.d
+ - Check SoundCard ==> speaker-test -Dhw:v1340 -c2 -twav
+ - Check MixerPCM ==> speaker-test -DSpeakers -c2 -twav
+ - Check SoftVol ==> speaker-test -DMusicPCM -c2 -twav
+ - Check Plugin ==> speaker-test -DMultimedia -c2 -twav
+ - Check MultiMedia aplay -DDMyNavPCM /usr/share/sounds/alsa/test.wav
+
+
+## Pulse audio integration
+
+By default Pulse only auto detect hardware sound card and virtual channel should be specified
+
+ 1) update ~/.asoundrc file and check basic ALSA virtual channel works as expected
+ 2) kill/restart pulseaudio server to force alsa hookplugin loading
+ 3) declare alsa virtual channel as pulse sink
+ - pacmd load-module module-alsa-sink device=MusicPCM
+ - pacmd load-module module-alsa-sink device=NavPCM control=NavAlsaCtl
+ - pacmd list-sinks | grep -i music
+ 4) check your virtual pulse sink work
+ - paplay -d alsa_output.MusicPCM /usr/share/sounds/alsa/test.wav
+ - paplay -d alsa_output.NavPCM /usr/share/sounds/alsa/Front_Center.wav
+
+optional integration with ALSA legacy apps
+
+ 5) start audio-pol4a controller
+ - repeat previous step(3) this time with device=Multimedia device=Navigation, ....
+ 6) check virtual channel with policy controller protection
+ - paplay -d alsa_output.Multimedia /usr/share/sounds/alsa/test.wav
+ - paplay -d alsa_output.Navigation /usr/share/sounds/alsa/Front_Center.wav
+
+
+Bug/Feature:
+ 1) when softvol control is initialised from plugin and not
+ from AGL binding. At 1st run ctl has invalid TLV and cannot be used
+ Bypass Solution:
+ * start audio-binder before playing sound (binding create control before softvol plugin)
+ * run a dummy aplay -DMyNavPCM "" to get a clean control
+ 2) When using Audio-Pol4a to protect virtual channel, the audio policy controller should
+ run before adding virtual channel into pulse.
+ 3) In order to leverage SMACK to protect virtual audio role, a Pulse rooting plugin should be used.
+
+
+## Alsa Config Sample
+
+```
+# ------------------------------------------------------
+# Mixer PCM allow to play multiple stream simultaneously
+# ------------------------------------------------------
+pcm.Speakers {
+ type dmix
+ slave {pcm "hw:v1340"} #Jabra Solmate 1
+ ipc_key 1001 # ipc_key should be unique to each dmix
+}
+
+# -----------------------------------------------------
+# Register ControllerHookPlugin (ToiBeFix fullpath)
+# -----------------------------------------------------
+pcm_hook_type.CtlHookPlugin {
+ install "AlsaInstallHook"
+ lib "/home/fulup/Workspace/Audio-4a/alsa-4a/build/alsa-hook/policy_alsa_hook.so"
+}
+
+
+# -------------------------------------------------------
+# Define one Audio Virtual Channel per Audio Roles
+# -------------------------------------------------------
+pcm.MusicPCM {
+ type softvol
+
+ # Point Slave on HOOK for policies control
+ slave.pcm "Speakers"
+
+ # name should match with HAL definition
+ control.name "Playback Multimedia"
+}
+
+pcm.NaviPCM {
+ type softvol
+
+ # Point Slave on HOOK for policies control
+ slave.pcm "Speakers"
+
+ # name should match with HAL definition
+ control.name "Playback Navigation"
+}
+
+pcm.UrgentPCM {
+ type softvol
+
+ # Point Slave on HOOK for policies control
+ slave.pcm "Speakers"
+
+ # name should match with HAL definition
+ control.name "Playback Emergency"
+}
+
+# ----------------------------------------------------
+# Define one hooked PCM channel per Audio Roles
+# ----------------------------------------------------
+pcm.Multimedia {
+ type hooks
+ slave {pcm "MusicPCM"}
+ hooks.0 {
+ comment "Defined used hook sharelib and provide arguments/config to install func"
+ type "CtlHookPlugin"
+ hook_args {
+
+ # print few log messages (default false)
+ verbose true
+
+ # uri to audio-4a policy engine
+ uri="unix:/var/tmp/pol4a"
+
+ # timeout in ms (default 500)
+ timeout 5000
+
+ # force API synchronous mode
+ synchronous true
+
+ # api subcall to request a role
+ request {
+ multimedia-role "{'uid':'alsa-hook-client'}"
+ signal-timeout "{'timeout':180, 'music':'quit'}"
+ }
+
+ # api subcall to request a role
+ release {
+ release-role "{'uid':'alsa-hook-client'}"
+ }
+
+ # map AGL event on Unix signal. Search in event for json key=value
+ events {
+ sig-02 {search music, value quit}
+ sig-31 {search event, value start}
+ sig-32 {search event, value start}
+ }
+ }
+ }
+}
+
+pcm.Navigation {
+ type hooks
+ slave {pcm "NaviPCM"}
+ hooks.0 {
+ comment "Defined used hook sharelib and provide arguments/config to install func"
+ type "CtlHookPlugin"
+ hook_args {
+
+ # print few log messages (default false)
+ verbose true
+
+ # uri to audio-4a policy engine
+ uri="unix:/var/tmp/pol4a"
+
+ # timeout in ms (default 500)
+ timeout 5000
+
+ # force API synchronous mode
+ synchronous true
+
+ # api subcall to request a role
+ request {
+ navigation-role "{'uid':'alsa-hook-client'}"
+ signal-timeout "{'timeout':5, 'navi':'quit'}"
+ }
+
+ # api subcall to request a role
+ release {
+ release-role "{'uid':'alsa-hook-client'}"
+ }
+
+ # map AGL event on Unix signal. Search in event for json key=value
+ events {
+ sig-02 {search navi, value quit}
+ sig-31 {search event, value start}
+ sig-32 {search event, value start}
+ }
+ }
+ }
+}
+
+
+```
+
+NOTE:
+
+* Hook plugin is loaded by Alsa libasound within client context. It inherits client process attributes, as UID/GID and
+SMACK label when running on AGL. The smack label is control by AGL security framework.
+As a result a control request succeeds only when client application permission match requested audio role inside Cynara security database.
+
+* Hook plugin keep a connection with the Audio-Agent until PCM is closed by the application. This connection allow the
+Audio-Agent to send events. eg: pause, quit, mute, ... \ No newline at end of file
diff --git a/conf.d/cmake/config.cmake b/conf.d/cmake/config.cmake
index 4ace99c..d3ed120 100644
--- a/conf.d/cmake/config.cmake
+++ b/conf.d/cmake/config.cmake
@@ -205,7 +205,7 @@ endif()
if(EXISTS ${CMAKE_SOURCE_DIR}/../afb-controller/build/afb-source/afb-control-afb.so)
set(CTL_BUILD_PATH "--binding=../../afb-controller/build/afb-source/afb-control-afb.so")
endif()
-set(CLOSING_MESSAGE "Debug from afb-daemon --port=1234 ${MONITORING_ALIAS} --ldpaths=. ${CTL_BUILD_PATH} --workdir=. --roothttp=../htdocs --tracereq=common --token= --verbose ")
+set(CLOSING_MESSAGE "Debug from afb-daemon --port=1234 ${MONITORING_ALIAS} --ldpaths=package/lib ${CTL_BUILD_PATH} --workdir=. --roothttp=../htdocs --tracereq=common --token= --verbose ")
set(PACKAGE_MESSAGE "Install widget file using in the target : afm-util install ${PROJECT_NAME}.wgt")
# When Present LUA is used by the controller
diff --git a/hook-plugin/PolicyHookTcp.c b/hook-plugin/PolicyHookTcp.c
deleted file mode 100644
index c4b7c15..0000000
--- a/hook-plugin/PolicyHookTcp.c
+++ /dev/null
@@ -1,560 +0,0 @@
-/*
- * Copyright (C) 2016 "IoT.bzh"
- * Author Fulup Ar Foll <fulup@iot.bzh>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * AfbCallBack (snd_ctl_hal_t *handle, int numid, void **response);
- * AlsaHookInit is mandatory and called with numid=0
- *
- * Syntax in .asoundrc file
- * CrlLabel { cb MyFunctionName name "My_Second_Control" }
- *
- * Testing:
- * aplay -DAlsaHook /usr/share/sounds/alsa/test.wav
- *
- * References:
- * https://www.spinics.net/lists/alsa-devel/msg54235.html
- * https://github.com/shivdasgujare/utilities/blob/master/nexuss/alsa-scenario-hook/src/alsa-wrapper.c
- */
-
-#define _GNU_SOURCE
-#include <stdio.h>
-#include <alsa/asoundlib.h>
-#include <alsa/conf.h>
-#include <alsa/pcm.h>
-
-#include <systemd/sd-event.h>
-#include <json-c/json.h>
-
-#include "afb/afb-wsj1.h"
-#include "afb/afb-ws-client.h"
-#include <pthread.h>
-#include <semaphore.h>
-
-
-#define PLUGIN_ENTRY_POINT AlsaInstallHook
- // Fulup Note: What ever you may find on Internet you should use
- // SND_CONFIG_DLSYM_VERSION_HOOK and not SND_CONFIG_DLSYM_VERSION_HOOK
- SND_DLSYM_BUILD_VERSION(PLUGIN_ENTRY_POINT, SND_PCM_DLSYM_VERSION)
-
-// this should be more than enough
-#define MAX_API_CALL 10
-#define MAX_EVT_CALL 10
-
-// timeout in ms
-#define REQUEST_DEFAULT_TIMEOUT 500
-#ifndef MAINLOOP_WATCHDOG
-#define MAINLOOP_WATCHDOG 100000
-#endif
-
-// closing message is added to query when PCM is closed
-#define CLOSING_MSG ",\"source\":-1}"
-
-// Currently not implemented
-#define UNUSED_ARG(x) UNUSED_ ## x __attribute__((__unused__))
-void OnRequestCB(void* UNUSED_ARG(handle) , const char* UNUSED_ARG(api), const char* UNUSED_ARG(verb), struct afb_wsj1_msg*UNUSED_ARG(msg)) {}
-
-typedef struct {
- const char *api;
- const char *openVerb;
- const char *closeVerb;
- long timeout;
- char *query;
- size_t length;
-
- sd_event_source *evtSource;
- char *callIdTag;
- void *afbClient;
-} afbRequestT;
-
-typedef struct {
- const char *name;
- int signal;
-} afbEventT;
-
-typedef struct {
- snd_pcm_t *pcm;
- const char *uri;
- struct afb_wsj1 *wsj1;
- sd_event *sdLoop;
- int verbose;
- sem_t semaphore;
- int count;
- int error;
- afbRequestT **request;
- afbEventT **event;
-} afbClientT;
-
-
-
-static void *LoopInThread(void *handle) {
- afbClientT *afbClient = (afbClientT*) handle;
- int count=0;
- int watchdog= MAINLOOP_WATCHDOG *1000;
-
- /* loop until end */
- for (;;) {
-
- if (afbClient->verbose) printf("ON-MAINLOOP ping=%d\n", count++);
- sd_event_run(afbClient->sdLoop, watchdog);
- }
-
- return NULL;
-}
-
-// lost connect with the AudioDaemon
-static void OnHangupCB(void *handle, struct afb_wsj1 *wsj1) {
-
- afbClientT *afbClient = (afbClientT*) handle;
- SNDERR("(Hoops) Lost Connection to %s", afbClient->uri);
-
- // try to close PCM when impossible terminate client
- int err = snd_pcm_close (afbClient->pcm);
- if (err) exit(1);
-}
-
-typedef enum {
- HOOK_INSTALL,
- HOOK_CLOSE,
-} hookActionT;
-
-
-void OnEventCB(void *handle, const char *event, struct afb_wsj1_msg *msg) {
- afbClientT *afbClient = (afbClientT*) handle;
- afbEventT **afbEvent = afbClient->event;
- json_object *eventJ, *tmpJ, *dataJ;
- const char *label;
- int value, done, index;
-
- eventJ = afb_wsj1_msg_object_j(msg);
- done= json_object_object_get_ex(eventJ,"data", &dataJ);
- if (!done) {
- SNDERR ("PCM_HOOK: uri=%s empty event label", afbClient->uri);
- goto OnErrorExit;
- }
-
- json_object_object_get_ex(dataJ,"signal", &tmpJ);
- label=json_object_get_string(tmpJ);
-
- json_object_object_get_ex(dataJ,"value", &tmpJ);
- value=json_object_get_int(tmpJ);
-
- for (index=0; afbEvent[index]!= NULL; index++) {
- if (!strcmp(afbEvent[index]->name, label)) break;
- }
-
- if (!afbEvent[index] || !afbEvent[index]->signal) {
- SNDERR ("PCM_HOOK: Unsupported uri=%s label=%s", afbClient->uri, label);
- return;
- }
-
- // send signal to self process
- kill (getpid(), afbEvent[index]->signal);
-
- if (afbClient->verbose) printf("ON-EVENT label=%s signal=%d\n", label, value);
- return;
-
-OnErrorExit:
- SNDERR("ON-EVENT %s(%s)\n", event, afb_wsj1_msg_object_s(msg));
- return;
-}
-
-// callback interface for wsj1
-static struct afb_wsj1_itf itf = {
- .on_hangup = OnHangupCB,
- .on_call = OnRequestCB,
- .on_event = OnEventCB
-};
-
-void OnResponseCB(void *handle, struct afb_wsj1_msg *msg) {
- afbRequestT *afbRequest= (afbRequestT*)handle;
- afbClientT *afbClient=(afbClientT*)afbRequest->afbClient;
-
- if (afbClient->verbose) printf("ON-RESPONSE call=%s response=%s\n", afbRequest->callIdTag, afb_wsj1_msg_object_s(msg));
-
- // Cancel timeout for this request
- sd_event_source_unref(afbRequest->evtSource);
-
- if (! afb_wsj1_msg_is_reply_ok(msg)) goto OnErrorExit;
-
- // When not more waiting call release semaphore
- afbClient->count--;
- if (afbClient->count == 0) {
- if (afbClient->verbose) printf("ON-RESPONSE No More Waiting Request\n");
- afbClient->error=0;
- sem_post (&afbClient->semaphore);
- }
- return;
-
-OnErrorExit:
- fprintf(stderr, "ON-RESPONSE ERROR call=%s response=%s\n", afbRequest->callIdTag, afb_wsj1_msg_object_s(msg));
- afbClient->error=1;
- sem_post (&afbClient->semaphore);
-}
-
-int OnTimeoutCB (sd_event_source* source, uint64_t timer, void* handle) {
- afbClientT *afbClient= (afbClientT*)handle;
-
- SNDERR("\nON-TIMEOUT Call Request Fail URI=%s\n", afbClient->uri);
-
- // Close PCM and release waiting client
- afbClient->error=1;
- sem_post (&afbClient->semaphore);
-
- return 0;
-}
-
-// Call AGL binder asynchronously by with a timeout
-static int CallWithTimeout(afbClientT *afbClient, afbRequestT *afbRequest, int count, hookActionT action) {
- uint64_t usec;
- const char * apiVerb;
- int err;
-
- // create a unique tag for request
- (void) asprintf(&afbRequest->callIdTag, "%d:%s/%s", count, afbRequest->api, afbRequest->openVerb);
-
- // create a timer with ~250us accuracy
- sd_event_now(afbClient->sdLoop, CLOCK_MONOTONIC, &usec);
- sd_event_add_time(afbClient->sdLoop, &afbRequest->evtSource, CLOCK_MONOTONIC, usec+afbRequest->timeout*1000, 250, OnTimeoutCB, afbClient);
-
-
- // on PCM close replace last '}' by CLOSING_MSG
- if (action == HOOK_CLOSE) apiVerb= afbRequest->closeVerb;
- else apiVerb= afbRequest->openVerb;
-
- // release action is optional
- if (apiVerb) {
- if (afbClient->verbose) printf("CALL-REQUEST api=%s/%s tag=%s\n", afbRequest->api, apiVerb, afbRequest->callIdTag);
- err = afb_wsj1_call_s(afbClient->wsj1, afbRequest->api, apiVerb, afbRequest->query, OnResponseCB, afbRequest);
- if (err) goto OnErrorExit;
- }
- // save client handle in request
- afbRequest->afbClient = afbClient;
- afbClient->count ++;
-
- return 0;
-
-OnErrorExit:
- fprintf(stderr, "LaunchCallRequest: Fail call %s//%s/%s&%s", afbClient->uri, afbRequest->api, apiVerb, afbRequest->query);
- return 1;
-}
-
-static int LaunchCallRequest(afbClientT *afbClient, hookActionT action) {
-
- pthread_t tid;
- int err, idx;
- afbRequestT **afbRequest= afbClient->request;
-
- if (action == HOOK_INSTALL) {
- // init waiting counting semaphore
- if (sem_init(&afbClient->semaphore, 1, 0) == -1) {
- fprintf(stderr, "LaunchCallRequest: Fail Semaphore Init: %s\n", afbClient->uri);
- }
-
- // Create a main loop
- err = sd_event_default(&afbClient->sdLoop);
- if (err < 0) {
- fprintf(stderr, "LaunchCallRequest: Connection to default event loop failed: %s\n", strerror(-err));
- goto OnErrorExit;
- }
-
- // start a thread with a mainloop to monitor Audio-Agent
- err = pthread_create(&tid, NULL, &LoopInThread, afbClient);
- if (err) goto OnErrorExit;
-
- // connect the websocket wsj1 to the uri given by the first argument
- afbClient->wsj1 = afb_ws_client_connect_wsj1(afbClient->sdLoop, afbClient->uri, &itf, afbClient);
- if (afbClient->wsj1 == NULL) {
- fprintf(stderr, "LaunchCallRequest: Connection to %s failed\n", afbClient->uri);
- goto OnErrorExit;
- }
- }
-
- // send call request to audio-agent asynchronously (respond with thread mainloop context)
- for (idx = 0; afbRequest[idx] != NULL; idx++) {
- err = CallWithTimeout(afbClient, afbRequest[idx], idx, action);
- if (err) goto OnErrorExit;
- }
-
- // launch counter to keep track of waiting request call
- afbClient->count=idx;
-
- return 0;
-
-OnErrorExit:
- return -1;
-}
-
-static int AlsaCloseHook(snd_pcm_hook_t *hook) {
-
- afbClientT *afbClient = (afbClientT*) snd_pcm_hook_get_private (hook);
-
- // launch call request and create a waiting mainloop thread
- int err = LaunchCallRequest(afbClient, HOOK_CLOSE);
- if (err < 0) {
- fprintf (stderr, "PCM Fail to Enter Mainloop\n");
- goto OnErrorExit;
- }
-
- // wait for all call request to return
- sem_wait(&afbClient->semaphore);
- if (afbClient->error) {
- fprintf (stderr, "AlsaCloseHook: Notice exit before audio-4a response\n");
- goto OnErrorExit;
- }
-
- if (afbClient->verbose) fprintf(stdout, "\nAlsaHook Close Success PCM=%s URI=%s\n", snd_pcm_name(afbClient->pcm), afbClient->uri);
- return 0;
-
-OnErrorExit:
- fprintf(stderr, "\nAlsaPcmHook Plugin Close Fail PCM=%s\n", snd_pcm_name(afbClient->pcm));
- return 0;
-}
-
-// Function call when Plugin PCM is OPEN
-int PLUGIN_ENTRY_POINT (snd_pcm_t *pcm, snd_config_t *conf) {
- snd_pcm_hook_t *h_close = NULL;
- snd_config_iterator_t it, next;
- afbClientT *afbClient = malloc(sizeof (afbClientT));
- afbRequestT **afbRequest = malloc(MAX_API_CALL * sizeof(afbRequestT*));
- afbEventT **afbEvent= malloc(MAX_EVT_CALL * sizeof(afbEventT*));
- int err;
-
- // start populating client handle
- afbClient->pcm = pcm;
- afbClient->verbose = 0;
- afbClient->request = afbRequest;
-
- // Get PCM arguments from asoundrc
- snd_config_for_each(it, next, conf) {
- snd_config_t *node = snd_config_iterator_entry(it);
- const char *id;
-
- // ignore comment en empty lines
- if (snd_config_get_id(node, &id) < 0) continue;
- if (strcmp(id, "comment") == 0 || strcmp(id, "hint") == 0) continue;
-
- if (strcmp(id, "uri") == 0) {
- const char *uri;
- if (snd_config_get_string(node, &uri) < 0) {
- SNDERR("Invalid String for %s", id);
- goto OnErrorExit;
- }
- afbClient->uri=strdup(uri);
- continue;
- }
-
- if (strcmp(id, "verbose") == 0) {
- afbClient->verbose= snd_config_get_bool(node);
- if (afbClient->verbose < 0) {
- SNDERR("Invalid Boolean for %s", id);
- goto OnErrorExit;
- }
- continue;
- }
-
- if (strcmp(id, "controls") == 0) {
- const char *callConf, *callLabel;
- snd_config_type_t ctype;
- snd_config_iterator_t currentCall, follow;
- snd_config_t *itemConf;
- int callCount=0;
-
- ctype = snd_config_get_type(node);
- if (ctype != SND_CONFIG_TYPE_COMPOUND) {
- snd_config_get_string(node, &callConf);
- SNDERR("Invalid compound type for %s", callConf);
- goto OnErrorExit;
- }
-
-
- // loop on each call
- snd_config_for_each(currentCall, follow, node) {
- snd_config_t *ctlconfig = snd_config_iterator_entry(currentCall);
-
- // ignore empty line
- if (snd_config_get_id(ctlconfig, &callLabel) < 0) continue;
-
- // each clt should be a valid config compound
- ctype = snd_config_get_type(ctlconfig);
- if (ctype != SND_CONFIG_TYPE_COMPOUND) {
- snd_config_get_string(node, &callConf);
- SNDERR("Invalid call element for %s value=%s", callLabel, callConf);
- goto OnErrorExit;
- }
-
- // allocate an empty call request
- afbRequest[callCount] = calloc(1, sizeof (afbRequestT));
-
-
- err = snd_config_search(ctlconfig, "api", &itemConf);
- if (!err) {
- const char *api;
- if (snd_config_get_string(itemConf, &api) < 0) {
- SNDERR("Invalid api string for %s", callLabel);
- goto OnErrorExit;
- }
- afbRequest[callCount]->api=strdup(api);
- }
-
- err = snd_config_search(ctlconfig, "request", &itemConf);
- if (!err) {
- const char *verb;
- if (snd_config_get_string(itemConf, &verb) < 0) {
- SNDERR("Invalid open verb string %s", id);
- goto OnErrorExit;
- }
- afbRequest[callCount]->openVerb=strdup(verb);
- }
-
- err = snd_config_search(ctlconfig, "release", &itemConf);
- if (!err) {
- const char *verb;
- if (snd_config_get_string(itemConf, &verb) < 0) {
- SNDERR("Invalid close verb string %s", id);
- goto OnErrorExit;
- }
- afbRequest[callCount]->closeVerb=strdup(verb);
- }
-
- err = snd_config_search(ctlconfig, "timeout", &itemConf);
- if (!err) {
- if (snd_config_get_integer(itemConf, &afbRequest[callCount]->timeout) < 0) {
- SNDERR("Invalid timeout Integer %s", id);
- goto OnErrorExit;
- }
- }
-
- err = snd_config_search(ctlconfig, "args", &itemConf);
- if (!err) {
- const char *query;
- if (snd_config_get_string(itemConf, &query) < 0) {
- SNDERR("Invalid args string %s", id);
- goto OnErrorExit;
- }
- // reserve enough space to ad closing message
- afbRequest[callCount]->length= strlen(query);
- afbRequest[callCount]->query = malloc (afbRequest[callCount]->length+strlen(CLOSING_MSG)+1);
- strcpy (afbRequest[callCount]->query, query);
-
- // cleanup string for json_tokener
- for (int idx = 0; query[idx] != '\0'; idx++) {
- if (query[idx] == '\'') afbRequest[callCount]->query[idx] = '"';
- else afbRequest[callCount]->query[idx] = query[idx];
- }
- json_object *queryJ = json_tokener_parse(afbRequest[callCount]->query);
- if (!queryJ) {
- SNDERR("Invalid Json %s args=%s should be args=\"{'tok1':'val1', 'tok2':'val2'}\" ", id, afbRequest[callCount]->query);
- goto OnErrorExit;
- }
- }
-
- // Simple check on call request validity
- if (!afbRequest[callCount]->query) afbRequest[callCount]->query= "";
- if (!afbRequest[callCount]->timeout) afbRequest[callCount]->timeout=REQUEST_DEFAULT_TIMEOUT ;
- if (!afbRequest[callCount]->openVerb || !afbRequest[callCount]->api) {
- SNDERR("Missing api/open(verb)/close(verb) %s in asoundrc", callLabel);
- goto OnErrorExit;
- }
-
- // move to next call if any
- callCount ++;
- if (callCount == MAX_API_CALL) {
- SNDERR("Too Many call MAX_API_CALL=%d", MAX_API_CALL);
- goto OnErrorExit;
- }
- afbRequest[callCount]=NULL; // afbRequest array is NULL terminated
-
- }
- continue;
- }
- if (strcmp(id, "events") == 0) {
- const char *callConf, *callLabel;
- snd_config_type_t ctype;
- snd_config_iterator_t currentCall, follow;
- int callCount=0;
-
- ctype = snd_config_get_type(node);
- if (ctype != SND_CONFIG_TYPE_COMPOUND) {
- snd_config_get_string(node, &callConf);
- SNDERR("Invalid compound type for %s", callConf);
- goto OnErrorExit;
- }
-
-
- // loop on each call
- snd_config_for_each(currentCall, follow, node) {
- snd_config_t *ctlconfig = snd_config_iterator_entry(currentCall);
- long sigval;
-
- // ignore empty line
- if (snd_config_get_id(ctlconfig, &callLabel) < 0) continue;
-
- // each clt should be a valid config compound
- ctype = snd_config_get_type(ctlconfig);
- if (ctype != SND_CONFIG_TYPE_INTEGER) {
- snd_config_get_string(ctlconfig, &callConf);
- SNDERR("Invalid signal number for %s value=%s", callLabel, callConf);
- goto OnErrorExit;
- }
-
- // allocate an empty call request
- snd_config_get_integer(ctlconfig, &sigval);
- afbEvent[callCount] = calloc(1, sizeof (afbEventT));
- afbEvent[callCount]->name=strdup(callLabel);
- afbEvent[callCount]->signal= (int)sigval;
-
- // move to next call if any
- callCount ++;
- if (callCount == MAX_EVT_CALL) {
- SNDERR("Too Many call MAX_EVT_CALL=%d", MAX_EVT_CALL);
- goto OnErrorExit;
- }
- afbEvent[callCount]=NULL; // afbEvent array is NULL terminated
-
- }
- continue;
- }
- }
-
- if (afbClient->verbose) fprintf(stdout, "\nAlsaHook Install Start PCM=%s URI=%s\n", snd_pcm_name(afbClient->pcm), afbClient->uri);
-
- err = snd_pcm_hook_add(&h_close, afbClient->pcm, SND_PCM_HOOK_TYPE_CLOSE, AlsaCloseHook, afbClient);
- if (err < 0) goto OnErrorExit;
-
- // launch call request and create a waiting mainloop thread
- err = LaunchCallRequest(afbClient, HOOK_INSTALL);
- if (err < 0) {
- fprintf (stderr, "PCM Fail to Enter Mainloop\n");
- goto OnErrorExit;
- }
-
- // wait for all call request to return
- sem_wait(&afbClient->semaphore);
- if (afbClient->error) {
- fprintf (stderr, "PCM Authorisation Deny from AAAA Controller (AGL Advanced Audio Agent)\n");
- goto OnErrorExit;
- }
-
- if (afbClient->verbose) fprintf(stdout, "\nAlsaHook Install Success PCM=%s URI=%s\n", snd_pcm_name(afbClient->pcm), afbClient->uri);
- return 0;
-
-OnErrorExit:
- fprintf(stderr, "\nAlsaPcmHook Plugin Install Fail PCM=%s\n", snd_pcm_name(pcm));
- if (h_close)
- snd_pcm_hook_remove(h_close);
-
- return -EINVAL;
-}
-
diff --git a/hook-plugin/PolicyHookUnix.c b/hook-plugin/PolicyHookUnix.c
deleted file mode 100644
index 345ed57..0000000
--- a/hook-plugin/PolicyHookUnix.c
+++ /dev/null
@@ -1,562 +0,0 @@
-/*
- * Copyright (C) 2016 "IoT.bzh"
- * Author Fulup Ar Foll <fulup@iot.bzh>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * AfbCallBack (snd_ctl_hal_t *handle, int numid, void **response);
- * AlsaHookInit is mandatory and called with numid=0
- *
- * Syntax in .asoundrc file
- * CrlLabel { cb MyFunctionName name "My_Second_Control" }
- *
- * Testing:
- * aplay -DAlsaHook /usr/share/sounds/alsa/test.wav
- *
- * References:
- * https://www.spinics.net/lists/alsa-devel/msg54235.html
- * https://github.com/shivdasgujare/utilities/blob/master/nexuss/alsa-scenario-hook/src/alsa-wrapper.c
- */
-
-#define _GNU_SOURCE
-#include <stdio.h>
-#include <alloca.h>
-
-#include <alsa/asoundlib.h>
-#include <alsa/conf.h>
-#include <alsa/pcm.h>
-
-#include <systemd/sd-event.h>
-#include <json-c/json.h>
-
-#include "afb/afb-wsj1.h"
-#include "afb/afb-ws-client.h"
-#include "afb/afb-proto-ws.h"
-
-#include <pthread.h>
-#include <semaphore.h>
-
-
-#define PLUGIN_ENTRY_POINT AlsaInstallHook
- // Fulup Note: What ever you may find on Internet you should use
- // SND_CONFIG_DLSYM_VERSION_HOOK and not SND_CONFIG_DLSYM_VERSION_HOOK
- SND_DLSYM_BUILD_VERSION(PLUGIN_ENTRY_POINT, SND_PCM_DLSYM_VERSION)
-
-// this should be more than enough
-#define MAX_API_CALL 10
-#define MAX_EVT_CALL 10
-
-// timeout in ms
-#define REQUEST_DEFAULT_TIMEOUT 500
-#ifndef MAINLOOP_WATCHDOG
-#define MAINLOOP_WATCHDOG 100000
-#endif
-
-// closing message is added to query when PCM is closed
-#define CLOSING_MSG ",\"source\":-1}"
-
-// Currently not implemented
-#define UNUSED_ARG(x) UNUSED_ ## x __attribute__((__unused__))
-
-typedef struct {
- const char *openVerb;
- const char *closeVerb;
- json_object *queryJ;
- long timeout;
-
- sd_event_source *evtSource;
- char *callIdTag;
- void *afbClient;
-} afbRequestT;
-
-typedef struct {
- const char *name;
- int signal;
-} afbEventT;
-
-typedef struct {
- char *name;
- snd_pcm_t *pcm;
- const char *uri;
- struct afb_proto_ws *pws;
- sd_event *sdLoop;
- int verbose;
- sem_t semaphore;
- int count;
- int error;
- afbRequestT **request;
- afbEventT **event;
-} afbClientT;
-
-
-static void *LoopInThread(void *handle) {
- afbClientT *afbClient = (afbClientT*) handle;
- int count=0;
- int watchdog= MAINLOOP_WATCHDOG *1000;
-
- /* loop until end */
- for (;;) {
-
- if (afbClient->verbose) printf("ON-MAINLOOP ping=%d\n", count++);
- sd_event_run(afbClient->sdLoop, watchdog);
- }
-
- return NULL;
-}
-
-// lost connect with the AudioDaemon
-static void OnHangupCB(void *handle) {
-
- afbClientT *afbClient = (afbClientT*) handle;
- SNDERR("(Hoops) Lost Connection to %s", afbClient->uri);
-
- // try to close PCM when impossible terminate client
- int err = snd_pcm_close (afbClient->pcm);
- if (err) exit(1);
-}
-
-typedef enum {
- HOOK_INSTALL,
- HOOK_CLOSE,
-} hookActionT;
-
-void OnEventCB(void *handle, const char *event, int evtid, struct json_object *eventJ) {
- afbClientT *afbClient = (afbClientT*) handle;
- afbEventT **afbEvent = afbClient->event;
- json_object *dataJ, *tmpJ;
- const char *label;
- int value, done, index;
-
- done= json_object_object_get_ex(eventJ,"data", &dataJ);
- if (!done) {
- SNDERR ("PCM_HOOK: uri=%s empty event label", afbClient->uri);
- goto OnErrorExit;
- }
-
- json_object_object_get_ex(dataJ,"signal", &tmpJ);
- label=json_object_get_string(tmpJ);
-
- json_object_object_get_ex(dataJ,"value", &tmpJ);
- value=json_object_get_int(tmpJ);
-
- for (index=0; afbEvent[index]!= NULL; index++) {
- if (!strcmp(afbEvent[index]->name, label)) break;
- }
-
- if (!afbEvent[index] || !afbEvent[index]->signal) {
- SNDERR ("PCM_HOOK: Unsupported uri=%s label=%s", afbClient->uri, label);
- return;
- }
-
- // send signal to self process
- kill (getpid(), afbEvent[index]->signal);
-
- if (afbClient->verbose) printf("ON-EVENT label=%s signal=%d\n", label, value);
- return;
-
-OnErrorExit:
- SNDERR("ON-EVENT %s(%s)\n", event, json_object_get_string(dataJ));
- return;
-}
-
-static void OnSuccessCB(void* UNUSED_ARG(ctx) , void* handle, json_object* responseJ, const char* info) {
-
- afbRequestT *afbRequest= (afbRequestT*)handle;
- afbClientT *afbClient=(afbClientT*)afbRequest->afbClient;
-
- if (afbClient->verbose) printf("OnSuccessCB callid='%s' response='%s' info='%s'\n", afbRequest->callIdTag, json_object_get_string(responseJ), info);
-
- // Cancel timeout for this request
- sd_event_source_unref(afbRequest->evtSource);
- free(afbRequest->callIdTag);
-
- // When not more waiting call release semaphore
- afbClient->count--;
- if (afbClient->count == 0) {
- if (afbClient->verbose) printf("OnSuccessCB No More Waiting Request\n");
- afbClient->error=0;
- sem_post (&afbClient->semaphore);
- }
-}
-
-static void OnFailureCB(void* UNUSED_ARG(ctx), void* handle, const char *status, const char *info) {
-
- afbRequestT *afbRequest= (afbRequestT*)handle;
- afbClientT *afbClient=(afbClientT*)afbRequest->afbClient;
-
- if (afbClient->verbose) printf("OnFailureCB callid='%s' status='%s' info='%s'\n", afbRequest->callIdTag, status, info);
-
- // Cancel timeout for this request
- sd_event_source_unref(afbRequest->evtSource);
- free(afbRequest->callIdTag);
-
- afbClient->error=1;
- sem_post (&afbClient->semaphore);
-}
-
-
-/* the callback interface for pws */
-static struct afb_proto_ws_client_itf itf = {
- .on_reply_success = OnSuccessCB,
- .on_reply_fail = OnFailureCB,
- .on_event_create = NULL,
- .on_event_remove = NULL,
- .on_event_subscribe = NULL,
- .on_event_unsubscribe = NULL,
- .on_event_push = OnEventCB,
- .on_event_broadcast = NULL,
- .on_subcall = NULL,
-};
-
-int OnTimeoutCB (sd_event_source* source, uint64_t timer, void* handle) {
- afbClientT *afbClient= (afbClientT*)handle;
-
- SNDERR("\nON-TIMEOUT Call Request Fail URI=%s\n", afbClient->uri);
-
- // Close PCM and release waiting client
- afbClient->error=1;
- sem_post (&afbClient->semaphore);
-
- return 0;
-}
-
-// Call AGL binder asynchronously by with a timeout
-static int CallWithTimeout(afbClientT *afbClient, afbRequestT *afbRequest, int count, hookActionT action) {
- uint64_t usec;
- const char * apiVerb;
- int err;
-
- // create a unique tag for request
- (void) asprintf(&afbRequest->callIdTag, "%d:%s", count, afbRequest->openVerb);
-
- // create a timer with ~250us accuracy
- sd_event_now(afbClient->sdLoop, CLOCK_MONOTONIC, &usec);
- sd_event_add_time(afbClient->sdLoop, &afbRequest->evtSource, CLOCK_MONOTONIC, usec+afbRequest->timeout*1000, 250, OnTimeoutCB, afbClient);
-
-
- // on PCM close replace last '}' by CLOSING_MSG
- if (action == HOOK_CLOSE) apiVerb= afbRequest->closeVerb;
- else apiVerb= afbRequest->openVerb;
-
- // release action is optional
- if (apiVerb) {
- char * sessionId;
- (void) asprintf(&sessionId, "alsa-hook-pid:%d", getpid());
- if (afbClient->verbose) printf("CALL-REQUEST verb=%s tag=%s\n", apiVerb, afbRequest->callIdTag);
- err = afb_proto_ws_client_call(afbClient->pws, apiVerb, afbRequest->queryJ, sessionId, afbRequest);
- if (err < 0 ) goto OnErrorExit;
- }
- // save client handle in request
- afbRequest->afbClient = afbClient;
- afbClient->count ++;
-
- return 0;
-
-OnErrorExit:
- fprintf(stderr, "LaunchCallRequest: Fail call %s//%s&%s", afbClient->uri, apiVerb, json_object_get_string(afbRequest->queryJ));
- return 1;
-}
-
-static int LaunchCallRequest(afbClientT *afbClient, hookActionT action) {
-
- pthread_t tid;
- int err, idx;
- afbRequestT **afbRequest= afbClient->request;
-
- if (action == HOOK_INSTALL) {
- // init waiting counting semaphore
- if (sem_init(&afbClient->semaphore, 1, 0) == -1) {
- fprintf(stderr, "LaunchCallRequest: Fail Semaphore Init: %s\n", afbClient->uri);
- }
-
- // Create a main loop
- err = sd_event_default(&afbClient->sdLoop);
- if (err < 0) {
- fprintf(stderr, "LaunchCallRequest: Connection to default event loop failed: %s\n", strerror(-err));
- goto OnErrorExit;
- }
-
- // start a thread with a mainloop to monitor Audio-Agent
- err = pthread_create(&tid, NULL, &LoopInThread, afbClient);
- if (err) goto OnErrorExit;
-
- afbClient->pws = afb_ws_client_connect_api(afbClient->sdLoop, afbClient->uri, &itf, afbClient);
- if (afbClient->pws == NULL) {
- fprintf(stderr, "LaunchCallRequest: Connection to %s failed\n", afbClient->uri);
- goto OnErrorExit;
- }
-
- // register hanghup callback
- afb_proto_ws_on_hangup(afbClient->pws, OnHangupCB);
- }
-
- // send call request to audio-agent asynchronously (respond with thread mainloop context)
- for (idx = 0; afbRequest[idx] != NULL; idx++) {
- err = CallWithTimeout(afbClient, afbRequest[idx], idx, action);
- if (err) goto OnErrorExit;
- }
-
- // launch counter to keep track of waiting request call
- afbClient->count=idx;
-
- return 0;
-
-OnErrorExit:
- return -1;
-}
-
-static int AlsaCloseHook(snd_pcm_hook_t *hook) {
-
- afbClientT *afbClient = (afbClientT*) snd_pcm_hook_get_private (hook);
-
- // launch call request and create a waiting mainloop thread
- int err = LaunchCallRequest(afbClient, HOOK_CLOSE);
- if (err < 0) {
- fprintf (stderr, "PCM Fail to Enter Mainloop\n");
- goto OnErrorExit;
- }
-
- // wait for all call request to return
- sem_wait(&afbClient->semaphore);
- if (afbClient->error) {
- fprintf (stderr, "AlsaCloseHook: Notice exit before audio-4a response\n");
- goto OnErrorExit;
- }
-
- if (afbClient->verbose) fprintf(stdout, "\nAlsaHook Close Success PCM=%s URI=%s\n", snd_pcm_name(afbClient->pcm), afbClient->uri);
- return 0;
-
-OnErrorExit:
- fprintf(stderr, "\nAlsaPcmHook Plugin Close Fail PCM=%s\n", snd_pcm_name(afbClient->pcm));
- return 0;
-}
-
-// Function call when Plugin PCM is OPEN
-int PLUGIN_ENTRY_POINT (snd_pcm_t *pcm, snd_config_t *conf) {
- snd_pcm_hook_t *h_close = NULL;
- snd_config_iterator_t it, next;
- afbClientT *afbClient = malloc(sizeof (afbClientT));
- afbRequestT **afbRequest = malloc(MAX_API_CALL * sizeof(afbRequestT*));
- afbEventT **afbEvent= malloc(MAX_EVT_CALL * sizeof(afbEventT*));
- int err;
-
- // start populating client handle
- afbClient->pcm = pcm;
- afbClient->name= strdup(snd_pcm_name(pcm));
- afbClient->verbose = 0;
- afbClient->request = afbRequest;
-
- // Get PCM arguments from asoundrc
- snd_config_for_each(it, next, conf) {
- snd_config_t *node = snd_config_iterator_entry(it);
- const char *id;
-
- // ignore comment en empty lines
- if (snd_config_get_id(node, &id) < 0) continue;
- if (strcmp(id, "comment") == 0 || strcmp(id, "hint") == 0) continue;
-
- if (strcmp(id, "ws-client") == 0) {
- const char *uri;
- if (snd_config_get_string(node, &uri) < 0) {
- SNDERR("Invalid String for %s", id);
- goto OnErrorExit;
- }
- afbClient->uri=strdup(uri);
- continue;
- }
-
- if (strcmp(id, "verbose") == 0) {
- afbClient->verbose= snd_config_get_bool(node);
- if (afbClient->verbose < 0) {
- SNDERR("Invalid Boolean for %s", id);
- goto OnErrorExit;
- }
- continue;
- }
-
- if (strcmp(id, "controls") == 0) {
- const char *callConf, *callLabel;
- snd_config_type_t ctype;
- snd_config_iterator_t currentCall, follow;
- snd_config_t *itemConf;
- int callCount=0;
-
- ctype = snd_config_get_type(node);
- if (ctype != SND_CONFIG_TYPE_COMPOUND) {
- snd_config_get_string(node, &callConf);
- SNDERR("Invalid compound type for %s", callConf);
- goto OnErrorExit;
- }
-
- // loop on each call
- snd_config_for_each(currentCall, follow, node) {
- snd_config_t *ctlconfig = snd_config_iterator_entry(currentCall);
-
- // ignore empty line
- if (snd_config_get_id(ctlconfig, &callLabel) < 0) continue;
-
- // each clt should be a valid config compound
- ctype = snd_config_get_type(ctlconfig);
- if (ctype != SND_CONFIG_TYPE_COMPOUND) {
- snd_config_get_string(node, &callConf);
- SNDERR("Invalid call element for %s value=%s", callLabel, callConf);
- goto OnErrorExit;
- }
-
- // allocate an empty call request
- afbRequest[callCount] = calloc(1, sizeof (afbRequestT));
-
- err = snd_config_search(ctlconfig, "request", &itemConf);
- if (!err) {
- const char *verb;
- if (snd_config_get_string(itemConf, &verb) < 0) {
- SNDERR("Invalid open verb string %s", id);
- goto OnErrorExit;
- }
- afbRequest[callCount]->openVerb=strdup(verb);
- }
-
- err = snd_config_search(ctlconfig, "release", &itemConf);
- if (!err) {
- const char *verb;
- if (snd_config_get_string(itemConf, &verb) < 0) {
- SNDERR("Invalid close verb string %s", id);
- goto OnErrorExit;
- }
- afbRequest[callCount]->closeVerb=strdup(verb);
- }
-
- err = snd_config_search(ctlconfig, "timeout", &itemConf);
- if (!err) {
- if (snd_config_get_integer(itemConf, &afbRequest[callCount]->timeout) < 0) {
- SNDERR("Invalid timeout Integer %s", id);
- goto OnErrorExit;
- }
- }
-
- err = snd_config_search(ctlconfig, "args", &itemConf);
- if (!err) {
- char *query;
- if (snd_config_get_string(itemConf, (const char**) &query) < 0) {
- SNDERR("Invalid args string %s", id);
- goto OnErrorExit;
- }
-
- // cleanup string for json_tokener
- for (int idx = 0; query[idx] != '\0'; idx++) {
- if (query[idx] == '\'') query[idx] = '"';
- }
- afbRequest[callCount]->queryJ = json_tokener_parse(query);
- if (!afbRequest[callCount]->queryJ) {
- SNDERR("Invalid Json %s args=%s should be args=\"{'tok1':'val1', 'tok2':'val2'}\" ", id, query);
- goto OnErrorExit;
- }
- }
-
- // Simple check on call request validity
- if (!afbRequest[callCount]->timeout) afbRequest[callCount]->timeout=REQUEST_DEFAULT_TIMEOUT ;
- if (!afbRequest[callCount]->openVerb || !afbRequest[callCount]->closeVerb) {
- SNDERR("Missing open(verb)/close(verb) %s in asoundrc", callLabel);
- goto OnErrorExit;
- }
-
- // move to next call if any
- callCount ++;
- if (callCount == MAX_API_CALL) {
- SNDERR("Too Many call MAX_API_CALL=%d", MAX_API_CALL);
- goto OnErrorExit;
- }
- afbRequest[callCount]=NULL; // afbRequest array is NULL terminated
-
- }
- continue;
- }
- if (strcmp(id, "events") == 0) {
- const char *callConf, *callLabel;
- snd_config_type_t ctype;
- snd_config_iterator_t currentCall, follow;
- int callCount=0;
-
- ctype = snd_config_get_type(node);
- if (ctype != SND_CONFIG_TYPE_COMPOUND) {
- snd_config_get_string(node, &callConf);
- SNDERR("Invalid compound type for %s", callConf);
- goto OnErrorExit;
- }
-
-
- // loop on each call
- snd_config_for_each(currentCall, follow, node) {
- snd_config_t *ctlconfig = snd_config_iterator_entry(currentCall);
- long sigval;
-
- // ignore empty line
- if (snd_config_get_id(ctlconfig, &callLabel) < 0) continue;
-
- // each clt should be a valid config compound
- ctype = snd_config_get_type(ctlconfig);
- if (ctype != SND_CONFIG_TYPE_INTEGER) {
- snd_config_get_string(ctlconfig, &callConf);
- SNDERR("Invalid signal number for %s value=%s", callLabel, callConf);
- goto OnErrorExit;
- }
-
- // allocate an empty call request
- snd_config_get_integer(ctlconfig, &sigval);
- afbEvent[callCount] = calloc(1, sizeof (afbEventT));
- afbEvent[callCount]->name=strdup(callLabel);
- afbEvent[callCount]->signal= (int)sigval;
-
- // move to next call if any
- callCount ++;
- if (callCount == MAX_EVT_CALL) {
- SNDERR("Too Many call MAX_EVT_CALL=%d", MAX_EVT_CALL);
- goto OnErrorExit;
- }
- afbEvent[callCount]=NULL; // afbEvent array is NULL terminated
-
- }
- continue;
- }
- }
-
- if (afbClient->verbose) fprintf(stdout, "\nAlsaHook Install Start PCM=%s URI=%s\n", snd_pcm_name(afbClient->pcm), afbClient->uri);
-
- err = snd_pcm_hook_add(&h_close, afbClient->pcm, SND_PCM_HOOK_TYPE_CLOSE, AlsaCloseHook, afbClient);
- if (err < 0) goto OnErrorExit;
-
- // launch call request and create a waiting mainloop thread
- err = LaunchCallRequest(afbClient, HOOK_INSTALL);
- if (err < 0) {
- fprintf (stderr, "PCM Fail to Enter Mainloop\n");
- goto OnErrorExit;
- }
-
- // wait for all call request to return
- sem_wait(&afbClient->semaphore);
- if (afbClient->error) {
- fprintf (stderr, "PCM Authorisation Deny from AAAA Controller (AGL Advanced Audio Agent)\n");
- goto OnErrorExit;
- }
-
- if (afbClient->verbose) fprintf(stdout, "\nAlsaHook Install Success PCM=%s URI=%s\n", afbClient->name, afbClient->uri);
- return 0;
-
-OnErrorExit:
- fprintf(stderr, "\nAlsaPcmHook Plugin Policy Control Fail PCM=%s\n", afbClient->name);
- if (h_close)
- snd_pcm_hook_remove(h_close);
-
- return -EINVAL;
-}
-
diff --git a/hook-plugin/README.md b/hook-plugin/README.md
deleted file mode 100644
index 3846e0b..0000000
--- a/hook-plugin/README.md
+++ /dev/null
@@ -1,121 +0,0 @@
-Alsa-Hook-Plugin
-
-Object: Provide a Hook on Alsa PCM to check permission again AGL Advance Audio Agent
-Status: Release Candidate
-Author: Fulup Ar Foll fulup@iot.bzh
-Date : August-2017
-
-Functionalities:
- - Execute a set of unix/ws RPC request again AGL binders to allow/deny access
- - Keep websocket open in an idependant thread in order to monitor event received from AGL audio agent
-
-Installation
- - Alsaplugins are typically search in /usr/share/alsa-lib. Nevertheless a full path might be given
- - This plugin implement a hook on a slave PCM. Typically this slave PCM is a dedicated virtual channel (eg: navigation, emergency,...)
- - Config should be place in ~/.asoundrc (see config sample in PROJECT_ROOT/conf.d/alsa)
-
-Test
- - Install a full .asoundrc from conf.d/project/alsa.d
- - speaker-test -DMyNavigationHook -c2 -twav
-
-Config
-```
-#
-# Author: Fulup Ar Foll
-# Object: PCM hook type
-#
-# Test : Note: Jabra_USB=hw:v1340
-# Check SoundCard ==> speaker-test -Dhw:v1340 -c2 -twav
-# Check MixerPCM ==> speaker-test -DSpeakers -c2 -twav
-# Check SoftVol ==> speaker-test -DMusicPCM -c2 -twav
-# Check Plugin ==> speaker-test -DMultimedia -c2 -twav
-# MultiMedia aplay -DDMyNavPCM /usr/share/sounds/alsa/test.wav
-#
-# Bug/Feature: when softvol control is initialised from plugin and not
-# from AGL binding. At 1st run ctl has invalid TLV and cannot be
-# use. Bypass Solution:
-# * start audio-binder before playing sound (binding create control before softvol plugin)
-# * run a dummy aplay -DMyNavPCM "" to get a clean control
-#
-# References: https://www.spinics.net/lists/alsa-devel/msg54235.html
-# --------------------------------------------------------------------
-
-# ------------------------------------------------------
-# Mixer PCM allow to play multiple stream simultaneously
-# ------------------------------------------------------
-pcm.Speakers {
- type dmix
- slave {pcm "hw:v1340"} #Jabra Solmate 1
- ipc_key 1001 # ipc_key should be unique to each dmix
-}
-
-# -----------------------------------------------------
-# Register ControllerHookPlugin (ToiBeFix fullpath)
-# -----------------------------------------------------
-pcm_hook_type.CtlHookPlugin {
- install "AlsaInstallHook"
- lib "/home/fulup/Workspace/Audio-4a/alsa-4a/build/hook-plugin/policy_hook_tcp.so"
- #lib "/home/fulup/Workspace/Audio-4a/alsa-4a/build/hook-plugin/policy_hook_unix.so"
-}
-
-
-# -------------------------------------------------------
-# Define one Audio Virtual Channel per Audio Roles
-# -------------------------------------------------------
-pcm.MusicPCM {
- type softvol
-
- # Point Slave on HOOK for policies control
- slave.pcm "Speakers"
-
- # name should match with HAL definition
- control.name "Playback Multimedia"
-}
-
-# ----------------------------------------------------
-# Define one hooked PCM channel per Audio Roles
-# ----------------------------------------------------
-pcm.Multimedia {
- type hooks
- slave {pcm "MusicPCM"}
- hooks.0 {
- comment "Defined used hook sharelib and provide arguments/config to install func"
- type "CtlHookPlugin"
- hook_args {
-
- # print few log messages (default false)
- verbose true
-
- # uri to audio-4a policy engine
- uri="ws://localhost:1234/api?token='audio-agent-token'"
- #ws-client="unix:/var/tmp/pol4a"
-
- # api subcall to request a role
- controls {
- # Request authorisation to write on navigation
- navigation-ctl {
- request "multimedia-role"
- release "release-role"
- args "{'uid':'alsa-hook-navigation'}"
- }
- }
- events { # map event reception to self generated signal
- pause 30
- resume 31
- stop 3
- }
- }
- }
-}
-
-
-```
-
-NOTE:
-
-* Hook plugin is loaded by Alsa libasound within client context. It inherits client process attributes, as UID/GID and
-SMACK label when running on AGL. The smack label is control by AGL security framework.
-As a result a control request succeeds only when client application permission match requested audio role inside Cynara security database.
-
-* Hook plugin keep a connection with the Audio-Agent until PCM is closed by the application. This connection allow the
-Audio-Agent to send events. eg: pause, quit, mute, ... \ No newline at end of file
diff --git a/nbproject/configurations.xml b/nbproject/configurations.xml
index 8977e53..07e636e 100644
--- a/nbproject/configurations.xml
+++ b/nbproject/configurations.xml
@@ -13,6 +13,10 @@
<in>Alsa-SetGet.c</in>
<in>Alsa-Ucm.c</in>
</df>
+ <df name="alsa-hook">
+ <in>PolicyAlsaHook.c</in>
+ <in>PolicyHookTcp.c</in>
+ </df>
<df name="Audio-Common">
<in>audio-common.c</in>
<in>filescan-utils.c</in>
@@ -70,9 +74,6 @@
<in>HighLevelApiConf.c</in>
<in>HighLevelBinding.c</in>
</df>
- <df name="hook-plugin">
- <in>PolicyHookCb.c</in>
- </df>
<df name="MostVolume">
<df name="external">
<in>ConnectionInfo.cpp</in>
@@ -126,10 +127,10 @@
<makefileType>
<makeTool>
<buildCommandWorkingDir>build</buildCommandWorkingDir>
- <buildCommand>${MAKE} -f Makefile install</buildCommand>
+ <buildCommand>${MAKE} -f Makefile</buildCommand>
<cleanCommand>${MAKE} -f Makefile clean</cleanCommand>
<executablePath>build/CMakeFiles/feature_tests.bin</executablePath>
- <cTool flags="0">
+ <cTool flags="2">
</cTool>
</makeTool>
<preBuild>
@@ -141,9 +142,7 @@
<item path="Audio-Common/audio-common.c" ex="false" tool="0" flavor2="3">
<cTool flags="2">
<incDir>
- <pElem>../../../opt/include/afb</pElem>
<pElem>Audio-Common</pElem>
- <pElem>/usr/include/json-c</pElem>
<pElem>build/Audio-Common</pElem>
</incDir>
</cTool>
@@ -151,10 +150,7 @@
<item path="Audio-Common/filescan-utils.c" ex="false" tool="0" flavor2="3">
<cTool flags="0">
<incDir>
- <pElem>../../../opt/include</pElem>
- <pElem>../../../opt/include/alsa</pElem>
<pElem>/usr/include/p11-kit-1</pElem>
- <pElem>/usr/include/json-c</pElem>
<pElem>/usr/include/lua5.3</pElem>
<pElem>Audio-Common</pElem>
<pElem>build/Audio-Common</pElem>
@@ -182,7 +178,6 @@
<cTool flags="2">
<incDir>
<pElem>Audio-Common</pElem>
- <pElem>/usr/include/json-c</pElem>
<pElem>build/Audio-Common</pElem>
</incDir>
</cTool>
@@ -194,10 +189,7 @@
<item path="Controller-afb/ctl-binding.c" ex="false" tool="0" flavor2="3">
<cTool flags="0">
<incDir>
- <pElem>../../../opt/include</pElem>
- <pElem>../../../opt/include/alsa</pElem>
<pElem>/usr/include/p11-kit-1</pElem>
- <pElem>/usr/include/json-c</pElem>
<pElem>/usr/include/lua5.3</pElem>
<pElem>Audio-Common</pElem>
<pElem>build/Controller-afb</pElem>
@@ -225,10 +217,7 @@
<item path="Controller-afb/ctl-dispatch.c" ex="false" tool="0" flavor2="3">
<cTool flags="0">
<incDir>
- <pElem>../../../opt/include</pElem>
- <pElem>../../../opt/include/alsa</pElem>
<pElem>/usr/include/p11-kit-1</pElem>
- <pElem>/usr/include/json-c</pElem>
<pElem>/usr/include/lua5.3</pElem>
<pElem>Audio-Common</pElem>
<pElem>build/Controller-afb</pElem>
@@ -256,10 +245,7 @@
<item path="Controller-afb/ctl-lua.c" ex="false" tool="0" flavor2="3">
<cTool flags="0">
<incDir>
- <pElem>../../../opt/include</pElem>
- <pElem>../../../opt/include/alsa</pElem>
<pElem>/usr/include/p11-kit-1</pElem>
- <pElem>/usr/include/json-c</pElem>
<pElem>/usr/include/lua5.3</pElem>
<pElem>Audio-Common</pElem>
<pElem>build/Controller-afb</pElem>
@@ -287,9 +273,7 @@
<item path="Controller-afb/ctl-misc.c" ex="false" tool="0" flavor2="3">
<cTool flags="2">
<incDir>
- <pElem>../../../opt/include/afb</pElem>
<pElem>Controller-afb</pElem>
- <pElem>/usr/include/json-c</pElem>
<pElem>build/Controller-afb</pElem>
</incDir>
</cTool>
@@ -297,10 +281,7 @@
<item path="Controller-afb/ctl-plugin-sample.c" ex="false" tool="0" flavor2="3">
<cTool flags="0">
<incDir>
- <pElem>../../../opt/include</pElem>
- <pElem>../../../opt/include/alsa</pElem>
<pElem>/usr/include/p11-kit-1</pElem>
- <pElem>/usr/include/json-c</pElem>
<pElem>/usr/include/lua5.3</pElem>
<pElem>Audio-Common</pElem>
<pElem>build/Controller-afb</pElem>
@@ -328,10 +309,7 @@
<item path="Controller-afb/ctl-timer.c" ex="false" tool="0" flavor2="3">
<cTool flags="0">
<incDir>
- <pElem>../../../opt/include</pElem>
- <pElem>../../../opt/include/alsa</pElem>
<pElem>/usr/include/p11-kit-1</pElem>
- <pElem>/usr/include/json-c</pElem>
<pElem>/usr/include/lua5.3</pElem>
<pElem>Audio-Common</pElem>
<pElem>build/Controller-afb</pElem>
@@ -533,13 +511,60 @@
</incDir>
</cTool>
</item>
- <folder path="0/Common">
+ <item path="alsa-hook/PolicyAlsaHook.c" ex="false" tool="0" flavor2="3">
+ <cTool flags="0">
+ <incDir>
+ <pElem>/usr/include/json-c</pElem>
+ <pElem>../../../opt/include</pElem>
+ <pElem>/usr/include/p11-kit-1</pElem>
+ <pElem>../../../opt/include/alsa</pElem>
+ <pElem>build/alsa-hook</pElem>
+ </incDir>
+ <preprocessorList>
+ <Elem>CONTROL_MAXPATH_LEN=255</Elem>
+ <Elem>MAX_LINEAR_DB_SCALE=24</Elem>
+ <Elem>MAX_SND_CARD=16</Elem>
+ <Elem>NATIVE_LINUX</Elem>
+ <Elem>PIC</Elem>
+ <Elem>TLV_BYTE_SIZE=256</Elem>
+ <Elem>policy_alsa_hook_EXPORTS</Elem>
+ </preprocessorList>
+ </cTool>
+ </item>
+ <item path="alsa-hook/PolicyHookTcp.c" ex="false" tool="0" flavor2="3">
+ <cTool flags="2">
+ <incDir>
+ <pElem>alsa-hook</pElem>
+ <pElem>../../../opt/include/alsa</pElem>
+ <pElem>/usr/include/json-c</pElem>
+ <pElem>../../../opt/include/afb</pElem>
+ <pElem>../../../opt/include</pElem>
+ <pElem>build/alsa-hook</pElem>
+ </incDir>
+ </cTool>
+ </item>
+ <folder path="0/Audio-Common">
<cTool>
<incDir>
+ <pElem>alsa-hook</pElem>
+ <pElem>../../../opt/include/alsa</pElem>
+ <pElem>/usr/include/json-c</pElem>
+ <pElem>../../../opt/include/afb</pElem>
<pElem>../../../opt/include</pElem>
+ <pElem>build/alsa-hook</pElem>
+ </incDir>
+ </cTool>
+ </folder>
+ <folder path="0/Common">
+ <cTool>
+ <incDir>
+ <pElem>alsa-hook</pElem>
<pElem>../../../opt/include/alsa</pElem>
- <pElem>/usr/include/p11-kit-1</pElem>
<pElem>/usr/include/json-c</pElem>
+ <pElem>../../../opt/include/afb</pElem>
+ <pElem>../../../opt/include</pElem>
+ <pElem>build/alsa-hook</pElem>
+ <pElem>/usr/include/p11-kit-1</pElem>
<pElem>/usr/include/lua5.3</pElem>
<pElem>Audio-Common</pElem>
<pElem>build/Controller-afb</pElem>
@@ -567,13 +592,28 @@
</preprocessorList>
</cTool>
</folder>
- <folder path="0/HAL-afb">
+ <folder path="0/Controller-afb">
<cTool>
<incDir>
+ <pElem>alsa-hook</pElem>
+ <pElem>../../../opt/include/alsa</pElem>
+ <pElem>/usr/include/json-c</pElem>
+ <pElem>../../../opt/include/afb</pElem>
<pElem>../../../opt/include</pElem>
+ <pElem>build/alsa-hook</pElem>
+ </incDir>
+ </cTool>
+ </folder>
+ <folder path="0/HAL-afb">
+ <cTool>
+ <incDir>
+ <pElem>alsa-hook</pElem>
<pElem>../../../opt/include/alsa</pElem>
- <pElem>/usr/include/p11-kit-1</pElem>
<pElem>/usr/include/json-c</pElem>
+ <pElem>../../../opt/include/afb</pElem>
+ <pElem>../../../opt/include</pElem>
+ <pElem>build/alsa-hook</pElem>
+ <pElem>/usr/include/p11-kit-1</pElem>
<pElem>/usr/include/lua5.3</pElem>
</incDir>
<preprocessorList>
@@ -595,7 +635,6 @@
<folder path="0/HAL-afb/HAL-interface">
<cTool>
<incDir>
- <pElem>../../../opt/include/afb</pElem>
<pElem>HAL-afb/HAL-interface</pElem>
</incDir>
</cTool>
@@ -606,7 +645,6 @@
<pElem>Audio-Common</pElem>
<pElem>build/Controller-afb</pElem>
<pElem>build/HAL-afb/HAL-plugin</pElem>
- <pElem>../../../opt/include/afb</pElem>
<pElem>HAL-afb/HAL-plugin</pElem>
</incDir>
<preprocessorList>
@@ -620,7 +658,6 @@
<folder path="0/HAL-afb/HDA-intel">
<cTool>
<incDir>
- <pElem>../../../opt/include/afb</pElem>
<pElem>HAL-afb/HDA-intel</pElem>
<pElem>Audio-Common</pElem>
<pElem>HAL-afb/HAL-interface</pElem>
@@ -632,7 +669,6 @@
<cTool>
<incDir>
<pElem>HAL-afb/Jabra-Solemate</pElem>
- <pElem>../../../opt/include/afb</pElem>
<pElem>Audio-Common</pElem>
<pElem>HAL-afb/HAL-interface</pElem>
<pElem>build/HAL-afb/Jabra-Solemate</pElem>
@@ -642,7 +678,6 @@
<folder path="0/HAL-afb/Scarlett-Focusrite">
<cTool>
<incDir>
- <pElem>../../../opt/include/afb</pElem>
<pElem>HAL-afb/Scarlett-Focusrite</pElem>
<pElem>Audio-Common</pElem>
<pElem>HAL-afb/HAL-interface</pElem>
@@ -656,7 +691,6 @@
<pElem>Audio-Common</pElem>
<pElem>build/Controller-afb</pElem>
<pElem>build/HAL-afb/HAL-plugin</pElem>
- <pElem>../../../opt/include/afb</pElem>
<pElem>HAL-afb/Unicens-USB</pElem>
</incDir>
<preprocessorList>
@@ -670,15 +704,17 @@
<folder path="0/HighLevel-afb">
<cTool>
<incDir>
- <pElem>../../../opt/include</pElem>
+ <pElem>alsa-hook</pElem>
<pElem>../../../opt/include/alsa</pElem>
- <pElem>/usr/include/p11-kit-1</pElem>
<pElem>/usr/include/json-c</pElem>
+ <pElem>../../../opt/include/afb</pElem>
+ <pElem>../../../opt/include</pElem>
+ <pElem>build/alsa-hook</pElem>
+ <pElem>/usr/include/p11-kit-1</pElem>
<pElem>/usr/include/lua5.3</pElem>
<pElem>Audio-Common</pElem>
<pElem>build/Controller-afb</pElem>
<pElem>build/HAL-afb/HAL-plugin</pElem>
- <pElem>../../../opt/include/afb</pElem>
<pElem>HighLevel-afb</pElem>
<pElem>Shared-Interface</pElem>
<pElem>build/HighLevel-afb</pElem>
@@ -704,10 +740,13 @@
<folder path="0/MostVolume">
<cTool>
<incDir>
- <pElem>../../../opt/include</pElem>
+ <pElem>alsa-hook</pElem>
<pElem>../../../opt/include/alsa</pElem>
- <pElem>/usr/include/p11-kit-1</pElem>
<pElem>/usr/include/json-c</pElem>
+ <pElem>../../../opt/include/afb</pElem>
+ <pElem>../../../opt/include</pElem>
+ <pElem>build/alsa-hook</pElem>
+ <pElem>/usr/include/p11-kit-1</pElem>
<pElem>/usr/include/lua5.3</pElem>
<pElem>Audio-Common</pElem>
<pElem>build/Controller-afb</pElem>
@@ -739,30 +778,6 @@
</incDir>
</cTool>
</folder>
- <folder path="0/hook-plugin">
- <cTool>
- <incDir>
- <pElem>/usr/include/json-c</pElem>
- <pElem>../../../opt/include</pElem>
- <pElem>/usr/include/p11-kit-1</pElem>
- <pElem>../../../opt/include/alsa</pElem>
- <pElem>build/hook-plugin</pElem>
- </incDir>
- <preprocessorList>
- <Elem>CONTROL_MAXPATH_LEN=255</Elem>
- <Elem>MAX_LINEAR_DB_SCALE=24</Elem>
- <Elem>MAX_SND_CARD=16</Elem>
- <Elem>NATIVE_LINUX</Elem>
- <Elem>PIC</Elem>
- <Elem>TLV_BYTE_SIZE=256</Elem>
- <Elem>policy_hook_cb_EXPORTS</Elem>
- </preprocessorList>
- </cTool>
- </folder>
- <item path="hook-plugin/PolicyHookCb.c" ex="false" tool="0" flavor2="3">
- <cTool flags="0">
- </cTool>
- </item>
</conf>
<conf name="Local_Alias" type="0">
<toolsSet>