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