2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2014 Andy Green <andy@warmcat.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 #include "private-libwebsockets.h"
25 lws_calllback_as_writeable(struct libwebsocket_context *context,
26 struct libwebsocket *wsi)
31 case LWS_CONNMODE_WS_CLIENT:
32 n = LWS_CALLBACK_CLIENT_WRITEABLE;
34 case LWS_CONNMODE_WS_SERVING:
35 n = LWS_CALLBACK_SERVER_WRITEABLE;
38 n = LWS_CALLBACK_HTTP_WRITEABLE;
41 lwsl_info("%s: %p (user=%p)\n", __func__, wsi, wsi->user_space);
42 return user_callback_handle_rxflow(wsi->protocol->callback, context,
43 wsi, (enum libwebsocket_callback_reasons) n,
44 wsi->user_space, NULL, 0);
48 lws_handle_POLLOUT_event(struct libwebsocket_context *context,
49 struct libwebsocket *wsi, struct libwebsocket_pollfd *pollfd)
52 struct lws_tokens eff_buf;
54 struct libwebsocket *wsi2;
60 /* pending truncated sends have uber priority */
62 if (wsi->truncated_send_len) {
63 if (lws_issue_raw(wsi, wsi->truncated_send_malloc +
64 wsi->truncated_send_offset,
65 wsi->truncated_send_len) < 0) {
66 lwsl_info("lws_handle_POLLOUT_event signalling to close\n");
69 /* leave POLLOUT active either way */
72 if (wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
73 lwsl_info("***** %x signalling to close in POLLOUT handler\n", wsi);
74 return -1; /* retry closing now */
77 /* protocol packets are next */
79 lwsl_info("servicing pps %d\n", wsi->pps);
81 case LWS_PPS_HTTP2_MY_SETTINGS:
82 case LWS_PPS_HTTP2_ACK_SETTINGS:
83 lws_http2_do_pps_send(context, wsi);
88 wsi->pps = LWS_PPS_NONE;
89 libwebsocket_rx_flow_control(wsi, 1);
91 return 0; /* leave POLLOUT active */
94 /* pending control packets have next priority */
96 if (wsi->state == WSI_STATE_ESTABLISHED && wsi->u.ws.ping_payload_len) {
97 n = libwebsocket_write(wsi,
98 &wsi->u.ws.ping_payload_buf[
99 LWS_SEND_BUFFER_PRE_PADDING],
100 wsi->u.ws.ping_payload_len,
104 /* well he is sent, mark him done */
105 wsi->u.ws.ping_payload_len = 0;
106 /* leave POLLOUT active either way */
110 /* if nothing critical, user can get the callback */
112 m = lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_IS_WRITEABLE,
116 #ifndef LWS_NO_EXTENSIONS
117 if (!wsi->extension_data_pending || handled == 2)
121 * check in on the active extensions, see if they
122 * had pending stuff to spill... they need to get the
123 * first look-in otherwise sequence will be disordered
125 * NULL, zero-length eff_buf means just spill pending
131 /* default to nobody has more to spill */
134 eff_buf.token = NULL;
135 eff_buf.token_len = 0;
137 /* give every extension a chance to spill */
139 m = lws_ext_callback_for_each_active(wsi,
140 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
143 lwsl_err("ext reports fatal error\n");
148 * at least one extension told us he has more
149 * to spill, so we will go around again after
153 /* assuming they gave us something to send, send it */
155 if (eff_buf.token_len) {
156 n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
159 lwsl_info("closing from POLLOUT spill\n");
163 * Keep amount spilled small to minimize chance of this
165 if (n != eff_buf.token_len) {
166 lwsl_err("Unable to spill ext %d vs %s\n",
167 eff_buf.token_len, n);
173 /* no extension has more to spill */
179 * There's more to spill from an extension, but we just sent
180 * something... did that leave the pipe choked?
183 if (!lws_send_pipe_choked(wsi))
184 /* no we could add more */
187 lwsl_info("choked in POLLOUT service\n");
190 * Yes, he's choked. Leave the POLLOUT masked on so we will
191 * come back here when he is unchoked. Don't call the user
192 * callback to enforce ordering of spilling, he'll get called
193 * when we come back here and there's nothing more to spill.
198 #ifndef LWS_NO_EXTENSIONS
199 wsi->extension_data_pending = 0;
206 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
207 lwsl_info("failled at set pollfd\n");
211 lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE);
217 * we are the 'network wsi' for potentially many muxed child wsi with
218 * no network connection of their own, who have to use us for all their
219 * network actions. So we use a round-robin scheme to share out the
220 * POLLOUT notifications to our children.
222 * But because any child could exhaust the socket's ability to take
223 * writes, we can only let one child get notified each time.
225 * In addition children may be closed / deleted / added between POLLOUT
226 * notifications, so we can't hold pointers
229 if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING) {
230 lwsl_info("%s: non http2\n", __func__);
234 wsi->u.http2.requested_POLLOUT = 0;
235 if (!wsi->u.http2.initialized) {
236 lwsl_info("pollout on uninitialized http2 conn\n");
240 lwsl_info("%s: doing children\n", __func__);
244 wsi2 = wsi2->u.http2.next_child_wsi;
245 lwsl_info("%s: child %p\n", __func__, wsi2);
248 if (!wsi2->u.http2.requested_POLLOUT)
250 wsi2->u.http2.requested_POLLOUT = 0;
251 if (lws_calllback_as_writeable(context, wsi2)) {
252 lwsl_debug("Closing POLLOUT child\n");
253 libwebsocket_close_and_free_session(context, wsi2,
254 LWS_CLOSE_STATUS_NOSTATUS);
257 } while (wsi2 != NULL && !lws_send_pipe_choked(wsi));
259 lwsl_info("%s: completed\n", __func__);
264 return lws_calllback_as_writeable(context, wsi);
270 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
271 struct libwebsocket *wsi, unsigned int sec)
274 * if extensions want in on it (eg, we are a mux parent)
275 * give them a chance to service child timeouts
277 if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_1HZ, NULL, sec) < 0)
280 if (!wsi->pending_timeout)
284 * if we went beyond the allowed time, kill the
287 if (sec > wsi->pending_timeout_limit) {
288 lwsl_info("TIMEDOUT WAITING on %d\n", wsi->pending_timeout);
289 libwebsocket_close_and_free_session(context,
290 wsi, LWS_CLOSE_STATUS_NOSTATUS);
297 int lws_rxflow_cache(struct libwebsocket *wsi, unsigned char *buf, int n, int len)
299 /* his RX is flowcontrolled, don't send remaining now */
300 if (wsi->rxflow_buffer) {
301 /* rxflow while we were spilling prev rxflow */
302 lwsl_info("stalling in existing rxflow buf\n");
306 /* a new rxflow, buffer it and warn caller */
307 lwsl_info("new rxflow input buffer len %d\n", len - n);
308 wsi->rxflow_buffer = (unsigned char *)malloc(len - n);
309 wsi->rxflow_len = len - n;
311 memcpy(wsi->rxflow_buffer, buf + n, len - n);
317 * libwebsocket_service_fd() - Service polled socket with something waiting
318 * @context: Websocket context
319 * @pollfd: The pollfd entry describing the socket fd and which events
322 * This function takes a pollfd that has POLLIN or POLLOUT activity and
323 * services it according to the state of the associated
324 * struct libwebsocket.
326 * The one call deals with all "service" that might happen on a socket
327 * including listen accepts, http files as well as websocket protocol.
329 * If a pollfd says it has something, you can just pass it to
330 * libwebsocket_serice_fd() whether it is a socket handled by lws or not.
331 * If it sees it is a lws socket, the traffic will be handled and
332 * pollfd->revents will be zeroed now.
334 * If the socket is foreign to lws, it leaves revents alone. So you can
335 * see if you should service yourself by checking the pollfd revents
336 * after letting lws try to service it.
340 libwebsocket_service_fd(struct libwebsocket_context *context,
341 struct libwebsocket_pollfd *pollfd)
343 struct libwebsocket *wsi;
346 int listen_socket_fds_index = 0;
350 char draining_flow = 0;
352 struct lws_tokens eff_buf;
354 if (context->listen_service_fd)
355 listen_socket_fds_index = context->lws_lookup[
356 context->listen_service_fd]->position_in_fds_table;
359 * you can call us with pollfd = NULL to just allow the once-per-second
360 * global timeout checks; if less than a second since the last check
361 * it returns immediately then.
366 /* TODO: if using libev, we should probably use timeout watchers... */
367 if (context->last_timeout_check_s != now) {
368 context->last_timeout_check_s = now;
370 lws_plat_service_periodic(context);
372 /* global timeout check once per second */
377 for (n = 0; n < context->fds_count; n++) {
378 m = context->fds[n].fd;
379 wsi = context->lws_lookup[m];
383 if (libwebsocket_service_timeout_check(context, wsi, now))
384 /* he did time out... */
386 /* it was the guy we came to service! */
388 /* mark as handled */
394 /* the socket we came to service timed out, nothing to do */
398 /* just here for timeout management? */
402 /* no, here to service a socket descriptor */
403 wsi = context->lws_lookup[pollfd->fd];
405 /* not lws connection ... leave revents alone and return */
409 * so that caller can tell we handled, past here we need to
410 * zero down pollfd->revents after handling
414 * deal with listen service piggybacking
415 * every listen_service_modulo services of other fds, we
416 * sneak one in to service the listen socket if there's anything waiting
418 * To handle connection storms, as found in ab, if we previously saw a
419 * pending connection here, it causes us to check again next time.
422 if (context->listen_service_fd && pollfd !=
423 &context->fds[listen_socket_fds_index]) {
424 context->listen_service_count++;
425 if (context->listen_service_extraseen ||
426 context->listen_service_count ==
427 context->listen_service_modulo) {
428 context->listen_service_count = 0;
430 if (context->listen_service_extraseen > 5)
434 * even with extpoll, we prepared this
435 * internal fds for listen
437 n = lws_poll_listen_fd(&context->fds[listen_socket_fds_index]);
438 if (n > 0) { /* there's a conn waiting for us */
439 libwebsocket_service_fd(context,
441 fds[listen_socket_fds_index]);
442 context->listen_service_extraseen++;
444 if (context->listen_service_extraseen)
446 listen_service_extraseen--;
454 /* handle session socket closed */
456 if ((!(pollfd->revents & LWS_POLLIN)) &&
457 (pollfd->revents & LWS_POLLHUP)) {
459 lwsl_debug("Session Socket %p (fd=%d) dead\n",
460 (void *)wsi, pollfd->fd);
462 goto close_and_handled;
465 /* okay, what we came here to do... */
468 case LWS_CONNMODE_HTTP_SERVING:
469 case LWS_CONNMODE_HTTP_SERVING_ACCEPTED:
470 case LWS_CONNMODE_SERVER_LISTENER:
471 case LWS_CONNMODE_SSL_ACK_PENDING:
472 n = lws_server_socket_service(context, wsi, pollfd);
474 goto close_and_handled;
477 case LWS_CONNMODE_WS_SERVING:
478 case LWS_CONNMODE_WS_CLIENT:
479 case LWS_CONNMODE_HTTP2_SERVING:
481 /* the guy requested a callback when it was OK to write */
483 if ((pollfd->revents & LWS_POLLOUT) &&
484 (wsi->state == WSI_STATE_ESTABLISHED || wsi->state == WSI_STATE_HTTP2_ESTABLISHED || wsi->state == WSI_STATE_HTTP2_ESTABLISHED_PRE_SETTINGS ||
485 wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) &&
486 lws_handle_POLLOUT_event(context, wsi, pollfd)) {
487 lwsl_info("libwebsocket_service_fd: closing\n");
488 goto close_and_handled;
491 if (wsi->rxflow_buffer &&
492 (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
493 lwsl_info("draining rxflow\n");
495 eff_buf.token = (char *)wsi->rxflow_buffer +
497 eff_buf.token_len = wsi->rxflow_len - wsi->rxflow_pos;
502 /* any incoming data ready? */
504 if (!(pollfd->revents & LWS_POLLIN))
507 eff_buf.token_len = lws_ssl_capable_read(context, wsi,
508 context->service_buffer,
509 sizeof(context->service_buffer));
510 switch (eff_buf.token_len) {
512 lwsl_info("service_fd: closing due to 0 length read\n");
513 goto close_and_handled;
514 case LWS_SSL_CAPABLE_MORE_SERVICE:
515 lwsl_info("SSL Capable more service\n");
518 case LWS_SSL_CAPABLE_ERROR:
519 lwsl_info("Closing when error\n");
520 goto close_and_handled;
524 * give any active extensions a chance to munge the buffer
525 * before parse. We pass in a pointer to an lws_tokens struct
526 * prepared with the default buffer and content length that's in
527 * there. Rather than rewrite the default buffer, extensions
528 * that expect to grow the buffer can adapt .token to
529 * point to their own per-connection buffer in the extension
530 * user allocation. By default with no extensions or no
531 * extension callback handling, just the normal input buffer is
532 * used then so it is efficient.
535 eff_buf.token = (char *)context->service_buffer;
542 m = lws_ext_callback_for_each_active(wsi,
543 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE, &eff_buf, 0);
545 goto close_and_handled;
549 /* service incoming data */
551 if (eff_buf.token_len) {
552 n = libwebsocket_read(context, wsi,
553 (unsigned char *)eff_buf.token,
562 eff_buf.token = NULL;
563 eff_buf.token_len = 0;
566 if (draining_flow && wsi->rxflow_buffer &&
567 wsi->rxflow_pos == wsi->rxflow_len) {
568 lwsl_info("flow buffer: drained\n");
569 free(wsi->rxflow_buffer);
570 wsi->rxflow_buffer = NULL;
571 /* having drained the rxflow buffer, can rearm POLLIN */
572 _libwebsocket_rx_flow_control(wsi); /* n ignored, needed for NO_SERVER case */
581 n = lws_client_socket_service(context, wsi, pollfd);
590 lwsl_debug("Close and handled\n");
591 libwebsocket_close_and_free_session(context, wsi,
592 LWS_CLOSE_STATUS_NOSTATUS);
601 * libwebsocket_service() - Service any pending websocket activity
602 * @context: Websocket context
603 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
604 * service otherwise block and service immediately, returning
605 * after the timeout if nothing needed service.
607 * This function deals with any pending websocket traffic, for three
608 * kinds of event. It handles these events on both server and client
609 * types of connection the same.
611 * 1) Accept new connections to our context's server
613 * 2) Call the receive callback for incoming frame data received by
614 * server or client connections.
616 * You need to call this service function periodically to all the above
617 * functions to happen; if your application is single-threaded you can
618 * just call it in your main event loop.
620 * Alternatively you can fork a new process that asynchronously handles
621 * calling this service in a loop. In that case you are happy if this
622 * call blocks your thread until it needs to take care of something and
623 * would call it with a large nonzero timeout. Your loop then takes no
624 * CPU while there is nothing happening.
626 * If you are calling it in a single-threaded app, you don't want it to
627 * wait around blocking other things in your loop from happening, so you
628 * would call it with a timeout_ms of 0, so it returns immediately if
629 * nothing is pending, or as soon as it services whatever was pending.
633 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
635 return lws_plat_service(context, timeout_ms);