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