2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2015 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;
58 int write_type = LWS_WRITE_PONG;
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 &&
97 wsi->u.ws.ping_pending_flag) ||
98 (wsi->state == WSI_STATE_RETURNED_CLOSE_ALREADY &&
99 wsi->u.ws.payload_is_close)) {
101 if (wsi->u.ws.payload_is_close)
102 write_type = LWS_WRITE_CLOSE;
104 n = libwebsocket_write(wsi,
105 &wsi->u.ws.ping_payload_buf[
106 LWS_SEND_BUFFER_PRE_PADDING],
107 wsi->u.ws.ping_payload_len,
112 /* well he is sent, mark him done */
113 wsi->u.ws.ping_pending_flag = 0;
114 if (wsi->u.ws.payload_is_close)
115 /* oh... a close frame was it... then we are done */
118 /* otherwise for PING, leave POLLOUT active either way */
122 /* if we are closing, don't confuse the user with writeable cb */
124 if (wsi->state == WSI_STATE_RETURNED_CLOSE_ALREADY)
127 /* if nothing critical, user can get the callback */
129 m = lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_IS_WRITEABLE,
131 #ifndef LWS_NO_EXTENSIONS
132 if (!wsi->extension_data_pending)
136 * check in on the active extensions, see if they
137 * had pending stuff to spill... they need to get the
138 * first look-in otherwise sequence will be disordered
140 * NULL, zero-length eff_buf means just spill pending
146 /* default to nobody has more to spill */
149 eff_buf.token = NULL;
150 eff_buf.token_len = 0;
152 /* give every extension a chance to spill */
154 m = lws_ext_callback_for_each_active(wsi,
155 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
158 lwsl_err("ext reports fatal error\n");
163 * at least one extension told us he has more
164 * to spill, so we will go around again after
168 /* assuming they gave us something to send, send it */
170 if (eff_buf.token_len) {
171 n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
174 lwsl_info("closing from POLLOUT spill\n");
178 * Keep amount spilled small to minimize chance of this
180 if (n != eff_buf.token_len) {
181 lwsl_err("Unable to spill ext %d vs %s\n",
182 eff_buf.token_len, n);
188 /* no extension has more to spill */
194 * There's more to spill from an extension, but we just sent
195 * something... did that leave the pipe choked?
198 if (!lws_send_pipe_choked(wsi))
199 /* no we could add more */
202 lwsl_info("choked in POLLOUT service\n");
205 * Yes, he's choked. Leave the POLLOUT masked on so we will
206 * come back here when he is unchoked. Don't call the user
207 * callback to enforce ordering of spilling, he'll get called
208 * when we come back here and there's nothing more to spill.
213 #ifndef LWS_NO_EXTENSIONS
214 wsi->extension_data_pending = 0;
220 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
221 lwsl_info("failled at set pollfd\n");
225 lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE);
230 * we are the 'network wsi' for potentially many muxed child wsi with
231 * no network connection of their own, who have to use us for all their
232 * network actions. So we use a round-robin scheme to share out the
233 * POLLOUT notifications to our children.
235 * But because any child could exhaust the socket's ability to take
236 * writes, we can only let one child get notified each time.
238 * In addition children may be closed / deleted / added between POLLOUT
239 * notifications, so we can't hold pointers
242 if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING) {
243 lwsl_info("%s: non http2\n", __func__);
247 wsi->u.http2.requested_POLLOUT = 0;
248 if (!wsi->u.http2.initialized) {
249 lwsl_info("pollout on uninitialized http2 conn\n");
253 lwsl_info("%s: doing children\n", __func__);
257 wsi2 = wsi2->u.http2.next_child_wsi;
258 lwsl_info("%s: child %p\n", __func__, wsi2);
261 if (!wsi2->u.http2.requested_POLLOUT)
263 wsi2->u.http2.requested_POLLOUT = 0;
264 if (lws_calllback_as_writeable(context, wsi2)) {
265 lwsl_debug("Closing POLLOUT child\n");
266 libwebsocket_close_and_free_session(context, wsi2,
267 LWS_CLOSE_STATUS_NOSTATUS);
270 } while (wsi2 != NULL && !lws_send_pipe_choked(wsi));
272 lwsl_info("%s: completed\n", __func__);
277 return lws_calllback_as_writeable(context, wsi);
283 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
284 struct libwebsocket *wsi, unsigned int sec)
287 * if extensions want in on it (eg, we are a mux parent)
288 * give them a chance to service child timeouts
290 if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_1HZ, NULL, sec) < 0)
293 if (!wsi->pending_timeout)
297 * if we went beyond the allowed time, kill the
300 if ((time_t)sec > wsi->pending_timeout_limit) {
301 lwsl_info("TIMEDOUT WAITING on %d\n", wsi->pending_timeout);
303 * Since he failed a timeout, he already had a chance to do
304 * something and was unable to... that includes situations like
305 * half closed connections. So process this "failed timeout"
306 * close as a violent death and don't try to do protocol
307 * cleanup like flush partials.
309 wsi->socket_is_permanently_unusable = 1;
310 libwebsocket_close_and_free_session(context,
311 wsi, LWS_CLOSE_STATUS_NOSTATUS);
318 int lws_rxflow_cache(struct libwebsocket *wsi, unsigned char *buf, int n, int len)
320 /* his RX is flowcontrolled, don't send remaining now */
321 if (wsi->rxflow_buffer) {
322 /* rxflow while we were spilling prev rxflow */
323 lwsl_info("stalling in existing rxflow buf\n");
327 /* a new rxflow, buffer it and warn caller */
328 lwsl_info("new rxflow input buffer len %d\n", len - n);
329 wsi->rxflow_buffer = lws_malloc(len - n);
330 wsi->rxflow_len = len - n;
332 memcpy(wsi->rxflow_buffer, buf + n, len - n);
338 * libwebsocket_service_fd() - Service polled socket with something waiting
339 * @context: Websocket context
340 * @pollfd: The pollfd entry describing the socket fd and which events
343 * This function takes a pollfd that has POLLIN or POLLOUT activity and
344 * services it according to the state of the associated
345 * struct libwebsocket.
347 * The one call deals with all "service" that might happen on a socket
348 * including listen accepts, http files as well as websocket protocol.
350 * If a pollfd says it has something, you can just pass it to
351 * libwebsocket_serice_fd() whether it is a socket handled by lws or not.
352 * If it sees it is a lws socket, the traffic will be handled and
353 * pollfd->revents will be zeroed now.
355 * If the socket is foreign to lws, it leaves revents alone. So you can
356 * see if you should service yourself by checking the pollfd revents
357 * after letting lws try to service it.
361 libwebsocket_service_fd(struct libwebsocket_context *context,
362 struct libwebsocket_pollfd *pollfd)
364 struct libwebsocket *wsi;
367 int listen_socket_fds_index = 0;
370 lws_sockfd_type our_fd = 0;
371 char draining_flow = 0;
373 struct lws_tokens eff_buf;
374 unsigned int pending = 0;
376 if (context->listen_service_fd)
377 listen_socket_fds_index = wsi_from_fd(context,context->listen_service_fd)->position_in_fds_table;
380 * you can call us with pollfd = NULL to just allow the once-per-second
381 * global timeout checks; if less than a second since the last check
382 * it returns immediately then.
387 /* TODO: if using libev, we should probably use timeout watchers... */
388 if (context->last_timeout_check_s != now) {
389 context->last_timeout_check_s = now;
391 lws_plat_service_periodic(context);
393 /* global timeout check once per second */
398 for (n = 0; n < context->fds_count; n++) {
399 mfd = context->fds[n].fd;
400 wsi = wsi_from_fd(context, mfd);
404 if (libwebsocket_service_timeout_check(context, wsi, now))
405 /* he did time out... */
407 /* it was the guy we came to service! */
409 /* he's gone, no need to mark as handled */
414 /* the socket we came to service timed out, nothing to do */
418 /* just here for timeout management? */
422 /* no, here to service a socket descriptor */
423 wsi = wsi_from_fd(context, pollfd->fd);
425 /* not lws connection ... leave revents alone and return */
429 * so that caller can tell we handled, past here we need to
430 * zero down pollfd->revents after handling
434 * deal with listen service piggybacking
435 * every listen_service_modulo services of other fds, we
436 * sneak one in to service the listen socket if there's anything waiting
438 * To handle connection storms, as found in ab, if we previously saw a
439 * pending connection here, it causes us to check again next time.
442 if (context->listen_service_fd && pollfd !=
443 &context->fds[listen_socket_fds_index]) {
444 context->listen_service_count++;
445 if (context->listen_service_extraseen ||
446 context->listen_service_count ==
447 context->listen_service_modulo) {
448 context->listen_service_count = 0;
450 if (context->listen_service_extraseen > 5)
454 * even with extpoll, we prepared this
455 * internal fds for listen
457 n = lws_poll_listen_fd(&context->fds[listen_socket_fds_index]);
458 if (n > 0) { /* there's a conn waiting for us */
459 libwebsocket_service_fd(context,
461 fds[listen_socket_fds_index]);
462 context->listen_service_extraseen++;
464 if (context->listen_service_extraseen)
466 listen_service_extraseen--;
474 /* handle session socket closed */
476 if ((!(pollfd->revents & LWS_POLLIN)) &&
477 (pollfd->revents & LWS_POLLHUP)) {
479 lwsl_debug("Session Socket %p (fd=%d) dead\n",
480 (void *)wsi, pollfd->fd);
482 goto close_and_handled;
485 /* okay, what we came here to do... */
488 case LWS_CONNMODE_HTTP_SERVING:
489 case LWS_CONNMODE_HTTP_SERVING_ACCEPTED:
490 case LWS_CONNMODE_SERVER_LISTENER:
491 case LWS_CONNMODE_SSL_ACK_PENDING:
492 n = lws_server_socket_service(context, wsi, pollfd);
494 goto close_and_handled;
497 case LWS_CONNMODE_WS_SERVING:
498 case LWS_CONNMODE_WS_CLIENT:
499 case LWS_CONNMODE_HTTP2_SERVING:
501 /* the guy requested a callback when it was OK to write */
503 if ((pollfd->revents & LWS_POLLOUT) &&
504 (wsi->state == WSI_STATE_ESTABLISHED ||
505 wsi->state == WSI_STATE_HTTP2_ESTABLISHED ||
506 wsi->state == WSI_STATE_HTTP2_ESTABLISHED_PRE_SETTINGS ||
507 wsi->state == WSI_STATE_RETURNED_CLOSE_ALREADY ||
508 wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) &&
509 lws_handle_POLLOUT_event(context, wsi, pollfd)) {
510 lwsl_info("libwebsocket_service_fd: closing\n");
511 goto close_and_handled;
514 if (wsi->rxflow_buffer &&
515 (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
516 lwsl_info("draining rxflow\n");
518 eff_buf.token = (char *)wsi->rxflow_buffer +
520 eff_buf.token_len = wsi->rxflow_len - wsi->rxflow_pos;
525 /* any incoming data ready? */
527 if (!(pollfd->revents & LWS_POLLIN))
531 eff_buf.token_len = lws_ssl_capable_read(context, wsi,
532 context->service_buffer,
533 pending?pending:sizeof(context->service_buffer));
534 switch (eff_buf.token_len) {
536 lwsl_info("service_fd: closing due to 0 length read\n");
537 goto close_and_handled;
538 case LWS_SSL_CAPABLE_MORE_SERVICE:
539 lwsl_info("SSL Capable more service\n");
542 case LWS_SSL_CAPABLE_ERROR:
543 lwsl_info("Closing when error\n");
544 goto close_and_handled;
548 * give any active extensions a chance to munge the buffer
549 * before parse. We pass in a pointer to an lws_tokens struct
550 * prepared with the default buffer and content length that's in
551 * there. Rather than rewrite the default buffer, extensions
552 * that expect to grow the buffer can adapt .token to
553 * point to their own per-connection buffer in the extension
554 * user allocation. By default with no extensions or no
555 * extension callback handling, just the normal input buffer is
556 * used then so it is efficient.
559 eff_buf.token = (char *)context->service_buffer;
566 m = lws_ext_callback_for_each_active(wsi,
567 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE, &eff_buf, 0);
569 goto close_and_handled;
573 /* service incoming data */
575 if (eff_buf.token_len) {
576 n = libwebsocket_read(context, wsi,
577 (unsigned char *)eff_buf.token,
586 eff_buf.token = NULL;
587 eff_buf.token_len = 0;
590 pending = lws_ssl_pending(wsi);
592 pending = pending > sizeof(context->service_buffer)?
593 sizeof(context->service_buffer):pending;
597 if (draining_flow && wsi->rxflow_buffer &&
598 wsi->rxflow_pos == wsi->rxflow_len) {
599 lwsl_info("flow buffer: drained\n");
600 lws_free2(wsi->rxflow_buffer);
601 /* having drained the rxflow buffer, can rearm POLLIN */
605 _libwebsocket_rx_flow_control(wsi); /* n ignored, needed for NO_SERVER case */
614 n = lws_client_socket_service(context, wsi, pollfd);
623 lwsl_debug("Close and handled\n");
624 libwebsocket_close_and_free_session(context, wsi,
625 LWS_CLOSE_STATUS_NOSTATUS);
626 // pollfd points to something else after the close
635 * libwebsocket_service() - Service any pending websocket activity
636 * @context: Websocket context
637 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
638 * service otherwise block and service immediately, returning
639 * after the timeout if nothing needed service.
641 * This function deals with any pending websocket traffic, for three
642 * kinds of event. It handles these events on both server and client
643 * types of connection the same.
645 * 1) Accept new connections to our context's server
647 * 2) Call the receive callback for incoming frame data received by
648 * server or client connections.
650 * You need to call this service function periodically to all the above
651 * functions to happen; if your application is single-threaded you can
652 * just call it in your main event loop.
654 * Alternatively you can fork a new process that asynchronously handles
655 * calling this service in a loop. In that case you are happy if this
656 * call blocks your thread until it needs to take care of something and
657 * would call it with a large nonzero timeout. Your loop then takes no
658 * CPU while there is nothing happening.
660 * If you are calling it in a single-threaded app, you don't want it to
661 * wait around blocking other things in your loop from happening, so you
662 * would call it with a timeout_ms of 0, so it returns immediately if
663 * nothing is pending, or as soon as it services whatever was pending.
667 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
669 return lws_plat_service(context, timeout_ms);