Expose use of the event loop
[src/app-framework-binder.git] / src / afb-ws.c
1 /*
2  * Copyright (C) 2016 "IoT.bzh"
3  * Author: José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #define _GNU_SOURCE
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <stdint.h>
22 #include <assert.h>
23 #include <errno.h>
24 #include <sys/uio.h>
25 #include <string.h>
26 #include <stdarg.h>
27
28 #include <systemd/sd-event.h>
29
30 #include "websock.h"
31 #include "afb-ws.h"
32
33 #include "afb-common.h"
34
35 /*
36  * declaration of the websock interface for afb-ws
37  */
38 static ssize_t aws_writev(struct afb_ws *ws, const struct iovec *iov, int iovcnt);
39 static ssize_t aws_readv(struct afb_ws *ws, const struct iovec *iov, int iovcnt);
40 static void aws_on_close(struct afb_ws *ws, uint16_t code, size_t size);
41 static void aws_on_text(struct afb_ws *ws, int last, size_t size);
42 static void aws_on_binary(struct afb_ws *ws, int last, size_t size);
43 static void aws_on_continue(struct afb_ws *ws, int last, size_t size);
44 static void aws_on_readable(struct afb_ws *ws);
45 static void aws_on_error(struct afb_ws *ws, uint16_t code, const void *data, size_t size);
46
47 static struct websock_itf aws_itf = {
48         .writev = (void*)aws_writev,
49         .readv = (void*)aws_readv,
50
51         .on_ping = NULL,
52         .on_pong = NULL,
53         .on_close = (void*)aws_on_close,
54         .on_text = (void*)aws_on_text,
55         .on_binary = (void*)aws_on_binary,
56         .on_continue = (void*)aws_on_continue,
57         .on_extension = NULL,
58
59         .on_error = (void*)aws_on_error
60 };
61
62 /*
63  * a common scheme of buffer handling
64  */
65 struct buf
66 {
67         char *buffer;
68         size_t size;
69 };
70
71 /*
72  * the state
73  */
74 enum state
75 {
76         waiting,
77         reading_text,
78         reading_binary
79 };
80
81 /*
82  * the afb_ws structure
83  */
84 struct afb_ws
85 {
86         int fd;                 /* the socket file descriptor */
87         enum state state;       /* current state */
88         const struct afb_ws_itf *itf; /* the callback interface */
89         void *closure;          /* closure when calling the callbacks */
90         struct websock *ws;     /* the websock handler */
91         sd_event_source *evsrc; /* the event source for the socket */
92         struct buf buffer;      /* the last read fragment */
93 };
94
95 /*
96  * Returns the current buffer of 'ws' that is reset.
97  */
98 static inline struct buf aws_pick_buffer(struct afb_ws *ws)
99 {
100         struct buf result = ws->buffer;
101         ws->buffer.buffer = NULL;
102         ws->buffer.size = 0;
103         return result;
104 }
105
106 /*
107  * Disconnect the websocket 'ws' and calls on_hangup if
108  * 'call_on_hangup' is not null.
109  */
110 static void aws_disconnect(struct afb_ws *ws, int call_on_hangup)
111 {
112         struct websock *wsi = ws->ws;
113         if (wsi != NULL) {
114                 ws->ws = NULL;
115                 sd_event_source_unref(ws->evsrc);
116                 ws->evsrc = NULL;
117                 websock_destroy(wsi);
118                 free(aws_pick_buffer(ws).buffer);
119                 ws->state = waiting;
120                 if (call_on_hangup && ws->itf->on_hangup)
121                         ws->itf->on_hangup(ws->closure);
122         }
123 }
124
125 static int io_event_callback(sd_event_source *src, int fd, uint32_t revents, void *ws)
126 {
127         if ((revents & EPOLLIN) != 0)
128                 aws_on_readable(ws);
129         if ((revents & EPOLLHUP) != 0)
130                 afb_ws_hangup(ws);
131         return 0;
132 }
133
134 /*
135  * Creates the afb_ws structure for the file descritor
136  * 'fd' and the callbacks described by the interface 'itf'
137  * and its 'closure'.
138  * When the creation is a success, the systemd event loop 'eloop' is
139  * used for handling event for 'fd'.
140  *
141  * Returns the handle for the afb_ws created or NULL on error.
142  */
143 struct afb_ws *afb_ws_create(struct sd_event *eloop, int fd, const struct afb_ws_itf *itf, void *closure)
144 {
145         int rc;
146         struct afb_ws *result;
147
148         assert(fd >= 0);
149
150         /* allocation */
151         result = malloc(sizeof * result);
152         if (result == NULL)
153                 goto error;
154
155         /* init */
156         result->fd = fd;
157         result->state = waiting;
158         result->itf = itf;
159         result->closure = closure;
160         result->buffer.buffer = NULL;
161         result->buffer.size = 0;
162
163         /* creates the websocket */
164         result->ws = websock_create_v13(&aws_itf, result);
165         if (result->ws == NULL)
166                 goto error2;
167
168         /* creates the evsrc */
169         rc = sd_event_add_io(eloop, &result->evsrc, result->fd, EPOLLIN, io_event_callback, result);
170         if (rc < 0) {
171                 errno = -rc;
172                 goto error3;
173         }
174         return result;
175
176 error3:
177         websock_destroy(result->ws);
178 error2:
179         free(result);
180 error:
181         return NULL;
182 }
183
184 /*
185  * Destroys the websocket 'ws'
186  * It first hangup (but without calling on_hangup for safety reasons)
187  * if needed.
188  */
189 void afb_ws_destroy(struct afb_ws *ws)
190 {
191         aws_disconnect(ws, 0);
192         free(ws);
193 }
194
195 /*
196  * Hangup the websocket 'ws'
197  */
198 void afb_ws_hangup(struct afb_ws *ws)
199 {
200         aws_disconnect(ws, 1);
201 }
202
203 /*
204  * Sends a 'close' command to the endpoint of 'ws' with the 'code' and the
205  * 'reason' (that can be NULL and that else should not be greater than 123
206  * characters).
207  * Returns 0 on success or -1 in case of error.
208  */
209 int afb_ws_close(struct afb_ws *ws, uint16_t code, const char *reason)
210 {
211         if (ws->ws == NULL) {
212                 /* disconnected */
213                 errno = EPIPE;
214                 return -1;
215         }
216         return websock_close(ws->ws, code, reason, reason == NULL ? 0 : strlen(reason));
217 }
218
219 /*
220  * Sends a 'close' command to the endpoint of 'ws' with the 'code' and the
221  * 'reason' (that can be NULL and that else should not be greater than 123
222  * characters).
223  * Raise an error after 'close' command is sent.
224  * Returns 0 on success or -1 in case of error.
225  */
226 int afb_ws_error(struct afb_ws *ws, uint16_t code, const char *reason)
227 {
228         if (ws->ws == NULL) {
229                 /* disconnected */
230                 errno = EPIPE;
231                 return -1;
232         }
233         return websock_error(ws->ws, code, reason, reason == NULL ? 0 : strlen(reason));
234 }
235
236 /*
237  * Sends a 'text' of 'length' to the endpoint of 'ws'.
238  * Returns 0 on success or -1 in case of error.
239  */
240 int afb_ws_text(struct afb_ws *ws, const char *text, size_t length)
241 {
242         if (ws->ws == NULL) {
243                 /* disconnected */
244                 errno = EPIPE;
245                 return -1;
246         }
247         return websock_text(ws->ws, 1, text, length);
248 }
249
250 /*
251  * Sends a variable list of texts to the endpoint of 'ws'.
252  * Returns 0 on success or -1 in case of error.
253  */
254 int afb_ws_texts(struct afb_ws *ws, ...)
255 {
256         va_list args;
257         struct iovec ios[32];
258         int count;
259         const char *s;
260
261         if (ws->ws == NULL) {
262                 /* disconnected */
263                 errno = EPIPE;
264                 return -1;
265         }
266
267         count = 0;
268         va_start(args, ws);
269         s = va_arg(args, const char *);
270         while (s != NULL) {
271                 if (count == 32) {
272                         errno = EINVAL;
273                         return -1;
274                 }
275                 ios[count].iov_base = (void*)s;
276                 ios[count].iov_len = strlen(s);
277                 count++;
278                 s = va_arg(args, const char *);
279         }
280         va_end(args);
281         return websock_text_v(ws->ws, 1, ios, count);
282 }
283
284 /*
285  * Sends a binary 'data' of 'length' to the endpoint of 'ws'.
286  * Returns 0 on success or -1 in case of error.
287  */
288 int afb_ws_binary(struct afb_ws *ws, const void *data, size_t length)
289 {
290         if (ws->ws == NULL) {
291                 /* disconnected */
292                 errno = EPIPE;
293                 return -1;
294         }
295         return websock_binary(ws->ws, 1, data, length);
296 }
297
298 /*
299  * callback for writing data
300  */
301 static ssize_t aws_writev(struct afb_ws *ws, const struct iovec *iov, int iovcnt)
302 {
303         ssize_t rc;
304         do {
305                 rc = writev(ws->fd, iov, iovcnt);
306         } while(rc == -1 && errno == EINTR);
307         return rc;
308 }
309
310 /*
311  * callback for reading data
312  */
313 static ssize_t aws_readv(struct afb_ws *ws, const struct iovec *iov, int iovcnt)
314 {
315         ssize_t rc;
316         do {
317                 rc = readv(ws->fd, iov, iovcnt);
318         } while(rc == -1 && errno == EINTR);
319         if (rc == 0) {
320                 errno = EPIPE;
321                 rc = -1;
322         }
323         return rc;
324 }
325
326 /*
327  * callback on incoming data
328  */
329 static void aws_on_readable(struct afb_ws *ws)
330 {
331         int rc;
332
333         assert(ws->ws != NULL);
334         rc = websock_dispatch(ws->ws);
335         if (rc < 0 && errno == EPIPE)
336                 afb_ws_hangup(ws);
337 }
338
339 /*
340  * Reads from the websocket handled by 'ws' data of length 'size'
341  * and append it to the current buffer of 'ws'.
342  * Returns 0 in case of error or 1 in case of success.
343  */
344 static int aws_read(struct afb_ws *ws, size_t size)
345 {
346         ssize_t sz;
347         char *buffer;
348
349         if (size != 0) {
350                 buffer = realloc(ws->buffer.buffer, ws->buffer.size + size + 1);
351                 if (buffer == NULL)
352                         return 0;
353                 ws->buffer.buffer = buffer;
354                 sz = websock_read(ws->ws, &buffer[ws->buffer.size], size);
355                 if ((size_t)sz != size)
356                         return 0;
357                 ws->buffer.size += size;
358         }
359         return 1;
360 }
361
362 /*
363  * Callback when 'close' command received from 'ws' with 'code' and 'size'.
364  */
365 static void aws_on_close(struct afb_ws *ws, uint16_t code, size_t size)
366 {
367         struct buf b;
368
369         ws->state = waiting;
370         free(aws_pick_buffer(ws).buffer);
371         if (ws->itf->on_close == NULL) {
372                 websock_drop(ws->ws);
373                 afb_ws_hangup(ws);
374         } else if (!aws_read(ws, size))
375                 ws->itf->on_close(ws->closure, code, NULL, 0);
376         else {
377                 b = aws_pick_buffer(ws);
378                 ws->itf->on_close(ws->closure, code, b.buffer, b.size);
379         }
380 }
381
382 /*
383  * Drops any incoming data and send an error of 'code'
384  */
385 static void aws_drop_error(struct afb_ws *ws, uint16_t code)
386 {
387         ws->state = waiting;
388         free(aws_pick_buffer(ws).buffer);
389         websock_drop(ws->ws);
390         websock_error(ws->ws, code, NULL, 0);
391 }
392
393 /*
394  * Reads either text or binary data of 'size' from 'ws' eventually 'last'.
395  */
396 static void aws_continue(struct afb_ws *ws, int last, size_t size)
397 {
398         struct buf b;
399         int istxt;
400
401         if (!aws_read(ws, size))
402                 aws_drop_error(ws, WEBSOCKET_CODE_ABNORMAL);
403         else if (last) {
404                 istxt = ws->state == reading_text;
405                 ws->state = waiting;
406                 b = aws_pick_buffer(ws);
407                 b.buffer[b.size] = 0;
408                 (istxt ? ws->itf->on_text : ws->itf->on_binary)(ws->closure, b.buffer, b.size);
409         }
410 }
411
412 /*
413  * Callback when 'text' message received from 'ws' with 'size' and possibly 'last'.
414  */
415 static void aws_on_text(struct afb_ws *ws, int last, size_t size)
416 {
417         if (ws->state != waiting)
418                 aws_drop_error(ws, WEBSOCKET_CODE_PROTOCOL_ERROR);
419         else if (ws->itf->on_text == NULL)
420                 aws_drop_error(ws, WEBSOCKET_CODE_CANT_ACCEPT);
421         else {
422                 ws->state = reading_text;
423                 aws_continue(ws, last, size);
424         }
425 }
426
427 /*
428  * Callback when 'binary' message received from 'ws' with 'size' and possibly 'last'.
429  */
430 static void aws_on_binary(struct afb_ws *ws, int last, size_t size)
431 {
432         if (ws->state != waiting)
433                 aws_drop_error(ws, WEBSOCKET_CODE_PROTOCOL_ERROR);
434         else if (ws->itf->on_binary == NULL)
435                 aws_drop_error(ws, WEBSOCKET_CODE_CANT_ACCEPT);
436         else {
437                 ws->state = reading_binary;
438                 aws_continue(ws, last, size);
439         }
440 }
441
442 /*
443  * Callback when 'close' command received from 'ws' with 'code' and 'size'.
444  */
445 static void aws_on_continue(struct afb_ws *ws, int last, size_t size)
446 {
447         if (ws->state == waiting)
448                 aws_drop_error(ws, WEBSOCKET_CODE_PROTOCOL_ERROR);
449         else
450                 aws_continue(ws, last, size);
451 }
452
453 /*
454  * Callback when 'close' command is sent to 'ws' with 'code' and 'size'.
455  */
456 static void aws_on_error(struct afb_ws *ws, uint16_t code, const void *data, size_t size)
457 {
458         if (ws->itf->on_error != NULL)
459                 ws->itf->on_error(ws->closure, code, data, size);
460         else
461                 afb_ws_hangup(ws);
462 }
463
464