82e379aa8cf72dee00a041c404338ce80ddc42c5
[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_RAW:
31                 n = LWS_CALLBACK_RAW_WRITEABLE;
32                 break;
33         case LWSCM_RAW_FILEDESC:
34                 n = LWS_CALLBACK_RAW_WRITEABLE_FILE;
35                 break;
36         case LWSCM_WS_CLIENT:
37                 n = LWS_CALLBACK_CLIENT_WRITEABLE;
38                 break;
39         case LWSCM_WSCL_ISSUE_HTTP_BODY:
40                 n = LWS_CALLBACK_CLIENT_HTTP_WRITEABLE;
41                 break;
42         case LWSCM_WS_SERVING:
43                 n = LWS_CALLBACK_SERVER_WRITEABLE;
44                 break;
45         default:
46                 n = LWS_CALLBACK_HTTP_WRITEABLE;
47                 break;
48         }
49         lwsl_debug("%s: %p (user=%p)\n", __func__, wsi, wsi->user_space);
50         return user_callback_handle_rxflow(wsi->protocol->callback,
51                                            wsi, (enum lws_callback_reasons) n,
52                                            wsi->user_space, NULL, 0);
53 }
54
55 int
56 lws_handle_POLLOUT_event(struct lws *wsi, struct lws_pollfd *pollfd)
57 {
58         int write_type = LWS_WRITE_PONG;
59         struct lws_tokens eff_buf;
60 #ifdef LWS_USE_HTTP2
61         struct lws *wsi2;
62 #endif
63         int ret, m, n;
64
65         //lwsl_err("%s: %p\n", __func__, wsi);
66
67         /*
68          * user callback is lowest priority to get these notifications
69          * actually, since other pending things cannot be disordered
70          */
71
72         /* Priority 1: pending truncated sends are incomplete ws fragments
73          *             If anything else sent first the protocol would be
74          *             corrupted.
75          */
76         if (wsi->trunc_len) {
77                 if (lws_issue_raw(wsi, wsi->trunc_alloc + wsi->trunc_offset,
78                                   wsi->trunc_len) < 0) {
79                         lwsl_info("%s signalling to close\n", __func__);
80                         return -1;
81                 }
82                 /* leave POLLOUT active either way */
83                 return 0;
84         } else
85                 if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE)
86                         return -1; /* retry closing now */
87
88         if (wsi->mode == LWSCM_WSCL_ISSUE_HTTP_BODY)
89                 goto user_service;
90
91
92 #ifdef LWS_USE_HTTP2
93         /* Priority 2: protocol packets
94          */
95         if (wsi->pps) {
96                 lwsl_info("servicing pps %d\n", wsi->pps);
97                 switch (wsi->pps) {
98                 case LWS_PPS_HTTP2_MY_SETTINGS:
99                 case LWS_PPS_HTTP2_ACK_SETTINGS:
100                         lws_http2_do_pps_send(lws_get_context(wsi), wsi);
101                         break;
102                 default:
103                         break;
104                 }
105                 wsi->pps = LWS_PPS_NONE;
106                 lws_rx_flow_control(wsi, 1);
107
108                 return 0; /* leave POLLOUT active */
109         }
110 #endif
111
112 #ifdef LWS_WITH_CGI
113         if (wsi->cgi)
114                 goto user_service_go_again;
115 #endif
116
117         /* Priority 3: pending control packets (pong or close)
118          */
119         if ((wsi->state == LWSS_ESTABLISHED &&
120              wsi->u.ws.ping_pending_flag) ||
121             (wsi->state == LWSS_RETURNED_CLOSE_ALREADY &&
122              wsi->u.ws.payload_is_close)) {
123
124                 if (wsi->u.ws.payload_is_close)
125                         write_type = LWS_WRITE_CLOSE;
126
127                 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
128                               wsi->u.ws.ping_payload_len, write_type);
129                 if (n < 0)
130                         return -1;
131
132                 /* well he is sent, mark him done */
133                 wsi->u.ws.ping_pending_flag = 0;
134                 if (wsi->u.ws.payload_is_close)
135                         /* oh... a close frame was it... then we are done */
136                         return -1;
137
138                 /* otherwise for PING, leave POLLOUT active either way */
139                 return 0;
140         }
141
142         if (wsi->state == LWSS_ESTABLISHED &&
143             !wsi->socket_is_permanently_unusable &&
144             wsi->u.ws.send_check_ping) {
145
146                 lwsl_info("issuing ping on wsi %p\n", wsi);
147                 wsi->u.ws.send_check_ping = 0;
148                 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
149                               0, LWS_WRITE_PING);
150                 if (n < 0)
151                         return -1;
152
153                 /*
154                  * we apparently were able to send the PING in a reasonable time
155                  * now reset the clock on our peer to be able to send the
156                  * PONG in a reasonable time.
157                  */
158
159                 lws_set_timeout(wsi, PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG,
160                                 wsi->context->timeout_secs);
161
162                 return 0;
163         }
164
165         /* Priority 4: if we are closing, not allowed to send more data frags
166          *             which means user callback or tx ext flush banned now
167          */
168         if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY)
169                 goto user_service;
170
171         /* Priority 5: Tx path extension with more to send
172          *
173          *             These are handled as new fragments each time around
174          *             So while we must block new writeable callback to enforce
175          *             payload ordering, but since they are always complete
176          *             fragments control packets can interleave OK.
177          */
178         if (wsi->state == LWSS_ESTABLISHED && wsi->u.ws.tx_draining_ext) {
179                 lwsl_ext("SERVICING TX EXT DRAINING\n");
180                 if (lws_write(wsi, NULL, 0, LWS_WRITE_CONTINUATION) < 0)
181                         return -1;
182                 /* leave POLLOUT active */
183                 return 0;
184         }
185
186         /* Priority 6: user can get the callback
187          */
188         m = lws_ext_cb_active(wsi, LWS_EXT_CB_IS_WRITEABLE, NULL, 0);
189         if (m)
190                 return -1;
191 #ifndef LWS_NO_EXTENSIONS
192         if (!wsi->extension_data_pending)
193                 goto user_service;
194 #endif
195         /*
196          * check in on the active extensions, see if they
197          * had pending stuff to spill... they need to get the
198          * first look-in otherwise sequence will be disordered
199          *
200          * NULL, zero-length eff_buf means just spill pending
201          */
202
203         ret = 1;
204         if (wsi->mode == LWSCM_RAW || wsi->mode == LWSCM_RAW_FILEDESC)
205                 ret = 0;
206         while (ret == 1) {
207
208                 /* default to nobody has more to spill */
209
210                 ret = 0;
211                 eff_buf.token = NULL;
212                 eff_buf.token_len = 0;
213
214                 /* give every extension a chance to spill */
215
216                 m = lws_ext_cb_active(wsi,
217                                         LWS_EXT_CB_PACKET_TX_PRESEND,
218                                                &eff_buf, 0);
219                 if (m < 0) {
220                         lwsl_err("ext reports fatal error\n");
221                         return -1;
222                 }
223                 if (m)
224                         /*
225                          * at least one extension told us he has more
226                          * to spill, so we will go around again after
227                          */
228                         ret = 1;
229
230                 /* assuming they gave us something to send, send it */
231
232                 if (eff_buf.token_len) {
233                         n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
234                                           eff_buf.token_len);
235                         if (n < 0) {
236                                 lwsl_info("closing from POLLOUT spill\n");
237                                 return -1;
238                         }
239                         /*
240                          * Keep amount spilled small to minimize chance of this
241                          */
242                         if (n != eff_buf.token_len) {
243                                 lwsl_err("Unable to spill ext %d vs %d\n",
244                                                           eff_buf.token_len, n);
245                                 return -1;
246                         }
247                 } else
248                         continue;
249
250                 /* no extension has more to spill */
251
252                 if (!ret)
253                         continue;
254
255                 /*
256                  * There's more to spill from an extension, but we just sent
257                  * something... did that leave the pipe choked?
258                  */
259
260                 if (!lws_send_pipe_choked(wsi))
261                         /* no we could add more */
262                         continue;
263
264                 lwsl_info("choked in POLLOUT service\n");
265
266                 /*
267                  * Yes, he's choked.  Leave the POLLOUT masked on so we will
268                  * come back here when he is unchoked.  Don't call the user
269                  * callback to enforce ordering of spilling, he'll get called
270                  * when we come back here and there's nothing more to spill.
271                  */
272
273                 return 0;
274         }
275 #ifndef LWS_NO_EXTENSIONS
276         wsi->extension_data_pending = 0;
277 #endif
278 user_service:
279         /* one shot */
280
281         if (pollfd)
282                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
283                         lwsl_info("failed at set pollfd\n");
284                         return 1;
285                 }
286
287         if (wsi->mode != LWSCM_WSCL_ISSUE_HTTP_BODY &&
288             !wsi->hdr_parsing_completed)
289                 return 0;
290
291 #ifdef LWS_WITH_CGI
292 user_service_go_again:
293 #endif
294
295 #ifdef LWS_USE_HTTP2
296         /*
297          * we are the 'network wsi' for potentially many muxed child wsi with
298          * no network connection of their own, who have to use us for all their
299          * network actions.  So we use a round-robin scheme to share out the
300          * POLLOUT notifications to our children.
301          *
302          * But because any child could exhaust the socket's ability to take
303          * writes, we can only let one child get notified each time.
304          *
305          * In addition children may be closed / deleted / added between POLLOUT
306          * notifications, so we can't hold pointers
307          */
308
309         if (wsi->mode != LWSCM_HTTP2_SERVING) {
310                 lwsl_info("%s: non http2\n", __func__);
311                 goto notify;
312         }
313
314         wsi->u.http2.requested_POLLOUT = 0;
315         if (!wsi->u.http2.initialized) {
316                 lwsl_info("pollout on uninitialized http2 conn\n");
317                 return 0;
318         }
319
320         lwsl_info("%s: doing children\n", __func__);
321
322         wsi2 = wsi;
323         do {
324                 wsi2 = wsi2->u.http2.next_child_wsi;
325                 lwsl_info("%s: child %p\n", __func__, wsi2);
326                 if (!wsi2)
327                         continue;
328                 if (!wsi2->u.http2.requested_POLLOUT)
329                         continue;
330                 wsi2->u.http2.requested_POLLOUT = 0;
331                 if (lws_calllback_as_writeable(wsi2)) {
332                         lwsl_debug("Closing POLLOUT child\n");
333                         lws_close_free_wsi(wsi2, LWS_CLOSE_STATUS_NOSTATUS);
334                 }
335                 wsi2 = wsi;
336         } while (wsi2 != NULL && !lws_send_pipe_choked(wsi));
337
338         lwsl_info("%s: completed\n", __func__);
339
340         return 0;
341 notify:
342 #endif
343         return lws_calllback_as_writeable(wsi);
344 }
345
346 int
347 lws_service_timeout_check(struct lws *wsi, unsigned int sec)
348 {
349 //#if LWS_POSIX
350         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
351         int n = 0;
352 //#endif
353
354         (void)n;
355
356         /*
357          * if extensions want in on it (eg, we are a mux parent)
358          * give them a chance to service child timeouts
359          */
360         if (lws_ext_cb_active(wsi, LWS_EXT_CB_1HZ, NULL, sec) < 0)
361                 return 0;
362
363         if (!wsi->pending_timeout)
364                 return 0;
365
366         /*
367          * if we went beyond the allowed time, kill the
368          * connection
369          */
370         if ((time_t)sec > wsi->pending_timeout_limit) {
371 //#if LWS_POSIX
372                 if (wsi->desc.sockfd != LWS_SOCK_INVALID && wsi->position_in_fds_table >= 0)
373                         n = pt->fds[wsi->position_in_fds_table].events;
374
375                 /* no need to log normal idle keepalive timeout */
376                 if (wsi->pending_timeout != PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE)
377                         lwsl_notice("wsi %p: TIMEDOUT WAITING on %d (did hdr %d, ah %p, wl %d, pfd events %d) %llu vs %llu\n",
378                             (void *)wsi, wsi->pending_timeout,
379                             wsi->hdr_parsing_completed, wsi->u.hdr.ah,
380                             pt->ah_wait_list_length, n, (unsigned long long)sec, (unsigned long long)wsi->pending_timeout_limit);
381 //#endif
382                 /*
383                  * Since he failed a timeout, he already had a chance to do
384                  * something and was unable to... that includes situations like
385                  * half closed connections.  So process this "failed timeout"
386                  * close as a violent death and don't try to do protocol
387                  * cleanup like flush partials.
388                  */
389                 wsi->socket_is_permanently_unusable = 1;
390                 if (wsi->mode == LWSCM_WSCL_WAITING_SSL)
391                         wsi->vhost->protocols[0].callback(wsi,
392                                 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
393                                 wsi->user_space, (void *)"Timed out waiting SSL", 21);
394
395                 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
396
397                 return 1;
398         }
399
400         return 0;
401 }
402
403 int lws_rxflow_cache(struct lws *wsi, unsigned char *buf, int n, int len)
404 {
405         /* his RX is flowcontrolled, don't send remaining now */
406         if (wsi->rxflow_buffer) {
407                 /* rxflow while we were spilling prev rxflow */
408                 lwsl_info("stalling in existing rxflow buf\n");
409                 return 1;
410         }
411
412         /* a new rxflow, buffer it and warn caller */
413         lwsl_info("new rxflow input buffer len %d\n", len - n);
414         wsi->rxflow_buffer = lws_malloc(len - n);
415         if (!wsi->rxflow_buffer)
416                 return -1;
417         wsi->rxflow_len = len - n;
418         wsi->rxflow_pos = 0;
419         memcpy(wsi->rxflow_buffer, buf + n, len - n);
420
421         return 0;
422 }
423
424 /* this is used by the platform service code to stop us waiting for network
425  * activity in poll() when we have something that already needs service
426  */
427
428 LWS_VISIBLE LWS_EXTERN int
429 lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi)
430 {
431         struct lws_context_per_thread *pt = &context->pt[tsi];
432         int n;
433
434         /* Figure out if we really want to wait in poll()
435          * We only need to wait if really nothing already to do and we have
436          * to wait for something from network
437          */
438
439         /* 1) if we know we are draining rx ext, do not wait in poll */
440         if (pt->rx_draining_ext_list)
441                 return 0;
442
443 #ifdef LWS_OPENSSL_SUPPORT
444         /* 2) if we know we have non-network pending data, do not wait in poll */
445         if (lws_ssl_anybody_has_buffered_read_tsi(context, tsi)) {
446                 lwsl_info("ssl buffered read\n");
447                 return 0;
448         }
449 #endif
450
451         /* 3) if any ah has pending rx, do not wait in poll */
452         for (n = 0; n < context->max_http_header_pool; n++)
453                 if (pt->ah_pool[n].rxpos != pt->ah_pool[n].rxlen) {
454                         /* any ah with pending rx must be attached to someone */
455                         if (!pt->ah_pool[n].wsi) {
456                                 lwsl_err("%s: assert: no wsi attached to ah\n", __func__);
457                                 assert(0);
458                         }
459                         return 0;
460                 }
461
462         return timeout_ms;
463 }
464
465 /*
466  * guys that need POLLIN service again without waiting for network action
467  * can force POLLIN here if not flowcontrolled, so they will get service.
468  *
469  * Return nonzero if anybody got their POLLIN faked
470  */
471 int
472 lws_service_flag_pending(struct lws_context *context, int tsi)
473 {
474         struct lws_context_per_thread *pt = &context->pt[tsi];
475 #ifdef LWS_OPENSSL_SUPPORT
476         struct lws *wsi_next;
477 #endif
478         struct lws *wsi;
479         int forced = 0;
480         int n;
481
482         /* POLLIN faking */
483
484         /*
485          * 1) For all guys with already-available ext data to drain, if they are
486          * not flowcontrolled, fake their POLLIN status
487          */
488         wsi = pt->rx_draining_ext_list;
489         while (wsi) {
490                 pt->fds[wsi->position_in_fds_table].revents |=
491                         pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN;
492                 if (pt->fds[wsi->position_in_fds_table].revents &
493                     LWS_POLLIN)
494                         forced = 1;
495                 wsi = wsi->u.ws.rx_draining_ext_list;
496         }
497
498 #ifdef LWS_OPENSSL_SUPPORT
499         /*
500          * 2) For all guys with buffered SSL read data already saved up, if they
501          * are not flowcontrolled, fake their POLLIN status so they'll get
502          * service to use up the buffered incoming data, even though their
503          * network socket may have nothing
504          */
505         wsi = pt->pending_read_list;
506         while (wsi) {
507                 wsi_next = wsi->pending_read_list_next;
508                 pt->fds[wsi->position_in_fds_table].revents |=
509                         pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN;
510                 if (pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN) {
511                         forced = 1;
512                         /*
513                          * he's going to get serviced now, take him off the
514                          * list of guys with buffered SSL.  If he still has some
515                          * at the end of the service, he'll get put back on the
516                          * list then.
517                          */
518                         lws_ssl_remove_wsi_from_buffered_list(wsi);
519                 }
520
521                 wsi = wsi_next;
522         }
523 #endif
524         /*
525          * 3) For any wsi who have an ah with pending RX who did not
526          * complete their current headers, and are not flowcontrolled,
527          * fake their POLLIN status so they will be able to drain the
528          * rx buffered in the ah
529          */
530         for (n = 0; n < context->max_http_header_pool; n++)
531                 if (pt->ah_pool[n].rxpos != pt->ah_pool[n].rxlen &&
532                     !pt->ah_pool[n].wsi->hdr_parsing_completed) {
533                         pt->fds[pt->ah_pool[n].wsi->position_in_fds_table].revents |=
534                                 pt->fds[pt->ah_pool[n].wsi->position_in_fds_table].events &
535                                         LWS_POLLIN;
536                         if (pt->fds[pt->ah_pool[n].wsi->position_in_fds_table].revents &
537                             LWS_POLLIN)
538                                 forced = 1;
539                 }
540
541         return forced;
542 }
543
544 #ifndef LWS_NO_CLIENT
545
546 LWS_VISIBLE int
547 lws_http_client_read(struct lws *wsi, char **buf, int *len)
548 {
549         int rlen, n;
550
551         rlen = lws_ssl_capable_read(wsi, (unsigned char *)*buf, *len);
552         *len = 0;
553
554         /* allow the source to signal he has data again next time */
555         lws_change_pollfd(wsi, 0, LWS_POLLIN);
556
557         if (rlen == LWS_SSL_CAPABLE_ERROR) {
558                 lwsl_notice("%s: SSL capable error\n", __func__);
559                 return -1;
560         }
561
562         if (rlen <= 0)
563                 return 0;
564
565         *len = rlen;
566         wsi->client_rx_avail = 0;
567
568         /*
569          * server may insist on transfer-encoding: chunked,
570          * so http client must deal with it
571          */
572 spin_chunks:
573         while (wsi->chunked && (wsi->chunk_parser != ELCP_CONTENT) && *len) {
574                 switch (wsi->chunk_parser) {
575                 case ELCP_HEX:
576                         if ((*buf)[0] == '\x0d') {
577                                 wsi->chunk_parser = ELCP_CR;
578                                 break;
579                         }
580                         n = char_to_hex((*buf)[0]);
581                         if (n < 0) {
582                                 lwsl_debug("chunking failure\n");
583                                 return -1;
584                         }
585                         wsi->chunk_remaining <<= 4;
586                         wsi->chunk_remaining |= n;
587                         break;
588                 case ELCP_CR:
589                         if ((*buf)[0] != '\x0a') {
590                                 lwsl_debug("chunking failure\n");
591                                 return -1;
592                         }
593                         wsi->chunk_parser = ELCP_CONTENT;
594                         lwsl_info("chunk %d\n", wsi->chunk_remaining);
595                         if (wsi->chunk_remaining)
596                                 break;
597                         lwsl_info("final chunk\n");
598                         goto completed;
599
600                 case ELCP_CONTENT:
601                         break;
602
603                 case ELCP_POST_CR:
604                         if ((*buf)[0] != '\x0d') {
605                                 lwsl_debug("chunking failure\n");
606
607                                 return -1;
608                         }
609
610                         wsi->chunk_parser = ELCP_POST_LF;
611                         break;
612
613                 case ELCP_POST_LF:
614                         if ((*buf)[0] != '\x0a')
615                                 return -1;
616
617                         wsi->chunk_parser = ELCP_HEX;
618                         wsi->chunk_remaining = 0;
619                         break;
620                 }
621                 (*buf)++;
622                 (*len)--;
623         }
624
625         if (wsi->chunked && !wsi->chunk_remaining)
626                 return 0;
627
628         if (wsi->u.http.content_remain &&
629             (int)wsi->u.http.content_remain < *len)
630                 n = wsi->u.http.content_remain;
631         else
632                 n = *len;
633
634         if (wsi->chunked && wsi->chunk_remaining &&
635             wsi->chunk_remaining < n)
636                 n = wsi->chunk_remaining;
637
638 #ifdef LWS_WITH_HTTP_PROXY
639         /* hubbub */
640         if (wsi->perform_rewrite)
641                 lws_rewrite_parse(wsi->rw, (unsigned char *)*buf, n);
642         else
643 #endif
644                 if (user_callback_handle_rxflow(wsi->protocol->callback,
645                                 wsi, LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ,
646                                 wsi->user_space, *buf, n)) {
647                         lwsl_debug("%s: LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ returned -1\n", __func__);
648
649                         return -1;
650                 }
651
652         if (wsi->chunked && wsi->chunk_remaining) {
653                 (*buf) += n;
654                 wsi->chunk_remaining -= n;
655                 *len -= n;
656         }
657
658         if (wsi->chunked && !wsi->chunk_remaining)
659                 wsi->chunk_parser = ELCP_POST_CR;
660
661         if (wsi->chunked && *len)
662                 goto spin_chunks;
663
664         if (wsi->chunked)
665                 return 0;
666
667         /* if we know the content length, decrement the content remaining */
668         if (wsi->u.http.content_length > 0)
669                 wsi->u.http.content_remain -= n;
670
671         if (wsi->u.http.content_remain || !wsi->u.http.content_length)
672                 return 0;
673
674 completed:
675         if (user_callback_handle_rxflow(wsi->protocol->callback,
676                         wsi, LWS_CALLBACK_COMPLETED_CLIENT_HTTP,
677                         wsi->user_space, NULL, 0)) {
678                 lwsl_debug("Completed call returned -1\n");
679                 return -1;
680         }
681
682         if (lws_http_transaction_completed_client(wsi)) {
683                 lwsl_notice("%s: transaction completed says -1\n", __func__);
684                 return -1;
685         }
686
687         return 0;
688 }
689 #endif
690
691 static int
692 lws_is_ws_with_ext(struct lws *wsi)
693 {
694 #if defined(LWS_NO_EXTENSIONS)
695         return 0;
696 #else
697         return wsi->state == LWSS_ESTABLISHED &&
698                !!wsi->count_act_ext;
699 #endif
700 }
701
702 LWS_VISIBLE int
703 lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd, int tsi)
704 {
705         struct lws_context_per_thread *pt = &context->pt[tsi];
706         lws_sockfd_type our_fd = 0, tmp_fd;
707         struct lws_tokens eff_buf;
708         unsigned int pending = 0;
709         struct lws *wsi, *wsi1;
710         char draining_flow = 0;
711         int timed_out = 0;
712         time_t now;
713         int n = 0, m;
714         int more;
715
716         if (!context->protocol_init_done)
717                 lws_protocol_init(context);
718
719         time(&now);
720
721         /*
722          * handle case that system time was uninitialized when lws started
723          * at boot, and got initialized a little later
724          */
725         if (context->time_up < 1464083026 && now > 1464083026)
726                 context->time_up = now;
727
728         /* TODO: if using libev, we should probably use timeout watchers... */
729         if (context->last_timeout_check_s != now) {
730                 context->last_timeout_check_s = now;
731
732                 lws_plat_service_periodic(context);
733
734                 /* retire unused deprecated context */
735 #if !defined(LWS_PLAT_OPTEE) && !defined(LWS_WITH_ESP32)
736 #if LWS_POSIX && !defined(_WIN32)
737                 if (context->deprecated && !context->count_wsi_allocated) {
738                         lwsl_notice("%s: ending deprecated context\n", __func__);
739                         kill(getpid(), SIGINT);
740                         return 0;
741                 }
742 #endif
743 #endif
744                 /* global timeout check once per second */
745
746                 if (pollfd)
747                         our_fd = pollfd->fd;
748
749                 wsi = context->pt[tsi].timeout_list;
750                 while (wsi) {
751                         /* we have to take copies, because he may be deleted */
752                         wsi1 = wsi->timeout_list;
753                         tmp_fd = wsi->desc.sockfd;
754                         if (lws_service_timeout_check(wsi, (unsigned int)now)) {
755                                 /* he did time out... */
756                                 if (tmp_fd == our_fd)
757                                         /* it was the guy we came to service! */
758                                         timed_out = 1;
759                                         /* he's gone, no need to mark as handled */
760                         }
761                         wsi = wsi1;
762                 }
763 #ifdef LWS_WITH_CGI
764                 lws_cgi_kill_terminated(pt);
765 #endif
766 #if 0
767                 {
768                         char s[300], *p = s;
769
770                         for (n = 0; n < context->count_threads; n++)
771                                 p += sprintf(p, " %7lu (%5d), ",
772                                              context->pt[n].count_conns,
773                                              context->pt[n].fds_count);
774
775                         lwsl_notice("load: %s\n", s);
776                 }
777 #endif
778         }
779
780         /*
781          * at intervals, check for ws connections needing ping-pong checks
782          */
783
784         if (context->ws_ping_pong_interval &&
785             context->last_ws_ping_pong_check_s < now + 10) {
786                 struct lws_vhost *vh = context->vhost_list;
787                 context->last_ws_ping_pong_check_s = now;
788
789                 while (vh) {
790                         for (n = 0; n < vh->count_protocols; n++) {
791                                 wsi = vh->same_vh_protocol_list[n];
792
793                                 while (wsi) {
794                                         if (wsi->state == LWSS_ESTABLISHED &&
795                                             !wsi->socket_is_permanently_unusable &&
796                                             !wsi->u.ws.send_check_ping &&
797                                             wsi->u.ws.time_next_ping_check &&
798                                             wsi->u.ws.time_next_ping_check < now) {
799
800                                                 lwsl_info("requesting ping-pong on wsi %p\n", wsi);
801                                                 wsi->u.ws.send_check_ping = 1;
802                                                 lws_set_timeout(wsi, PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING,
803                                                                 context->timeout_secs);
804                                                 lws_callback_on_writable(wsi);
805                                                 wsi->u.ws.time_next_ping_check = now +
806                                                                 wsi->context->ws_ping_pong_interval;
807                                         }
808                                         wsi = wsi->same_vh_protocol_next;
809                                 }
810                         }
811                         vh = vh->vhost_next;
812                 }
813         }
814
815         /* the socket we came to service timed out, nothing to do */
816         if (timed_out)
817                 return 0;
818
819         /* just here for timeout management? */
820         if (!pollfd)
821                 return 0;
822
823         /* no, here to service a socket descriptor */
824         wsi = wsi_from_fd(context, pollfd->fd);
825         if (!wsi)
826                 /* not lws connection ... leave revents alone and return */
827                 return 0;
828
829         /*
830          * so that caller can tell we handled, past here we need to
831          * zero down pollfd->revents after handling
832          */
833
834 #if LWS_POSIX
835         /* handle session socket closed */
836
837         if ((!(pollfd->revents & pollfd->events & LWS_POLLIN)) &&
838             (pollfd->revents & LWS_POLLHUP)) {
839                 wsi->socket_is_permanently_unusable = 1;
840                 lwsl_debug("Session Socket %p (fd=%d) dead\n",
841                                                        (void *)wsi, pollfd->fd);
842
843                 goto close_and_handled;
844         }
845
846 #ifdef _WIN32
847         if (pollfd->revents & LWS_POLLOUT)
848                 wsi->sock_send_blocking = FALSE;
849 #endif
850
851 #endif
852
853 //       lwsl_debug("fd=%d, revents=%d, mode=%d, state=%d\n", pollfd->fd, pollfd->revents, (int)wsi->mode, (int)wsi->state);
854         if (pollfd->revents & LWS_POLLHUP)
855                 goto close_and_handled;
856
857
858 #ifdef LWS_OPENSSL_SUPPORT
859        if ((wsi->state == LWSS_SHUTDOWN) && lws_is_ssl(wsi) && wsi->ssl)
860        {
861                n = SSL_shutdown(wsi->ssl);
862                lwsl_debug("SSH_shutdown=%d for fd %d\n", n, wsi->desc.sockfd);
863                if (n == 1)
864                {
865                        n = shutdown(wsi->desc.sockfd, SHUT_WR);
866                        goto close_and_handled;
867                }
868                else
869                {
870                        lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
871                        n = 0;
872                        goto handled;
873                }
874        }
875 #endif
876
877         /* okay, what we came here to do... */
878
879         switch (wsi->mode) {
880         case LWSCM_HTTP_SERVING:
881         case LWSCM_HTTP_CLIENT:
882         case LWSCM_HTTP_SERVING_ACCEPTED:
883         case LWSCM_SERVER_LISTENER:
884         case LWSCM_SSL_ACK_PENDING:
885         case LWSCM_SSL_ACK_PENDING_RAW:
886                 if (wsi->state == LWSS_CLIENT_HTTP_ESTABLISHED)
887                         goto handled;
888
889 #ifdef LWS_WITH_CGI
890                 if (wsi->cgi && (pollfd->revents & LWS_POLLOUT)) {
891                         n = lws_handle_POLLOUT_event(wsi, pollfd);
892                         if (n)
893                                 goto close_and_handled;
894                         goto handled;
895                 }
896 #endif
897                 /* fallthru */
898         case LWSCM_RAW:
899                 n = lws_server_socket_service(context, wsi, pollfd);
900                 if (n) /* closed by above */
901                         return 1;
902                 goto handled;
903
904         case LWSCM_RAW_FILEDESC:
905
906                 if (pollfd->revents & LWS_POLLOUT) {
907                         n = lws_calllback_as_writeable(wsi);
908                         if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
909                                 lwsl_info("failed at set pollfd\n");
910                                 return 1;
911                         }
912                         if (n)
913                                 goto close_and_handled;
914                 }
915                 n = LWS_CALLBACK_RAW_RX;
916                 if (wsi->mode == LWSCM_RAW_FILEDESC)
917                         n = LWS_CALLBACK_RAW_RX_FILE;
918
919                 if (pollfd->revents & LWS_POLLIN) {
920                         if (user_callback_handle_rxflow(
921                                         wsi->protocol->callback,
922                                         wsi, n,
923                                         wsi->user_space, NULL, 0)) {
924                                 lwsl_debug("raw rx callback closed it\n");
925                                 goto close_and_handled;
926                         }
927                 }
928
929                 if (pollfd->revents & LWS_POLLHUP)
930                         goto close_and_handled;
931                 n = 0;
932                 goto handled;
933
934         case LWSCM_WS_SERVING:
935         case LWSCM_WS_CLIENT:
936         case LWSCM_HTTP2_SERVING:
937         case LWSCM_HTTP_CLIENT_ACCEPTED:
938
939                 /* 1: something requested a callback when it was OK to write */
940
941                 if ((pollfd->revents & LWS_POLLOUT) &&
942                     ((wsi->state == LWSS_ESTABLISHED ||
943                      wsi->state == LWSS_HTTP2_ESTABLISHED ||
944                      wsi->state == LWSS_HTTP2_ESTABLISHED_PRE_SETTINGS ||
945                      wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
946                      wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE)) &&
947                     lws_handle_POLLOUT_event(wsi, pollfd)) {
948                         if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY)
949                                 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
950                         lwsl_info("lws_service_fd: closing\n");
951                         goto close_and_handled;
952                 }
953
954                 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
955                     wsi->state == LWSS_AWAITING_CLOSE_ACK) {
956                         /*
957                          * we stopped caring about anything except control
958                          * packets.  Force flow control off, defeat tx
959                          * draining.
960                          */
961                         lws_rx_flow_control(wsi, 1);
962                         wsi->u.ws.tx_draining_ext = 0;
963                 }
964
965                 if (wsi->u.ws.tx_draining_ext)
966                         /* we cannot deal with new RX until the TX ext
967                          * path has been drained.  It's because new
968                          * rx will, eg, crap on the wsi rx buf that
969                          * may be needed to retain state.
970                          *
971                          * TX ext drain path MUST go through event loop
972                          * to avoid blocking.
973                          */
974                         break;
975
976                 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
977                         /* We cannot deal with any kind of new RX
978                          * because we are RX-flowcontrolled.
979                          */
980                         break;
981
982                 /* 2: RX Extension needs to be drained
983                  */
984
985                 if (wsi->state == LWSS_ESTABLISHED &&
986                     wsi->u.ws.rx_draining_ext) {
987
988                         lwsl_ext("%s: RX EXT DRAINING: Service\n", __func__);
989 #ifndef LWS_NO_CLIENT
990                         if (wsi->mode == LWSCM_WS_CLIENT) {
991                                 n = lws_client_rx_sm(wsi, 0);
992                                 if (n < 0)
993                                         /* we closed wsi */
994                                         n = 0;
995                         } else
996 #endif
997                                 n = lws_rx_sm(wsi, 0);
998
999                         goto handled;
1000                 }
1001
1002                 if (wsi->u.ws.rx_draining_ext)
1003                         /*
1004                          * We have RX EXT content to drain, but can't do it
1005                          * right now.  That means we cannot do anything lower
1006                          * priority either.
1007                          */
1008                         break;
1009
1010                 /* 3: RX Flowcontrol buffer needs to be drained
1011                  */
1012
1013                 if (wsi->rxflow_buffer) {
1014                         lwsl_info("draining rxflow (len %d)\n",
1015                                 wsi->rxflow_len - wsi->rxflow_pos
1016                         );
1017                         /* well, drain it */
1018                         eff_buf.token = (char *)wsi->rxflow_buffer +
1019                                                 wsi->rxflow_pos;
1020                         eff_buf.token_len = wsi->rxflow_len - wsi->rxflow_pos;
1021                         draining_flow = 1;
1022                         goto drain;
1023                 }
1024
1025                 /* 4: any incoming (or ah-stashed incoming rx) data ready?
1026                  * notice if rx flow going off raced poll(), rx flow wins
1027                  */
1028
1029                 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
1030                         break;
1031
1032 read:
1033                 /* all the union members start with hdr, so even in ws mode
1034                  * we can deal with the ah via u.hdr
1035                  */
1036                 if (wsi->u.hdr.ah) {
1037                         lwsl_info("%s: %p: inherited ah rx\n", __func__, wsi);
1038                         eff_buf.token_len = wsi->u.hdr.ah->rxlen -
1039                                             wsi->u.hdr.ah->rxpos;
1040                         eff_buf.token = (char *)wsi->u.hdr.ah->rx +
1041                                         wsi->u.hdr.ah->rxpos;
1042                 } else {
1043                         if (wsi->mode != LWSCM_HTTP_CLIENT_ACCEPTED) {
1044                                 /*
1045                                  * extension may not consume everything (eg, pmd may be constrained
1046                                  * as to what it can output...) has to go in per-wsi rx buf area.
1047                                  * Otherwise in large temp serv_buf area.
1048                                  */
1049                                 eff_buf.token = (char *)pt->serv_buf;
1050                                 if (lws_is_ws_with_ext(wsi)) {
1051                                         eff_buf.token_len = wsi->u.ws.rx_ubuf_alloc;
1052                                 } else {
1053                                         eff_buf.token_len = context->pt_serv_buf_size;
1054                                 }
1055
1056                                 eff_buf.token_len = lws_ssl_capable_read(wsi,
1057                                         (unsigned char *)eff_buf.token, pending ? pending :
1058                                         eff_buf.token_len);
1059                                 switch (eff_buf.token_len) {
1060                                 case 0:
1061                                         lwsl_info("%s: zero length read\n", __func__);
1062                                         goto close_and_handled;
1063                                 case LWS_SSL_CAPABLE_MORE_SERVICE:
1064                                         lwsl_info("SSL Capable more service\n");
1065                                         n = 0;
1066                                         goto handled;
1067                                 case LWS_SSL_CAPABLE_ERROR:
1068                                         lwsl_info("Closing when error\n");
1069                                         goto close_and_handled;
1070                                 }
1071                                 // lwsl_notice("Actual RX %d\n", eff_buf.token_len);
1072                         }
1073                 }
1074
1075 drain:
1076 #ifndef LWS_NO_CLIENT
1077                 if (wsi->mode == LWSCM_HTTP_CLIENT_ACCEPTED &&
1078                     !wsi->told_user_closed) {
1079
1080                         /*
1081                          * In SSL mode we get POLLIN notification about
1082                          * encrypted data in.
1083                          *
1084                          * But that is not necessarily related to decrypted
1085                          * data out becoming available; in may need to perform
1086                          * other in or out before that happens.
1087                          *
1088                          * simply mark ourselves as having readable data
1089                          * and turn off our POLLIN
1090                          */
1091                         wsi->client_rx_avail = 1;
1092                         lws_change_pollfd(wsi, LWS_POLLIN, 0);
1093
1094                         /* let user code know, he'll usually ask for writeable
1095                          * callback and drain / re-enable it there
1096                          */
1097                         if (user_callback_handle_rxflow(
1098                                         wsi->protocol->callback,
1099                                         wsi, LWS_CALLBACK_RECEIVE_CLIENT_HTTP,
1100                                         wsi->user_space, NULL, 0)) {
1101                                 lwsl_debug("LWS_CALLBACK_RECEIVE_CLIENT_HTTP closed it\n");
1102                                 goto close_and_handled;
1103                         }
1104                 }
1105 #endif
1106                 /*
1107                  * give any active extensions a chance to munge the buffer
1108                  * before parse.  We pass in a pointer to an lws_tokens struct
1109                  * prepared with the default buffer and content length that's in
1110                  * there.  Rather than rewrite the default buffer, extensions
1111                  * that expect to grow the buffer can adapt .token to
1112                  * point to their own per-connection buffer in the extension
1113                  * user allocation.  By default with no extensions or no
1114                  * extension callback handling, just the normal input buffer is
1115                  * used then so it is efficient.
1116                  */
1117                 do {
1118                         more = 0;
1119
1120                         m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_RX_PREPARSE,
1121                                               &eff_buf, 0);
1122                         if (m < 0)
1123                                 goto close_and_handled;
1124                         if (m)
1125                                 more = 1;
1126
1127                         /* service incoming data */
1128
1129                         if (eff_buf.token_len) {
1130                                 /*
1131                                  * if draining from rxflow buffer, not
1132                                  * critical to track what was used since at the
1133                                  * use it bumps wsi->rxflow_pos.  If we come
1134                                  * around again it will pick up from where it
1135                                  * left off.
1136                                  */
1137                                 // lwsl_notice("doing lws_read from pt->serv_buf %p %p for len %d\n", pt->serv_buf, eff_buf.token, (int)eff_buf.token_len);
1138
1139                                 n = lws_read(wsi, (unsigned char *)eff_buf.token,
1140                                              eff_buf.token_len);
1141                                 if (n < 0) {
1142                                         /* we closed wsi */
1143                                         n = 0;
1144                                         goto handled;
1145                                 }
1146                         }
1147
1148                         eff_buf.token = NULL;
1149                         eff_buf.token_len = 0;
1150                 } while (more);
1151
1152                 if (wsi->u.hdr.ah) {
1153                         lwsl_notice("%s: %p: detaching\n",
1154                                  __func__, wsi);
1155                         /* show we used all the pending rx up */
1156                         wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1157                         /* we can run the normal ah detach flow despite
1158                          * being in ws union mode, since all union members
1159                          * start with hdr */
1160                         lws_header_table_detach(wsi, 0);
1161                 }
1162
1163                 pending = lws_ssl_pending(wsi);
1164                 if (pending) {
1165                         if (lws_is_ws_with_ext(wsi))
1166                                 pending = pending > wsi->u.ws.rx_ubuf_alloc ?
1167                                         wsi->u.ws.rx_ubuf_alloc : pending;
1168                         else
1169                                 pending = pending > context->pt_serv_buf_size ?
1170                                         context->pt_serv_buf_size : pending;
1171                         goto read;
1172                 }
1173
1174                 if (draining_flow && wsi->rxflow_buffer &&
1175                     wsi->rxflow_pos == wsi->rxflow_len) {
1176                         lwsl_info("flow buffer: drained\n");
1177                         lws_free_set_NULL(wsi->rxflow_buffer);
1178                         /* having drained the rxflow buffer, can rearm POLLIN */
1179 #ifdef LWS_NO_SERVER
1180                         n =
1181 #endif
1182                         _lws_rx_flow_control(wsi);
1183                         /* n ignored, needed for NO_SERVER case */
1184                 }
1185
1186                 break;
1187 #ifdef LWS_WITH_CGI
1188         case LWSCM_CGI: /* we exist to handle a cgi's stdin/out/err data...
1189                          * do the callback on our master wsi
1190                          */
1191                 {
1192                         struct lws_cgi_args args;
1193
1194                         if (wsi->cgi_channel >= LWS_STDOUT &&
1195                             !(pollfd->revents & pollfd->events & LWS_POLLIN))
1196                                 break;
1197                         if (wsi->cgi_channel == LWS_STDIN &&
1198                             !(pollfd->revents & pollfd->events & LWS_POLLOUT))
1199                                 break;
1200
1201                         if (wsi->cgi_channel == LWS_STDIN)
1202                                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
1203                                         lwsl_info("failed at set pollfd\n");
1204                                         return 1;
1205                                 }
1206
1207                         args.ch = wsi->cgi_channel;
1208                         args.stdwsi = &wsi->parent->cgi->stdwsi[0];
1209                         args.hdr_state = wsi->hdr_state;
1210
1211                         //lwsl_err("CGI LWS_STDOUT waiting wsi %p mode %d state %d\n",
1212                         //       wsi->parent, wsi->parent->mode, wsi->parent->state);
1213
1214                         if (user_callback_handle_rxflow(
1215                                         wsi->parent->protocol->callback,
1216                                         wsi->parent, LWS_CALLBACK_CGI,
1217                                         wsi->parent->user_space,
1218                                         (void *)&args, 0))
1219                                 return 1;
1220
1221                         break;
1222                 }
1223 #endif
1224         default:
1225 #ifdef LWS_NO_CLIENT
1226                 break;
1227 #else
1228                 if ((pollfd->revents & LWS_POLLOUT) &&
1229                     lws_handle_POLLOUT_event(wsi, pollfd)) {
1230                         lwsl_debug("POLLOUT event closed it\n");
1231                         goto close_and_handled;
1232                 }
1233
1234                 n = lws_client_socket_service(context, wsi, pollfd);
1235                 if (n)
1236                         return 1;
1237                 goto handled;
1238 #endif
1239         }
1240
1241         n = 0;
1242         goto handled;
1243
1244 close_and_handled:
1245         lwsl_debug("Close and handled\n");
1246         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1247         /*
1248          * pollfd may point to something else after the close
1249          * due to pollfd swapping scheme on delete on some platforms
1250          * we can't clear revents now because it'd be the wrong guy's revents
1251          */
1252         return 1;
1253
1254 handled:
1255         pollfd->revents = 0;
1256         return n;
1257 }
1258
1259 LWS_VISIBLE int
1260 lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd)
1261 {
1262         return lws_service_fd_tsi(context, pollfd, 0);
1263 }
1264
1265 LWS_VISIBLE int
1266 lws_service(struct lws_context *context, int timeout_ms)
1267 {
1268         return lws_plat_service(context, timeout_ms);
1269 }
1270
1271 LWS_VISIBLE int
1272 lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi)
1273 {
1274         return _lws_plat_service_tsi(context, timeout_ms, tsi);
1275 }
1276