try to avoid unnecessary copy
[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_sender_itf event_sender_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 > ctxClientEventSenderAdd(result->context, (struct afb_event_sender){ .itf = &event_sender_itf, .closure = result }))
88                 goto error5;
89
90         return result;
91
92 error5:
93         /* TODO */
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         ctxClientEventSenderRemove(ws->context, (struct afb_event_sender){ .itf = &event_sender_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
166 static int aws_wsreq_parse(struct afb_wsreq *r, char *text, size_t size)
167 {
168         char *pos, *end, c;
169         int aux;
170
171         /* scan */
172         pos = text;
173         end = text + size;
174
175         /* scans: [ */
176         while(pos < end && *pos == ' ') pos++;
177         if (pos == end) goto bad_header;
178         if (*pos++ != '[') goto bad_header;
179
180         /* scans code: 2|3|4 */
181         while(pos < end && *pos == ' ') pos++;
182         if (pos == end) goto bad_header;
183         switch (*pos++) {
184         case '2': r->code = CALL; break;
185         case '3': r->code = RETOK; break;
186         case '4': r->code = RETERR; break;
187         default: goto bad_header;
188         }
189
190         /* scans: , */
191         while(pos < end && *pos == ' ') pos++;
192         if (pos == end) goto bad_header;
193         if (*pos++ != ',') goto bad_header;
194
195         /* scans id: "id" */
196         while(pos < end && *pos == ' ') pos++;
197         if (pos == end) goto bad_header;
198         if (*pos++ != '"') goto bad_header;
199         r->id = pos;
200         while(pos < end && *pos != '"') pos++;
201         if (pos == end) goto bad_header;
202         r->idlen = (size_t)(pos++ - r->id);
203
204         /* scans: , */
205         while(pos < end && *pos == ' ') pos++;
206         if (pos == end) goto bad_header;
207         if (*pos++ != ',') goto bad_header;
208
209         /* scans the method if needed */
210         if (r->code == CALL) {
211                 /* scans: " */
212                 while(pos < end && *pos == ' ') pos++;
213                 if (pos == end) goto bad_header;
214                 if (*pos++ != '"') goto bad_header;
215
216                 /* scans: api/ */
217                 r->api = pos;
218                 while(pos < end && *pos != '"' && *pos != '/') pos++;
219                 if (pos == end) goto bad_header;
220                 if (*pos != '/') goto bad_header;
221                 r->apilen = (size_t)(pos++ - r->api);
222                 if (r->apilen && r->api[r->apilen - 1] == '\\')
223                         r->apilen--;
224
225                 /* scans: verb" */
226                 r->verb = pos;
227                 while(pos < end && *pos != '"') pos++;
228                 if (pos == end) goto bad_header;
229                 r->verblen = (size_t)(pos++ - r->verb);
230
231                 /* scans: , */
232                 while(pos < end && *pos == ' ') pos++;
233                 if (pos == end) goto bad_header;
234                 if (*pos++ != ',') goto bad_header;
235         }
236
237         /* scan obj */
238         while(pos < end && *pos == ' ') pos++;
239         if (pos == end) goto bad_header;
240         aux = 0;
241         r->obj = pos;
242         while (pos < end && (aux != 0 || (*pos != ',' && *pos != ']'))) {
243                 if (pos == end) goto bad_header;
244                 switch(*pos) {
245                 case '{': case '[': aux++; break;
246                 case '}': case ']': if (!aux--) goto bad_header; break;
247                 case '"':
248                         do {
249                                 pos += 1 + (*pos == '\\');
250                         } while(pos < end && *pos != '"');
251                 default:
252                         break;
253                 }
254                 pos++;
255         }
256         if (pos > end) goto bad_header;
257         if (pos == end && aux != 0) goto bad_header;
258         c = *pos;
259         r->objlen = (size_t)(pos++ - r->obj);
260         while (r->objlen && r->obj[r->objlen - 1] == ' ')
261                 r->objlen--;
262
263         /* scan the token (if any) */
264         if (c == ',') {
265                 /* scans token: "token" */
266                 while(pos < end && *pos == ' ') pos++;
267                 if (pos == end) goto bad_header;
268                 if (*pos++ != '"') goto bad_header;
269                 r->tok = pos;
270                 while(pos < end && *pos != '"') pos++;
271                 if (pos == end) goto bad_header;
272                 r->toklen = (size_t)(pos++ - r->tok);
273                 while(pos < end && *pos == ' ') pos++;
274                 if (pos == end) goto bad_header;
275                 c = *pos++;
276         }
277
278         /* scan: ] */
279         if (c != ']') goto bad_header;
280         while(pos < end && *pos == ' ') pos++;
281         if (pos != end) goto bad_header;
282
283         /* done */
284         r->text = text;
285         r->size = size;
286         return 1;
287
288 bad_header:
289         return 0;
290 }
291
292 static void aws_on_text(struct afb_ws_json *ws, char *text, size_t size)
293 {
294         struct afb_req r;
295         struct afb_wsreq *wsreq;
296
297         /* allocate */
298         wsreq = calloc(1, sizeof *wsreq);
299         if (wsreq == NULL)
300                 goto alloc_error;
301
302         /* init */
303         if (!aws_wsreq_parse(wsreq, text, size))
304                 goto bad_header;
305
306         /* fill and record the request */
307         wsreq->aws = ws;
308         wsreq->next = ws->requests;
309         ws->requests = wsreq;
310
311         r.req_closure = wsreq;
312         r.itf = &wsreq_itf;
313         afb_apis_call(r, ws->context, wsreq->api, wsreq->apilen, wsreq->verb, wsreq->verblen);
314         return;
315
316 bad_header:
317         free(wsreq);
318 alloc_error:
319         free(text);
320         afb_ws_close(ws->ws, 1008, NULL);
321         return;
322 }
323
324 static struct json_object *wsreq_json(struct afb_wsreq *wsreq)
325 {
326         struct json_object *root = wsreq->root;
327         if (root == NULL) {
328                 json_tokener_reset(wsreq->aws->tokener);
329                 root = json_tokener_parse_ex(wsreq->aws->tokener, wsreq->obj, (int)wsreq->objlen);
330                 if (root == NULL) {
331                         /* lazy error detection of json request. Is it to improve? */
332                         root = json_object_new_string_len(wsreq->obj, (int)wsreq->objlen);
333                 }
334                 wsreq->root = root;
335         }
336         return root;
337 }
338
339 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name)
340 {
341         struct afb_arg arg;
342         struct json_object *value, *root;
343
344         root = wsreq_json(wsreq);
345         if (json_object_object_get_ex(root, name, &value)) {
346                 arg.name = name;
347                 arg.value = json_object_get_string(value);
348         } else {
349                 arg.name = NULL;
350                 arg.value = NULL;
351         }
352         arg.path = NULL;
353         return arg;
354 }
355
356 static int wsreq_session_create(struct afb_wsreq *wsreq)
357 {
358         struct AFB_clientCtx *context = wsreq->aws->context;
359         if (context->created)
360                 return 0;
361         return wsreq_session_check(wsreq, 1);
362 }
363
364 static int wsreq_session_check(struct afb_wsreq *wsreq, int refresh)
365 {
366         struct AFB_clientCtx *context = wsreq->aws->context;
367
368         if (wsreq->tok == NULL)
369                 return 0;
370
371         if (!ctxTokenCheckLen (context, wsreq->tok, wsreq->toklen))
372                 return 0;
373
374         if (refresh) {
375                 ctxTokenNew (context);
376         }
377
378         return 1;
379 }
380
381 static void wsreq_session_close(struct afb_wsreq *wsreq)
382 {
383         struct AFB_clientCtx *context = wsreq->aws->context;
384         ctxClientClose(context);
385 }
386
387 static void aws_emit(struct afb_ws_json *aws, int code, const char *id, size_t idlen, struct json_object *data)
388 {
389         json_object *msg;
390         const char *token;
391         const char *txt;
392
393         /* pack the message */
394         msg = json_object_new_array();
395         json_object_array_add(msg, json_object_new_int(code));
396         json_object_array_add(msg, json_object_new_string_len(id, (int)idlen));
397         json_object_array_add(msg, data);
398         token = aws->context->token;
399         if (token)
400                 json_object_array_add(msg, json_object_new_string(token));
401
402         /* emits the reply */
403         txt = json_object_to_json_string(msg);
404         afb_ws_text(aws->ws, txt, strlen(txt));
405         json_object_put(msg);
406 }
407
408 static void wsreq_reply(struct afb_wsreq *wsreq, int retcode, const char *status, const char *info, json_object *resp)
409 {
410         aws_emit(wsreq->aws, retcode, wsreq->id, wsreq->idlen, afb_msg_json_reply(status, info, resp, NULL, NULL));
411         /* TODO eliminates the wsreq */
412 }
413
414 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info)
415 {
416         wsreq_reply(wsreq, RETERR, status, info, NULL);
417 }
418
419 static void wsreq_success(struct afb_wsreq *wsreq, json_object *obj, const char *info)
420 {
421         wsreq_reply(wsreq, RETOK, "success", info, obj);
422 }
423
424 static const char *wsreq_raw(struct afb_wsreq *wsreq, size_t *size)
425 {
426         *size = wsreq->objlen;
427         return wsreq->obj;
428 }
429
430 static void wsreq_send(struct afb_wsreq *wsreq, const char *buffer, size_t size)
431 {
432         afb_ws_text(wsreq->aws->ws, buffer, size);
433 }
434
435 static void aws_send_event(struct afb_ws_json *aws, const char *event, struct json_object *object)
436 {
437         aws_emit(aws, EVENT, event, strlen(event), afb_msg_json_event(event, object));
438 }
439