refactor libev eliminate all code ifdefs
[platform/upstream/libwebsockets.git] / lib / service.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2014 Andy Green <andy@warmcat.com>
5  *
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.
10  *
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.
15  *
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,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23
24 int
25 lws_handle_POLLOUT_event(struct libwebsocket_context *context,
26                    struct libwebsocket *wsi, struct libwebsocket_pollfd *pollfd)
27 {
28         int n;
29         struct lws_tokens eff_buf;
30         int ret;
31         int m;
32         int handled = 0;
33
34         /* pending truncated sends have uber priority */
35
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");
41                         return -1;
42                 }
43                 /* leave POLLOUT active either way */
44                 return 0;
45         } else
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 */
49                 }
50
51
52         m = lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_IS_WRITEABLE,
53                                                                        NULL, 0);
54         if (handled == 1)
55                 goto notify_action;
56 #ifndef LWS_NO_EXTENSIONS
57         if (!wsi->extension_data_pending || handled == 2)
58                 goto user_service;
59 #endif
60         /*
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
64          *
65          * NULL, zero-length eff_buf means just spill pending
66          */
67
68         ret = 1;
69         while (ret == 1) {
70
71                 /* default to nobody has more to spill */
72
73                 ret = 0;
74                 eff_buf.token = NULL;
75                 eff_buf.token_len = 0;
76
77                 /* give every extension a chance to spill */
78                 
79                 m = lws_ext_callback_for_each_active(wsi,
80                                         LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
81                                                                    &eff_buf, 0);
82                 if (m < 0) {
83                         lwsl_err("ext reports fatal error\n");
84                         return -1;
85                 }
86                 if (m)
87                         /*
88                          * at least one extension told us he has more
89                          * to spill, so we will go around again after
90                          */
91                         ret = 1;
92
93                 /* assuming they gave us something to send, send it */
94
95                 if (eff_buf.token_len) {
96                         n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
97                                                              eff_buf.token_len);
98                         if (n < 0) {
99                                 lwsl_info("closing from POLLOUT spill\n");
100                                 return -1;
101                         }
102                         /*
103                          * Keep amount spilled small to minimize chance of this
104                          */
105                         if (n != eff_buf.token_len) {
106                                 lwsl_err("Unable to spill ext %d vs %s\n",
107                                                           eff_buf.token_len, n);
108                                 return -1;
109                         }
110                 } else
111                         continue;
112
113                 /* no extension has more to spill */
114
115                 if (!ret)
116                         continue;
117
118                 /*
119                  * There's more to spill from an extension, but we just sent
120                  * something... did that leave the pipe choked?
121                  */
122
123                 if (!lws_send_pipe_choked(wsi))
124                         /* no we could add more */
125                         continue;
126
127                 lwsl_info("choked in POLLOUT service\n");
128
129                 /*
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.
134                  */
135
136                 return 0;
137         }
138 #ifndef LWS_NO_EXTENSIONS
139         wsi->extension_data_pending = 0;
140
141 user_service:
142 #endif
143         /* one shot */
144
145         if (pollfd) {
146                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
147                         return 1;
148
149                 lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE);
150         }
151
152 notify_action:
153         if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
154                 n = LWS_CALLBACK_CLIENT_WRITEABLE;
155         else
156                 n = LWS_CALLBACK_SERVER_WRITEABLE;
157
158         return user_callback_handle_rxflow(wsi->protocol->callback, context,
159                         wsi, (enum libwebsocket_callback_reasons) n,
160                                                       wsi->user_space, NULL, 0);
161 }
162
163
164
165 int
166 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
167                                      struct libwebsocket *wsi, unsigned int sec)
168 {
169         /*
170          * if extensions want in on it (eg, we are a mux parent)
171          * give them a chance to service child timeouts
172          */
173         if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_1HZ, NULL, sec) < 0)
174                 return 0;
175
176         if (!wsi->pending_timeout)
177                 return 0;
178
179         /*
180          * if we went beyond the allowed time, kill the
181          * connection
182          */
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);
187                 return 1;
188         }
189
190         return 0;
191 }
192
193 /**
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
197  *              happened.
198  *
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.
202  *
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.
205  *
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.
210  *
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.
214  */
215
216 LWS_VISIBLE int
217 libwebsocket_service_fd(struct libwebsocket_context *context,
218                                                           struct libwebsocket_pollfd *pollfd)
219 {
220         struct libwebsocket *wsi;
221         int n;
222         int m;
223         int listen_socket_fds_index = 0;
224         time_t now;
225         int timed_out = 0;
226         int our_fd = 0;
227         char draining_flow = 0;
228         int more;
229         struct lws_tokens eff_buf;
230
231         if (context->listen_service_fd)
232                 listen_socket_fds_index = context->lws_lookup[
233                              context->listen_service_fd]->position_in_fds_table;
234
235         /*
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.
239          */
240
241         time(&now);
242
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;
246
247                 lws_plat_service_periodic(context);
248
249                 /* global timeout check once per second */
250
251                 if (pollfd)
252                         our_fd = pollfd->fd;
253
254                 for (n = 0; n < context->fds_count; n++) {
255                         m = context->fds[n].fd;
256                         wsi = context->lws_lookup[m];
257                         if (!wsi)
258                                 continue;
259
260                         if (libwebsocket_service_timeout_check(context, wsi, now))
261                                 /* he did time out... */
262                                 if (m == our_fd) {
263                                         /* it was the guy we came to service! */
264                                         timed_out = 1;
265                                         /* mark as handled */
266                                         pollfd->revents = 0;
267                                 }
268                 }
269         }
270
271         /* the socket we came to service timed out, nothing to do */
272         if (timed_out)
273                 return 0;
274
275         /* just here for timeout management? */
276         if (pollfd == NULL)
277                 return 0;
278
279         /* no, here to service a socket descriptor */
280         wsi = context->lws_lookup[pollfd->fd];
281         if (wsi == NULL)
282                 /* not lws connection ... leave revents alone and return */
283                 return 0;
284
285         /*
286          * so that caller can tell we handled, past here we need to
287          * zero down pollfd->revents after handling
288          */
289
290         /*
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
294          *
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.
297          */
298
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;
306                         m = 1;
307                         if (context->listen_service_extraseen > 5)
308                                 m = 2;
309                         while (m--) {
310                                 /*
311                                  * even with extpoll, we prepared this
312                                  * internal fds for listen
313                                  */
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,
317                                                 &context->
318                                                   fds[listen_socket_fds_index]);
319                                         context->listen_service_extraseen++;
320                                 } else {
321                                         if (context->listen_service_extraseen)
322                                                 context->
323                                                      listen_service_extraseen--;
324                                         break;
325                                 }
326                         }
327                 }
328
329         }
330
331         /* handle session socket closed */
332
333         if ((!(pollfd->revents & LWS_POLLIN)) &&
334                         (pollfd->revents & LWS_POLLHUP)) {
335
336                 lwsl_debug("Session Socket %p (fd=%d) dead\n",
337                                                        (void *)wsi, pollfd->fd);
338
339                 goto close_and_handled;
340         }
341
342         /* okay, what we came here to do... */
343
344         switch (wsi->mode) {
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);
350                 if (n < 0)
351                         goto close_and_handled;
352                 goto handled;
353
354         case LWS_CONNMODE_WS_SERVING:
355         case LWS_CONNMODE_WS_CLIENT:
356
357                 /* the guy requested a callback when it was OK to write */
358
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;
365                 }
366
367                 if (wsi->u.ws.rxflow_buffer &&
368                               (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW)) {
369                         lwsl_info("draining rxflow\n");
370                         /* well, drain it */
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;
375                         draining_flow = 1;
376                         goto drain;
377                 }
378
379                 /* any incoming data ready? */
380
381                 if (!(pollfd->revents & LWS_POLLIN))
382                         break;
383
384 read_pending:
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) {
389                 case 0:
390                         lwsl_info("service_fd: closing due to 0 length read\n");
391                         goto close_and_handled;
392                 case LWS_SSL_CAPABLE_ERROR:
393                         n = 0;
394                         goto handled;
395                 case LWS_SSL_CAPABLE_MORE_SERVICE:
396                         goto close_and_handled;
397                 }
398
399                 /*
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.
409                  */
410
411                 eff_buf.token = (char *)context->service_buffer;
412 drain:
413
414                 do {
415
416                         more = 0;
417                         
418                         m = lws_ext_callback_for_each_active(wsi,
419                                 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE, &eff_buf, 0);
420                         if (m < 0)
421                                 goto close_and_handled;
422                         if (m)
423                                 more = 1;
424
425                         /* service incoming data */
426
427                         if (eff_buf.token_len) {
428                                 n = libwebsocket_read(context, wsi,
429                                         (unsigned char *)eff_buf.token,
430                                                             eff_buf.token_len);
431                                 if (n < 0) {
432                                         /* we closed wsi */
433                                         n = 0;
434                                         goto handled;
435                                 }
436                         }
437
438                         eff_buf.token = NULL;
439                         eff_buf.token_len = 0;
440                 } while (more);
441
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 */
449                 }
450
451                 if (lws_ssl_pending(wsi))
452                         goto read_pending;
453                 break;
454
455         default:
456 #ifdef LWS_NO_CLIENT
457                 break;
458 #else
459                 n = lws_client_socket_service(context, wsi, pollfd);
460                 goto handled;
461 #endif
462         }
463
464         n = 0;
465         goto handled;
466
467 close_and_handled:
468         libwebsocket_close_and_free_session(context, wsi,
469                                                 LWS_CLOSE_STATUS_NOSTATUS);
470         n = 1;
471
472 handled:
473         pollfd->revents = 0;
474         return n;
475 }
476
477 /**
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.
483  *
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.
487  *
488  *      1) Accept new connections to our context's server
489  *
490  *      2) Call the receive callback for incoming frame data received by
491  *          server or client connections.
492  *
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.
496  *
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.
502  *
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.
507  */
508
509 LWS_VISIBLE int
510 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
511 {
512         return lws_plat_service(context, timeout_ms);
513 }
514