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