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 */
51 /* protocol packets are next */
53 lwsl_err("servicing pps %d\n", wsi->pps);
55 case LWS_PPS_HTTP2_MY_SETTINGS:
56 case LWS_PPS_HTTP2_ACK_SETTINGS:
57 lws_http2_do_pps_send(context, wsi);
62 wsi->pps = LWS_PPS_NONE;
63 libwebsocket_rx_flow_control(wsi, 1);
65 return 0; /* leave POLLOUT active */
68 /* pending control packets have next priority */
70 if (wsi->state == WSI_STATE_ESTABLISHED && wsi->u.ws.ping_payload_len) {
71 n = libwebsocket_write(wsi,
72 &wsi->u.ws.ping_payload_buf[
73 LWS_SEND_BUFFER_PRE_PADDING],
74 wsi->u.ws.ping_payload_len,
78 /* well he is sent, mark him done */
79 wsi->u.ws.ping_payload_len = 0;
80 /* leave POLLOUT active either way */
84 /* if nothing critical, user can get the callback */
86 m = lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_IS_WRITEABLE,
90 #ifndef LWS_NO_EXTENSIONS
91 if (!wsi->extension_data_pending || handled == 2)
95 * check in on the active extensions, see if they
96 * had pending stuff to spill... they need to get the
97 * first look-in otherwise sequence will be disordered
99 * NULL, zero-length eff_buf means just spill pending
105 /* default to nobody has more to spill */
108 eff_buf.token = NULL;
109 eff_buf.token_len = 0;
111 /* give every extension a chance to spill */
113 m = lws_ext_callback_for_each_active(wsi,
114 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
117 lwsl_err("ext reports fatal error\n");
122 * at least one extension told us he has more
123 * to spill, so we will go around again after
127 /* assuming they gave us something to send, send it */
129 if (eff_buf.token_len) {
130 n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
133 lwsl_info("closing from POLLOUT spill\n");
137 * Keep amount spilled small to minimize chance of this
139 if (n != eff_buf.token_len) {
140 lwsl_err("Unable to spill ext %d vs %s\n",
141 eff_buf.token_len, n);
147 /* no extension has more to spill */
153 * There's more to spill from an extension, but we just sent
154 * something... did that leave the pipe choked?
157 if (!lws_send_pipe_choked(wsi))
158 /* no we could add more */
161 lwsl_info("choked in POLLOUT service\n");
164 * Yes, he's choked. Leave the POLLOUT masked on so we will
165 * come back here when he is unchoked. Don't call the user
166 * callback to enforce ordering of spilling, he'll get called
167 * when we come back here and there's nothing more to spill.
172 #ifndef LWS_NO_EXTENSIONS
173 wsi->extension_data_pending = 0;
180 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
181 lwsl_info("failled at set pollfd\n");
185 lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE);
189 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
190 n = LWS_CALLBACK_CLIENT_WRITEABLE;
192 n = LWS_CALLBACK_SERVER_WRITEABLE;
194 return user_callback_handle_rxflow(wsi->protocol->callback, context,
195 wsi, (enum libwebsocket_callback_reasons) n,
196 wsi->user_space, NULL, 0);
202 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
203 struct libwebsocket *wsi, unsigned int sec)
206 * if extensions want in on it (eg, we are a mux parent)
207 * give them a chance to service child timeouts
209 if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_1HZ, NULL, sec) < 0)
212 if (!wsi->pending_timeout)
216 * if we went beyond the allowed time, kill the
219 if (sec > wsi->pending_timeout_limit) {
220 lwsl_info("TIMEDOUT WAITING on %d\n", wsi->pending_timeout);
221 libwebsocket_close_and_free_session(context,
222 wsi, LWS_CLOSE_STATUS_NOSTATUS);
229 int lws_rxflow_cache(struct libwebsocket *wsi, unsigned char *buf, int n, int len)
231 /* his RX is flowcontrolled, don't send remaining now */
232 if (wsi->rxflow_buffer) {
233 /* rxflow while we were spilling prev rxflow */
234 lwsl_info("stalling in existing rxflow buf\n");
238 /* a new rxflow, buffer it and warn caller */
239 lwsl_info("new rxflow input buffer len %d\n", len - n);
240 wsi->rxflow_buffer = (unsigned char *)malloc(len - n);
241 wsi->rxflow_len = len - n;
243 memcpy(wsi->rxflow_buffer, buf + n, len - n);
249 * libwebsocket_service_fd() - Service polled socket with something waiting
250 * @context: Websocket context
251 * @pollfd: The pollfd entry describing the socket fd and which events
254 * This function takes a pollfd that has POLLIN or POLLOUT activity and
255 * services it according to the state of the associated
256 * struct libwebsocket.
258 * The one call deals with all "service" that might happen on a socket
259 * including listen accepts, http files as well as websocket protocol.
261 * If a pollfd says it has something, you can just pass it to
262 * libwebsocket_serice_fd() whether it is a socket handled by lws or not.
263 * If it sees it is a lws socket, the traffic will be handled and
264 * pollfd->revents will be zeroed now.
266 * If the socket is foreign to lws, it leaves revents alone. So you can
267 * see if you should service yourself by checking the pollfd revents
268 * after letting lws try to service it.
272 libwebsocket_service_fd(struct libwebsocket_context *context,
273 struct libwebsocket_pollfd *pollfd)
275 struct libwebsocket *wsi;
278 int listen_socket_fds_index = 0;
282 char draining_flow = 0;
284 struct lws_tokens eff_buf;
286 if (context->listen_service_fd)
287 listen_socket_fds_index = context->lws_lookup[
288 context->listen_service_fd]->position_in_fds_table;
291 * you can call us with pollfd = NULL to just allow the once-per-second
292 * global timeout checks; if less than a second since the last check
293 * it returns immediately then.
298 /* TODO: if using libev, we should probably use timeout watchers... */
299 if (context->last_timeout_check_s != now) {
300 context->last_timeout_check_s = now;
302 lws_plat_service_periodic(context);
304 /* global timeout check once per second */
309 for (n = 0; n < context->fds_count; n++) {
310 m = context->fds[n].fd;
311 wsi = context->lws_lookup[m];
315 if (libwebsocket_service_timeout_check(context, wsi, now))
316 /* he did time out... */
318 /* it was the guy we came to service! */
320 /* mark as handled */
326 /* the socket we came to service timed out, nothing to do */
330 /* just here for timeout management? */
334 /* no, here to service a socket descriptor */
335 wsi = context->lws_lookup[pollfd->fd];
337 /* not lws connection ... leave revents alone and return */
341 * so that caller can tell we handled, past here we need to
342 * zero down pollfd->revents after handling
346 * deal with listen service piggybacking
347 * every listen_service_modulo services of other fds, we
348 * sneak one in to service the listen socket if there's anything waiting
350 * To handle connection storms, as found in ab, if we previously saw a
351 * pending connection here, it causes us to check again next time.
354 if (context->listen_service_fd && pollfd !=
355 &context->fds[listen_socket_fds_index]) {
356 context->listen_service_count++;
357 if (context->listen_service_extraseen ||
358 context->listen_service_count ==
359 context->listen_service_modulo) {
360 context->listen_service_count = 0;
362 if (context->listen_service_extraseen > 5)
366 * even with extpoll, we prepared this
367 * internal fds for listen
369 n = lws_poll_listen_fd(&context->fds[listen_socket_fds_index]);
370 if (n > 0) { /* there's a conn waiting for us */
371 libwebsocket_service_fd(context,
373 fds[listen_socket_fds_index]);
374 context->listen_service_extraseen++;
376 if (context->listen_service_extraseen)
378 listen_service_extraseen--;
386 /* handle session socket closed */
388 if ((!(pollfd->revents & LWS_POLLIN)) &&
389 (pollfd->revents & LWS_POLLHUP)) {
391 lwsl_debug("Session Socket %p (fd=%d) dead\n",
392 (void *)wsi, pollfd->fd);
394 goto close_and_handled;
397 /* okay, what we came here to do... */
400 case LWS_CONNMODE_HTTP_SERVING:
401 case LWS_CONNMODE_HTTP_SERVING_ACCEPTED:
402 case LWS_CONNMODE_SERVER_LISTENER:
403 case LWS_CONNMODE_SSL_ACK_PENDING:
404 n = lws_server_socket_service(context, wsi, pollfd);
406 goto close_and_handled;
409 case LWS_CONNMODE_WS_SERVING:
410 case LWS_CONNMODE_WS_CLIENT:
411 case LWS_CONNMODE_HTTP2_SERVING:
413 /* the guy requested a callback when it was OK to write */
415 if ((pollfd->revents & LWS_POLLOUT) &&
416 (wsi->state == WSI_STATE_ESTABLISHED || wsi->state == WSI_STATE_HTTP2_ESTABLISHED || wsi->state == WSI_STATE_HTTP2_ESTABLISHED_PRE_SETTINGS ||
417 wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) &&
418 lws_handle_POLLOUT_event(context, wsi, pollfd)) {
419 lwsl_info("libwebsocket_service_fd: closing\n");
420 goto close_and_handled;
423 if (wsi->rxflow_buffer &&
424 (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
425 lwsl_info("draining rxflow\n");
427 eff_buf.token = (char *)wsi->rxflow_buffer +
429 eff_buf.token_len = wsi->rxflow_len - wsi->rxflow_pos;
434 /* any incoming data ready? */
436 if (!(pollfd->revents & LWS_POLLIN))
440 eff_buf.token_len = lws_ssl_capable_read(wsi,
441 context->service_buffer,
442 sizeof(context->service_buffer));
443 switch (eff_buf.token_len) {
445 lwsl_info("service_fd: closing due to 0 length read\n");
446 goto close_and_handled;
447 case LWS_SSL_CAPABLE_MORE_SERVICE:
448 lwsl_info("SSL Capable more service\n");
451 case LWS_SSL_CAPABLE_ERROR:
452 lwsl_info("Closing when error\n");
453 goto close_and_handled;
457 * give any active extensions a chance to munge the buffer
458 * before parse. We pass in a pointer to an lws_tokens struct
459 * prepared with the default buffer and content length that's in
460 * there. Rather than rewrite the default buffer, extensions
461 * that expect to grow the buffer can adapt .token to
462 * point to their own per-connection buffer in the extension
463 * user allocation. By default with no extensions or no
464 * extension callback handling, just the normal input buffer is
465 * used then so it is efficient.
468 eff_buf.token = (char *)context->service_buffer;
475 m = lws_ext_callback_for_each_active(wsi,
476 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE, &eff_buf, 0);
478 goto close_and_handled;
482 /* service incoming data */
484 if (eff_buf.token_len) {
485 n = libwebsocket_read(context, wsi,
486 (unsigned char *)eff_buf.token,
495 eff_buf.token = NULL;
496 eff_buf.token_len = 0;
499 if (draining_flow && wsi->rxflow_buffer &&
500 wsi->rxflow_pos == wsi->rxflow_len) {
501 lwsl_info("flow buffer: drained\n");
502 free(wsi->rxflow_buffer);
503 wsi->rxflow_buffer = NULL;
504 /* having drained the rxflow buffer, can rearm POLLIN */
505 n = _libwebsocket_rx_flow_control(wsi); /* n ignored, needed for NO_SERVER case */
508 if (lws_ssl_pending(wsi))
516 n = lws_client_socket_service(context, wsi, pollfd);
525 lwsl_debug("Close and handled\n");
526 libwebsocket_close_and_free_session(context, wsi,
527 LWS_CLOSE_STATUS_NOSTATUS);
536 * libwebsocket_service() - Service any pending websocket activity
537 * @context: Websocket context
538 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
539 * service otherwise block and service immediately, returning
540 * after the timeout if nothing needed service.
542 * This function deals with any pending websocket traffic, for three
543 * kinds of event. It handles these events on both server and client
544 * types of connection the same.
546 * 1) Accept new connections to our context's server
548 * 2) Call the receive callback for incoming frame data received by
549 * server or client connections.
551 * You need to call this service function periodically to all the above
552 * functions to happen; if your application is single-threaded you can
553 * just call it in your main event loop.
555 * Alternatively you can fork a new process that asynchronously handles
556 * calling this service in a loop. In that case you are happy if this
557 * call blocks your thread until it needs to take care of something and
558 * would call it with a large nonzero timeout. Your loop then takes no
559 * CPU while there is nothing happening.
561 * If you are calling it in a single-threaded app, you don't want it to
562 * wait around blocking other things in your loop from happening, so you
563 * would call it with a timeout_ms of 0, so it returns immediately if
564 * nothing is pending, or as soon as it services whatever was pending.
568 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
570 return lws_plat_service(context, timeout_ms);