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