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