+/*
+ * Returns the current buffer of 'ws' that is reset.
+ */
+static inline struct buf aws_pick_buffer(struct afb_ws *ws)
+{
+ struct buf result = ws->buffer;
+ ws->buffer.buffer = NULL;
+ ws->buffer.size = 0;
+ return result;
+}
+
+/*
+ * Disconnect the websocket 'ws' and calls on_hangup if
+ * 'call_on_hangup' is not null.
+ */
+static void aws_disconnect(struct afb_ws *ws, int call_on_hangup)
+{
+ struct websock *wsi = ws->ws;
+ if (wsi != NULL) {
+ ws->ws = NULL;
+ sd_event_source_unref(ws->evsrc);
+ ws->evsrc = NULL;
+ websock_destroy(wsi);
+ free(aws_pick_buffer(ws).buffer);
+ ws->state = waiting;
+ if (call_on_hangup && ws->itf->on_hangup)
+ ws->itf->on_hangup(ws->closure);
+ }
+}
+
+static int io_event_callback(sd_event_source *src, int fd, uint32_t revents, void *ws)
+{
+ if ((revents & EPOLLIN) != 0)
+ aws_on_readable(ws);
+ if ((revents & EPOLLHUP) != 0)
+ afb_ws_hangup(ws);
+ return 0;
+}
+
+/*
+ * Creates the afb_ws structure for the file descritor
+ * 'fd' and the callbacks described by the interface 'itf'
+ * and its 'closure'.
+ *
+ * Returns the handle for the afb_ws created or NULL on error.
+ */