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