ssl optimize poll when buffered ssl read data
[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 #ifdef LWS_USE_HTTP2
51         /* protocol packets are next */
52         if (wsi->pps) {
53                 lwsl_info("servicing pps %d\n", wsi->pps);
54                 switch (wsi->pps) {
55                 case LWS_PPS_HTTP2_MY_SETTINGS:
56                 case LWS_PPS_HTTP2_ACK_SETTINGS:
57                         lws_http2_do_pps_send(context, wsi);
58                         break;
59                 default:
60                         break;
61                 }
62                 wsi->pps = LWS_PPS_NONE;
63                 libwebsocket_rx_flow_control(wsi, 1);
64                 
65                 return 0; /* leave POLLOUT active */
66         }
67 #endif
68         /* pending control packets have next priority */
69         
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,
75                                                                LWS_WRITE_PONG);
76                 if (n < 0)
77                         return -1;
78                 /* well he is sent, mark him done */
79                 wsi->u.ws.ping_payload_len = 0;
80                 /* leave POLLOUT active either way */
81                 return 0;
82         }
83
84         /* if nothing critical, user can get the callback */
85         
86         m = lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_IS_WRITEABLE,
87                                                                        NULL, 0);
88         if (handled == 1)
89                 goto notify_action;
90 #ifndef LWS_NO_EXTENSIONS
91         if (!wsi->extension_data_pending || handled == 2)
92                 goto user_service;
93 #endif
94         /*
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
98          *
99          * NULL, zero-length eff_buf means just spill pending
100          */
101
102         ret = 1;
103         while (ret == 1) {
104
105                 /* default to nobody has more to spill */
106
107                 ret = 0;
108                 eff_buf.token = NULL;
109                 eff_buf.token_len = 0;
110
111                 /* give every extension a chance to spill */
112                 
113                 m = lws_ext_callback_for_each_active(wsi,
114                                         LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
115                                                                    &eff_buf, 0);
116                 if (m < 0) {
117                         lwsl_err("ext reports fatal error\n");
118                         return -1;
119                 }
120                 if (m)
121                         /*
122                          * at least one extension told us he has more
123                          * to spill, so we will go around again after
124                          */
125                         ret = 1;
126
127                 /* assuming they gave us something to send, send it */
128
129                 if (eff_buf.token_len) {
130                         n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
131                                                              eff_buf.token_len);
132                         if (n < 0) {
133                                 lwsl_info("closing from POLLOUT spill\n");
134                                 return -1;
135                         }
136                         /*
137                          * Keep amount spilled small to minimize chance of this
138                          */
139                         if (n != eff_buf.token_len) {
140                                 lwsl_err("Unable to spill ext %d vs %s\n",
141                                                           eff_buf.token_len, n);
142                                 return -1;
143                         }
144                 } else
145                         continue;
146
147                 /* no extension has more to spill */
148
149                 if (!ret)
150                         continue;
151
152                 /*
153                  * There's more to spill from an extension, but we just sent
154                  * something... did that leave the pipe choked?
155                  */
156
157                 if (!lws_send_pipe_choked(wsi))
158                         /* no we could add more */
159                         continue;
160
161                 lwsl_info("choked in POLLOUT service\n");
162
163                 /*
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.
168                  */
169
170                 return 0;
171         }
172 #ifndef LWS_NO_EXTENSIONS
173         wsi->extension_data_pending = 0;
174
175 user_service:
176 #endif
177         /* one shot */
178
179         if (pollfd) {
180                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
181                         lwsl_info("failled at set pollfd\n");
182                         return 1;
183                 }
184
185                 lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE);
186         }
187
188 notify_action:
189         if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
190                 n = LWS_CALLBACK_CLIENT_WRITEABLE;
191         else
192                 n = LWS_CALLBACK_SERVER_WRITEABLE;
193
194         return user_callback_handle_rxflow(wsi->protocol->callback, context,
195                         wsi, (enum libwebsocket_callback_reasons) n,
196                                                       wsi->user_space, NULL, 0);
197 }
198
199
200
201 int
202 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
203                                      struct libwebsocket *wsi, unsigned int sec)
204 {
205         /*
206          * if extensions want in on it (eg, we are a mux parent)
207          * give them a chance to service child timeouts
208          */
209         if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_1HZ, NULL, sec) < 0)
210                 return 0;
211
212         if (!wsi->pending_timeout)
213                 return 0;
214
215         /*
216          * if we went beyond the allowed time, kill the
217          * connection
218          */
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);
223                 return 1;
224         }
225
226         return 0;
227 }
228
229 int lws_rxflow_cache(struct libwebsocket *wsi, unsigned char *buf, int n, int len)
230 {
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");
235                 return 1;
236         }
237
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;
242         wsi->rxflow_pos = 0;
243         memcpy(wsi->rxflow_buffer, buf + n, len - n);
244
245         return 0;
246 }
247
248 /**
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
252  *              happened.
253  *
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.
257  *
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.
260  *
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.
265  *
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.
269  */
270
271 LWS_VISIBLE int
272 libwebsocket_service_fd(struct libwebsocket_context *context,
273                                                           struct libwebsocket_pollfd *pollfd)
274 {
275         struct libwebsocket *wsi;
276         int n;
277         int m;
278         int listen_socket_fds_index = 0;
279         time_t now;
280         int timed_out = 0;
281         int our_fd = 0;
282         char draining_flow = 0;
283         int more;
284         struct lws_tokens eff_buf;
285
286         if (context->listen_service_fd)
287                 listen_socket_fds_index = context->lws_lookup[
288                              context->listen_service_fd]->position_in_fds_table;
289
290         /*
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.
294          */
295
296         time(&now);
297
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;
301
302                 lws_plat_service_periodic(context);
303
304                 /* global timeout check once per second */
305
306                 if (pollfd)
307                         our_fd = pollfd->fd;
308
309                 for (n = 0; n < context->fds_count; n++) {
310                         m = context->fds[n].fd;
311                         wsi = context->lws_lookup[m];
312                         if (!wsi)
313                                 continue;
314
315                         if (libwebsocket_service_timeout_check(context, wsi, now))
316                                 /* he did time out... */
317                                 if (m == our_fd) {
318                                         /* it was the guy we came to service! */
319                                         timed_out = 1;
320                                         /* mark as handled */
321                                         pollfd->revents = 0;
322                                 }
323                 }
324         }
325
326         /* the socket we came to service timed out, nothing to do */
327         if (timed_out)
328                 return 0;
329
330         /* just here for timeout management? */
331         if (pollfd == NULL)
332                 return 0;
333
334         /* no, here to service a socket descriptor */
335         wsi = context->lws_lookup[pollfd->fd];
336         if (wsi == NULL)
337                 /* not lws connection ... leave revents alone and return */
338                 return 0;
339
340         /*
341          * so that caller can tell we handled, past here we need to
342          * zero down pollfd->revents after handling
343          */
344
345         /*
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
349          *
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.
352          */
353
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;
361                         m = 1;
362                         if (context->listen_service_extraseen > 5)
363                                 m = 2;
364                         while (m--) {
365                                 /*
366                                  * even with extpoll, we prepared this
367                                  * internal fds for listen
368                                  */
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,
372                                                 &context->
373                                                   fds[listen_socket_fds_index]);
374                                         context->listen_service_extraseen++;
375                                 } else {
376                                         if (context->listen_service_extraseen)
377                                                 context->
378                                                      listen_service_extraseen--;
379                                         break;
380                                 }
381                         }
382                 }
383
384         }
385
386         /* handle session socket closed */
387
388         if ((!(pollfd->revents & LWS_POLLIN)) &&
389                         (pollfd->revents & LWS_POLLHUP)) {
390
391                 lwsl_debug("Session Socket %p (fd=%d) dead\n",
392                                                        (void *)wsi, pollfd->fd);
393
394                 goto close_and_handled;
395         }
396
397         /* okay, what we came here to do... */
398
399         switch (wsi->mode) {
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);
405                 if (n < 0)
406                         goto close_and_handled;
407                 goto handled;
408
409         case LWS_CONNMODE_WS_SERVING:
410         case LWS_CONNMODE_WS_CLIENT:
411         case LWS_CONNMODE_HTTP2_SERVING:
412
413                 /* the guy requested a callback when it was OK to write */
414
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;
421                 }
422
423                 if (wsi->rxflow_buffer &&
424                               (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
425                         lwsl_info("draining rxflow\n");
426                         /* well, drain it */
427                         eff_buf.token = (char *)wsi->rxflow_buffer +
428                                                 wsi->rxflow_pos;
429                         eff_buf.token_len = wsi->rxflow_len - wsi->rxflow_pos;
430                         draining_flow = 1;
431                         goto drain;
432                 }
433
434                 /* any incoming data ready? */
435
436                 if (!(pollfd->revents & LWS_POLLIN))
437                         break;
438
439                 eff_buf.token_len = lws_ssl_capable_read(context, wsi,
440                                 context->service_buffer,
441                                                sizeof(context->service_buffer));
442                 switch (eff_buf.token_len) {
443                 case 0:
444                         lwsl_info("service_fd: closing due to 0 length read\n");
445                         goto close_and_handled;
446                 case LWS_SSL_CAPABLE_MORE_SERVICE:
447                         lwsl_info("SSL Capable more service\n");
448                         n = 0;
449                         goto handled;
450                 case LWS_SSL_CAPABLE_ERROR:
451                         lwsl_info("Closing when error\n");
452                         goto close_and_handled;
453                 }
454
455                 /*
456                  * give any active extensions a chance to munge the buffer
457                  * before parse.  We pass in a pointer to an lws_tokens struct
458                  * prepared with the default buffer and content length that's in
459                  * there.  Rather than rewrite the default buffer, extensions
460                  * that expect to grow the buffer can adapt .token to
461                  * point to their own per-connection buffer in the extension
462                  * user allocation.  By default with no extensions or no
463                  * extension callback handling, just the normal input buffer is
464                  * used then so it is efficient.
465                  */
466
467                 eff_buf.token = (char *)context->service_buffer;
468 drain:
469
470                 do {
471
472                         more = 0;
473                         
474                         m = lws_ext_callback_for_each_active(wsi,
475                                 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE, &eff_buf, 0);
476                         if (m < 0)
477                                 goto close_and_handled;
478                         if (m)
479                                 more = 1;
480
481                         /* service incoming data */
482
483                         if (eff_buf.token_len) {
484                                 n = libwebsocket_read(context, wsi,
485                                         (unsigned char *)eff_buf.token,
486                                                             eff_buf.token_len);
487                                 if (n < 0) {
488                                         /* we closed wsi */
489                                         n = 0;
490                                         goto handled;
491                                 }
492                         }
493
494                         eff_buf.token = NULL;
495                         eff_buf.token_len = 0;
496                 } while (more);
497
498                 if (draining_flow && wsi->rxflow_buffer &&
499                                  wsi->rxflow_pos == wsi->rxflow_len) {
500                         lwsl_info("flow buffer: drained\n");
501                         free(wsi->rxflow_buffer);
502                         wsi->rxflow_buffer = NULL;
503                         /* having drained the rxflow buffer, can rearm POLLIN */
504                         n = _libwebsocket_rx_flow_control(wsi); /* n ignored, needed for NO_SERVER case */
505                 }
506
507                 break;
508
509         default:
510 #ifdef LWS_NO_CLIENT
511                 break;
512 #else
513                 n = lws_client_socket_service(context, wsi, pollfd);
514                 goto handled;
515 #endif
516         }
517
518         n = 0;
519         goto handled;
520
521 close_and_handled:
522         lwsl_debug("Close and handled\n");
523         libwebsocket_close_and_free_session(context, wsi,
524                                                 LWS_CLOSE_STATUS_NOSTATUS);
525         n = 1;
526
527 handled:
528         pollfd->revents = 0;
529         return n;
530 }
531
532 /**
533  * libwebsocket_service() - Service any pending websocket activity
534  * @context:    Websocket context
535  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
536  *              service otherwise block and service immediately, returning
537  *              after the timeout if nothing needed service.
538  *
539  *      This function deals with any pending websocket traffic, for three
540  *      kinds of event.  It handles these events on both server and client
541  *      types of connection the same.
542  *
543  *      1) Accept new connections to our context's server
544  *
545  *      2) Call the receive callback for incoming frame data received by
546  *          server or client connections.
547  *
548  *      You need to call this service function periodically to all the above
549  *      functions to happen; if your application is single-threaded you can
550  *      just call it in your main event loop.
551  *
552  *      Alternatively you can fork a new process that asynchronously handles
553  *      calling this service in a loop.  In that case you are happy if this
554  *      call blocks your thread until it needs to take care of something and
555  *      would call it with a large nonzero timeout.  Your loop then takes no
556  *      CPU while there is nothing happening.
557  *
558  *      If you are calling it in a single-threaded app, you don't want it to
559  *      wait around blocking other things in your loop from happening, so you
560  *      would call it with a timeout_ms of 0, so it returns immediately if
561  *      nothing is pending, or as soon as it services whatever was pending.
562  */
563
564 LWS_VISIBLE int
565 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
566 {
567         return lws_plat_service(context, timeout_ms);
568 }
569