public api remove context from user callback API BREAK
[platform/upstream/libwebsockets.git] / lib / service.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2015 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 static int
25 lws_calllback_as_writeable(struct lws *wsi)
26 {
27         int n;
28
29         switch (wsi->mode) {
30         case LWS_CONNMODE_WS_CLIENT:
31                 n = LWS_CALLBACK_CLIENT_WRITEABLE;
32                 break;
33         case LWS_CONNMODE_WS_SERVING:
34                 n = LWS_CALLBACK_SERVER_WRITEABLE;
35                 break;
36         default:
37                 n = LWS_CALLBACK_HTTP_WRITEABLE;
38                 break;
39         }
40         lwsl_info("%s: %p (user=%p)\n", __func__, wsi, wsi->user_space);
41         return user_callback_handle_rxflow(wsi->protocol->callback,
42                                            wsi, (enum lws_callback_reasons) n,
43                                            wsi->user_space, NULL, 0);
44 }
45
46 int
47 lws_handle_POLLOUT_event(struct lws *wsi, struct lws_pollfd *pollfd)
48 {
49         int write_type = LWS_WRITE_PONG;
50         struct lws_tokens eff_buf;
51 #ifdef LWS_USE_HTTP2
52         struct lws *wsi2;
53 #endif
54         int ret, m, n;
55
56         /* pending truncated sends have uber priority */
57
58         if (wsi->truncated_send_len) {
59                 if (lws_issue_raw(wsi, wsi->truncated_send_malloc +
60                                 wsi->truncated_send_offset,
61                                                 wsi->truncated_send_len) < 0) {
62                         lwsl_info("%s signalling to close\n", __func__);
63                         return -1;
64                 }
65                 /* leave POLLOUT active either way */
66                 return 0;
67         } else
68                 if (wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE)
69                         return -1; /* retry closing now */
70
71 #ifdef LWS_USE_HTTP2
72         /* protocol packets are next */
73         if (wsi->pps) {
74                 lwsl_info("servicing pps %d\n", wsi->pps);
75                 switch (wsi->pps) {
76                 case LWS_PPS_HTTP2_MY_SETTINGS:
77                 case LWS_PPS_HTTP2_ACK_SETTINGS:
78                         lws_http2_do_pps_send(lws_get_ctx(wsi), wsi);
79                         break;
80                 default:
81                         break;
82                 }
83                 wsi->pps = LWS_PPS_NONE;
84                 lws_rx_flow_control(wsi, 1);
85
86                 return 0; /* leave POLLOUT active */
87         }
88 #endif
89         /* pending control packets have next priority */
90
91         if ((wsi->state == WSI_STATE_ESTABLISHED &&
92              wsi->u.ws.ping_pending_flag) ||
93             (wsi->state == WSI_STATE_RETURNED_CLOSE_ALREADY &&
94              wsi->u.ws.payload_is_close)) {
95
96                 if (wsi->u.ws.payload_is_close)
97                         write_type = LWS_WRITE_CLOSE;
98
99                 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[
100                                         LWS_SEND_BUFFER_PRE_PADDING],
101                               wsi->u.ws.ping_payload_len, write_type);
102                 if (n < 0)
103                         return -1;
104
105                 /* well he is sent, mark him done */
106                 wsi->u.ws.ping_pending_flag = 0;
107                 if (wsi->u.ws.payload_is_close)
108                         /* oh... a close frame was it... then we are done */
109                         return -1;
110
111                 /* otherwise for PING, leave POLLOUT active either way */
112                 return 0;
113         }
114
115         /* if we are closing, don't confuse the user with writeable cb */
116
117         if (wsi->state == WSI_STATE_RETURNED_CLOSE_ALREADY)
118                 goto user_service;
119
120         /* if nothing critical, user can get the callback */
121
122         m = lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_IS_WRITEABLE,
123                                                                        NULL, 0);
124 #ifndef LWS_NO_EXTENSIONS
125         if (!wsi->extension_data_pending)
126                 goto user_service;
127 #endif
128         /*
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
132          *
133          * NULL, zero-length eff_buf means just spill pending
134          */
135
136         ret = 1;
137         while (ret == 1) {
138
139                 /* default to nobody has more to spill */
140
141                 ret = 0;
142                 eff_buf.token = NULL;
143                 eff_buf.token_len = 0;
144
145                 /* give every extension a chance to spill */
146
147                 m = lws_ext_callback_for_each_active(wsi,
148                                         LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
149                                                                    &eff_buf, 0);
150                 if (m < 0) {
151                         lwsl_err("ext reports fatal error\n");
152                         return -1;
153                 }
154                 if (m)
155                         /*
156                          * at least one extension told us he has more
157                          * to spill, so we will go around again after
158                          */
159                         ret = 1;
160
161                 /* assuming they gave us something to send, send it */
162
163                 if (eff_buf.token_len) {
164                         n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
165                                                              eff_buf.token_len);
166                         if (n < 0) {
167                                 lwsl_info("closing from POLLOUT spill\n");
168                                 return -1;
169                         }
170                         /*
171                          * Keep amount spilled small to minimize chance of this
172                          */
173                         if (n != eff_buf.token_len) {
174                                 lwsl_err("Unable to spill ext %d vs %s\n",
175                                                           eff_buf.token_len, n);
176                                 return -1;
177                         }
178                 } else
179                         continue;
180
181                 /* no extension has more to spill */
182
183                 if (!ret)
184                         continue;
185
186                 /*
187                  * There's more to spill from an extension, but we just sent
188                  * something... did that leave the pipe choked?
189                  */
190
191                 if (!lws_send_pipe_choked(wsi))
192                         /* no we could add more */
193                         continue;
194
195                 lwsl_info("choked in POLLOUT service\n");
196
197                 /*
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.
202                  */
203
204                 return 0;
205         }
206 #ifndef LWS_NO_EXTENSIONS
207         wsi->extension_data_pending = 0;
208 #endif
209 user_service:
210         /* one shot */
211
212         if (pollfd) {
213                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
214                         lwsl_info("failed at set pollfd\n");
215                         return 1;
216                 }
217
218                 lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_WRITE);
219         }
220
221 #ifdef LWS_USE_HTTP2
222         /*
223          * we are the 'network wsi' for potentially many muxed child wsi with
224          * no network connection of their own, who have to use us for all their
225          * network actions.  So we use a round-robin scheme to share out the
226          * POLLOUT notifications to our children.
227          *
228          * But because any child could exhaust the socket's ability to take
229          * writes, we can only let one child get notified each time.
230          *
231          * In addition children may be closed / deleted / added between POLLOUT
232          * notifications, so we can't hold pointers
233          */
234
235         if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING) {
236                 lwsl_info("%s: non http2\n", __func__);
237                 goto notify;
238         }
239
240         wsi->u.http2.requested_POLLOUT = 0;
241         if (!wsi->u.http2.initialized) {
242                 lwsl_info("pollout on uninitialized http2 conn\n");
243                 return 0;
244         }
245
246         lwsl_info("%s: doing children\n", __func__);
247
248         wsi2 = wsi;
249         do {
250                 wsi2 = wsi2->u.http2.next_child_wsi;
251                 lwsl_info("%s: child %p\n", __func__, wsi2);
252                 if (!wsi2)
253                         continue;
254                 if (!wsi2->u.http2.requested_POLLOUT)
255                         continue;
256                 wsi2->u.http2.requested_POLLOUT = 0;
257                 if (lws_calllback_as_writeable(wsi2)) {
258                         lwsl_debug("Closing POLLOUT child\n");
259                         lws_close_free_wsi(wsi2, LWS_CLOSE_STATUS_NOSTATUS);
260                 }
261                 wsi2 = wsi;
262         } while (wsi2 != NULL && !lws_send_pipe_choked(wsi));
263
264         lwsl_info("%s: completed\n", __func__);
265
266         return 0;
267 notify:
268 #endif
269         return lws_calllback_as_writeable(wsi);
270 }
271
272 int
273 lws_service_timeout_check(struct lws *wsi, unsigned int sec)
274 {
275         /*
276          * if extensions want in on it (eg, we are a mux parent)
277          * give them a chance to service child timeouts
278          */
279         if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_1HZ,
280                                              NULL, sec) < 0)
281                 return 0;
282
283         if (!wsi->pending_timeout)
284                 return 0;
285
286         /*
287          * if we went beyond the allowed time, kill the
288          * connection
289          */
290         if ((time_t)sec > wsi->pending_timeout_limit) {
291                 lwsl_info("wsi %p: TIMEDOUT WAITING on %d\n",
292                           (void *)wsi, wsi->pending_timeout);
293                 /*
294                  * Since he failed a timeout, he already had a chance to do
295                  * something and was unable to... that includes situations like
296                  * half closed connections.  So process this "failed timeout"
297                  * close as a violent death and don't try to do protocol
298                  * cleanup like flush partials.
299                  */
300                 wsi->socket_is_permanently_unusable = 1;
301                 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
302
303                 return 1;
304         }
305
306         return 0;
307 }
308
309 int lws_rxflow_cache(struct lws *wsi, unsigned char *buf, int n, int len)
310 {
311         /* his RX is flowcontrolled, don't send remaining now */
312         if (wsi->rxflow_buffer) {
313                 /* rxflow while we were spilling prev rxflow */
314                 lwsl_info("stalling in existing rxflow buf\n");
315                 return 1;
316         }
317
318         /* a new rxflow, buffer it and warn caller */
319         lwsl_info("new rxflow input buffer len %d\n", len - n);
320         wsi->rxflow_buffer = lws_malloc(len - n);
321         wsi->rxflow_len = len - n;
322         wsi->rxflow_pos = 0;
323         memcpy(wsi->rxflow_buffer, buf + n, len - n);
324
325         return 0;
326 }
327
328 /**
329  * lws_service_fd() - Service polled socket with something waiting
330  * @context:    Websocket context
331  * @pollfd:     The pollfd entry describing the socket fd and which events
332  *              happened.
333  *
334  *      This function takes a pollfd that has POLLIN or POLLOUT activity and
335  *      services it according to the state of the associated
336  *      struct lws.
337  *
338  *      The one call deals with all "service" that might happen on a socket
339  *      including listen accepts, http files as well as websocket protocol.
340  *
341  *      If a pollfd says it has something, you can just pass it to
342  *      lws_service_fd() whether it is a socket handled by lws or not.
343  *      If it sees it is a lws socket, the traffic will be handled and
344  *      pollfd->revents will be zeroed now.
345  *
346  *      If the socket is foreign to lws, it leaves revents alone.  So you can
347  *      see if you should service yourself by checking the pollfd revents
348  *      after letting lws try to service it.
349  */
350
351 LWS_VISIBLE int
352 lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd)
353 {
354 #if LWS_POSIX
355         int listen_socket_fds_index = 0;
356 #endif
357         lws_sockfd_type our_fd = 0;
358         struct lws_tokens eff_buf;
359         unsigned int pending = 0;
360         char draining_flow = 0;
361         lws_sockfd_type mfd;
362         int timed_out = 0;
363         struct lws *wsi;
364         time_t now;
365         int n, m;
366         int more;
367
368 #if LWS_POSIX
369         if (context->listen_service_fd)
370                 listen_socket_fds_index = wsi_from_fd(context,
371                         context->listen_service_fd)->position_in_fds_table;
372 #endif
373          /*
374          * you can call us with pollfd = NULL to just allow the once-per-second
375          * global timeout checks; if less than a second since the last check
376          * it returns immediately then.
377          */
378
379         time(&now);
380
381         /* TODO: if using libev, we should probably use timeout watchers... */
382         if (context->last_timeout_check_s != now) {
383                 context->last_timeout_check_s = now;
384
385                 lws_plat_service_periodic(context);
386
387                 /* global timeout check once per second */
388
389                 if (pollfd)
390                         our_fd = pollfd->fd;
391
392                 for (n = 0; n < context->fds_count; n++) {
393                         mfd = context->fds[n].fd;
394                         wsi = wsi_from_fd(context, mfd);
395                         if (!wsi)
396                                 continue;
397
398                         if (lws_service_timeout_check(wsi, (unsigned int)now))
399                                 /* he did time out... */
400                                 if (mfd == our_fd)
401                                         /* it was the guy we came to service! */
402                                         timed_out = 1;
403                                         /* he's gone, no need to mark as handled */
404                 }
405         }
406
407         /* the socket we came to service timed out, nothing to do */
408         if (timed_out)
409                 return 0;
410
411         /* just here for timeout management? */
412         if (!pollfd)
413                 return 0;
414
415         /* no, here to service a socket descriptor */
416         wsi = wsi_from_fd(context, pollfd->fd);
417         if (!wsi)
418                 /* not lws connection ... leave revents alone and return */
419                 return 0;
420
421         /*
422          * so that caller can tell we handled, past here we need to
423          * zero down pollfd->revents after handling
424          */
425
426 #if LWS_POSIX
427         /*
428          * deal with listen service piggybacking
429          * every listen_service_modulo services of other fds, we
430          * sneak one in to service the listen socket if there's anything waiting
431          *
432          * To handle connection storms, as found in ab, if we previously saw a
433          * pending connection here, it causes us to check again next time.
434          */
435
436         if (context->listen_service_fd && pollfd !=
437                                        &context->fds[listen_socket_fds_index]) {
438                 context->listen_service_count++;
439                 if (context->listen_service_extraseen ||
440                                 context->listen_service_count ==
441                                                context->listen_service_modulo) {
442                         context->listen_service_count = 0;
443                         m = 1;
444                         if (context->listen_service_extraseen > 5)
445                                 m = 2;
446                         while (m--) {
447                                 /*
448                                  * even with extpoll, we prepared this
449                                  * internal fds for listen
450                                  */
451                                 n = lws_poll_listen_fd(
452                                         &context->fds[listen_socket_fds_index]);
453                                 if (n > 0) { /* there's a conn waiting for us */
454                                         lws_service_fd(context,
455                                                 &context->
456                                                   fds[listen_socket_fds_index]);
457                                         context->listen_service_extraseen++;
458                                 } else {
459                                         if (context->listen_service_extraseen)
460                                                 context->
461                                                      listen_service_extraseen--;
462                                         break;
463                                 }
464                         }
465                 }
466
467         }
468
469         /* handle session socket closed */
470
471         if ((!(pollfd->revents & LWS_POLLIN)) &&
472                         (pollfd->revents & LWS_POLLHUP)) {
473
474                 lwsl_debug("Session Socket %p (fd=%d) dead\n",
475                                                        (void *)wsi, pollfd->fd);
476
477                 goto close_and_handled;
478         }
479 #endif
480
481         /* okay, what we came here to do... */
482
483         switch (wsi->mode) {
484         case LWS_CONNMODE_HTTP_SERVING:
485         case LWS_CONNMODE_HTTP_SERVING_ACCEPTED:
486         case LWS_CONNMODE_SERVER_LISTENER:
487         case LWS_CONNMODE_SSL_ACK_PENDING:
488                 n = lws_server_socket_service(context, wsi, pollfd);
489                 if (n) /* closed by above */
490                         return 1;
491                 pending = lws_ssl_pending(wsi);
492                 if (pending)
493                         goto handle_pending;
494                 goto handled;
495
496         case LWS_CONNMODE_WS_SERVING:
497         case LWS_CONNMODE_WS_CLIENT:
498         case LWS_CONNMODE_HTTP2_SERVING:
499
500                 /* the guy requested a callback when it was OK to write */
501
502                 if ((pollfd->revents & LWS_POLLOUT) &&
503                     (wsi->state == WSI_STATE_ESTABLISHED ||
504                      wsi->state == WSI_STATE_HTTP2_ESTABLISHED ||
505                      wsi->state == WSI_STATE_HTTP2_ESTABLISHED_PRE_SETTINGS ||
506                      wsi->state == WSI_STATE_RETURNED_CLOSE_ALREADY ||
507                      wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) &&
508                            lws_handle_POLLOUT_event(wsi, pollfd)) {
509                         if (wsi->state == WSI_STATE_RETURNED_CLOSE_ALREADY)
510                                 wsi->state = WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE;
511                         lwsl_info("lws_service_fd: closing\n");
512                         goto close_and_handled;
513                 }
514
515                 if (wsi->rxflow_buffer &&
516                               (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
517                         lwsl_info("draining rxflow\n");
518                         /* well, drain it */
519                         eff_buf.token = (char *)wsi->rxflow_buffer +
520                                                 wsi->rxflow_pos;
521                         eff_buf.token_len = wsi->rxflow_len - wsi->rxflow_pos;
522                         draining_flow = 1;
523                         goto drain;
524                 }
525
526                 /* any incoming data ready? */
527
528                 if (!(pollfd->revents & LWS_POLLIN))
529                         break;
530 read:
531
532                 eff_buf.token_len = lws_ssl_capable_read(wsi,
533                                         context->service_buffer,
534                                         pending ? pending :
535                                         sizeof(context->service_buffer));
536                 switch (eff_buf.token_len) {
537                 case 0:
538                         lwsl_info("service_fd: closing due to 0 length read\n");
539                         goto close_and_handled;
540                 case LWS_SSL_CAPABLE_MORE_SERVICE:
541                         lwsl_info("SSL Capable more service\n");
542                         n = 0;
543                         goto handled;
544                 case LWS_SSL_CAPABLE_ERROR:
545                         lwsl_info("Closing when error\n");
546                         goto close_and_handled;
547                 }
548
549                 /*
550                  * give any active extensions a chance to munge the buffer
551                  * before parse.  We pass in a pointer to an lws_tokens struct
552                  * prepared with the default buffer and content length that's in
553                  * there.  Rather than rewrite the default buffer, extensions
554                  * that expect to grow the buffer can adapt .token to
555                  * point to their own per-connection buffer in the extension
556                  * user allocation.  By default with no extensions or no
557                  * extension callback handling, just the normal input buffer is
558                  * used then so it is efficient.
559                  */
560
561                 eff_buf.token = (char *)context->service_buffer;
562 drain:
563
564                 do {
565                         more = 0;
566
567                         m = lws_ext_callback_for_each_active(wsi,
568                                 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE, &eff_buf, 0);
569                         if (m < 0)
570                                 goto close_and_handled;
571                         if (m)
572                                 more = 1;
573
574                         /* service incoming data */
575
576                         if (eff_buf.token_len) {
577                                 n = lws_read(wsi, (unsigned char *)eff_buf.token,
578                                              eff_buf.token_len);
579                                 if (n < 0) {
580                                         /* we closed wsi */
581                                         n = 0;
582                                         goto handled;
583                                 }
584                         }
585
586                         eff_buf.token = NULL;
587                         eff_buf.token_len = 0;
588                 } while (more);
589
590                 pending = lws_ssl_pending(wsi);
591                 if (pending) {
592 handle_pending:
593                         pending = pending > sizeof(context->service_buffer) ?
594                                 sizeof(context->service_buffer) : pending;
595                         goto read;
596                 }
597
598                 if (draining_flow && wsi->rxflow_buffer &&
599                                  wsi->rxflow_pos == wsi->rxflow_len) {
600                         lwsl_info("flow buffer: drained\n");
601                         lws_free2(wsi->rxflow_buffer);
602                         /* having drained the rxflow buffer, can rearm POLLIN */
603 #ifdef LWS_NO_SERVER
604                         n =
605 #endif
606                         _lws_rx_flow_control(wsi);
607                         /* n ignored, needed for NO_SERVER case */
608                 }
609
610                 break;
611
612         default:
613 #ifdef LWS_NO_CLIENT
614                 break;
615 #else
616                 n = lws_client_socket_service(context, wsi, pollfd);
617                 goto handled;
618 #endif
619         }
620
621         n = 0;
622         goto handled;
623
624 close_and_handled:
625         lwsl_debug("Close and handled\n");
626         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
627         /*
628          * pollfd may point to something else after the close
629          * due to pollfd swapping scheme on delete on some platforms
630          * we can't clear revents now because it'd be the wrong guy's revents
631          */
632         return 1;
633
634 handled:
635         pollfd->revents = 0;
636         return n;
637 }
638
639 /**
640  * lws_service() - Service any pending websocket activity
641  * @context:    Websocket context
642  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
643  *              service otherwise block and service immediately, returning
644  *              after the timeout if nothing needed service.
645  *
646  *      This function deals with any pending websocket traffic, for three
647  *      kinds of event.  It handles these events on both server and client
648  *      types of connection the same.
649  *
650  *      1) Accept new connections to our context's server
651  *
652  *      2) Call the receive callback for incoming frame data received by
653  *          server or client connections.
654  *
655  *      You need to call this service function periodically to all the above
656  *      functions to happen; if your application is single-threaded you can
657  *      just call it in your main event loop.
658  *
659  *      Alternatively you can fork a new process that asynchronously handles
660  *      calling this service in a loop.  In that case you are happy if this
661  *      call blocks your thread until it needs to take care of something and
662  *      would call it with a large nonzero timeout.  Your loop then takes no
663  *      CPU while there is nothing happening.
664  *
665  *      If you are calling it in a single-threaded app, you don't want it to
666  *      wait around blocking other things in your loop from happening, so you
667  *      would call it with a timeout_ms of 0, so it returns immediately if
668  *      nothing is pending, or as soon as it services whatever was pending.
669  */
670
671 LWS_VISIBLE int
672 lws_service(struct lws_context *context, int timeout_ms)
673 {
674         return lws_plat_service(context, timeout_ms);
675 }
676