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,
114 #ifndef LWS_NO_EXTENSIONS
115 if (!wsi->extension_data_pending || handled == 2)
119 * check in on the active extensions, see if they
120 * had pending stuff to spill... they need to get the
121 * first look-in otherwise sequence will be disordered
123 * NULL, zero-length eff_buf means just spill pending
129 /* default to nobody has more to spill */
132 eff_buf.token = NULL;
133 eff_buf.token_len = 0;
135 /* give every extension a chance to spill */
137 m = lws_ext_callback_for_each_active(wsi,
138 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
141 lwsl_err("ext reports fatal error\n");
146 * at least one extension told us he has more
147 * to spill, so we will go around again after
151 /* assuming they gave us something to send, send it */
153 if (eff_buf.token_len) {
154 n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
157 lwsl_info("closing from POLLOUT spill\n");
161 * Keep amount spilled small to minimize chance of this
163 if (n != eff_buf.token_len) {
164 lwsl_err("Unable to spill ext %d vs %s\n",
165 eff_buf.token_len, n);
171 /* no extension has more to spill */
177 * There's more to spill from an extension, but we just sent
178 * something... did that leave the pipe choked?
181 if (!lws_send_pipe_choked(wsi))
182 /* no we could add more */
185 lwsl_info("choked in POLLOUT service\n");
188 * Yes, he's choked. Leave the POLLOUT masked on so we will
189 * come back here when he is unchoked. Don't call the user
190 * callback to enforce ordering of spilling, he'll get called
191 * when we come back here and there's nothing more to spill.
196 #ifndef LWS_NO_EXTENSIONS
197 wsi->extension_data_pending = 0;
204 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
205 lwsl_info("failled at set pollfd\n");
209 lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE);
214 * we are the 'network wsi' for potentially many muxed child wsi with
215 * no network connection of their own, who have to use us for all their
216 * network actions. So we use a round-robin scheme to share out the
217 * POLLOUT notifications to our children.
219 * But because any child could exhaust the socket's ability to take
220 * writes, we can only let one child get notified each time.
222 * In addition children may be closed / deleted / added between POLLOUT
223 * notifications, so we can't hold pointers
226 if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING) {
227 lwsl_info("%s: non http2\n", __func__);
231 wsi->u.http2.requested_POLLOUT = 0;
232 if (!wsi->u.http2.initialized) {
233 lwsl_info("pollout on uninitialized http2 conn\n");
237 lwsl_info("%s: doing children\n", __func__);
241 wsi2 = wsi2->u.http2.next_child_wsi;
242 lwsl_info("%s: child %p\n", __func__, wsi2);
245 if (!wsi2->u.http2.requested_POLLOUT)
247 wsi2->u.http2.requested_POLLOUT = 0;
248 if (lws_calllback_as_writeable(context, wsi2)) {
249 lwsl_debug("Closing POLLOUT child\n");
250 libwebsocket_close_and_free_session(context, wsi2,
251 LWS_CLOSE_STATUS_NOSTATUS);
254 } while (wsi2 != NULL && !lws_send_pipe_choked(wsi));
256 lwsl_info("%s: completed\n", __func__);
261 return lws_calllback_as_writeable(context, wsi);
267 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
268 struct libwebsocket *wsi, unsigned int sec)
271 * if extensions want in on it (eg, we are a mux parent)
272 * give them a chance to service child timeouts
274 if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_1HZ, NULL, sec) < 0)
277 if (!wsi->pending_timeout)
281 * if we went beyond the allowed time, kill the
284 if (sec > wsi->pending_timeout_limit) {
285 lwsl_info("TIMEDOUT WAITING on %d\n", wsi->pending_timeout);
286 libwebsocket_close_and_free_session(context,
287 wsi, LWS_CLOSE_STATUS_NOSTATUS);
294 int lws_rxflow_cache(struct libwebsocket *wsi, unsigned char *buf, int n, int len)
296 /* his RX is flowcontrolled, don't send remaining now */
297 if (wsi->rxflow_buffer) {
298 /* rxflow while we were spilling prev rxflow */
299 lwsl_info("stalling in existing rxflow buf\n");
303 /* a new rxflow, buffer it and warn caller */
304 lwsl_info("new rxflow input buffer len %d\n", len - n);
305 wsi->rxflow_buffer = (unsigned char *)malloc(len - n);
306 wsi->rxflow_len = len - n;
308 memcpy(wsi->rxflow_buffer, buf + n, len - n);
314 * libwebsocket_service_fd() - Service polled socket with something waiting
315 * @context: Websocket context
316 * @pollfd: The pollfd entry describing the socket fd and which events
319 * This function takes a pollfd that has POLLIN or POLLOUT activity and
320 * services it according to the state of the associated
321 * struct libwebsocket.
323 * The one call deals with all "service" that might happen on a socket
324 * including listen accepts, http files as well as websocket protocol.
326 * If a pollfd says it has something, you can just pass it to
327 * libwebsocket_serice_fd() whether it is a socket handled by lws or not.
328 * If it sees it is a lws socket, the traffic will be handled and
329 * pollfd->revents will be zeroed now.
331 * If the socket is foreign to lws, it leaves revents alone. So you can
332 * see if you should service yourself by checking the pollfd revents
333 * after letting lws try to service it.
337 libwebsocket_service_fd(struct libwebsocket_context *context,
338 struct libwebsocket_pollfd *pollfd)
340 struct libwebsocket *wsi;
343 int listen_socket_fds_index = 0;
347 char draining_flow = 0;
349 struct lws_tokens eff_buf;
351 if (context->listen_service_fd)
352 listen_socket_fds_index = context->lws_lookup[
353 context->listen_service_fd]->position_in_fds_table;
356 * you can call us with pollfd = NULL to just allow the once-per-second
357 * global timeout checks; if less than a second since the last check
358 * it returns immediately then.
363 /* TODO: if using libev, we should probably use timeout watchers... */
364 if (context->last_timeout_check_s != now) {
365 context->last_timeout_check_s = now;
367 lws_plat_service_periodic(context);
369 /* global timeout check once per second */
374 for (n = 0; n < context->fds_count; n++) {
375 m = context->fds[n].fd;
376 wsi = context->lws_lookup[m];
380 if (libwebsocket_service_timeout_check(context, wsi, now))
381 /* he did time out... */
383 /* it was the guy we came to service! */
385 /* mark as handled */
391 /* the socket we came to service timed out, nothing to do */
395 /* just here for timeout management? */
399 /* no, here to service a socket descriptor */
400 wsi = context->lws_lookup[pollfd->fd];
402 /* not lws connection ... leave revents alone and return */
406 * so that caller can tell we handled, past here we need to
407 * zero down pollfd->revents after handling
411 * deal with listen service piggybacking
412 * every listen_service_modulo services of other fds, we
413 * sneak one in to service the listen socket if there's anything waiting
415 * To handle connection storms, as found in ab, if we previously saw a
416 * pending connection here, it causes us to check again next time.
419 if (context->listen_service_fd && pollfd !=
420 &context->fds[listen_socket_fds_index]) {
421 context->listen_service_count++;
422 if (context->listen_service_extraseen ||
423 context->listen_service_count ==
424 context->listen_service_modulo) {
425 context->listen_service_count = 0;
427 if (context->listen_service_extraseen > 5)
431 * even with extpoll, we prepared this
432 * internal fds for listen
434 n = lws_poll_listen_fd(&context->fds[listen_socket_fds_index]);
435 if (n > 0) { /* there's a conn waiting for us */
436 libwebsocket_service_fd(context,
438 fds[listen_socket_fds_index]);
439 context->listen_service_extraseen++;
441 if (context->listen_service_extraseen)
443 listen_service_extraseen--;
451 /* handle session socket closed */
453 if ((!(pollfd->revents & LWS_POLLIN)) &&
454 (pollfd->revents & LWS_POLLHUP)) {
456 lwsl_debug("Session Socket %p (fd=%d) dead\n",
457 (void *)wsi, pollfd->fd);
459 goto close_and_handled;
462 /* okay, what we came here to do... */
465 case LWS_CONNMODE_HTTP_SERVING:
466 case LWS_CONNMODE_HTTP_SERVING_ACCEPTED:
467 case LWS_CONNMODE_SERVER_LISTENER:
468 case LWS_CONNMODE_SSL_ACK_PENDING:
469 n = lws_server_socket_service(context, wsi, pollfd);
471 goto close_and_handled;
474 case LWS_CONNMODE_WS_SERVING:
475 case LWS_CONNMODE_WS_CLIENT:
476 case LWS_CONNMODE_HTTP2_SERVING:
478 /* the guy requested a callback when it was OK to write */
480 if ((pollfd->revents & LWS_POLLOUT) &&
481 (wsi->state == WSI_STATE_ESTABLISHED || wsi->state == WSI_STATE_HTTP2_ESTABLISHED || wsi->state == WSI_STATE_HTTP2_ESTABLISHED_PRE_SETTINGS ||
482 wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) &&
483 lws_handle_POLLOUT_event(context, wsi, pollfd)) {
484 lwsl_info("libwebsocket_service_fd: closing\n");
485 goto close_and_handled;
488 if (wsi->rxflow_buffer &&
489 (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
490 lwsl_info("draining rxflow\n");
492 eff_buf.token = (char *)wsi->rxflow_buffer +
494 eff_buf.token_len = wsi->rxflow_len - wsi->rxflow_pos;
499 /* any incoming data ready? */
501 if (!(pollfd->revents & LWS_POLLIN))
504 eff_buf.token_len = lws_ssl_capable_read(context, wsi,
505 context->service_buffer,
506 sizeof(context->service_buffer));
507 switch (eff_buf.token_len) {
509 lwsl_info("service_fd: closing due to 0 length read\n");
510 goto close_and_handled;
511 case LWS_SSL_CAPABLE_MORE_SERVICE:
512 lwsl_info("SSL Capable more service\n");
515 case LWS_SSL_CAPABLE_ERROR:
516 lwsl_info("Closing when error\n");
517 goto close_and_handled;
521 * give any active extensions a chance to munge the buffer
522 * before parse. We pass in a pointer to an lws_tokens struct
523 * prepared with the default buffer and content length that's in
524 * there. Rather than rewrite the default buffer, extensions
525 * that expect to grow the buffer can adapt .token to
526 * point to their own per-connection buffer in the extension
527 * user allocation. By default with no extensions or no
528 * extension callback handling, just the normal input buffer is
529 * used then so it is efficient.
532 eff_buf.token = (char *)context->service_buffer;
539 m = lws_ext_callback_for_each_active(wsi,
540 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE, &eff_buf, 0);
542 goto close_and_handled;
546 /* service incoming data */
548 if (eff_buf.token_len) {
549 n = libwebsocket_read(context, wsi,
550 (unsigned char *)eff_buf.token,
559 eff_buf.token = NULL;
560 eff_buf.token_len = 0;
563 if (draining_flow && wsi->rxflow_buffer &&
564 wsi->rxflow_pos == wsi->rxflow_len) {
565 lwsl_info("flow buffer: drained\n");
566 free(wsi->rxflow_buffer);
567 wsi->rxflow_buffer = NULL;
568 /* having drained the rxflow buffer, can rearm POLLIN */
569 _libwebsocket_rx_flow_control(wsi); /* n ignored, needed for NO_SERVER case */
578 n = lws_client_socket_service(context, wsi, pollfd);
587 lwsl_debug("Close and handled\n");
588 libwebsocket_close_and_free_session(context, wsi,
589 LWS_CLOSE_STATUS_NOSTATUS);
598 * libwebsocket_service() - Service any pending websocket activity
599 * @context: Websocket context
600 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
601 * service otherwise block and service immediately, returning
602 * after the timeout if nothing needed service.
604 * This function deals with any pending websocket traffic, for three
605 * kinds of event. It handles these events on both server and client
606 * types of connection the same.
608 * 1) Accept new connections to our context's server
610 * 2) Call the receive callback for incoming frame data received by
611 * server or client connections.
613 * You need to call this service function periodically to all the above
614 * functions to happen; if your application is single-threaded you can
615 * just call it in your main event loop.
617 * Alternatively you can fork a new process that asynchronously handles
618 * calling this service in a loop. In that case you are happy if this
619 * call blocks your thread until it needs to take care of something and
620 * would call it with a large nonzero timeout. Your loop then takes no
621 * CPU while there is nothing happening.
623 * If you are calling it in a single-threaded app, you don't want it to
624 * wait around blocking other things in your loop from happening, so you
625 * would call it with a timeout_ms of 0, so it returns immediately if
626 * nothing is pending, or as soon as it services whatever was pending.
630 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
632 return lws_plat_service(context, timeout_ms);