explicit use of json-c
[src/app-framework-binder.git] / src / afb-ws-json.c
1 /*
2  * Copyright 2016 IoT.bzh
3  * Author: José Bollo <jose.bollo@iot.bzh>
4  *
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
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17
18 #define _GNU_SOURCE
19
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <assert.h>
23 #include <errno.h>
24 #include <string.h>
25
26 #include <json-c/json.h>
27
28 #include "afb-ws.h"
29 #include "afb-ws-json.h"
30 #include "afb-msg-json.h"
31 #include "session.h"
32 #include "afb-req-itf.h"
33 #include "afb-apis.h"
34 #include "afb-context.h"
35
36 static void aws_on_hangup(struct afb_ws_json *ws);
37 static void aws_on_text(struct afb_ws_json *ws, char *text, size_t size);
38
39 static struct afb_ws_itf aws_itf = {
40         .on_hangup = (void*)aws_on_hangup,
41         .on_text = (void*)aws_on_text
42 };
43
44 struct afb_wsreq;
45
46 struct afb_ws_json
47 {
48         void (*cleanup)(void*);
49         void *cleanup_closure;
50         struct afb_wsreq *requests;
51         struct AFB_clientCtx *session;
52         struct json_tokener *tokener;
53         struct afb_ws *ws;
54 };
55
56 static void aws_send_event(struct afb_ws_json *ws, const char *event, struct json_object *object);
57
58 static const struct afb_event_listener_itf event_listener_itf = {
59         .send = (void*)aws_send_event
60 };
61
62 struct afb_ws_json *afb_ws_json_create(int fd, struct AFB_clientCtx *session, void (*cleanup)(void*), void *cleanup_closure)
63 {
64         struct afb_ws_json *result;
65
66         assert(fd >= 0);
67         assert(session != NULL);
68
69         result = malloc(sizeof * result);
70         if (result == NULL)
71                 goto error;
72
73         result->cleanup = cleanup;
74         result->cleanup_closure = cleanup_closure;
75         result->requests = NULL;
76         result->session = ctxClientAddRef(session);
77         if (result->session == NULL)
78                 goto error2;
79
80         result->tokener = json_tokener_new();
81         if (result->tokener == NULL)
82                 goto error3;
83
84         result->ws = afb_ws_create(fd, &aws_itf, result);
85         if (result->ws == NULL)
86                 goto error4;
87
88         if (0 > ctxClientEventListenerAdd(result->session, (struct afb_event_listener){ .itf = &event_listener_itf, .closure = result }))
89                 goto error5;
90
91         return result;
92
93 error5:
94         afb_ws_destroy(result->ws);
95 error4:
96         json_tokener_free(result->tokener);
97 error3:
98         ctxClientUnref(result->session);
99 error2:
100         free(result);
101 error:
102         close(fd);
103         return NULL;
104 }
105
106 static void aws_on_hangup(struct afb_ws_json *ws)
107 {
108         ctxClientEventListenerRemove(ws->session, (struct afb_event_listener){ .itf = &event_listener_itf, .closure = ws });
109         afb_ws_destroy(ws->ws);
110         json_tokener_free(ws->tokener);
111         if (ws->cleanup != NULL)
112                 ws->cleanup(ws->cleanup_closure);
113         ctxClientUnref(ws->session);
114         free(ws);
115 }
116
117 #define CALL 2
118 #define RETOK 3
119 #define RETERR 4
120 #define EVENT 5
121
122 struct afb_wsreq
123 {
124         struct afb_context context;
125         int refcount;
126         struct afb_ws_json *aws;
127         struct afb_wsreq *next;
128         char *text;
129         size_t size;
130         int code;
131         char *id;
132         size_t idlen;
133         char *api;
134         size_t apilen;
135         char *verb;
136         size_t verblen;
137         char *obj;
138         size_t objlen;
139         char *tok;
140         size_t toklen;
141         struct json_object *root;
142 };
143
144 static void wsreq_addref(struct afb_wsreq *wsreq);
145 static void wsreq_unref(struct afb_wsreq *wsreq);
146 static struct json_object *wsreq_json(struct afb_wsreq *wsreq);
147 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name);
148 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info);
149 static void wsreq_success(struct afb_wsreq *wsreq, struct json_object *obj, const char *info);
150 static const char *wsreq_raw(struct afb_wsreq *wsreq, size_t *size);
151 static void wsreq_send(struct afb_wsreq *wsreq, const char *buffer, size_t size);
152
153
154 static const struct afb_req_itf wsreq_itf = {
155         .json = (void*)wsreq_json,
156         .get = (void*)wsreq_get,
157         .success = (void*)wsreq_success,
158         .fail = (void*)wsreq_fail,
159         .raw = (void*)wsreq_raw,
160         .send = (void*)wsreq_send,
161         .context_get = (void*)afb_context_get,
162         .context_set = (void*)afb_context_set,
163         .addref = (void*)wsreq_addref,
164         .unref = (void*)wsreq_unref
165 };
166
167 static int aws_wsreq_parse(struct afb_wsreq *r, char *text, size_t size)
168 {
169         char *pos, *end, c;
170         int aux;
171
172         /* scan */
173         pos = text;
174         end = text + size;
175
176         /* scans: [ */
177         while(pos < end && *pos == ' ') pos++;
178         if (pos == end) goto bad_header;
179         if (*pos++ != '[') goto bad_header;
180
181         /* scans code: 2|3|4 */
182         while(pos < end && *pos == ' ') pos++;
183         if (pos == end) goto bad_header;
184         switch (*pos++) {
185         case '2': r->code = CALL; break;
186         case '3': r->code = RETOK; break;
187         case '4': r->code = RETERR; break;
188         default: goto bad_header;
189         }
190
191         /* scans: , */
192         while(pos < end && *pos == ' ') pos++;
193         if (pos == end) goto bad_header;
194         if (*pos++ != ',') goto bad_header;
195
196         /* scans id: "id" */
197         while(pos < end && *pos == ' ') pos++;
198         if (pos == end) goto bad_header;
199         if (*pos++ != '"') goto bad_header;
200         r->id = pos;
201         while(pos < end && *pos != '"') pos++;
202         if (pos == end) goto bad_header;
203         r->idlen = (size_t)(pos++ - r->id);
204
205         /* scans: , */
206         while(pos < end && *pos == ' ') pos++;
207         if (pos == end) goto bad_header;
208         if (*pos++ != ',') goto bad_header;
209
210         /* scans the method if needed */
211         if (r->code == CALL) {
212                 /* scans: " */
213                 while(pos < end && *pos == ' ') pos++;
214                 if (pos == end) goto bad_header;
215                 if (*pos++ != '"') goto bad_header;
216
217                 /* scans: api/ */
218                 r->api = pos;
219                 while(pos < end && *pos != '"' && *pos != '/') pos++;
220                 if (pos == end) goto bad_header;
221                 if (*pos != '/') goto bad_header;
222                 r->apilen = (size_t)(pos++ - r->api);
223                 if (r->apilen && r->api[r->apilen - 1] == '\\')
224                         r->apilen--;
225
226                 /* scans: verb" */
227                 r->verb = pos;
228                 while(pos < end && *pos != '"') pos++;
229                 if (pos == end) goto bad_header;
230                 r->verblen = (size_t)(pos++ - r->verb);
231
232                 /* scans: , */
233                 while(pos < end && *pos == ' ') pos++;
234                 if (pos == end) goto bad_header;
235                 if (*pos++ != ',') goto bad_header;
236         }
237
238         /* scan obj */
239         while(pos < end && *pos == ' ') pos++;
240         if (pos == end) goto bad_header;
241         aux = 0;
242         r->obj = pos;
243         while (pos < end && (aux != 0 || (*pos != ',' && *pos != ']'))) {
244                 if (pos == end) goto bad_header;
245                 switch(*pos) {
246                 case '{': case '[': aux++; break;
247                 case '}': case ']': if (!aux--) goto bad_header; break;
248                 case '"':
249                         do {
250                                 pos += 1 + (*pos == '\\');
251                         } while(pos < end && *pos != '"');
252                 default:
253                         break;
254                 }
255                 pos++;
256         }
257         if (pos > end) goto bad_header;
258         if (pos == end && aux != 0) goto bad_header;
259         c = *pos;
260         r->objlen = (size_t)(pos++ - r->obj);
261         while (r->objlen && r->obj[r->objlen - 1] == ' ')
262                 r->objlen--;
263
264         /* scan the token (if any) */
265         if (c == ',') {
266                 /* scans token: "token" */
267                 while(pos < end && *pos == ' ') pos++;
268                 if (pos == end) goto bad_header;
269                 if (*pos++ != '"') goto bad_header;
270                 r->tok = pos;
271                 while(pos < end && *pos != '"') pos++;
272                 if (pos == end) goto bad_header;
273                 r->toklen = (size_t)(pos++ - r->tok);
274                 while(pos < end && *pos == ' ') pos++;
275                 if (pos == end) goto bad_header;
276                 c = *pos++;
277         }
278
279         /* scan: ] */
280         if (c != ']') goto bad_header;
281         while(pos < end && *pos == ' ') pos++;
282         if (pos != end) goto bad_header;
283
284         /* done */
285         r->text = text;
286         r->size = size;
287         return 1;
288
289 bad_header:
290         return 0;
291 }
292
293 static void aws_on_text(struct afb_ws_json *ws, char *text, size_t size)
294 {
295         struct afb_req r;
296         struct afb_wsreq *wsreq;
297
298         /* allocate */
299         wsreq = calloc(1, sizeof *wsreq);
300         if (wsreq == NULL)
301                 goto alloc_error;
302
303         /* init */
304         if (!aws_wsreq_parse(wsreq, text, size))
305                 goto bad_header;
306
307         /* fill and record the request */
308         if (wsreq->tok != NULL)
309                 wsreq->tok[wsreq->toklen] = 0;
310         afb_context_init(&wsreq->context, ws->session, wsreq->tok);
311         if (!wsreq->context.invalidated)
312                 wsreq->context.validated = 1;
313         wsreq->refcount = 1;
314         wsreq->aws = ws;
315         wsreq->next = ws->requests;
316         ws->requests = wsreq;
317
318         r.closure = wsreq;
319         r.itf = &wsreq_itf;
320         afb_apis_call(r, &wsreq->context, wsreq->api, wsreq->apilen, wsreq->verb, wsreq->verblen);
321         wsreq_unref(wsreq);
322         return;
323
324 bad_header:
325         free(wsreq);
326 alloc_error:
327         free(text);
328         afb_ws_close(ws->ws, 1008, NULL);
329         return;
330 }
331
332 static void wsreq_addref(struct afb_wsreq *wsreq)
333 {
334         wsreq->refcount++;
335 }
336
337 static void wsreq_unref(struct afb_wsreq *wsreq)
338 {
339         if (--wsreq->refcount == 0) {
340                 afb_context_disconnect(&wsreq->context);
341                 free(wsreq->text);
342                 free(wsreq);
343         }
344 }
345
346 static struct json_object *wsreq_json(struct afb_wsreq *wsreq)
347 {
348         struct json_object *root = wsreq->root;
349         if (root == NULL) {
350                 json_tokener_reset(wsreq->aws->tokener);
351                 root = json_tokener_parse_ex(wsreq->aws->tokener, wsreq->obj, (int)wsreq->objlen);
352                 if (root == NULL) {
353                         /* lazy error detection of json request. Is it to improve? */
354                         root = json_object_new_string_len(wsreq->obj, (int)wsreq->objlen);
355                 }
356                 wsreq->root = root;
357         }
358         return root;
359 }
360
361 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name)
362 {
363         struct afb_arg arg;
364         struct json_object *value, *root;
365
366         root = wsreq_json(wsreq);
367         if (json_object_object_get_ex(root, name, &value)) {
368                 arg.name = name;
369                 arg.value = json_object_get_string(value);
370         } else {
371                 arg.name = NULL;
372                 arg.value = NULL;
373         }
374         arg.path = NULL;
375         return arg;
376 }
377
378 static void aws_emit(struct afb_ws_json *aws, int code, const char *id, size_t idlen, struct json_object *data, const char *token)
379 {
380         json_object *msg;
381         const char *txt;
382
383         /* pack the message */
384         msg = json_object_new_array();
385         json_object_array_add(msg, json_object_new_int(code));
386         json_object_array_add(msg, json_object_new_string_len(id, (int)idlen));
387         json_object_array_add(msg, data);
388         if (token)
389                 json_object_array_add(msg, json_object_new_string(token));
390
391         /* emits the reply */
392         txt = json_object_to_json_string(msg);
393         afb_ws_text(aws->ws, txt, strlen(txt));
394         json_object_put(msg);
395 }
396
397 static void wsreq_reply(struct afb_wsreq *wsreq, int retcode, const char *status, const char *info, json_object *resp)
398 {
399         const char *token = afb_context_sent_token(&wsreq->context);
400         aws_emit(wsreq->aws, retcode, wsreq->id, wsreq->idlen, afb_msg_json_reply(status, info, resp, token, NULL), token);
401 }
402
403 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info)
404 {
405         wsreq_reply(wsreq, RETERR, status, info, NULL);
406 }
407
408 static void wsreq_success(struct afb_wsreq *wsreq, json_object *obj, const char *info)
409 {
410         wsreq_reply(wsreq, RETOK, "success", info, obj);
411 }
412
413 static const char *wsreq_raw(struct afb_wsreq *wsreq, size_t *size)
414 {
415         *size = wsreq->objlen;
416         return wsreq->obj;
417 }
418
419 static void wsreq_send(struct afb_wsreq *wsreq, const char *buffer, size_t size)
420 {
421         afb_ws_text(wsreq->aws->ws, buffer, size);
422 }
423
424 static void aws_send_event(struct afb_ws_json *aws, const char *event, struct json_object *object)
425 {
426         aws_emit(aws, EVENT, event, strlen(event), afb_msg_json_event(event, object), NULL);
427 }
428