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;
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) {
99 if (wsi->u.ws.payload_is_close)
100 write_type = LWS_WRITE_CLOSE;
102 n = libwebsocket_write(wsi,
103 &wsi->u.ws.ping_payload_buf[
104 LWS_SEND_BUFFER_PRE_PADDING],
105 wsi->u.ws.ping_payload_len,
110 /* well he is sent, mark him done */
111 wsi->u.ws.ping_pending_flag = 0;
112 if (wsi->u.ws.payload_is_close)
113 /* oh... a close frame was it... then we are done */
116 /* otherwise for PING, leave POLLOUT active either way */
120 /* if nothing critical, user can get the callback */
122 m = lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_IS_WRITEABLE,
124 #ifndef LWS_NO_EXTENSIONS
125 if (!wsi->extension_data_pending)
129 * check in on the active extensions, see if they
130 * had pending stuff to spill... they need to get the
131 * first look-in otherwise sequence will be disordered
133 * NULL, zero-length eff_buf means just spill pending
139 /* default to nobody has more to spill */
142 eff_buf.token = NULL;
143 eff_buf.token_len = 0;
145 /* give every extension a chance to spill */
147 m = lws_ext_callback_for_each_active(wsi,
148 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
151 lwsl_err("ext reports fatal error\n");
156 * at least one extension told us he has more
157 * to spill, so we will go around again after
161 /* assuming they gave us something to send, send it */
163 if (eff_buf.token_len) {
164 n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
167 lwsl_info("closing from POLLOUT spill\n");
171 * Keep amount spilled small to minimize chance of this
173 if (n != eff_buf.token_len) {
174 lwsl_err("Unable to spill ext %d vs %s\n",
175 eff_buf.token_len, n);
181 /* no extension has more to spill */
187 * There's more to spill from an extension, but we just sent
188 * something... did that leave the pipe choked?
191 if (!lws_send_pipe_choked(wsi))
192 /* no we could add more */
195 lwsl_info("choked in POLLOUT service\n");
198 * Yes, he's choked. Leave the POLLOUT masked on so we will
199 * come back here when he is unchoked. Don't call the user
200 * callback to enforce ordering of spilling, he'll get called
201 * when we come back here and there's nothing more to spill.
206 #ifndef LWS_NO_EXTENSIONS
207 wsi->extension_data_pending = 0;
214 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
215 lwsl_info("failled at set pollfd\n");
219 lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE);
224 * we are the 'network wsi' for potentially many muxed child wsi with
225 * no network connection of their own, who have to use us for all their
226 * network actions. So we use a round-robin scheme to share out the
227 * POLLOUT notifications to our children.
229 * But because any child could exhaust the socket's ability to take
230 * writes, we can only let one child get notified each time.
232 * In addition children may be closed / deleted / added between POLLOUT
233 * notifications, so we can't hold pointers
236 if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING) {
237 lwsl_info("%s: non http2\n", __func__);
241 wsi->u.http2.requested_POLLOUT = 0;
242 if (!wsi->u.http2.initialized) {
243 lwsl_info("pollout on uninitialized http2 conn\n");
247 lwsl_info("%s: doing children\n", __func__);
251 wsi2 = wsi2->u.http2.next_child_wsi;
252 lwsl_info("%s: child %p\n", __func__, wsi2);
255 if (!wsi2->u.http2.requested_POLLOUT)
257 wsi2->u.http2.requested_POLLOUT = 0;
258 if (lws_calllback_as_writeable(context, wsi2)) {
259 lwsl_debug("Closing POLLOUT child\n");
260 libwebsocket_close_and_free_session(context, wsi2,
261 LWS_CLOSE_STATUS_NOSTATUS);
264 } while (wsi2 != NULL && !lws_send_pipe_choked(wsi));
266 lwsl_info("%s: completed\n", __func__);
271 return lws_calllback_as_writeable(context, wsi);
277 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
278 struct libwebsocket *wsi, unsigned int sec)
281 * if extensions want in on it (eg, we are a mux parent)
282 * give them a chance to service child timeouts
284 if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_1HZ, NULL, sec) < 0)
287 if (!wsi->pending_timeout)
291 * if we went beyond the allowed time, kill the
294 if (sec > wsi->pending_timeout_limit) {
295 lwsl_info("TIMEDOUT WAITING on %d\n", wsi->pending_timeout);
297 * Since he failed a timeout, he already had a chance to do
298 * something and was unable to... that includes situations like
299 * half closed connections. So process this "failed timeout"
300 * close as a violent death and don't try to do protocol
301 * cleanup like flush partials.
303 wsi->socket_is_permanently_unusable = 1;
304 libwebsocket_close_and_free_session(context,
305 wsi, LWS_CLOSE_STATUS_NOSTATUS);
312 int lws_rxflow_cache(struct libwebsocket *wsi, unsigned char *buf, int n, int len)
314 /* his RX is flowcontrolled, don't send remaining now */
315 if (wsi->rxflow_buffer) {
316 /* rxflow while we were spilling prev rxflow */
317 lwsl_info("stalling in existing rxflow buf\n");
321 /* a new rxflow, buffer it and warn caller */
322 lwsl_info("new rxflow input buffer len %d\n", len - n);
323 wsi->rxflow_buffer = lws_malloc(len - n);
324 wsi->rxflow_len = len - n;
326 memcpy(wsi->rxflow_buffer, buf + n, len - n);
332 * libwebsocket_service_fd() - Service polled socket with something waiting
333 * @context: Websocket context
334 * @pollfd: The pollfd entry describing the socket fd and which events
337 * This function takes a pollfd that has POLLIN or POLLOUT activity and
338 * services it according to the state of the associated
339 * struct libwebsocket.
341 * The one call deals with all "service" that might happen on a socket
342 * including listen accepts, http files as well as websocket protocol.
344 * If a pollfd says it has something, you can just pass it to
345 * libwebsocket_serice_fd() whether it is a socket handled by lws or not.
346 * If it sees it is a lws socket, the traffic will be handled and
347 * pollfd->revents will be zeroed now.
349 * If the socket is foreign to lws, it leaves revents alone. So you can
350 * see if you should service yourself by checking the pollfd revents
351 * after letting lws try to service it.
355 libwebsocket_service_fd(struct libwebsocket_context *context,
356 struct libwebsocket_pollfd *pollfd)
358 struct libwebsocket *wsi;
361 int listen_socket_fds_index = 0;
365 char draining_flow = 0;
367 struct lws_tokens eff_buf;
369 if (context->listen_service_fd)
370 listen_socket_fds_index = wsi_from_fd(context,context->listen_service_fd)->position_in_fds_table;
373 * you can call us with pollfd = NULL to just allow the once-per-second
374 * global timeout checks; if less than a second since the last check
375 * it returns immediately then.
380 /* TODO: if using libev, we should probably use timeout watchers... */
381 if (context->last_timeout_check_s != now) {
382 context->last_timeout_check_s = now;
384 lws_plat_service_periodic(context);
386 /* global timeout check once per second */
391 for (n = 0; n < context->fds_count; n++) {
392 m = context->fds[n].fd;
393 wsi = wsi_from_fd(context,m);
397 if (libwebsocket_service_timeout_check(context, wsi, now))
398 /* he did time out... */
400 /* it was the guy we came to service! */
402 /* mark as handled */
409 /* the socket we came to service timed out, nothing to do */
413 /* just here for timeout management? */
417 /* no, here to service a socket descriptor */
418 wsi = wsi_from_fd(context,pollfd->fd);
420 /* not lws connection ... leave revents alone and return */
424 * so that caller can tell we handled, past here we need to
425 * zero down pollfd->revents after handling
429 * deal with listen service piggybacking
430 * every listen_service_modulo services of other fds, we
431 * sneak one in to service the listen socket if there's anything waiting
433 * To handle connection storms, as found in ab, if we previously saw a
434 * pending connection here, it causes us to check again next time.
437 if (context->listen_service_fd && pollfd !=
438 &context->fds[listen_socket_fds_index]) {
439 context->listen_service_count++;
440 if (context->listen_service_extraseen ||
441 context->listen_service_count ==
442 context->listen_service_modulo) {
443 context->listen_service_count = 0;
445 if (context->listen_service_extraseen > 5)
449 * even with extpoll, we prepared this
450 * internal fds for listen
452 n = lws_poll_listen_fd(&context->fds[listen_socket_fds_index]);
453 if (n > 0) { /* there's a conn waiting for us */
454 libwebsocket_service_fd(context,
456 fds[listen_socket_fds_index]);
457 context->listen_service_extraseen++;
459 if (context->listen_service_extraseen)
461 listen_service_extraseen--;
469 /* handle session socket closed */
471 if ((!(pollfd->revents & LWS_POLLIN)) &&
472 (pollfd->revents & LWS_POLLHUP)) {
474 lwsl_debug("Session Socket %p (fd=%d) dead\n",
475 (void *)wsi, pollfd->fd);
477 goto close_and_handled;
480 /* okay, what we came here to do... */
483 case LWS_CONNMODE_HTTP_SERVING:
484 case LWS_CONNMODE_HTTP_SERVING_ACCEPTED:
485 case LWS_CONNMODE_SERVER_LISTENER:
486 case LWS_CONNMODE_SSL_ACK_PENDING:
487 n = lws_server_socket_service(context, wsi, pollfd);
489 goto close_and_handled;
492 case LWS_CONNMODE_WS_SERVING:
493 case LWS_CONNMODE_WS_CLIENT:
494 case LWS_CONNMODE_HTTP2_SERVING:
496 /* the guy requested a callback when it was OK to write */
498 if ((pollfd->revents & LWS_POLLOUT) &&
499 (wsi->state == WSI_STATE_ESTABLISHED ||
500 wsi->state == WSI_STATE_HTTP2_ESTABLISHED ||
501 wsi->state == WSI_STATE_HTTP2_ESTABLISHED_PRE_SETTINGS ||
502 wsi->state == WSI_STATE_RETURNED_CLOSE_ALREADY ||
503 wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) &&
504 lws_handle_POLLOUT_event(context, wsi, pollfd)) {
505 lwsl_info("libwebsocket_service_fd: closing\n");
506 goto close_and_handled;
509 if (wsi->rxflow_buffer &&
510 (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
511 lwsl_info("draining rxflow\n");
513 eff_buf.token = (char *)wsi->rxflow_buffer +
515 eff_buf.token_len = wsi->rxflow_len - wsi->rxflow_pos;
520 /* any incoming data ready? */
522 if (!(pollfd->revents & LWS_POLLIN))
525 eff_buf.token_len = lws_ssl_capable_read(context, wsi,
526 context->service_buffer,
527 sizeof(context->service_buffer));
528 switch (eff_buf.token_len) {
530 lwsl_info("service_fd: closing due to 0 length read\n");
531 goto close_and_handled;
532 case LWS_SSL_CAPABLE_MORE_SERVICE:
533 lwsl_info("SSL Capable more service\n");
536 case LWS_SSL_CAPABLE_ERROR:
537 lwsl_info("Closing when error\n");
538 goto close_and_handled;
542 * give any active extensions a chance to munge the buffer
543 * before parse. We pass in a pointer to an lws_tokens struct
544 * prepared with the default buffer and content length that's in
545 * there. Rather than rewrite the default buffer, extensions
546 * that expect to grow the buffer can adapt .token to
547 * point to their own per-connection buffer in the extension
548 * user allocation. By default with no extensions or no
549 * extension callback handling, just the normal input buffer is
550 * used then so it is efficient.
553 eff_buf.token = (char *)context->service_buffer;
560 m = lws_ext_callback_for_each_active(wsi,
561 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE, &eff_buf, 0);
563 goto close_and_handled;
567 /* service incoming data */
569 if (eff_buf.token_len) {
570 n = libwebsocket_read(context, wsi,
571 (unsigned char *)eff_buf.token,
580 eff_buf.token = NULL;
581 eff_buf.token_len = 0;
584 if (draining_flow && wsi->rxflow_buffer &&
585 wsi->rxflow_pos == wsi->rxflow_len) {
586 lwsl_info("flow buffer: drained\n");
587 lws_free2(wsi->rxflow_buffer);
588 /* having drained the rxflow buffer, can rearm POLLIN */
592 _libwebsocket_rx_flow_control(wsi); /* n ignored, needed for NO_SERVER case */
601 n = lws_client_socket_service(context, wsi, pollfd);
610 lwsl_debug("Close and handled\n");
611 libwebsocket_close_and_free_session(context, wsi,
612 LWS_CLOSE_STATUS_NOSTATUS);
621 * libwebsocket_service() - Service any pending websocket activity
622 * @context: Websocket context
623 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
624 * service otherwise block and service immediately, returning
625 * after the timeout if nothing needed service.
627 * This function deals with any pending websocket traffic, for three
628 * kinds of event. It handles these events on both server and client
629 * types of connection the same.
631 * 1) Accept new connections to our context's server
633 * 2) Call the receive callback for incoming frame data received by
634 * server or client connections.
636 * You need to call this service function periodically to all the above
637 * functions to happen; if your application is single-threaded you can
638 * just call it in your main event loop.
640 * Alternatively you can fork a new process that asynchronously handles
641 * calling this service in a loop. In that case you are happy if this
642 * call blocks your thread until it needs to take care of something and
643 * would call it with a large nonzero timeout. Your loop then takes no
644 * CPU while there is nothing happening.
646 * If you are calling it in a single-threaded app, you don't want it to
647 * wait around blocking other things in your loop from happening, so you
648 * would call it with a timeout_ms of 0, so it returns immediately if
649 * nothing is pending, or as soon as it services whatever was pending.
653 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
655 return lws_plat_service(context, timeout_ms);