f5dcefc460b1508ca75c8fb71807ce61a7382770
[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 #ifdef LWS_USE_HTTP2
241         /*
242          * we are the 'network wsi' for potentially many muxed child wsi with
243          * no network connection of their own, who have to use us for all their
244          * network actions.  So we use a round-robin scheme to share out the
245          * POLLOUT notifications to our children.
246          *
247          * But because any child could exhaust the socket's ability to take
248          * writes, we can only let one child get notified each time.
249          *
250          * In addition children may be closed / deleted / added between POLLOUT
251          * notifications, so we can't hold pointers
252          */
253
254         if (wsi->mode != LWSCM_HTTP2_SERVING) {
255                 lwsl_info("%s: non http2\n", __func__);
256                 goto notify;
257         }
258
259         wsi->u.http2.requested_POLLOUT = 0;
260         if (!wsi->u.http2.initialized) {
261                 lwsl_info("pollout on uninitialized http2 conn\n");
262                 return 0;
263         }
264
265         lwsl_info("%s: doing children\n", __func__);
266
267         wsi2 = wsi;
268         do {
269                 wsi2 = wsi2->u.http2.next_child_wsi;
270                 lwsl_info("%s: child %p\n", __func__, wsi2);
271                 if (!wsi2)
272                         continue;
273                 if (!wsi2->u.http2.requested_POLLOUT)
274                         continue;
275                 wsi2->u.http2.requested_POLLOUT = 0;
276                 if (lws_calllback_as_writeable(wsi2)) {
277                         lwsl_debug("Closing POLLOUT child\n");
278                         lws_close_free_wsi(wsi2, LWS_CLOSE_STATUS_NOSTATUS);
279                 }
280                 wsi2 = wsi;
281         } while (wsi2 != NULL && !lws_send_pipe_choked(wsi));
282
283         lwsl_info("%s: completed\n", __func__);
284
285         return 0;
286 notify:
287 #endif
288         return lws_calllback_as_writeable(wsi);
289 }
290
291 int
292 lws_service_timeout_check(struct lws *wsi, unsigned int sec)
293 {
294         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
295         struct lws **pwsi;
296
297         /*
298          * if extensions want in on it (eg, we are a mux parent)
299          * give them a chance to service child timeouts
300          */
301         if (lws_ext_cb_active(wsi, LWS_EXT_CB_1HZ, NULL, sec) < 0)
302                 return 0;
303
304         if (!wsi->pending_timeout)
305                 return 0;
306
307         /*
308          * if we went beyond the allowed time, kill the
309          * connection
310          */
311         if ((time_t)sec > wsi->pending_timeout_limit) {
312 #if LWS_POSIX
313                 lwsl_notice("wsi %p: TIMEDOUT WAITING on %d (did hdr %d, ah %p, wl %d, pfd events %d)\n",
314                             (void *)wsi, wsi->pending_timeout,
315                             wsi->hdr_parsing_completed, wsi->u.hdr.ah,
316                             pt->ah_wait_list_length,
317                             pt->fds[wsi->sock].events);
318 #endif
319                 lws_pt_lock(pt);
320
321                 pwsi = &pt->ah_wait_list;
322                 if (!pwsi)
323                         return 0;
324                 while (*pwsi) {
325                         if (*pwsi == wsi)
326                                 break;
327                         pwsi = &(*pwsi)->u.hdr.ah_wait_list;
328                         lwsl_err("%s: pwsi=%p\n", __func__, pwsi);
329                 }
330                 lws_pt_unlock(pt);
331
332                 if (!*pwsi)
333                         lwsl_err("*** not on ah wait list ***\n");
334                 /*
335                  * Since he failed a timeout, he already had a chance to do
336                  * something and was unable to... that includes situations like
337                  * half closed connections.  So process this "failed timeout"
338                  * close as a violent death and don't try to do protocol
339                  * cleanup like flush partials.
340                  */
341                 wsi->socket_is_permanently_unusable = 1;
342                 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
343
344                 return 1;
345         }
346
347         return 0;
348 }
349
350 int lws_rxflow_cache(struct lws *wsi, unsigned char *buf, int n, int len)
351 {
352         /* his RX is flowcontrolled, don't send remaining now */
353         if (wsi->rxflow_buffer) {
354                 /* rxflow while we were spilling prev rxflow */
355                 lwsl_info("stalling in existing rxflow buf\n");
356                 return 1;
357         }
358
359         /* a new rxflow, buffer it and warn caller */
360         lwsl_info("new rxflow input buffer len %d\n", len - n);
361         wsi->rxflow_buffer = lws_malloc(len - n);
362         wsi->rxflow_len = len - n;
363         wsi->rxflow_pos = 0;
364         memcpy(wsi->rxflow_buffer, buf + n, len - n);
365
366         return 0;
367 }
368
369 /* this is used by the platform service code to stop us waiting for network
370  * activity in poll() when we have something that already needs service
371  */
372
373 int
374 lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi)
375 {
376         struct lws_context_per_thread *pt = &context->pt[tsi];
377         int n;
378
379         /* Figure out if we really want to wait in poll()
380          * We only need to wait if really nothing already to do and we have
381          * to wait for something from network
382          */
383
384         /* 1) if we know we are draining rx ext, do not wait in poll */
385         if (pt->rx_draining_ext_list)
386                 timeout_ms = 0;
387
388 #ifdef LWS_OPENSSL_SUPPORT
389         /* 2) if we know we have non-network pending data, do not wait in poll */
390         if (lws_ssl_anybody_has_buffered_read_tsi(context, tsi)) {
391                 timeout_ms = 0;
392                 lwsl_err("ssl buffered read\n");
393         }
394 #endif
395
396         /* 3) if any ah has pending rx, do not wait in poll */
397         for (n = 0; n < context->max_http_header_pool; n++)
398                 if (pt->ah_pool[n].rxpos != pt->ah_pool[n].rxlen) {
399                         /* any ah with pending rx must be attached to someone */
400                         assert(pt->ah_pool[n].wsi);
401                         timeout_ms = 0;
402                         break;
403                 }
404
405         return timeout_ms;
406 }
407
408 /*
409  * guys that need POLLIN service again without waiting for network action
410  * can force POLLIN here if not flowcontrolled, so they will get service.
411  *
412  * Return nonzero if anybody got their POLLIN faked
413  */
414 int
415 lws_service_flag_pending(struct lws_context *context, int tsi)
416 {
417         struct lws_context_per_thread *pt = &context->pt[tsi];
418 #ifdef LWS_OPENSSL_SUPPORT
419         struct lws *wsi_next;
420 #endif
421         struct lws *wsi;
422         int forced = 0;
423         int n;
424
425         /* POLLIN faking */
426
427         /*
428          * 1) For all guys with already-available ext data to drain, if they are
429          * not flowcontrolled, fake their POLLIN status
430          */
431         wsi = pt->rx_draining_ext_list;
432         while (wsi) {
433                 pt->fds[wsi->position_in_fds_table].revents |=
434                         pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN;
435                 if (pt->fds[wsi->position_in_fds_table].revents &
436                     LWS_POLLIN)
437                         forced = 1;
438                 wsi = wsi->u.ws.rx_draining_ext_list;
439         }
440
441 #ifdef LWS_OPENSSL_SUPPORT
442         /*
443          * 2) For all guys with buffered SSL read data already saved up, if they
444          * are not flowcontrolled, fake their POLLIN status so they'll get
445          * service to use up the buffered incoming data, even though their
446          * network socket may have nothing
447          */
448         wsi = pt->pending_read_list;
449         while (wsi) {
450                 wsi_next = wsi->pending_read_list_next;
451                 pt->fds[wsi->position_in_fds_table].revents |=
452                         pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN;
453                 if (pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN) {
454                         forced = 1;
455                         /*
456                          * he's going to get serviced now, take him off the
457                          * list of guys with buffered SSL.  If he still has some
458                          * at the end of the service, he'll get put back on the
459                          * list then.
460                          */
461                         lws_ssl_remove_wsi_from_buffered_list(wsi);
462                 }
463
464                 wsi = wsi_next;
465         }
466 #endif
467         /*
468          * 3) For any wsi who have an ah with pending RX who did not
469          * complete their current headers, and are not flowcontrolled,
470          * fake their POLLIN status so they will be able to drain the
471          * rx buffered in the ah
472          */
473         for (n = 0; n < context->max_http_header_pool; n++)
474                 if (pt->ah_pool[n].rxpos != pt->ah_pool[n].rxlen &&
475                     !pt->ah_pool[n].wsi->hdr_parsing_completed) {
476                         pt->fds[pt->ah_pool[n].wsi->position_in_fds_table].revents |=
477                                 pt->fds[pt->ah_pool[n].wsi->position_in_fds_table].events &
478                                         LWS_POLLIN;
479                         if (pt->fds[pt->ah_pool[n].wsi->position_in_fds_table].revents &
480                             LWS_POLLIN)
481                                 forced = 1;
482                 }
483
484         return forced;
485 }
486
487 /**
488  * lws_service_fd() - Service polled socket with something waiting
489  * @context:    Websocket context
490  * @pollfd:     The pollfd entry describing the socket fd and which events
491  *              happened.
492  *
493  *      This function takes a pollfd that has POLLIN or POLLOUT activity and
494  *      services it according to the state of the associated
495  *      struct lws.
496  *
497  *      The one call deals with all "service" that might happen on a socket
498  *      including listen accepts, http files as well as websocket protocol.
499  *
500  *      If a pollfd says it has something, you can just pass it to
501  *      lws_service_fd() whether it is a socket handled by lws or not.
502  *      If it sees it is a lws socket, the traffic will be handled and
503  *      pollfd->revents will be zeroed now.
504  *
505  *      If the socket is foreign to lws, it leaves revents alone.  So you can
506  *      see if you should service yourself by checking the pollfd revents
507  *      after letting lws try to service it.
508  */
509
510 LWS_VISIBLE int
511 lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd, int tsi)
512 {
513         struct lws_context_per_thread *pt = &context->pt[tsi];
514         lws_sockfd_type our_fd = 0, tmp_fd;
515         struct lws_tokens eff_buf;
516         unsigned int pending = 0;
517         struct lws *wsi, *wsi1;
518         char draining_flow = 0;
519         int timed_out = 0;
520         time_t now;
521         int n, m;
522         int more;
523
524         /*
525          * you can call us with pollfd = NULL to just allow the once-per-second
526          * global timeout checks; if less than a second since the last check
527          * it returns immediately then.
528          */
529
530         time(&now);
531
532         /* TODO: if using libev, we should probably use timeout watchers... */
533         if (context->last_timeout_check_s != now) {
534                 context->last_timeout_check_s = now;
535
536                 lws_plat_service_periodic(context);
537
538                 /* global timeout check once per second */
539
540                 if (pollfd)
541                         our_fd = pollfd->fd;
542
543                 wsi = context->pt[tsi].timeout_list;
544                 while (wsi) {
545                         /* we have to take copies, because he may be deleted */
546                         wsi1 = wsi->timeout_list;
547                         tmp_fd = wsi->sock;
548                         if (lws_service_timeout_check(wsi, (unsigned int)now)) {
549                                 /* he did time out... */
550                                 if (tmp_fd == our_fd)
551                                         /* it was the guy we came to service! */
552                                         timed_out = 1;
553                                         /* he's gone, no need to mark as handled */
554                         }
555                         wsi = wsi1;
556                 }
557 #if 0
558                 {
559                         char s[300], *p = s;
560
561                         for (n = 0; n < context->count_threads; n++)
562                                 p += sprintf(p, " %7lu (%5d), ",
563                                              context->pt[n].count_conns,
564                                              context->pt[n].fds_count);
565
566                         lwsl_notice("load: %s\n", s);
567                 }
568 #endif
569         }
570
571         /* the socket we came to service timed out, nothing to do */
572         if (timed_out)
573                 return 0;
574
575         /* just here for timeout management? */
576         if (!pollfd)
577                 return 0;
578
579         /* no, here to service a socket descriptor */
580         wsi = wsi_from_fd(context, pollfd->fd);
581         if (!wsi)
582                 /* not lws connection ... leave revents alone and return */
583                 return 0;
584
585         /*
586          * so that caller can tell we handled, past here we need to
587          * zero down pollfd->revents after handling
588          */
589
590 #if LWS_POSIX
591
592         /* handle session socket closed */
593
594         if ((!(pollfd->revents & pollfd->events & LWS_POLLIN)) &&
595             (pollfd->revents & LWS_POLLHUP)) {
596                 wsi->socket_is_permanently_unusable = 1;
597                 lwsl_debug("Session Socket %p (fd=%d) dead\n",
598                                                        (void *)wsi, pollfd->fd);
599
600                 goto close_and_handled;
601         }
602
603 #ifdef _WIN32
604         if (pollfd->revents & LWS_POLLOUT)
605                 wsi->sock_send_blocking = FALSE;
606 #endif
607
608 #endif
609
610         /* okay, what we came here to do... */
611
612         switch (wsi->mode) {
613         case LWSCM_HTTP_SERVING:
614         case LWSCM_HTTP_SERVING_ACCEPTED:
615         case LWSCM_SERVER_LISTENER:
616         case LWSCM_SSL_ACK_PENDING:
617                 n = lws_server_socket_service(context, wsi, pollfd);
618                 if (n) /* closed by above */
619                         return 1;
620                 pending = lws_ssl_pending(wsi);
621                 if (pending)
622                         goto handle_pending;
623                 goto handled;
624
625         case LWSCM_WS_SERVING:
626         case LWSCM_WS_CLIENT:
627         case LWSCM_HTTP2_SERVING:
628
629                 /* 1: something requested a callback when it was OK to write */
630
631                 if ((pollfd->revents & LWS_POLLOUT) &&
632                     (wsi->state == LWSS_ESTABLISHED ||
633                      wsi->state == LWSS_HTTP2_ESTABLISHED ||
634                      wsi->state == LWSS_HTTP2_ESTABLISHED_PRE_SETTINGS ||
635                      wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
636                      wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) &&
637                     lws_handle_POLLOUT_event(wsi, pollfd)) {
638                         if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY)
639                                 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
640                         lwsl_info("lws_service_fd: closing\n");
641                         goto close_and_handled;
642                 }
643
644                 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
645                     wsi->state == LWSS_AWAITING_CLOSE_ACK) {
646                         /*
647                          * we stopped caring about anything except control
648                          * packets.  Force flow control off, defeat tx
649                          * draining.
650                          */
651                         lws_rx_flow_control(wsi, 1);
652                         wsi->u.ws.tx_draining_ext = 0;
653                 }
654
655                 if (wsi->u.ws.tx_draining_ext) {
656                         /* we cannot deal with new RX until the TX ext
657                          * path has been drained.  It's because new
658                          * rx will, eg, crap on the wsi rx buf that
659                          * may be needed to retain state.
660                          *
661                          * TX ext drain path MUST go through event loop
662                          * to avoid blocking.
663                          */
664                         break;
665                 }
666
667                 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
668                         /* We cannot deal with any kind of new RX
669                          * because we are RX-flowcontrolled.
670                          */
671                         break;
672
673                 /* 2: RX Extension needs to be drained
674                  */
675
676                 if (wsi->state == LWSS_ESTABLISHED &&
677                     wsi->u.ws.rx_draining_ext) {
678
679                         lwsl_ext("%s: RX EXT DRAINING: Service\n", __func__);
680 #ifndef LWS_NO_CLIENT
681                         if (wsi->mode == LWSCM_WS_CLIENT) {
682                                 n = lws_client_rx_sm(wsi, 0);
683                                 if (n < 0)
684                                         /* we closed wsi */
685                                         n = 0;
686                         } else
687 #endif
688                                 n = lws_rx_sm(wsi, 0);
689
690                         goto handled;
691                 }
692
693                 if (wsi->u.ws.rx_draining_ext)
694                         /*
695                          * We have RX EXT content to drain, but can't do it
696                          * right now.  That means we cannot do anything lower
697                          * priority either.
698                          */
699                         break;
700
701                 /* 3: RX Flowcontrol buffer needs to be drained
702                  */
703
704                 if (wsi->rxflow_buffer) {
705                         lwsl_info("draining rxflow (len %d)\n",
706                                 wsi->rxflow_len - wsi->rxflow_pos
707                         );
708                         /* well, drain it */
709                         eff_buf.token = (char *)wsi->rxflow_buffer +
710                                                 wsi->rxflow_pos;
711                         eff_buf.token_len = wsi->rxflow_len - wsi->rxflow_pos;
712                         draining_flow = 1;
713                         goto drain;
714                 }
715
716                 /* 4: any incoming (or ah-stashed incoming rx) data ready?
717                  * notice if rx flow going off raced poll(), rx flow wins
718                  */
719
720                 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
721                         break;
722 read:
723
724                 /* all the union members start with hdr, so even in ws mode
725                  * we can deal with the ah via u.hdr
726                  */
727                 if (wsi->u.hdr.ah) {
728                         lwsl_err("%s: %p: using inherited ah rx\n", __func__, wsi);
729                         eff_buf.token_len = wsi->u.hdr.ah->rxlen -
730                                             wsi->u.hdr.ah->rxpos;
731                         eff_buf.token = (char *)wsi->u.hdr.ah->rx +
732                                         wsi->u.hdr.ah->rxpos;
733                 } else {
734
735                         eff_buf.token_len = lws_ssl_capable_read(wsi, pt->serv_buf,
736                                              pending ? pending : LWS_MAX_SOCKET_IO_BUF);
737                         switch (eff_buf.token_len) {
738                         case 0:
739                                 lwsl_info("service_fd: closing due to 0 length read\n");
740                                 goto close_and_handled;
741                         case LWS_SSL_CAPABLE_MORE_SERVICE:
742                                 lwsl_info("SSL Capable more service\n");
743                                 n = 0;
744                                 goto handled;
745                         case LWS_SSL_CAPABLE_ERROR:
746                                 lwsl_info("Closing when error\n");
747                                 goto close_and_handled;
748                         }
749
750                         eff_buf.token = (char *)pt->serv_buf;
751                 }
752                 /*
753                  * give any active extensions a chance to munge the buffer
754                  * before parse.  We pass in a pointer to an lws_tokens struct
755                  * prepared with the default buffer and content length that's in
756                  * there.  Rather than rewrite the default buffer, extensions
757                  * that expect to grow the buffer can adapt .token to
758                  * point to their own per-connection buffer in the extension
759                  * user allocation.  By default with no extensions or no
760                  * extension callback handling, just the normal input buffer is
761                  * used then so it is efficient.
762                  */
763 drain:
764                 do {
765                         more = 0;
766
767                         m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_RX_PREPARSE,
768                                               &eff_buf, 0);
769                         if (m < 0)
770                                 goto close_and_handled;
771                         if (m)
772                                 more = 1;
773
774                         /* service incoming data */
775
776                         if (eff_buf.token_len) {
777                                 /*
778                                  * if draining from rxflow buffer, not
779                                  * critical to track what was used since at the
780                                  * use it bumps wsi->rxflow_pos.  If we come
781                                  * around again it will pick up from where it
782                                  * left off.
783                                  */
784                                 n = lws_read(wsi, (unsigned char *)eff_buf.token,
785                                              eff_buf.token_len);
786                                 if (n < 0) {
787                                         /* we closed wsi */
788                                         n = 0;
789                                         goto handled;
790                                 }
791                         }
792
793                         eff_buf.token = NULL;
794                         eff_buf.token_len = 0;
795                 } while (more);
796
797                 if (wsi->u.hdr.ah) {
798                         lwsl_err("%s: %p: detaching inherited used ah\n", __func__, wsi);
799                         /* show we used all the pending rx up */
800                         wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
801                         /* we can run the normal ah detach flow despite
802                          * being in ws union mode, since all union members
803                          * start with hdr */
804                         lws_header_table_detach(wsi);
805                 }
806
807                 pending = lws_ssl_pending(wsi);
808                 if (pending) {
809 handle_pending:
810                         pending = pending > LWS_MAX_SOCKET_IO_BUF ?
811                                         LWS_MAX_SOCKET_IO_BUF : pending;
812                         goto read;
813                 }
814
815                 if (draining_flow && wsi->rxflow_buffer &&
816                     wsi->rxflow_pos == wsi->rxflow_len) {
817                         lwsl_info("flow buffer: drained\n");
818                         lws_free_set_NULL(wsi->rxflow_buffer);
819                         /* having drained the rxflow buffer, can rearm POLLIN */
820 #ifdef LWS_NO_SERVER
821                         n =
822 #endif
823                         _lws_rx_flow_control(wsi);
824                         /* n ignored, needed for NO_SERVER case */
825                 }
826
827                 break;
828
829         default:
830 #ifdef LWS_NO_CLIENT
831                 break;
832 #else
833                 n = lws_client_socket_service(context, wsi, pollfd);
834                 if (n)
835                         return 1;
836                 goto handled;
837 #endif
838         }
839
840         n = 0;
841         goto handled;
842
843 close_and_handled:
844         lwsl_debug("Close and handled\n");
845         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
846         /*
847          * pollfd may point to something else after the close
848          * due to pollfd swapping scheme on delete on some platforms
849          * we can't clear revents now because it'd be the wrong guy's revents
850          */
851         return 1;
852
853 handled:
854         pollfd->revents = 0;
855         return n;
856 }
857
858 LWS_VISIBLE int
859 lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd)
860 {
861         return lws_service_fd_tsi(context, pollfd, 0);
862 }
863
864 /**
865  * lws_service() - Service any pending websocket activity
866  * @context:    Websocket context
867  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
868  *              service otherwise block and service immediately, returning
869  *              after the timeout if nothing needed service.
870  *
871  *      This function deals with any pending websocket traffic, for three
872  *      kinds of event.  It handles these events on both server and client
873  *      types of connection the same.
874  *
875  *      1) Accept new connections to our context's server
876  *
877  *      2) Call the receive callback for incoming frame data received by
878  *          server or client connections.
879  *
880  *      You need to call this service function periodically to all the above
881  *      functions to happen; if your application is single-threaded you can
882  *      just call it in your main event loop.
883  *
884  *      Alternatively you can fork a new process that asynchronously handles
885  *      calling this service in a loop.  In that case you are happy if this
886  *      call blocks your thread until it needs to take care of something and
887  *      would call it with a large nonzero timeout.  Your loop then takes no
888  *      CPU while there is nothing happening.
889  *
890  *      If you are calling it in a single-threaded app, you don't want it to
891  *      wait around blocking other things in your loop from happening, so you
892  *      would call it with a timeout_ms of 0, so it returns immediately if
893  *      nothing is pending, or as soon as it services whatever was pending.
894  */
895
896 LWS_VISIBLE int
897 lws_service(struct lws_context *context, int timeout_ms)
898 {
899         return lws_plat_service(context, timeout_ms);
900 }
901
902 LWS_VISIBLE int
903 lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi)
904 {
905         return lws_plat_service_tsi(context, timeout_ms, tsi);
906 }
907