2 * Copyright (C) 2016, 2017 "IoT.bzh"
3 * Author: José Bollo <jose.bollo@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
23 #include <json-c/json.h>
24 #include <afb/afb-event-itf.h>
26 #include "afb-subcall.h"
27 #include "afb-msg-json.h"
28 #include "afb-apiset.h"
29 #include "afb-context.h"
37 struct afb_xreq *caller;
38 void (*callback)(void*, int, struct json_object*);
42 static void subcall_destroy(struct afb_xreq *xreq)
44 struct subcall *subcall = CONTAINER_OF_XREQ(struct subcall, xreq);
46 json_object_put(subcall->xreq.json);
47 afb_cred_unref(subcall->xreq.cred);
48 afb_xreq_unref(subcall->caller);
52 static void subcall_reply(struct afb_xreq *xreq, int iserror, struct json_object *obj)
54 struct subcall *subcall = CONTAINER_OF_XREQ(struct subcall, xreq);
56 subcall->callback(subcall->closure, iserror, obj);
60 static int subcall_subscribe(struct afb_xreq *xreq, struct afb_event event)
62 struct subcall *subcall = CONTAINER_OF_XREQ(struct subcall, xreq);
64 return afb_xreq_subscribe(subcall->caller, event);
67 static int subcall_unsubscribe(struct afb_xreq *xreq, struct afb_event event)
69 struct subcall *subcall = CONTAINER_OF_XREQ(struct subcall, xreq);
71 return afb_xreq_unsubscribe(subcall->caller, event);
74 const struct afb_xreq_query_itf afb_subcall_xreq_itf = {
75 .reply = subcall_reply,
76 .unref = subcall_destroy,
77 .subscribe = subcall_subscribe,
78 .unsubscribe = subcall_unsubscribe
82 struct afb_xreq *caller,
85 struct json_object *args,
86 void (*callback)(void*, int, struct json_object*),
90 struct subcall *subcall;
91 size_t lenapi, lenverb;
94 lenapi = 1 + strlen(api);
95 lenverb = 1 + strlen(verb);
96 subcall = malloc(lenapi + lenverb + sizeof *subcall);
97 if (subcall == NULL) {
98 json_object_put(args); /* keep args existing */
99 callback(closure, 1, afb_msg_json_internal_error());
101 afb_xreq_init(&subcall->xreq, &afb_subcall_xreq_itf);
102 afb_context_subinit(&subcall->xreq.context, &caller->context);
103 subcall->xreq.cred = afb_cred_addref(caller->cred);
104 subcall->xreq.json = args;
105 copy = (char*)&subcall[1];
106 memcpy(copy, api, lenapi);
107 subcall->xreq.api = copy;
108 copy = ©[lenapi];
109 memcpy(copy, verb, lenverb);
110 subcall->xreq.verb = copy;
111 subcall->caller = caller;
112 subcall->callback = callback;
113 subcall->closure = closure;
114 afb_xreq_addref(caller);
115 afb_xreq_process(&subcall->xreq, caller->apiset);