adds vectored function for text and binary
[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 text data described in the 'count' 'iovec' to the endpoint of 'ws'.
286  * Returns 0 on success or -1 in case of error.
287  */
288 int afb_ws_text_v(struct afb_ws *ws, const struct iovec *iovec, int count)
289 {
290         if (ws->ws == NULL) {
291                 /* disconnected */
292                 errno = EPIPE;
293                 return -1;
294         }
295         return websock_text_v(ws->ws, 1, iovec, count);
296 }
297
298 /*
299  * Sends a binary 'data' of 'length' to the endpoint of 'ws'.
300  * Returns 0 on success or -1 in case of error.
301  */
302 int afb_ws_binary(struct afb_ws *ws, const void *data, size_t length)
303 {
304         if (ws->ws == NULL) {
305                 /* disconnected */
306                 errno = EPIPE;
307                 return -1;
308         }
309         return websock_binary(ws->ws, 1, data, length);
310 }
311
312 /*
313  * Sends a binary data described in the 'count' 'iovec' to the endpoint of 'ws'.
314  * Returns 0 on success or -1 in case of error.
315  */
316 int afb_ws_binary_v(struct afb_ws *ws, const struct iovec *iovec, int count)
317 {
318         if (ws->ws == NULL) {
319                 /* disconnected */
320                 errno = EPIPE;
321                 return -1;
322         }
323         return websock_binary_v(ws->ws, 1, iovec, count);
324 }
325
326 /*
327  * callback for writing data
328  */
329 static ssize_t aws_writev(struct afb_ws *ws, const struct iovec *iov, int iovcnt)
330 {
331         ssize_t rc;
332         do {
333                 rc = writev(ws->fd, iov, iovcnt);
334         } while(rc == -1 && errno == EINTR);
335         return rc;
336 }
337
338 /*
339  * callback for reading data
340  */
341 static ssize_t aws_readv(struct afb_ws *ws, const struct iovec *iov, int iovcnt)
342 {
343         ssize_t rc;
344         do {
345                 rc = readv(ws->fd, iov, iovcnt);
346         } while(rc == -1 && errno == EINTR);
347         if (rc == 0) {
348                 errno = EPIPE;
349                 rc = -1;
350         }
351         return rc;
352 }
353
354 /*
355  * callback on incoming data
356  */
357 static void aws_on_readable(struct afb_ws *ws)
358 {
359         int rc;
360
361         assert(ws->ws != NULL);
362         rc = websock_dispatch(ws->ws);
363         if (rc < 0 && errno == EPIPE)
364                 afb_ws_hangup(ws);
365 }
366
367 /*
368  * Reads from the websocket handled by 'ws' data of length 'size'
369  * and append it to the current buffer of 'ws'.
370  * Returns 0 in case of error or 1 in case of success.
371  */
372 static int aws_read(struct afb_ws *ws, size_t size)
373 {
374         ssize_t sz;
375         char *buffer;
376
377         if (size != 0) {
378                 buffer = realloc(ws->buffer.buffer, ws->buffer.size + size + 1);
379                 if (buffer == NULL)
380                         return 0;
381                 ws->buffer.buffer = buffer;
382                 sz = websock_read(ws->ws, &buffer[ws->buffer.size], size);
383                 if ((size_t)sz != size)
384                         return 0;
385                 ws->buffer.size += size;
386         }
387         return 1;
388 }
389
390 /*
391  * Callback when 'close' command received from 'ws' with 'code' and 'size'.
392  */
393 static void aws_on_close(struct afb_ws *ws, uint16_t code, size_t size)
394 {
395         struct buf b;
396
397         ws->state = waiting;
398         free(aws_pick_buffer(ws).buffer);
399         if (ws->itf->on_close == NULL) {
400                 websock_drop(ws->ws);
401                 afb_ws_hangup(ws);
402         } else if (!aws_read(ws, size))
403                 ws->itf->on_close(ws->closure, code, NULL, 0);
404         else {
405                 b = aws_pick_buffer(ws);
406                 ws->itf->on_close(ws->closure, code, b.buffer, b.size);
407         }
408 }
409
410 /*
411  * Drops any incoming data and send an error of 'code'
412  */
413 static void aws_drop_error(struct afb_ws *ws, uint16_t code)
414 {
415         ws->state = waiting;
416         free(aws_pick_buffer(ws).buffer);
417         websock_drop(ws->ws);
418         websock_error(ws->ws, code, NULL, 0);
419 }
420
421 /*
422  * Reads either text or binary data of 'size' from 'ws' eventually 'last'.
423  */
424 static void aws_continue(struct afb_ws *ws, int last, size_t size)
425 {
426         struct buf b;
427         int istxt;
428
429         if (!aws_read(ws, size))
430                 aws_drop_error(ws, WEBSOCKET_CODE_ABNORMAL);
431         else if (last) {
432                 istxt = ws->state == reading_text;
433                 ws->state = waiting;
434                 b = aws_pick_buffer(ws);
435                 b.buffer[b.size] = 0;
436                 (istxt ? ws->itf->on_text : ws->itf->on_binary)(ws->closure, b.buffer, b.size);
437         }
438 }
439
440 /*
441  * Callback when 'text' message received from 'ws' with 'size' and possibly 'last'.
442  */
443 static void aws_on_text(struct afb_ws *ws, int last, size_t size)
444 {
445         if (ws->state != waiting)
446                 aws_drop_error(ws, WEBSOCKET_CODE_PROTOCOL_ERROR);
447         else if (ws->itf->on_text == NULL)
448                 aws_drop_error(ws, WEBSOCKET_CODE_CANT_ACCEPT);
449         else {
450                 ws->state = reading_text;
451                 aws_continue(ws, last, size);
452         }
453 }
454
455 /*
456  * Callback when 'binary' message received from 'ws' with 'size' and possibly 'last'.
457  */
458 static void aws_on_binary(struct afb_ws *ws, int last, size_t size)
459 {
460         if (ws->state != waiting)
461                 aws_drop_error(ws, WEBSOCKET_CODE_PROTOCOL_ERROR);
462         else if (ws->itf->on_binary == NULL)
463                 aws_drop_error(ws, WEBSOCKET_CODE_CANT_ACCEPT);
464         else {
465                 ws->state = reading_binary;
466                 aws_continue(ws, last, size);
467         }
468 }
469
470 /*
471  * Callback when 'close' command received from 'ws' with 'code' and 'size'.
472  */
473 static void aws_on_continue(struct afb_ws *ws, int last, size_t size)
474 {
475         if (ws->state == waiting)
476                 aws_drop_error(ws, WEBSOCKET_CODE_PROTOCOL_ERROR);
477         else
478                 aws_continue(ws, last, size);
479 }
480
481 /*
482  * Callback when 'close' command is sent to 'ws' with 'code' and 'size'.
483  */
484 static void aws_on_error(struct afb_ws *ws, uint16_t code, const void *data, size_t size)
485 {
486         if (ws->itf->on_error != NULL)
487                 ws->itf->on_error(ws->closure, code, data, size);
488         else
489                 afb_ws_hangup(ws);
490 }
491
492