Add verbs for closing and setting LOA
[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         struct afb_context context;
133         int refcount;
134         struct afb_ws_json1 *aws;
135         struct afb_wsreq *next;
136         char *text;
137         size_t size;
138         int code;
139         char *id;
140         size_t idlen;
141         char *api;
142         size_t apilen;
143         char *verb;
144         size_t verblen;
145         char *obj;
146         size_t objlen;
147         char *tok;
148         size_t toklen;
149         struct json_object *root;
150 };
151
152 static void wsreq_addref(struct afb_wsreq *wsreq);
153 static void wsreq_unref(struct afb_wsreq *wsreq);
154 static struct json_object *wsreq_json(struct afb_wsreq *wsreq);
155 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name);
156 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info);
157 static void wsreq_success(struct afb_wsreq *wsreq, struct json_object *obj, const char *info);
158 static const char *wsreq_raw(struct afb_wsreq *wsreq, size_t *size);
159 static void wsreq_send(struct afb_wsreq *wsreq, const char *buffer, size_t size);
160
161
162 static const struct afb_req_itf wsreq_itf = {
163         .json = (void*)wsreq_json,
164         .get = (void*)wsreq_get,
165         .success = (void*)wsreq_success,
166         .fail = (void*)wsreq_fail,
167         .raw = (void*)wsreq_raw,
168         .send = (void*)wsreq_send,
169         .context_get = (void*)afb_context_get,
170         .context_set = (void*)afb_context_set,
171         .addref = (void*)wsreq_addref,
172         .unref = (void*)wsreq_unref,
173         .session_close = (void*)afb_context_close,
174         .session_set_LOA = (void*)afb_context_change_loa
175 };
176
177 static int aws_wsreq_parse(struct afb_wsreq *r, char *text, size_t size)
178 {
179         char *pos, *end, c;
180         int aux;
181
182         /* scan */
183         pos = text;
184         end = text + size;
185
186         /* scans: [ */
187         while(pos < end && *pos == ' ') pos++;
188         if (pos == end) goto bad_header;
189         if (*pos++ != '[') goto bad_header;
190
191         /* scans code: 2|3|4 */
192         while(pos < end && *pos == ' ') pos++;
193         if (pos == end) goto bad_header;
194         switch (*pos++) {
195         case '2': r->code = CALL; break;
196         case '3': r->code = RETOK; break;
197         case '4': r->code = RETERR; break;
198         default: goto bad_header;
199         }
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 id: "id" */
207         while(pos < end && *pos == ' ') pos++;
208         if (pos == end) goto bad_header;
209         if (*pos++ != '"') goto bad_header;
210         r->id = pos;
211         while(pos < end && *pos != '"') pos++;
212         if (pos == end) goto bad_header;
213         r->idlen = (size_t)(pos++ - r->id);
214
215         /* scans: , */
216         while(pos < end && *pos == ' ') pos++;
217         if (pos == end) goto bad_header;
218         if (*pos++ != ',') goto bad_header;
219
220         /* scans the method if needed */
221         if (r->code == CALL) {
222                 /* scans: " */
223                 while(pos < end && *pos == ' ') pos++;
224                 if (pos == end) goto bad_header;
225                 if (*pos++ != '"') goto bad_header;
226
227                 /* scans: api/ */
228                 r->api = pos;
229                 while(pos < end && *pos != '"' && *pos != '/') pos++;
230                 if (pos == end) goto bad_header;
231                 if (*pos != '/') goto bad_header;
232                 r->apilen = (size_t)(pos++ - r->api);
233                 if (r->apilen && r->api[r->apilen - 1] == '\\')
234                         r->apilen--;
235
236                 /* scans: verb" */
237                 r->verb = pos;
238                 while(pos < end && *pos != '"') pos++;
239                 if (pos == end) goto bad_header;
240                 r->verblen = (size_t)(pos++ - r->verb);
241
242                 /* scans: , */
243                 while(pos < end && *pos == ' ') pos++;
244                 if (pos == end) goto bad_header;
245                 if (*pos++ != ',') goto bad_header;
246         }
247
248         /* scan obj */
249         while(pos < end && *pos == ' ') pos++;
250         if (pos == end) goto bad_header;
251         aux = 0;
252         r->obj = pos;
253         while (pos < end && (aux != 0 || (*pos != ',' && *pos != ']'))) {
254                 if (pos == end) goto bad_header;
255                 switch(*pos) {
256                 case '{': case '[': aux++; break;
257                 case '}': case ']': if (!aux--) goto bad_header; break;
258                 case '"':
259                         do {
260                                 pos += 1 + (*pos == '\\');
261                         } while(pos < end && *pos != '"');
262                 default:
263                         break;
264                 }
265                 pos++;
266         }
267         if (pos > end) goto bad_header;
268         if (pos == end && aux != 0) goto bad_header;
269         c = *pos;
270         r->objlen = (size_t)(pos++ - r->obj);
271         while (r->objlen && r->obj[r->objlen - 1] == ' ')
272                 r->objlen--;
273
274         /* scan the token (if any) */
275         if (c == ',') {
276                 /* scans token: "token" */
277                 while(pos < end && *pos == ' ') pos++;
278                 if (pos == end) goto bad_header;
279                 if (*pos++ != '"') goto bad_header;
280                 r->tok = pos;
281                 while(pos < end && *pos != '"') pos++;
282                 if (pos == end) goto bad_header;
283                 r->toklen = (size_t)(pos++ - r->tok);
284                 while(pos < end && *pos == ' ') pos++;
285                 if (pos == end) goto bad_header;
286                 c = *pos++;
287         }
288
289         /* scan: ] */
290         if (c != ']') goto bad_header;
291         while(pos < end && *pos == ' ') pos++;
292         if (pos != end) goto bad_header;
293
294         /* done */
295         r->text = text;
296         r->size = size;
297         return 1;
298
299 bad_header:
300         return 0;
301 }
302
303 static void aws_on_text(struct afb_ws_json1 *ws, char *text, size_t size)
304 {
305         struct afb_req r;
306         struct afb_wsreq *wsreq;
307
308         /* allocate */
309         wsreq = calloc(1, sizeof *wsreq);
310         if (wsreq == NULL)
311                 goto alloc_error;
312
313         /* init */
314         if (!aws_wsreq_parse(wsreq, text, size))
315                 goto bad_header;
316
317         /* fill and record the request */
318         if (wsreq->tok != NULL)
319                 wsreq->tok[wsreq->toklen] = 0;
320         afb_context_init(&wsreq->context, ws->session, wsreq->tok);
321         if (!wsreq->context.invalidated)
322                 wsreq->context.validated = 1;
323         if (ws->new_session != 0) {
324                 wsreq->context.created = 1;
325                 ws->new_session = 0;
326         }
327         wsreq->refcount = 1;
328         wsreq->aws = ws;
329         wsreq->next = ws->requests;
330         ws->requests = wsreq;
331
332         r.closure = wsreq;
333         r.itf = &wsreq_itf;
334         afb_apis_call(r, &wsreq->context, wsreq->api, wsreq->apilen, wsreq->verb, wsreq->verblen);
335         wsreq_unref(wsreq);
336         return;
337
338 bad_header:
339         free(wsreq);
340 alloc_error:
341         free(text);
342         afb_ws_close(ws->ws, 1008, NULL);
343         return;
344 }
345
346 static void wsreq_addref(struct afb_wsreq *wsreq)
347 {
348         wsreq->refcount++;
349 }
350
351 static void wsreq_unref(struct afb_wsreq *wsreq)
352 {
353         if (--wsreq->refcount == 0) {
354                 struct afb_wsreq **prv = &wsreq->aws->requests;
355                 while(*prv != NULL) {
356                         if (*prv == wsreq) {
357                                 *prv = wsreq->next;
358                                 break;
359                         }
360                         prv = &(*prv)->next;
361                 }
362                 afb_context_disconnect(&wsreq->context);
363                 json_object_put(wsreq->root);
364                 free(wsreq->text);
365                 free(wsreq);
366         }
367 }
368
369 static struct json_object *wsreq_json(struct afb_wsreq *wsreq)
370 {
371         struct json_object *root = wsreq->root;
372         if (root == NULL) {
373                 json_tokener_reset(wsreq->aws->tokener);
374                 root = json_tokener_parse_ex(wsreq->aws->tokener, wsreq->obj, (int)wsreq->objlen);
375                 if (root == NULL) {
376                         /* lazy error detection of json request. Is it to improve? */
377                         root = json_object_new_string_len(wsreq->obj, (int)wsreq->objlen);
378                 }
379                 wsreq->root = root;
380         }
381         return root;
382 }
383
384 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name)
385 {
386         struct afb_arg arg;
387         struct json_object *value, *root;
388
389         root = wsreq_json(wsreq);
390         if (json_object_object_get_ex(root, name, &value)) {
391                 arg.name = name;
392                 arg.value = json_object_get_string(value);
393         } else {
394                 arg.name = NULL;
395                 arg.value = NULL;
396         }
397         arg.path = NULL;
398         return arg;
399 }
400
401 static void aws_emit(struct afb_ws_json1 *aws, int code, const char *id, size_t idlen, struct json_object *data, const char *token)
402 {
403         json_object *msg;
404         const char *txt;
405
406         /* pack the message */
407         msg = json_object_new_array();
408         json_object_array_add(msg, json_object_new_int(code));
409         json_object_array_add(msg, json_object_new_string_len(id, (int)idlen));
410         json_object_array_add(msg, data);
411         if (token)
412                 json_object_array_add(msg, json_object_new_string(token));
413
414         /* emits the reply */
415         txt = json_object_to_json_string(msg);
416         afb_ws_text(aws->ws, txt, strlen(txt));
417         json_object_put(msg);
418 }
419
420 static void wsreq_reply(struct afb_wsreq *wsreq, int retcode, const char *status, const char *info, json_object *resp)
421 {
422         const char *uuid = afb_context_sent_uuid(&wsreq->context);
423         const char *token = afb_context_sent_token(&wsreq->context);
424         struct json_object *reply = afb_msg_json_reply(status, info, resp, token, uuid);
425         aws_emit(wsreq->aws, retcode, wsreq->id, wsreq->idlen, reply, token);
426 }
427
428 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info)
429 {
430         wsreq_reply(wsreq, RETERR, status, info, NULL);
431 }
432
433 static void wsreq_success(struct afb_wsreq *wsreq, json_object *obj, const char *info)
434 {
435         wsreq_reply(wsreq, RETOK, "success", info, obj);
436 }
437
438 static const char *wsreq_raw(struct afb_wsreq *wsreq, size_t *size)
439 {
440         *size = wsreq->objlen;
441         return wsreq->obj;
442 }
443
444 static void wsreq_send(struct afb_wsreq *wsreq, const char *buffer, size_t size)
445 {
446         afb_ws_text(wsreq->aws->ws, buffer, size);
447 }
448
449 static void aws_send_event(struct afb_ws_json1 *aws, const char *event, struct json_object *object)
450 {
451         aws_emit(aws, EVENT, event, strlen(event), afb_msg_json_event(event, object), NULL);
452 }
453