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