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_handle_POLLOUT_event(struct libwebsocket_context *context,
26 struct libwebsocket *wsi, struct libwebsocket_pollfd *pollfd)
29 struct lws_tokens eff_buf;
34 /* pending truncated sends have uber priority */
36 if (wsi->truncated_send_len) {
37 if (lws_issue_raw(wsi, wsi->truncated_send_malloc +
38 wsi->truncated_send_offset,
39 wsi->truncated_send_len) < 0) {
40 lwsl_info("lws_handle_POLLOUT_event signalling to close\n");
43 /* leave POLLOUT active either way */
46 if (wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
47 lwsl_info("***** %x signalling to close in POLLOUT handler\n", wsi);
48 return -1; /* retry closing now */
52 m = lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_IS_WRITEABLE,
56 #ifndef LWS_NO_EXTENSIONS
57 if (!wsi->extension_data_pending || handled == 2)
61 * check in on the active extensions, see if they
62 * had pending stuff to spill... they need to get the
63 * first look-in otherwise sequence will be disordered
65 * NULL, zero-length eff_buf means just spill pending
71 /* default to nobody has more to spill */
75 eff_buf.token_len = 0;
77 /* give every extension a chance to spill */
79 m = lws_ext_callback_for_each_active(wsi,
80 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
83 lwsl_err("ext reports fatal error\n");
88 * at least one extension told us he has more
89 * to spill, so we will go around again after
93 /* assuming they gave us something to send, send it */
95 if (eff_buf.token_len) {
96 n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
99 lwsl_info("closing from POLLOUT spill\n");
103 * Keep amount spilled small to minimize chance of this
105 if (n != eff_buf.token_len) {
106 lwsl_err("Unable to spill ext %d vs %s\n",
107 eff_buf.token_len, n);
113 /* no extension has more to spill */
119 * There's more to spill from an extension, but we just sent
120 * something... did that leave the pipe choked?
123 if (!lws_send_pipe_choked(wsi))
124 /* no we could add more */
127 lwsl_info("choked in POLLOUT service\n");
130 * Yes, he's choked. Leave the POLLOUT masked on so we will
131 * come back here when he is unchoked. Don't call the user
132 * callback to enforce ordering of spilling, he'll get called
133 * when we come back here and there's nothing more to spill.
138 #ifndef LWS_NO_EXTENSIONS
139 wsi->extension_data_pending = 0;
146 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
149 lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE);
153 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
154 n = LWS_CALLBACK_CLIENT_WRITEABLE;
156 n = LWS_CALLBACK_SERVER_WRITEABLE;
158 return user_callback_handle_rxflow(wsi->protocol->callback, context,
159 wsi, (enum libwebsocket_callback_reasons) n,
160 wsi->user_space, NULL, 0);
166 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
167 struct libwebsocket *wsi, unsigned int sec)
170 * if extensions want in on it (eg, we are a mux parent)
171 * give them a chance to service child timeouts
173 if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_1HZ, NULL, sec) < 0)
176 if (!wsi->pending_timeout)
180 * if we went beyond the allowed time, kill the
183 if (sec > wsi->pending_timeout_limit) {
184 lwsl_info("TIMEDOUT WAITING on %d\n", wsi->pending_timeout);
185 libwebsocket_close_and_free_session(context,
186 wsi, LWS_CLOSE_STATUS_NOSTATUS);
194 * libwebsocket_service_fd() - Service polled socket with something waiting
195 * @context: Websocket context
196 * @pollfd: The pollfd entry describing the socket fd and which events
199 * This function takes a pollfd that has POLLIN or POLLOUT activity and
200 * services it according to the state of the associated
201 * struct libwebsocket.
203 * The one call deals with all "service" that might happen on a socket
204 * including listen accepts, http files as well as websocket protocol.
206 * If a pollfd says it has something, you can just pass it to
207 * libwebsocket_serice_fd() whether it is a socket handled by lws or not.
208 * If it sees it is a lws socket, the traffic will be handled and
209 * pollfd->revents will be zeroed now.
211 * If the socket is foreign to lws, it leaves revents alone. So you can
212 * see if you should service yourself by checking the pollfd revents
213 * after letting lws try to service it.
217 libwebsocket_service_fd(struct libwebsocket_context *context,
218 struct libwebsocket_pollfd *pollfd)
220 struct libwebsocket *wsi;
223 int listen_socket_fds_index = 0;
227 char draining_flow = 0;
229 struct lws_tokens eff_buf;
231 if (context->listen_service_fd)
232 listen_socket_fds_index = context->lws_lookup[
233 context->listen_service_fd]->position_in_fds_table;
236 * you can call us with pollfd = NULL to just allow the once-per-second
237 * global timeout checks; if less than a second since the last check
238 * it returns immediately then.
243 /* TODO: if using libev, we should probably use timeout watchers... */
244 if (context->last_timeout_check_s != now) {
245 context->last_timeout_check_s = now;
247 lws_plat_service_periodic(context);
249 /* global timeout check once per second */
254 for (n = 0; n < context->fds_count; n++) {
255 m = context->fds[n].fd;
256 wsi = context->lws_lookup[m];
260 if (libwebsocket_service_timeout_check(context, wsi, now))
261 /* he did time out... */
263 /* it was the guy we came to service! */
265 /* mark as handled */
271 /* the socket we came to service timed out, nothing to do */
275 /* just here for timeout management? */
279 /* no, here to service a socket descriptor */
280 wsi = context->lws_lookup[pollfd->fd];
282 /* not lws connection ... leave revents alone and return */
286 * so that caller can tell we handled, past here we need to
287 * zero down pollfd->revents after handling
291 * deal with listen service piggybacking
292 * every listen_service_modulo services of other fds, we
293 * sneak one in to service the listen socket if there's anything waiting
295 * To handle connection storms, as found in ab, if we previously saw a
296 * pending connection here, it causes us to check again next time.
299 if (context->listen_service_fd && pollfd !=
300 &context->fds[listen_socket_fds_index]) {
301 context->listen_service_count++;
302 if (context->listen_service_extraseen ||
303 context->listen_service_count ==
304 context->listen_service_modulo) {
305 context->listen_service_count = 0;
307 if (context->listen_service_extraseen > 5)
311 * even with extpoll, we prepared this
312 * internal fds for listen
314 n = lws_poll_listen_fd(&context->fds[listen_socket_fds_index]);
315 if (n > 0) { /* there's a conn waiting for us */
316 libwebsocket_service_fd(context,
318 fds[listen_socket_fds_index]);
319 context->listen_service_extraseen++;
321 if (context->listen_service_extraseen)
323 listen_service_extraseen--;
331 /* handle session socket closed */
333 if ((!(pollfd->revents & LWS_POLLIN)) &&
334 (pollfd->revents & LWS_POLLHUP)) {
336 lwsl_debug("Session Socket %p (fd=%d) dead\n",
337 (void *)wsi, pollfd->fd);
339 goto close_and_handled;
342 /* okay, what we came here to do... */
345 case LWS_CONNMODE_HTTP_SERVING:
346 case LWS_CONNMODE_HTTP_SERVING_ACCEPTED:
347 case LWS_CONNMODE_SERVER_LISTENER:
348 case LWS_CONNMODE_SSL_ACK_PENDING:
349 n = lws_server_socket_service(context, wsi, pollfd);
351 goto close_and_handled;
354 case LWS_CONNMODE_WS_SERVING:
355 case LWS_CONNMODE_WS_CLIENT:
357 /* the guy requested a callback when it was OK to write */
359 if ((pollfd->revents & LWS_POLLOUT) &&
360 (wsi->state == WSI_STATE_ESTABLISHED ||
361 wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) &&
362 lws_handle_POLLOUT_event(context, wsi, pollfd)) {
363 lwsl_info("libwebsocket_service_fd: closing\n");
364 goto close_and_handled;
367 if (wsi->u.ws.rxflow_buffer &&
368 (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW)) {
369 lwsl_info("draining rxflow\n");
371 eff_buf.token = (char *)wsi->u.ws.rxflow_buffer +
372 wsi->u.ws.rxflow_pos;
373 eff_buf.token_len = wsi->u.ws.rxflow_len -
374 wsi->u.ws.rxflow_pos;
379 /* any incoming data ready? */
381 if (!(pollfd->revents & LWS_POLLIN))
385 eff_buf.token_len = lws_ssl_capable_read(wsi,
386 context->service_buffer,
387 sizeof(context->service_buffer));
388 switch (eff_buf.token_len) {
390 lwsl_info("service_fd: closing due to 0 length read\n");
391 goto close_and_handled;
392 case LWS_SSL_CAPABLE_ERROR:
395 case LWS_SSL_CAPABLE_MORE_SERVICE:
396 goto close_and_handled;
400 * give any active extensions a chance to munge the buffer
401 * before parse. We pass in a pointer to an lws_tokens struct
402 * prepared with the default buffer and content length that's in
403 * there. Rather than rewrite the default buffer, extensions
404 * that expect to grow the buffer can adapt .token to
405 * point to their own per-connection buffer in the extension
406 * user allocation. By default with no extensions or no
407 * extension callback handling, just the normal input buffer is
408 * used then so it is efficient.
411 eff_buf.token = (char *)context->service_buffer;
418 m = lws_ext_callback_for_each_active(wsi,
419 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE, &eff_buf, 0);
421 goto close_and_handled;
425 /* service incoming data */
427 if (eff_buf.token_len) {
428 n = libwebsocket_read(context, wsi,
429 (unsigned char *)eff_buf.token,
438 eff_buf.token = NULL;
439 eff_buf.token_len = 0;
442 if (draining_flow && wsi->u.ws.rxflow_buffer &&
443 wsi->u.ws.rxflow_pos == wsi->u.ws.rxflow_len) {
444 lwsl_info("flow buffer: drained\n");
445 free(wsi->u.ws.rxflow_buffer);
446 wsi->u.ws.rxflow_buffer = NULL;
447 /* having drained the rxflow buffer, can rearm POLLIN */
448 n = _libwebsocket_rx_flow_control(wsi); /* n ignored, needed for NO_SERVER case */
451 if (lws_ssl_pending(wsi))
459 n = lws_client_socket_service(context, wsi, pollfd);
468 libwebsocket_close_and_free_session(context, wsi,
469 LWS_CLOSE_STATUS_NOSTATUS);
478 * libwebsocket_service() - Service any pending websocket activity
479 * @context: Websocket context
480 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
481 * service otherwise block and service immediately, returning
482 * after the timeout if nothing needed service.
484 * This function deals with any pending websocket traffic, for three
485 * kinds of event. It handles these events on both server and client
486 * types of connection the same.
488 * 1) Accept new connections to our context's server
490 * 2) Call the receive callback for incoming frame data received by
491 * server or client connections.
493 * You need to call this service function periodically to all the above
494 * functions to happen; if your application is single-threaded you can
495 * just call it in your main event loop.
497 * Alternatively you can fork a new process that asynchronously handles
498 * calling this service in a loop. In that case you are happy if this
499 * call blocks your thread until it needs to take care of something and
500 * would call it with a large nonzero timeout. Your loop then takes no
501 * CPU while there is nothing happening.
503 * If you are calling it in a single-threaded app, you don't want it to
504 * wait around blocking other things in your loop from happening, so you
505 * would call it with a timeout_ms of 0, so it returns immediately if
506 * nothing is pending, or as soon as it services whatever was pending.
510 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
512 return lws_plat_service(context, timeout_ms);