add explicit parent child wsi relationships
[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 LWSCM_WS_CLIENT:
31                 n = LWS_CALLBACK_CLIENT_WRITEABLE;
32                 break;
33         case LWSCM_WS_SERVING:
34                 n = LWS_CALLBACK_SERVER_WRITEABLE;
35                 break;
36         default:
37                 n = LWS_CALLBACK_HTTP_WRITEABLE;
38                 break;
39         }
40         lwsl_debug("%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         /*
57          * user callback is lowest priority to get these notifications
58          * actually, since other pending things cannot be disordered
59          */
60
61         /* Priority 1: pending truncated sends are incomplete ws fragments
62          *             If anything else sent first the protocol would be
63          *             corrupted.
64          */
65         if (wsi->trunc_len) {
66                 if (lws_issue_raw(wsi, wsi->trunc_alloc + wsi->trunc_offset,
67                                   wsi->trunc_len) < 0) {
68                         lwsl_info("%s signalling to close\n", __func__);
69                         return -1;
70                 }
71                 /* leave POLLOUT active either way */
72                 return 0;
73         } else
74                 if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE)
75                         return -1; /* retry closing now */
76
77
78 #ifdef LWS_USE_HTTP2
79         /* Priority 2: protocol packets
80          */
81         if (wsi->pps) {
82                 lwsl_info("servicing pps %d\n", wsi->pps);
83                 switch (wsi->pps) {
84                 case LWS_PPS_HTTP2_MY_SETTINGS:
85                 case LWS_PPS_HTTP2_ACK_SETTINGS:
86                         lws_http2_do_pps_send(lws_get_context(wsi), wsi);
87                         break;
88                 default:
89                         break;
90                 }
91                 wsi->pps = LWS_PPS_NONE;
92                 lws_rx_flow_control(wsi, 1);
93
94                 return 0; /* leave POLLOUT active */
95         }
96 #endif
97         /* Priority 3: pending control packets (pong or close)
98          */
99         if ((wsi->state == LWSS_ESTABLISHED &&
100              wsi->u.ws.ping_pending_flag) ||
101             (wsi->state == LWSS_RETURNED_CLOSE_ALREADY &&
102              wsi->u.ws.payload_is_close)) {
103
104                 if (wsi->u.ws.payload_is_close)
105                         write_type = LWS_WRITE_CLOSE;
106
107                 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
108                               wsi->u.ws.ping_payload_len, write_type);
109                 if (n < 0)
110                         return -1;
111
112                 /* well he is sent, mark him done */
113                 wsi->u.ws.ping_pending_flag = 0;
114                 if (wsi->u.ws.payload_is_close)
115                         /* oh... a close frame was it... then we are done */
116                         return -1;
117
118                 /* otherwise for PING, leave POLLOUT active either way */
119                 return 0;
120         }
121
122         /* Priority 4: if we are closing, not allowed to send more data frags
123          *             which means user callback or tx ext flush banned now
124          */
125         if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY)
126                 goto user_service;
127
128         /* Priority 5: Tx path extension with more to send
129          *
130          *             These are handled as new fragments each time around
131          *             So while we must block new writeable callback to enforce
132          *             payload ordering, but since they are always complete
133          *             fragments control packets can interleave OK.
134          */
135         if (wsi->state == LWSS_ESTABLISHED && wsi->u.ws.tx_draining_ext) {
136                 lwsl_ext("SERVICING TX EXT DRAINING\n");
137                 if (lws_write(wsi, NULL, 0, LWS_WRITE_CONTINUATION) < 0)
138                         return -1;
139                 /* leave POLLOUT active */
140                 return 0;
141         }
142
143         /* Priority 6: user can get the callback
144          */
145         m = lws_ext_cb_active(wsi, LWS_EXT_CB_IS_WRITEABLE, NULL, 0);
146 #ifndef LWS_NO_EXTENSIONS
147         if (!wsi->extension_data_pending)
148                 goto user_service;
149 #endif
150         /*
151          * check in on the active extensions, see if they
152          * had pending stuff to spill... they need to get the
153          * first look-in otherwise sequence will be disordered
154          *
155          * NULL, zero-length eff_buf means just spill pending
156          */
157
158         ret = 1;
159         while (ret == 1) {
160
161                 /* default to nobody has more to spill */
162
163                 ret = 0;
164                 eff_buf.token = NULL;
165                 eff_buf.token_len = 0;
166
167                 /* give every extension a chance to spill */
168
169                 m = lws_ext_cb_active(wsi,
170                                         LWS_EXT_CB_PACKET_TX_PRESEND,
171                                                &eff_buf, 0);
172                 if (m < 0) {
173                         lwsl_err("ext reports fatal error\n");
174                         return -1;
175                 }
176                 if (m)
177                         /*
178                          * at least one extension told us he has more
179                          * to spill, so we will go around again after
180                          */
181                         ret = 1;
182
183                 /* assuming they gave us something to send, send it */
184
185                 if (eff_buf.token_len) {
186                         n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
187                                           eff_buf.token_len);
188                         if (n < 0) {
189                                 lwsl_info("closing from POLLOUT spill\n");
190                                 return -1;
191                         }
192                         /*
193                          * Keep amount spilled small to minimize chance of this
194                          */
195                         if (n != eff_buf.token_len) {
196                                 lwsl_err("Unable to spill ext %d vs %s\n",
197                                                           eff_buf.token_len, n);
198                                 return -1;
199                         }
200                 } else
201                         continue;
202
203                 /* no extension has more to spill */
204
205                 if (!ret)
206                         continue;
207
208                 /*
209                  * There's more to spill from an extension, but we just sent
210                  * something... did that leave the pipe choked?
211                  */
212
213                 if (!lws_send_pipe_choked(wsi))
214                         /* no we could add more */
215                         continue;
216
217                 lwsl_info("choked in POLLOUT service\n");
218
219                 /*
220                  * Yes, he's choked.  Leave the POLLOUT masked on so we will
221                  * come back here when he is unchoked.  Don't call the user
222                  * callback to enforce ordering of spilling, he'll get called
223                  * when we come back here and there's nothing more to spill.
224                  */
225
226                 return 0;
227         }
228 #ifndef LWS_NO_EXTENSIONS
229         wsi->extension_data_pending = 0;
230 #endif
231 user_service:
232         /* one shot */
233
234         if (pollfd)
235                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
236                         lwsl_info("failed at set pollfd\n");
237                         return 1;
238                 }
239
240         if (!wsi->hdr_parsing_completed)
241                 return 0;
242
243 #ifdef LWS_USE_HTTP2
244         /*
245          * we are the 'network wsi' for potentially many muxed child wsi with
246          * no network connection of their own, who have to use us for all their
247          * network actions.  So we use a round-robin scheme to share out the
248          * POLLOUT notifications to our children.
249          *
250          * But because any child could exhaust the socket's ability to take
251          * writes, we can only let one child get notified each time.
252          *
253          * In addition children may be closed / deleted / added between POLLOUT
254          * notifications, so we can't hold pointers
255          */
256
257         if (wsi->mode != LWSCM_HTTP2_SERVING) {
258                 lwsl_info("%s: non http2\n", __func__);
259                 goto notify;
260         }
261
262         wsi->u.http2.requested_POLLOUT = 0;
263         if (!wsi->u.http2.initialized) {
264                 lwsl_info("pollout on uninitialized http2 conn\n");
265                 return 0;
266         }
267
268         lwsl_info("%s: doing children\n", __func__);
269
270         wsi2 = wsi;
271         do {
272                 wsi2 = wsi2->u.http2.next_child_wsi;
273                 lwsl_info("%s: child %p\n", __func__, wsi2);
274                 if (!wsi2)
275                         continue;
276                 if (!wsi2->u.http2.requested_POLLOUT)
277                         continue;
278                 wsi2->u.http2.requested_POLLOUT = 0;
279                 if (lws_calllback_as_writeable(wsi2)) {
280                         lwsl_debug("Closing POLLOUT child\n");
281                         lws_close_free_wsi(wsi2, LWS_CLOSE_STATUS_NOSTATUS);
282                 }
283                 wsi2 = wsi;
284         } while (wsi2 != NULL && !lws_send_pipe_choked(wsi));
285
286         lwsl_info("%s: completed\n", __func__);
287
288         return 0;
289 notify:
290 #endif
291         return lws_calllback_as_writeable(wsi);
292 }
293
294 int
295 lws_service_timeout_check(struct lws *wsi, unsigned int sec)
296 {
297         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
298
299         /*
300          * if extensions want in on it (eg, we are a mux parent)
301          * give them a chance to service child timeouts
302          */
303         if (lws_ext_cb_active(wsi, LWS_EXT_CB_1HZ, NULL, sec) < 0)
304                 return 0;
305
306         if (!wsi->pending_timeout)
307                 return 0;
308
309         /*
310          * if we went beyond the allowed time, kill the
311          * connection
312          */
313         if ((time_t)sec > wsi->pending_timeout_limit) {
314 #if LWS_POSIX
315                 lwsl_notice("wsi %p: TIMEDOUT WAITING on %d (did hdr %d, ah %p, wl %d, pfd events %d)\n",
316                             (void *)wsi, wsi->pending_timeout,
317                             wsi->hdr_parsing_completed, wsi->u.hdr.ah,
318                             pt->ah_wait_list_length,
319                             pt->fds[wsi->sock].events);
320 #endif
321                 /*
322                  * Since he failed a timeout, he already had a chance to do
323                  * something and was unable to... that includes situations like
324                  * half closed connections.  So process this "failed timeout"
325                  * close as a violent death and don't try to do protocol
326                  * cleanup like flush partials.
327                  */
328                 wsi->socket_is_permanently_unusable = 1;
329                 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
330
331                 return 1;
332         }
333
334         return 0;
335 }
336
337 int lws_rxflow_cache(struct lws *wsi, unsigned char *buf, int n, int len)
338 {
339         /* his RX is flowcontrolled, don't send remaining now */
340         if (wsi->rxflow_buffer) {
341                 /* rxflow while we were spilling prev rxflow */
342                 lwsl_info("stalling in existing rxflow buf\n");
343                 return 1;
344         }
345
346         /* a new rxflow, buffer it and warn caller */
347         lwsl_info("new rxflow input buffer len %d\n", len - n);
348         wsi->rxflow_buffer = lws_malloc(len - n);
349         wsi->rxflow_len = len - n;
350         wsi->rxflow_pos = 0;
351         memcpy(wsi->rxflow_buffer, buf + n, len - n);
352
353         return 0;
354 }
355
356 /* this is used by the platform service code to stop us waiting for network
357  * activity in poll() when we have something that already needs service
358  */
359
360 int
361 lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi)
362 {
363         struct lws_context_per_thread *pt = &context->pt[tsi];
364         int n;
365
366         /* Figure out if we really want to wait in poll()
367          * We only need to wait if really nothing already to do and we have
368          * to wait for something from network
369          */
370
371         /* 1) if we know we are draining rx ext, do not wait in poll */
372         if (pt->rx_draining_ext_list)
373                 timeout_ms = 0;
374
375 #ifdef LWS_OPENSSL_SUPPORT
376         /* 2) if we know we have non-network pending data, do not wait in poll */
377         if (lws_ssl_anybody_has_buffered_read_tsi(context, tsi)) {
378                 timeout_ms = 0;
379                 lwsl_err("ssl buffered read\n");
380         }
381 #endif
382
383         /* 3) if any ah has pending rx, do not wait in poll */
384         for (n = 0; n < context->max_http_header_pool; n++)
385                 if (pt->ah_pool[n].rxpos != pt->ah_pool[n].rxlen) {
386                         /* any ah with pending rx must be attached to someone */
387                         assert(pt->ah_pool[n].wsi);
388                         timeout_ms = 0;
389                         break;
390                 }
391
392         return timeout_ms;
393 }
394
395 /*
396  * guys that need POLLIN service again without waiting for network action
397  * can force POLLIN here if not flowcontrolled, so they will get service.
398  *
399  * Return nonzero if anybody got their POLLIN faked
400  */
401 int
402 lws_service_flag_pending(struct lws_context *context, int tsi)
403 {
404         struct lws_context_per_thread *pt = &context->pt[tsi];
405 #ifdef LWS_OPENSSL_SUPPORT
406         struct lws *wsi_next;
407 #endif
408         struct lws *wsi;
409         int forced = 0;
410         int n;
411
412         /* POLLIN faking */
413
414         /*
415          * 1) For all guys with already-available ext data to drain, if they are
416          * not flowcontrolled, fake their POLLIN status
417          */
418         wsi = pt->rx_draining_ext_list;
419         while (wsi) {
420                 pt->fds[wsi->position_in_fds_table].revents |=
421                         pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN;
422                 if (pt->fds[wsi->position_in_fds_table].revents &
423                     LWS_POLLIN)
424                         forced = 1;
425                 wsi = wsi->u.ws.rx_draining_ext_list;
426         }
427
428 #ifdef LWS_OPENSSL_SUPPORT
429         /*
430          * 2) For all guys with buffered SSL read data already saved up, if they
431          * are not flowcontrolled, fake their POLLIN status so they'll get
432          * service to use up the buffered incoming data, even though their
433          * network socket may have nothing
434          */
435         wsi = pt->pending_read_list;
436         while (wsi) {
437                 wsi_next = wsi->pending_read_list_next;
438                 pt->fds[wsi->position_in_fds_table].revents |=
439                         pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN;
440                 if (pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN) {
441                         forced = 1;
442                         /*
443                          * he's going to get serviced now, take him off the
444                          * list of guys with buffered SSL.  If he still has some
445                          * at the end of the service, he'll get put back on the
446                          * list then.
447                          */
448                         lws_ssl_remove_wsi_from_buffered_list(wsi);
449                 }
450
451                 wsi = wsi_next;
452         }
453 #endif
454         /*
455          * 3) For any wsi who have an ah with pending RX who did not
456          * complete their current headers, and are not flowcontrolled,
457          * fake their POLLIN status so they will be able to drain the
458          * rx buffered in the ah
459          */
460         for (n = 0; n < context->max_http_header_pool; n++)
461                 if (pt->ah_pool[n].rxpos != pt->ah_pool[n].rxlen &&
462                     !pt->ah_pool[n].wsi->hdr_parsing_completed) {
463                         pt->fds[pt->ah_pool[n].wsi->position_in_fds_table].revents |=
464                                 pt->fds[pt->ah_pool[n].wsi->position_in_fds_table].events &
465                                         LWS_POLLIN;
466                         if (pt->fds[pt->ah_pool[n].wsi->position_in_fds_table].revents &
467                             LWS_POLLIN)
468                                 forced = 1;
469                 }
470
471         return forced;
472 }
473
474 /**
475  * lws_service_fd() - Service polled socket with something waiting
476  * @context:    Websocket context
477  * @pollfd:     The pollfd entry describing the socket fd and which events
478  *              happened.
479  *
480  *      This function takes a pollfd that has POLLIN or POLLOUT activity and
481  *      services it according to the state of the associated
482  *      struct lws.
483  *
484  *      The one call deals with all "service" that might happen on a socket
485  *      including listen accepts, http files as well as websocket protocol.
486  *
487  *      If a pollfd says it has something, you can just pass it to
488  *      lws_service_fd() whether it is a socket handled by lws or not.
489  *      If it sees it is a lws socket, the traffic will be handled and
490  *      pollfd->revents will be zeroed now.
491  *
492  *      If the socket is foreign to lws, it leaves revents alone.  So you can
493  *      see if you should service yourself by checking the pollfd revents
494  *      after letting lws try to service it.
495  */
496
497 LWS_VISIBLE int
498 lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd, int tsi)
499 {
500         struct lws_context_per_thread *pt = &context->pt[tsi];
501         lws_sockfd_type our_fd = 0, tmp_fd;
502         struct lws_tokens eff_buf;
503         unsigned int pending = 0;
504         struct lws *wsi, *wsi1;
505         char draining_flow = 0;
506         int timed_out = 0;
507         time_t now;
508         int n = 0, m;
509         int more;
510
511         /*
512          * you can call us with pollfd = NULL to just allow the once-per-second
513          * global timeout checks; if less than a second since the last check
514          * it returns immediately then.
515          */
516
517         time(&now);
518
519         /* TODO: if using libev, we should probably use timeout watchers... */
520         if (context->last_timeout_check_s != now) {
521                 context->last_timeout_check_s = now;
522
523                 lws_plat_service_periodic(context);
524
525                 /* global timeout check once per second */
526
527                 if (pollfd)
528                         our_fd = pollfd->fd;
529
530                 wsi = context->pt[tsi].timeout_list;
531                 while (wsi) {
532                         /* we have to take copies, because he may be deleted */
533                         wsi1 = wsi->timeout_list;
534                         tmp_fd = wsi->sock;
535                         if (lws_service_timeout_check(wsi, (unsigned int)now)) {
536                                 /* he did time out... */
537                                 if (tmp_fd == our_fd)
538                                         /* it was the guy we came to service! */
539                                         timed_out = 1;
540                                         /* he's gone, no need to mark as handled */
541                         }
542                         wsi = wsi1;
543                 }
544 #ifdef LWS_WITH_CGI
545                 lws_cgi_kill_terminated(pt);
546 #endif
547 #if 0
548                 {
549                         char s[300], *p = s;
550
551                         for (n = 0; n < context->count_threads; n++)
552                                 p += sprintf(p, " %7lu (%5d), ",
553                                              context->pt[n].count_conns,
554                                              context->pt[n].fds_count);
555
556                         lwsl_notice("load: %s\n", s);
557                 }
558 #endif
559         }
560
561         /* the socket we came to service timed out, nothing to do */
562         if (timed_out)
563                 return 0;
564
565         /* just here for timeout management? */
566         if (!pollfd)
567                 return 0;
568
569         /* no, here to service a socket descriptor */
570         wsi = wsi_from_fd(context, pollfd->fd);
571         if (!wsi)
572                 /* not lws connection ... leave revents alone and return */
573                 return 0;
574
575         /*
576          * so that caller can tell we handled, past here we need to
577          * zero down pollfd->revents after handling
578          */
579
580 #if LWS_POSIX
581         /* handle session socket closed */
582
583         if ((!(pollfd->revents & pollfd->events & LWS_POLLIN)) &&
584             (pollfd->revents & LWS_POLLHUP)) {
585                 wsi->socket_is_permanently_unusable = 1;
586                 lwsl_debug("Session Socket %p (fd=%d) dead\n",
587                                                        (void *)wsi, pollfd->fd);
588
589                 goto close_and_handled;
590         }
591
592 #ifdef _WIN32
593         if (pollfd->revents & LWS_POLLOUT)
594                 wsi->sock_send_blocking = FALSE;
595 #endif
596
597 #endif
598
599         lwsl_debug("fd=%d, revents=%d\n", pollfd->fd, pollfd->revents);
600
601         /* okay, what we came here to do... */
602
603         switch (wsi->mode) {
604         case LWSCM_HTTP_SERVING:
605         case LWSCM_HTTP_CLIENT:
606         case LWSCM_HTTP_SERVING_ACCEPTED:
607         case LWSCM_SERVER_LISTENER:
608         case LWSCM_SSL_ACK_PENDING:
609                 if (wsi->state == LWSS_CLIENT_HTTP_ESTABLISHED) {
610                         goto handled;
611                 }
612                 n = lws_server_socket_service(context, wsi, pollfd);
613                 if (n) /* closed by above */
614                         return 1;
615                 pending = lws_ssl_pending(wsi);
616                 if (pending)
617                         goto handle_pending;
618                 goto handled;
619
620         case LWSCM_WS_SERVING:
621         case LWSCM_WS_CLIENT:
622         case LWSCM_HTTP2_SERVING:
623         case LWSCM_HTTP_CLIENT_ACCEPTED:
624
625                 /* 1: something requested a callback when it was OK to write */
626
627                 if ((pollfd->revents & LWS_POLLOUT) &&
628                     (wsi->state == LWSS_ESTABLISHED ||
629                      wsi->state == LWSS_HTTP2_ESTABLISHED ||
630                      wsi->state == LWSS_HTTP2_ESTABLISHED_PRE_SETTINGS ||
631                      wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
632                      wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) &&
633                     lws_handle_POLLOUT_event(wsi, pollfd)) {
634                         if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY)
635                                 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
636                         lwsl_info("lws_service_fd: closing\n");
637                         goto close_and_handled;
638                 }
639
640                 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
641                     wsi->state == LWSS_AWAITING_CLOSE_ACK) {
642                         /*
643                          * we stopped caring about anything except control
644                          * packets.  Force flow control off, defeat tx
645                          * draining.
646                          */
647                         lws_rx_flow_control(wsi, 1);
648                         wsi->u.ws.tx_draining_ext = 0;
649                 }
650
651                 if (wsi->u.ws.tx_draining_ext)
652                         /* we cannot deal with new RX until the TX ext
653                          * path has been drained.  It's because new
654                          * rx will, eg, crap on the wsi rx buf that
655                          * may be needed to retain state.
656                          *
657                          * TX ext drain path MUST go through event loop
658                          * to avoid blocking.
659                          */
660                         break;
661
662                 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
663                         /* We cannot deal with any kind of new RX
664                          * because we are RX-flowcontrolled.
665                          */
666                         break;
667
668                 /* 2: RX Extension needs to be drained
669                  */
670
671                 if (wsi->state == LWSS_ESTABLISHED &&
672                     wsi->u.ws.rx_draining_ext) {
673
674                         lwsl_ext("%s: RX EXT DRAINING: Service\n", __func__);
675 #ifndef LWS_NO_CLIENT
676                         if (wsi->mode == LWSCM_WS_CLIENT) {
677                                 n = lws_client_rx_sm(wsi, 0);
678                                 if (n < 0)
679                                         /* we closed wsi */
680                                         n = 0;
681                         } else
682 #endif
683                                 n = lws_rx_sm(wsi, 0);
684
685                         goto handled;
686                 }
687
688                 if (wsi->u.ws.rx_draining_ext)
689                         /*
690                          * We have RX EXT content to drain, but can't do it
691                          * right now.  That means we cannot do anything lower
692                          * priority either.
693                          */
694                         break;
695
696                 /* 3: RX Flowcontrol buffer needs to be drained
697                  */
698
699                 if (wsi->rxflow_buffer) {
700                         lwsl_info("draining rxflow (len %d)\n",
701                                 wsi->rxflow_len - wsi->rxflow_pos
702                         );
703                         /* well, drain it */
704                         eff_buf.token = (char *)wsi->rxflow_buffer +
705                                                 wsi->rxflow_pos;
706                         eff_buf.token_len = wsi->rxflow_len - wsi->rxflow_pos;
707                         draining_flow = 1;
708                         goto drain;
709                 }
710
711                 /* 4: any incoming (or ah-stashed incoming rx) data ready?
712                  * notice if rx flow going off raced poll(), rx flow wins
713                  */
714
715                 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
716                         break;
717 read:
718
719                 /* all the union members start with hdr, so even in ws mode
720                  * we can deal with the ah via u.hdr
721                  */
722                 if (wsi->u.hdr.ah) {
723                         lwsl_err("%s: %p: using inherited ah rx\n", __func__, wsi);
724                         eff_buf.token_len = wsi->u.hdr.ah->rxlen -
725                                             wsi->u.hdr.ah->rxpos;
726                         eff_buf.token = (char *)wsi->u.hdr.ah->rx +
727                                         wsi->u.hdr.ah->rxpos;
728                 } else {
729
730                         eff_buf.token_len = lws_ssl_capable_read(wsi, pt->serv_buf,
731                                              pending ? pending : LWS_MAX_SOCKET_IO_BUF);
732                         switch (eff_buf.token_len) {
733                         case 0:
734                                 lwsl_info("service_fd: closing due to 0 length read\n");
735                                 goto close_and_handled;
736                         case LWS_SSL_CAPABLE_MORE_SERVICE:
737                                 lwsl_info("SSL Capable more service\n");
738                                 n = 0;
739                                 goto handled;
740                         case LWS_SSL_CAPABLE_ERROR:
741                                 lwsl_info("Closing when error\n");
742                                 goto close_and_handled;
743                         }
744
745                         eff_buf.token = (char *)pt->serv_buf;
746                 }
747
748                 /*
749                  * give any active extensions a chance to munge the buffer
750                  * before parse.  We pass in a pointer to an lws_tokens struct
751                  * prepared with the default buffer and content length that's in
752                  * there.  Rather than rewrite the default buffer, extensions
753                  * that expect to grow the buffer can adapt .token to
754                  * point to their own per-connection buffer in the extension
755                  * user allocation.  By default with no extensions or no
756                  * extension callback handling, just the normal input buffer is
757                  * used then so it is efficient.
758                  */
759 drain:
760                 if (wsi->mode == LWSCM_HTTP_CLIENT_ACCEPTED) {
761                         lwsl_notice("%s: calling LWS_CALLBACK_RECEIVE_CLIENT_HTTP, "
762                                     "rem %d len %d\n", __func__,
763                                     wsi->u.http.content_remain, eff_buf.token_len);
764                         if (wsi->u.http.content_remain < eff_buf.token_len)
765                                 n = wsi->u.http.content_remain;
766                         else
767                                 n = eff_buf.token_len;
768                         if (user_callback_handle_rxflow(wsi->protocol->callback,
769                                         wsi, LWS_CALLBACK_RECEIVE_CLIENT_HTTP,
770                                         wsi->user_space, (void *)eff_buf.token,
771                                         eff_buf.token_len))
772                                 goto close_and_handled;
773                         wsi->u.http.content_remain -= n;
774                         if (wsi->u.http.content_remain)
775                                 goto handled;
776
777                         lwsl_notice("%s: client http receved all content\n",
778                                     __func__);
779                         if (user_callback_handle_rxflow(wsi->protocol->callback,
780                                         wsi, LWS_CALLBACK_COMPLETED_CLIENT_HTTP,
781                                         wsi->user_space, NULL, 0))
782                                 goto close_and_handled;
783
784                         if (wsi->u.http.connection_type == HTTP_CONNECTION_CLOSE)
785                                 goto close_and_handled;
786                         goto handled;
787                 }
788                 do {
789                         more = 0;
790
791                         m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_RX_PREPARSE,
792                                               &eff_buf, 0);
793                         if (m < 0)
794                                 goto close_and_handled;
795                         if (m)
796                                 more = 1;
797
798                         /* service incoming data */
799
800                         if (eff_buf.token_len) {
801                                 /*
802                                  * if draining from rxflow buffer, not
803                                  * critical to track what was used since at the
804                                  * use it bumps wsi->rxflow_pos.  If we come
805                                  * around again it will pick up from where it
806                                  * left off.
807                                  */
808                                 n = lws_read(wsi, (unsigned char *)eff_buf.token,
809                                              eff_buf.token_len);
810                                 if (n < 0) {
811                                         /* we closed wsi */
812                                         n = 0;
813                                         goto handled;
814                                 }
815                         }
816
817                         eff_buf.token = NULL;
818                         eff_buf.token_len = 0;
819                 } while (more);
820
821                 if (wsi->u.hdr.ah) {
822                         lwsl_err("%s: %p: detaching inherited used ah\n",
823                                  __func__, wsi);
824                         /* show we used all the pending rx up */
825                         wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
826                         /* we can run the normal ah detach flow despite
827                          * being in ws union mode, since all union members
828                          * start with hdr */
829                         lws_header_table_detach(wsi, 0);
830                 }
831
832                 pending = lws_ssl_pending(wsi);
833                 if (pending) {
834 handle_pending:
835                         pending = pending > LWS_MAX_SOCKET_IO_BUF ?
836                                         LWS_MAX_SOCKET_IO_BUF : pending;
837                         goto read;
838                 }
839
840                 if (draining_flow && wsi->rxflow_buffer &&
841                     wsi->rxflow_pos == wsi->rxflow_len) {
842                         lwsl_info("flow buffer: drained\n");
843                         lws_free_set_NULL(wsi->rxflow_buffer);
844                         /* having drained the rxflow buffer, can rearm POLLIN */
845 #ifdef LWS_NO_SERVER
846                         n =
847 #endif
848                         _lws_rx_flow_control(wsi);
849                         /* n ignored, needed for NO_SERVER case */
850                 }
851
852                 break;
853 #ifdef LWS_WITH_CGI
854         case LWSCM_CGI: /* we exist to handle a cgi's stdin/out/err data...
855                          * do the callback on our master wsi
856                          */
857                 {
858                         struct lws_cgi_args args;
859
860                         if (wsi->cgi_channel >= LWS_STDOUT &&
861                             !(pollfd->revents & pollfd->events & LWS_POLLIN))
862                                 break;
863                         if (wsi->cgi_channel == LWS_STDIN &&
864                             !(pollfd->revents & pollfd->events & LWS_POLLOUT))
865                                 break;
866
867                         if (wsi->cgi_channel == LWS_STDIN)
868                                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
869                                         lwsl_info("failed at set pollfd\n");
870                                         return 1;
871                                 }
872
873                         args.ch = wsi->cgi_channel;
874                         args.stdwsi = &wsi->parent->cgi->stdwsi[0];
875
876                         if (user_callback_handle_rxflow(
877                                         wsi->parent->protocol->callback,
878                                         wsi->parent, LWS_CALLBACK_CGI,
879                                         wsi->parent->user_space,
880                                         (void *)&args, 0))
881                                 return 1;
882
883                         break;
884                 }
885 #endif
886         default:
887 #ifdef LWS_NO_CLIENT
888                 break;
889 #else
890                 n = lws_client_socket_service(context, wsi, pollfd);
891                 if (n)
892                         return 1;
893                 goto handled;
894 #endif
895         }
896
897         n = 0;
898         goto handled;
899
900 close_and_handled:
901         lwsl_debug("Close and handled\n");
902         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
903         /*
904          * pollfd may point to something else after the close
905          * due to pollfd swapping scheme on delete on some platforms
906          * we can't clear revents now because it'd be the wrong guy's revents
907          */
908         return 1;
909
910 handled:
911         pollfd->revents = 0;
912         return n;
913 }
914
915 LWS_VISIBLE int
916 lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd)
917 {
918         return lws_service_fd_tsi(context, pollfd, 0);
919 }
920
921 /**
922  * lws_service() - Service any pending websocket activity
923  * @context:    Websocket context
924  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
925  *              service otherwise block and service immediately, returning
926  *              after the timeout if nothing needed service.
927  *
928  *      This function deals with any pending websocket traffic, for three
929  *      kinds of event.  It handles these events on both server and client
930  *      types of connection the same.
931  *
932  *      1) Accept new connections to our context's server
933  *
934  *      2) Call the receive callback for incoming frame data received by
935  *          server or client connections.
936  *
937  *      You need to call this service function periodically to all the above
938  *      functions to happen; if your application is single-threaded you can
939  *      just call it in your main event loop.
940  *
941  *      Alternatively you can fork a new process that asynchronously handles
942  *      calling this service in a loop.  In that case you are happy if this
943  *      call blocks your thread until it needs to take care of something and
944  *      would call it with a large nonzero timeout.  Your loop then takes no
945  *      CPU while there is nothing happening.
946  *
947  *      If you are calling it in a single-threaded app, you don't want it to
948  *      wait around blocking other things in your loop from happening, so you
949  *      would call it with a timeout_ms of 0, so it returns immediately if
950  *      nothing is pending, or as soon as it services whatever was pending.
951  */
952
953 LWS_VISIBLE int
954 lws_service(struct lws_context *context, int timeout_ms)
955 {
956         return lws_plat_service(context, timeout_ms);
957 }
958
959 LWS_VISIBLE int
960 lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi)
961 {
962         return lws_plat_service_tsi(context, timeout_ms, tsi);
963 }
964