afb-proto-ws: Serialize incoming message
[src/app-framework-binder.git] / src / afb-proto-ws.c
1 /*
2  * Copyright (C) 2015-2018 "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 <string.h>
22 #include <assert.h>
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include <errno.h>
26 #include <endian.h>
27 #include <netdb.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <sys/un.h>
31 #include <pthread.h>
32
33 #include <json-c/json.h>
34
35 #include "afb-ws.h"
36 #include "afb-msg-json.h"
37 #include "afb-proto-ws.h"
38 #include "fdev.h"
39
40 struct afb_proto_ws;
41
42 /******** implementation of internal binder protocol per api **************/
43 /*
44
45 This protocol is asymetric: there is a client and a server
46
47 The client can require the following actions:
48
49   - call a verb
50
51   - ask for description
52
53 The server must reply to the previous actions by
54
55   - answering success or failure of the call
56
57   - answering the required description
58
59 The server can also within the context of a call
60
61   - subscribe or unsubscribe an event
62
63 For the purpose of handling events the server can:
64
65   - create/destroy an event
66
67   - push or brodcast data as an event
68
69 */
70 /************** constants for protocol definition *************************/
71
72 #define CHAR_FOR_CALL             'C'
73 #define CHAR_FOR_REPLY            'Y'
74 #define CHAR_FOR_EVT_BROADCAST    '*'
75 #define CHAR_FOR_EVT_ADD          '+'
76 #define CHAR_FOR_EVT_DEL          '-'
77 #define CHAR_FOR_EVT_PUSH         '!'
78 #define CHAR_FOR_EVT_SUBSCRIBE    'S'
79 #define CHAR_FOR_EVT_UNSUBSCRIBE  'U'
80 #define CHAR_FOR_DESCRIBE         'D'
81 #define CHAR_FOR_DESCRIPTION      'd'
82
83 /******************* handling calls *****************************/
84
85 /*
86  * structure for recording calls on client side
87  */
88 struct client_call {
89         struct client_call *next;       /* the next call */
90         struct afb_proto_ws *protows;   /* the proto_ws */
91         void *request;                  /* the request closure */
92         uint32_t callid;                /* the message identifier */
93 };
94
95 /*
96  * structure for a ws request
97  */
98 struct afb_proto_ws_call {
99         struct client_call *next;       /* the next call */
100         struct afb_proto_ws *protows;   /* the client of the request */
101         uint32_t refcount;              /* reference count */
102         uint32_t callid;                /* the incoming request callid */
103         char *buffer;                   /* the incoming buffer */
104 };
105
106 /*
107  * structure for recording describe requests
108  */
109 struct client_describe
110 {
111         struct client_describe *next;
112         struct afb_proto_ws *protows;
113         void (*callback)(void*, struct json_object*);
114         void *closure;
115         uint32_t descid;
116 };
117
118 /*
119  * structure for jobs of describing
120  */
121 struct afb_proto_ws_describe
122 {
123         struct afb_proto_ws *protows;
124         uint32_t descid;
125 };
126
127 /******************* proto description for client or servers ******************/
128
129 struct afb_proto_ws
130 {
131         /* count of references */
132         int refcount;
133
134         /* file descriptor */
135         struct fdev *fdev;
136
137         /* resource control */
138         pthread_mutex_t mutex;
139
140         /* websocket */
141         struct afb_ws *ws;
142
143         /* the client closure */
144         void *closure;
145
146         /* the client side interface */
147         const struct afb_proto_ws_client_itf *client_itf;
148
149         /* the server side interface */
150         const struct afb_proto_ws_server_itf *server_itf;
151
152         /* emitted calls (client side) */
153         struct client_call *calls;
154
155         /* pending description (client side) */
156         struct client_describe *describes;
157
158         /* on hangup callback */
159         void (*on_hangup)(void *closure);
160
161         /* queuing facility for processing messages */
162         int (*queuing)(struct afb_proto_ws *proto, void (*process)(int s, void *c), void *closure);
163 };
164
165 /******************* streaming objects **********************************/
166
167 #define WRITEBUF_COUNT_MAX  32
168 struct writebuf
169 {
170         struct iovec iovec[WRITEBUF_COUNT_MAX];
171         uint32_t uints[WRITEBUF_COUNT_MAX];
172         int count;
173 };
174
175 struct readbuf
176 {
177         char *base, *head, *end;
178 };
179
180 struct binary
181 {
182         struct afb_proto_ws *protows;
183         struct readbuf rb;
184 };
185
186 /******************* common useful tools **********************************/
187
188 /**
189  * translate a pointer to some integer
190  * @param ptr the pointer to translate
191  * @return an integer
192  */
193 static inline uint32_t ptr2id(void *ptr)
194 {
195         return (uint32_t)(((intptr_t)ptr) >> 6);
196 }
197
198 /******************* serialisation part **********************************/
199
200 static char *readbuf_get(struct readbuf *rb, uint32_t length)
201 {
202         char *before = rb->head;
203         char *after = before + length;
204         if (after > rb->end)
205                 return 0;
206         rb->head = after;
207         return before;
208 }
209
210 __attribute__((unused))
211 static int readbuf_char(struct readbuf *rb, char *value)
212 {
213         if (rb->head >= rb->end)
214                 return 0;
215         *value = *rb->head++;
216         return 1;
217 }
218
219 static int readbuf_uint32(struct readbuf *rb, uint32_t *value)
220 {
221         char *after = rb->head + sizeof *value;
222         if (after > rb->end)
223                 return 0;
224         memcpy(value, rb->head, sizeof *value);
225         rb->head = after;
226         *value = le32toh(*value);
227         return 1;
228 }
229
230 static int _readbuf_string_(struct readbuf *rb, const char **value, size_t *length, int nulok)
231 {
232         uint32_t len;
233         if (!readbuf_uint32(rb, &len))
234                 return 0;
235         if (!len) {
236                 if (!nulok)
237                         return 0;
238                 *value = NULL;
239                 if (length)
240                         *length = 0;
241                 return 1;
242         }
243         if (length)
244                 *length = (size_t)(len - 1);
245         return (*value = readbuf_get(rb, len)) != NULL &&  rb->head[-1] == 0;
246 }
247
248
249 static int readbuf_string(struct readbuf *rb, const char **value, size_t *length)
250 {
251         return _readbuf_string_(rb, value, length, 0);
252 }
253
254 static int readbuf_nullstring(struct readbuf *rb, const char **value, size_t *length)
255 {
256         return _readbuf_string_(rb, value, length, 1);
257 }
258
259 static int readbuf_object(struct readbuf *rb, struct json_object **object)
260 {
261         const char *string;
262         struct json_object *o;
263         enum json_tokener_error jerr;
264         int rc = readbuf_string(rb, &string, NULL);
265         if (rc) {
266                 o = json_tokener_parse_verbose(string, &jerr);
267                 if (jerr != json_tokener_success)
268                         o = json_object_new_string(string);
269                 *object = o;
270         }
271         return rc;
272 }
273
274 static int writebuf_put(struct writebuf *wb, const void *value, size_t length)
275 {
276         int i = wb->count;
277         if (i == WRITEBUF_COUNT_MAX)
278                 return 0;
279         wb->iovec[i].iov_base = (void*)value;
280         wb->iovec[i].iov_len = length;
281         wb->count = i + 1;
282         return 1;
283 }
284
285 static int writebuf_char(struct writebuf *wb, char value)
286 {
287         int i = wb->count;
288         if (i == WRITEBUF_COUNT_MAX)
289                 return 0;
290         *(char*)&wb->uints[i] = value;
291         wb->iovec[i].iov_base = &wb->uints[i];
292         wb->iovec[i].iov_len = 1;
293         wb->count = i + 1;
294         return 1;
295 }
296
297 static int writebuf_uint32(struct writebuf *wb, uint32_t value)
298 {
299         int i = wb->count;
300         if (i == WRITEBUF_COUNT_MAX)
301                 return 0;
302         wb->uints[i] = htole32(value);
303         wb->iovec[i].iov_base = &wb->uints[i];
304         wb->iovec[i].iov_len = sizeof wb->uints[i];
305         wb->count = i + 1;
306         return 1;
307 }
308
309 static int writebuf_string_length(struct writebuf *wb, const char *value, size_t length)
310 {
311         uint32_t len = (uint32_t)++length;
312         return (size_t)len == length && len && writebuf_uint32(wb, len) && writebuf_put(wb, value, length);
313 }
314
315 static int writebuf_string(struct writebuf *wb, const char *value)
316 {
317         return writebuf_string_length(wb, value, strlen(value));
318 }
319
320 static int writebuf_nullstring(struct writebuf *wb, const char *value)
321 {
322         return value ? writebuf_string_length(wb, value, strlen(value)) : writebuf_uint32(wb, 0);
323 }
324
325 static int writebuf_object(struct writebuf *wb, struct json_object *object)
326 {
327         const char *string = json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN);
328         return string != NULL && writebuf_string(wb, string);
329 }
330
331 /******************* queuing of messages *****************/
332
333 /* queue the processing of the received message (except if size=0 cause it's not a valid message) */
334 static void queue_message_processing(struct afb_proto_ws *protows, char *data, size_t size, void (*processing)(int,void*))
335 {
336         struct binary *binary;
337
338         if (size) {
339                 binary = malloc(sizeof *binary);
340                 if (!binary) {
341                         /* TODO process the problem */
342                         errno = ENOMEM;
343                 } else {
344                         binary->protows = protows;
345                         binary->rb.base = data;
346                         binary->rb.head = data;
347                         binary->rb.end = data + size;
348                         if (!protows->queuing
349                          || protows->queuing(protows, processing, binary) < 0)
350                                 processing(0, binary);
351                         return;
352                 }
353         }
354         free(data);
355 }
356
357 /******************* ws request part for server *****************/
358
359 void afb_proto_ws_call_addref(struct afb_proto_ws_call *call)
360 {
361         __atomic_add_fetch(&call->refcount, 1, __ATOMIC_RELAXED);
362 }
363
364 void afb_proto_ws_call_unref(struct afb_proto_ws_call *call)
365 {
366         if (__atomic_sub_fetch(&call->refcount, 1, __ATOMIC_RELAXED))
367                 return;
368
369         afb_proto_ws_unref(call->protows);
370         free(call->buffer);
371         free(call);
372 }
373
374 int afb_proto_ws_call_reply(struct afb_proto_ws_call *call, struct json_object *obj, const char *error, const char *info)
375 {
376         int rc = -1;
377         struct writebuf wb = { .count = 0 };
378         struct afb_proto_ws *protows = call->protows;
379
380         if (writebuf_char(&wb, CHAR_FOR_REPLY)
381          && writebuf_uint32(&wb, call->callid)
382          && writebuf_nullstring(&wb, error)
383          && writebuf_nullstring(&wb, info)
384          && writebuf_object(&wb, obj)) {
385                 pthread_mutex_lock(&protows->mutex);
386                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
387                 pthread_mutex_unlock(&protows->mutex);
388                 if (rc >= 0) {
389                         rc = 0;
390                         goto success;
391                 }
392         }
393 success:
394         return rc;
395 }
396
397 int afb_proto_ws_call_subscribe(struct afb_proto_ws_call *call, const char *event_name, int event_id)
398 {
399         int rc = -1;
400         struct writebuf wb = { .count = 0 };
401         struct afb_proto_ws *protows = call->protows;
402
403         if (writebuf_char(&wb, CHAR_FOR_EVT_SUBSCRIBE)
404          && writebuf_uint32(&wb, call->callid)
405          && writebuf_uint32(&wb, (uint32_t)event_id)
406          && writebuf_string(&wb, event_name)) {
407                 pthread_mutex_lock(&protows->mutex);
408                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
409                 pthread_mutex_unlock(&protows->mutex);
410                 if (rc >= 0) {
411                         rc = 0;
412                         goto success;
413                 }
414         }
415 success:
416         return rc;
417 }
418
419 int afb_proto_ws_call_unsubscribe(struct afb_proto_ws_call *call, const char *event_name, int event_id)
420 {
421         int rc = -1;
422         struct writebuf wb = { .count = 0 };
423         struct afb_proto_ws *protows = call->protows;
424
425         if (writebuf_char(&wb, CHAR_FOR_EVT_UNSUBSCRIBE)
426          && writebuf_uint32(&wb, call->callid)
427          && writebuf_uint32(&wb, (uint32_t)event_id)
428          && writebuf_string(&wb, event_name)) {
429                 pthread_mutex_lock(&protows->mutex);
430                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
431                 pthread_mutex_unlock(&protows->mutex);
432                 if (rc >= 0) {
433                         rc = 0;
434                         goto success;
435                 }
436         }
437 success:
438         return rc;
439 }
440
441 /******************* client part **********************************/
442
443 /* search a memorized call */
444 static struct client_call *client_call_search_locked(struct afb_proto_ws *protows, uint32_t callid)
445 {
446         struct client_call *call;
447
448         call = protows->calls;
449         while (call != NULL && call->callid != callid)
450                 call = call->next;
451
452         return call;
453 }
454
455 static struct client_call *client_call_search_unlocked(struct afb_proto_ws *protows, uint32_t callid)
456 {
457         struct client_call *result;
458
459         pthread_mutex_lock(&protows->mutex);
460         result = client_call_search_locked(protows, callid);
461         pthread_mutex_unlock(&protows->mutex);
462         return result;
463 }
464
465 /* free and release the memorizing call */
466 static void client_call_destroy(struct client_call *call)
467 {
468         struct client_call **prv;
469         struct afb_proto_ws *protows = call->protows;
470
471         pthread_mutex_lock(&protows->mutex);
472         prv = &call->protows->calls;
473         while (*prv != NULL) {
474                 if (*prv == call) {
475                         *prv = call->next;
476                         break;
477                 }
478                 prv = &(*prv)->next;
479         }
480         pthread_mutex_unlock(&protows->mutex);
481         free(call);
482 }
483
484 /* get event data from the message */
485 static int client_msg_event_read(struct readbuf *rb, uint32_t *eventid, const char **name)
486 {
487         return readbuf_uint32(rb, eventid) && readbuf_string(rb, name, NULL);
488 }
489
490 /* get event from the message */
491 static int client_msg_call_get(struct afb_proto_ws *protows, struct readbuf *rb, struct client_call **call)
492 {
493         uint32_t callid;
494
495         /* get event data from the message */
496         if (!readbuf_uint32(rb, &callid)) {
497                 return 0;
498         }
499
500         /* get the call */
501         *call = client_call_search_unlocked(protows, callid);
502         if (*call == NULL) {
503                 return 0;
504         }
505
506         return 1;
507 }
508
509 /* adds an event */
510 static void client_on_event_create(struct afb_proto_ws *protows, struct readbuf *rb)
511 {
512         const char *event_name;
513         uint32_t event_id;
514
515         if (protows->client_itf->on_event_create && client_msg_event_read(rb, &event_id, &event_name))
516                 protows->client_itf->on_event_create(protows->closure, event_name, (int)event_id);
517 }
518
519 /* removes an event */
520 static void client_on_event_remove(struct afb_proto_ws *protows, struct readbuf *rb)
521 {
522         const char *event_name;
523         uint32_t event_id;
524
525         if (protows->client_itf->on_event_remove && client_msg_event_read(rb, &event_id, &event_name))
526                 protows->client_itf->on_event_remove(protows->closure, event_name, (int)event_id);
527 }
528
529 /* subscribes an event */
530 static void client_on_event_subscribe(struct afb_proto_ws *protows, struct readbuf *rb)
531 {
532         const char *event_name;
533         uint32_t event_id;
534         struct client_call *call;
535
536         if (protows->client_itf->on_event_subscribe && client_msg_call_get(protows, rb, &call) && client_msg_event_read(rb, &event_id, &event_name))
537                 protows->client_itf->on_event_subscribe(protows->closure, call->request, event_name, (int)event_id);
538 }
539
540 /* unsubscribes an event */
541 static void client_on_event_unsubscribe(struct afb_proto_ws *protows, struct readbuf *rb)
542 {
543         const char *event_name;
544         uint32_t event_id;
545         struct client_call *call;
546
547         if (protows->client_itf->on_event_unsubscribe && client_msg_call_get(protows, rb, &call) && client_msg_event_read(rb, &event_id, &event_name))
548                 protows->client_itf->on_event_unsubscribe(protows->closure, call->request, event_name, (int)event_id);
549 }
550
551 /* receives broadcasted events */
552 static void client_on_event_broadcast(struct afb_proto_ws *protows, struct readbuf *rb)
553 {
554         const char *event_name;
555         struct json_object *object;
556
557         if (protows->client_itf->on_event_broadcast && readbuf_string(rb, &event_name, NULL) && readbuf_object(rb, &object))
558                 protows->client_itf->on_event_broadcast(protows->closure, event_name, object);
559 }
560
561 /* pushs an event */
562 static void client_on_event_push(struct afb_proto_ws *protows, struct readbuf *rb)
563 {
564         const char *event_name;
565         uint32_t event_id;
566         struct json_object *object;
567
568         if (protows->client_itf->on_event_push && client_msg_event_read(rb, &event_id, &event_name) && readbuf_object(rb, &object))
569                 protows->client_itf->on_event_push(protows->closure, event_name, (int)event_id, object);
570 }
571
572 static void client_on_reply(struct afb_proto_ws *protows, struct readbuf *rb)
573 {
574         struct client_call *call;
575         struct json_object *object;
576         const char *error, *info;
577
578         if (!client_msg_call_get(protows, rb, &call))
579                 return;
580
581         if (readbuf_nullstring(rb, &error, NULL) && readbuf_nullstring(rb, &info, NULL) && readbuf_object(rb, &object)) {
582                 protows->client_itf->on_reply(protows->closure, call->request, object, error, info);
583         } else {
584                 protows->client_itf->on_reply(protows->closure, call->request, NULL, "proto-error", "can't process success");
585         }
586         client_call_destroy(call);
587 }
588
589 static void client_on_description(struct afb_proto_ws *protows, struct readbuf *rb)
590 {
591         uint32_t descid;
592         struct client_describe *desc, **prv;
593         struct json_object *object;
594
595         if (readbuf_uint32(rb, &descid)) {
596                 pthread_mutex_lock(&protows->mutex);
597                 prv = &protows->describes;
598                 while ((desc = *prv) && desc->descid != descid)
599                         prv = &desc->next;
600                 if (!desc)
601                         pthread_mutex_unlock(&protows->mutex);
602                 else {
603                         *prv = desc->next;
604                         pthread_mutex_unlock(&protows->mutex);
605                         if (!readbuf_object(rb, &object))
606                                 object = NULL;
607                         desc->callback(desc->closure, object);
608                         free(desc);
609                 }
610         }
611 }
612
613 /* callback when receiving binary data */
614 static void client_on_binary_job(int sig, void *closure)
615 {
616         struct binary *binary = closure;
617
618         if (!sig) {
619                 switch (*binary->rb.head++) {
620                 case CHAR_FOR_REPLY: /* reply */
621                         client_on_reply(binary->protows, &binary->rb);
622                         break;
623                 case CHAR_FOR_EVT_BROADCAST: /* broadcast */
624                         client_on_event_broadcast(binary->protows, &binary->rb);
625                         break;
626                 case CHAR_FOR_EVT_ADD: /* creates the event */
627                         client_on_event_create(binary->protows, &binary->rb);
628                         break;
629                 case CHAR_FOR_EVT_DEL: /* removes the event */
630                         client_on_event_remove(binary->protows, &binary->rb);
631                         break;
632                 case CHAR_FOR_EVT_PUSH: /* pushs the event */
633                         client_on_event_push(binary->protows, &binary->rb);
634                         break;
635                 case CHAR_FOR_EVT_SUBSCRIBE: /* subscribe event for a request */
636                         client_on_event_subscribe(binary->protows, &binary->rb);
637                         break;
638                 case CHAR_FOR_EVT_UNSUBSCRIBE: /* unsubscribe event for a request */
639                         client_on_event_unsubscribe(binary->protows, &binary->rb);
640                         break;
641                 case CHAR_FOR_DESCRIPTION: /* description */
642                         client_on_description(binary->protows, &binary->rb);
643                         break;
644                 default: /* unexpected message */
645                         /* TODO: close the connection */
646                         break;
647                 }
648         }
649         free(binary->rb.base);
650         free(binary);
651 }
652
653 /* callback when receiving binary data */
654 static void client_on_binary(void *closure, char *data, size_t size)
655 {
656         struct afb_proto_ws *protows = closure;
657
658         queue_message_processing(protows, data, size, client_on_binary_job);
659 }
660
661 int afb_proto_ws_client_call(
662                 struct afb_proto_ws *protows,
663                 const char *verb,
664                 struct json_object *args,
665                 const char *sessionid,
666                 void *request,
667                 const char *user_creds
668 )
669 {
670         int rc = -1;
671         struct client_call *call;
672         struct writebuf wb = { .count = 0 };
673
674         /* allocate call data */
675         call = malloc(sizeof *call);
676         if (call == NULL) {
677                 errno = ENOMEM;
678                 return -1;
679         }
680         call->request = request;
681
682         /* init call data */
683         pthread_mutex_lock(&protows->mutex);
684         call->callid = ptr2id(call);
685         while(client_call_search_locked(protows, call->callid) != NULL)
686                 call->callid++;
687         call->protows = protows;
688         call->next = protows->calls;
689         protows->calls = call;
690         pthread_mutex_unlock(&protows->mutex);
691
692         /* creates the call message */
693         if (!writebuf_char(&wb, CHAR_FOR_CALL)
694          || !writebuf_uint32(&wb, call->callid)
695          || !writebuf_string(&wb, verb)
696          || !writebuf_string(&wb, sessionid)
697          || !writebuf_object(&wb, args)
698          || !writebuf_nullstring(&wb, user_creds)) {
699                 errno = EINVAL;
700                 goto clean;
701         }
702
703         /* send */
704         pthread_mutex_lock(&protows->mutex);
705         rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
706         pthread_mutex_unlock(&protows->mutex);
707         if (rc >= 0) {
708                 rc = 0;
709                 goto end;
710         }
711
712 clean:
713         client_call_destroy(call);
714 end:
715         return rc;
716 }
717
718 /* get the description */
719 int afb_proto_ws_client_describe(struct afb_proto_ws *protows, void (*callback)(void*, struct json_object*), void *closure)
720 {
721         struct client_describe *desc, *d;
722         struct writebuf wb = { .count = 0 };
723
724         desc = malloc(sizeof *desc);
725         if (!desc) {
726                 errno = ENOMEM;
727                 goto error;
728         }
729
730         /* fill in stack the description of the task */
731         pthread_mutex_lock(&protows->mutex);
732         desc->descid = ptr2id(desc);
733         d = protows->describes;
734         while (d) {
735                 if (d->descid != desc->descid)
736                         d = d->next;
737                 else {
738                         desc->descid++;
739                         d = protows->describes;
740                 }
741         }
742         desc->callback = callback;
743         desc->closure = closure;
744         desc->protows = protows;
745         desc->next = protows->describes;
746         protows->describes = desc;
747
748         /* send */
749         if (writebuf_char(&wb, CHAR_FOR_DESCRIBE)
750          && writebuf_uint32(&wb, desc->descid)
751          && afb_ws_binary_v(protows->ws, wb.iovec, wb.count) >= 0) {
752                 pthread_mutex_unlock(&protows->mutex);
753                 return 0;
754         }
755
756         d = protows->describes;
757         if (d == desc)
758                 protows->describes = desc->next;
759         else {
760                 while(d && d->next != desc)
761                         d = d->next;
762                 if (d)
763                         d->next = desc->next;
764         }
765         pthread_mutex_unlock(&protows->mutex);
766         free(desc);
767 error:
768         /* TODO? callback(closure, NULL); */
769         return -1;
770 }
771
772 /******************* client description part for server *****************************/
773
774 /* on call, propagate it to the ws service */
775 static void server_on_call(struct afb_proto_ws *protows, struct readbuf *rb)
776 {
777         struct afb_proto_ws_call *call;
778         const char *uuid, *verb, *user_creds;
779         uint32_t callid;
780         size_t lenverb;
781         struct json_object *object;
782
783         afb_proto_ws_addref(protows);
784
785         /* reads the call message data */
786         if (!readbuf_uint32(rb, &callid)
787          || !readbuf_string(rb, &verb, &lenverb)
788          || !readbuf_string(rb, &uuid, NULL)
789          || !readbuf_object(rb, &object)
790          || !readbuf_nullstring(rb, &user_creds, NULL))
791                 goto overflow;
792
793         /* create the request */
794         call = malloc(sizeof *call);
795         if (call == NULL)
796                 goto out_of_memory;
797
798         call->protows = protows;
799         call->callid = callid;
800         call->refcount = 1;
801         call->buffer = rb->base;
802         rb->base = NULL; /* don't free the buffer */
803
804         protows->server_itf->on_call(protows->closure, call, verb, object, uuid, user_creds);
805         return;
806
807 out_of_memory:
808         json_object_put(object);
809
810 overflow:
811         afb_proto_ws_unref(protows);
812 }
813
814 static int server_send_description(struct afb_proto_ws *protows, uint32_t descid, struct json_object *descobj)
815 {
816         int rc;
817         struct writebuf wb = { .count = 0 };
818
819         if (writebuf_char(&wb, CHAR_FOR_DESCRIPTION)
820          && writebuf_uint32(&wb, descid)
821          && writebuf_object(&wb, descobj)) {
822                 pthread_mutex_lock(&protows->mutex);
823                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
824                 pthread_mutex_unlock(&protows->mutex);
825                 if (rc >= 0)
826                         return 0;
827         }
828         return -1;
829 }
830
831 int afb_proto_ws_describe_put(struct afb_proto_ws_describe *describe, struct json_object *description)
832 {
833         int rc = server_send_description(describe->protows, describe->descid, description);
834         afb_proto_ws_unref(describe->protows);
835         free(describe);
836         return rc;
837 }
838
839 /* on describe, propagate it to the ws service */
840 static void server_on_describe(struct afb_proto_ws *protows, struct readbuf *rb)
841 {
842         uint32_t descid;
843         struct afb_proto_ws_describe *desc;
844
845         /* reads the descid */
846         if (readbuf_uint32(rb, &descid)) {
847                 if (protows->server_itf->on_describe) {
848                         /* create asynchronous job */
849                         desc = malloc(sizeof *desc);
850                         if (desc) {
851                                 desc->descid = descid;
852                                 desc->protows = protows;
853                                 afb_proto_ws_addref(protows);
854                                 protows->server_itf->on_describe(protows->closure, desc);
855                                 return;
856                         }
857                 }
858                 server_send_description(protows, descid, NULL);
859         }
860 }
861
862 /* callback when receiving binary data */
863 static void server_on_binary_job(int sig, void *closure)
864 {
865         struct binary *binary = closure;
866
867         if (!sig) {
868                 switch (*binary->rb.head++) {
869                 case CHAR_FOR_CALL:
870                         server_on_call(binary->protows, &binary->rb);
871                         break;
872                 case CHAR_FOR_DESCRIBE:
873                         server_on_describe(binary->protows, &binary->rb);
874                         break;
875                 default: /* unexpected message */
876                         /* TODO: close the connection */
877                         break;
878                 }
879         }
880         free(binary->rb.base);
881         free(binary);
882 }
883
884 static void server_on_binary(void *closure, char *data, size_t size)
885 {
886         struct afb_proto_ws *protows = closure;
887
888         queue_message_processing(protows, data, size, server_on_binary_job);
889 }
890
891 /******************* server part: manage events **********************************/
892
893 static int server_event_send(struct afb_proto_ws *protows, char order, const char *event_name, int event_id, struct json_object *data)
894 {
895         struct writebuf wb = { .count = 0 };
896         int rc;
897
898         if (writebuf_char(&wb, order)
899          && (order == CHAR_FOR_EVT_BROADCAST || writebuf_uint32(&wb, event_id))
900          && writebuf_string(&wb, event_name)
901          && (order == CHAR_FOR_EVT_ADD || order == CHAR_FOR_EVT_DEL || writebuf_object(&wb, data))) {
902                 pthread_mutex_lock(&protows->mutex);
903                 rc = afb_ws_binary_v(protows->ws, wb.iovec, wb.count);
904                 pthread_mutex_unlock(&protows->mutex);
905                 if (rc >= 0)
906                         return 0;
907         }
908         return -1;
909 }
910
911 int afb_proto_ws_server_event_create(struct afb_proto_ws *protows, const char *event_name, int event_id)
912 {
913         return server_event_send(protows, CHAR_FOR_EVT_ADD, event_name, event_id, NULL);
914 }
915
916 int afb_proto_ws_server_event_remove(struct afb_proto_ws *protows, const char *event_name, int event_id)
917 {
918         return server_event_send(protows, CHAR_FOR_EVT_DEL, event_name, event_id, NULL);
919 }
920
921 int afb_proto_ws_server_event_push(struct afb_proto_ws *protows, const char *event_name, int event_id, struct json_object *data)
922 {
923         return server_event_send(protows, CHAR_FOR_EVT_PUSH, event_name, event_id, data);
924 }
925
926 int afb_proto_ws_server_event_broadcast(struct afb_proto_ws *protows, const char *event_name, struct json_object *data)
927 {
928         return server_event_send(protows, CHAR_FOR_EVT_BROADCAST, event_name, 0, data);
929 }
930
931 /*****************************************************/
932
933 /* callback when receiving a hangup */
934 static void on_hangup(void *closure)
935 {
936         struct afb_proto_ws *protows = closure;
937         struct client_describe *cd, *ncd;
938         struct client_call *call, *ncall;
939
940         ncd = __atomic_exchange_n(&protows->describes, NULL, __ATOMIC_RELAXED);
941         ncall = __atomic_exchange_n(&protows->calls, NULL, __ATOMIC_RELAXED);
942
943         while (ncall) {
944                 call= ncall;
945                 ncall = call->next;
946                 protows->client_itf->on_reply(protows->closure, call->request, NULL, "disconnected", "server hung up");
947                 free(call);
948         }
949
950         while (ncd) {
951                 cd= ncd;
952                 ncd = cd->next;
953                 cd->callback(cd->closure, NULL);
954                 free(cd);
955         }
956
957         if (protows->fdev) {
958                 fdev_unref(protows->fdev);
959                 protows->fdev = 0;
960                 if (protows->on_hangup)
961                         protows->on_hangup(protows->closure);
962         }
963 }
964
965 /*****************************************************/
966
967 static const struct afb_ws_itf proto_ws_client_ws_itf =
968 {
969         .on_close = NULL,
970         .on_text = NULL,
971         .on_binary = client_on_binary,
972         .on_error = NULL,
973         .on_hangup = on_hangup
974 };
975
976 static const struct afb_ws_itf server_ws_itf =
977 {
978         .on_close = NULL,
979         .on_text = NULL,
980         .on_binary = server_on_binary,
981         .on_error = NULL,
982         .on_hangup = on_hangup
983 };
984
985 /*****************************************************/
986
987 static struct afb_proto_ws *afb_proto_ws_create(struct fdev *fdev, const struct afb_proto_ws_server_itf *itfs, const struct afb_proto_ws_client_itf *itfc, void *closure, const struct afb_ws_itf *itf)
988 {
989         struct afb_proto_ws *protows;
990
991         protows = calloc(1, sizeof *protows);
992         if (protows == NULL)
993                 errno = ENOMEM;
994         else {
995                 fcntl(fdev_fd(fdev), F_SETFD, FD_CLOEXEC);
996                 fcntl(fdev_fd(fdev), F_SETFL, O_NONBLOCK);
997                 protows->ws = afb_ws_create(fdev, itf, protows);
998                 if (protows->ws != NULL) {
999                         protows->fdev = fdev;
1000                         protows->refcount = 1;
1001                         protows->closure = closure;
1002                         protows->server_itf = itfs;
1003                         protows->client_itf = itfc;
1004                         pthread_mutex_init(&protows->mutex, NULL);
1005                         return protows;
1006                 }
1007                 free(protows);
1008         }
1009         return NULL;
1010 }
1011
1012 struct afb_proto_ws *afb_proto_ws_create_client(struct fdev *fdev, const struct afb_proto_ws_client_itf *itf, void *closure)
1013 {
1014         return afb_proto_ws_create(fdev, NULL, itf, closure, &proto_ws_client_ws_itf);
1015 }
1016
1017 struct afb_proto_ws *afb_proto_ws_create_server(struct fdev *fdev, const struct afb_proto_ws_server_itf *itf, void *closure)
1018 {
1019         return afb_proto_ws_create(fdev, itf, NULL, closure, &server_ws_itf);
1020 }
1021
1022 void afb_proto_ws_unref(struct afb_proto_ws *protows)
1023 {
1024         if (protows && !__atomic_sub_fetch(&protows->refcount, 1, __ATOMIC_RELAXED)) {
1025                 afb_proto_ws_hangup(protows);
1026                 afb_ws_destroy(protows->ws);
1027                 pthread_mutex_destroy(&protows->mutex);
1028                 free(protows);
1029         }
1030 }
1031
1032 void afb_proto_ws_addref(struct afb_proto_ws *protows)
1033 {
1034         __atomic_add_fetch(&protows->refcount, 1, __ATOMIC_RELAXED);
1035 }
1036
1037 int afb_proto_ws_is_client(struct afb_proto_ws *protows)
1038 {
1039         return !!protows->client_itf;
1040 }
1041
1042 int afb_proto_ws_is_server(struct afb_proto_ws *protows)
1043 {
1044         return !!protows->server_itf;
1045 }
1046
1047 void afb_proto_ws_hangup(struct afb_proto_ws *protows)
1048 {
1049         afb_ws_hangup(protows->ws);
1050 }
1051
1052 void afb_proto_ws_on_hangup(struct afb_proto_ws *protows, void (*on_hangup)(void *closure))
1053 {
1054         protows->on_hangup = on_hangup;
1055 }
1056
1057 void afb_proto_ws_set_queuing(struct afb_proto_ws *protows, int (*queuing)(struct afb_proto_ws*, void (*)(int,void*), void*))
1058 {
1059         protows->queuing = queuing;
1060 }