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