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