Add unix domain socket
[platform/upstream/libwebsockets.git] / lib / libwebsockets.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2016 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 #ifdef LWS_HAVE_SYS_TYPES_H
25 #include <sys/types.h>
26 #endif
27
28 #if defined(WIN32) || defined(_WIN32)
29 #else
30 #include <sys/wait.h>
31 #endif
32
33 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
34 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
35
36 static const char * const log_level_names[] = {
37         "ERR",
38         "WARN",
39         "NOTICE",
40         "INFO",
41         "DEBUG",
42         "PARSER",
43         "HEADER",
44         "EXTENSION",
45         "CLIENT",
46         "LATENCY",
47 };
48
49 void
50 lws_free_wsi(struct lws *wsi)
51 {
52         if (!wsi)
53                 return;
54
55         /* Protocol user data may be allocated either internally by lws
56          * or by specified the user.
57          * We should only free what we allocated. */
58         if (wsi->protocol && wsi->protocol->per_session_data_size &&
59             wsi->user_space && !wsi->user_space_externally_allocated)
60                 lws_free(wsi->user_space);
61
62         lws_free_set_NULL(wsi->rxflow_buffer);
63         lws_free_set_NULL(wsi->trunc_alloc);
64
65         if (wsi->u.hdr.ah)
66                 /* we're closing, losing some rx is OK */
67                 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
68
69         /* we may not have an ah, but may be on the waiting list... */
70         lws_header_table_detach(wsi, 0);
71
72         wsi->context->count_wsi_allocated--;
73         lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
74                         wsi->context->count_wsi_allocated);
75
76         lws_free(wsi);
77 }
78
79 static void
80 lws_remove_from_timeout_list(struct lws *wsi)
81 {
82         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
83
84         if (!wsi->timeout_list_prev) /* ie, not part of the list */
85                 return;
86
87         lws_pt_lock(pt);
88         /* if we have a next guy, set his prev to our prev */
89         if (wsi->timeout_list)
90                 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
91         /* set our prev guy to our next guy instead of us */
92         *wsi->timeout_list_prev = wsi->timeout_list;
93
94         /* we're out of the list, we should not point anywhere any more */
95         wsi->timeout_list_prev = NULL;
96         wsi->timeout_list = NULL;
97         lws_pt_unlock(pt);
98 }
99
100 /**
101  * lws_set_timeout() - marks the wsi as subject to a timeout
102  *
103  * You will not need this unless you are doing something special
104  *
105  * @wsi:        Websocket connection instance
106  * @reason:     timeout reason
107  * @secs:       how many seconds
108  */
109
110 LWS_VISIBLE void
111 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
112 {
113         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
114         time_t now;
115
116         lws_pt_lock(pt);
117
118         time(&now);
119
120         if (reason && !wsi->timeout_list_prev) {
121                 /* our next guy is current first guy */
122                 wsi->timeout_list = pt->timeout_list;
123                 /* if there is a next guy, set his prev ptr to our next ptr */
124                 if (wsi->timeout_list)
125                         wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
126                 /* our prev ptr is first ptr */
127                 wsi->timeout_list_prev = &pt->timeout_list;
128                 /* set the first guy to be us */
129                 *wsi->timeout_list_prev = wsi;
130         }
131
132         lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
133         wsi->pending_timeout_limit = now + secs;
134         wsi->pending_timeout = reason;
135
136         lws_pt_unlock(pt);
137
138         if (!reason)
139                 lws_remove_from_timeout_list(wsi);
140 }
141
142 void
143 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
144 {
145         struct lws_context_per_thread *pt;
146         struct lws **pwsi, *wsi1, *wsi2;
147         struct lws_context *context;
148         struct lws_tokens eff_buf;
149         int n, m, ret;
150
151         if (!wsi)
152                 return;
153
154         context = wsi->context;
155         pt = &context->pt[(int)wsi->tsi];
156
157         /* if we have children, close them first */
158         if (wsi->child_list) {
159                 wsi2 = wsi->child_list;
160                 while (wsi2) {
161                         //lwsl_notice("%s: closing %p: close child %p\n",
162                         //              __func__, wsi, wsi2);
163                         wsi1 = wsi2->sibling_list;
164                         //lwsl_notice("%s: closing %p: next sibling %p\n",
165                         //              __func__, wsi2, wsi1);
166                         wsi2->parent = NULL;
167                         /* stop it doing shutdown processing */
168                         wsi2->socket_is_permanently_unusable = 1;
169                         lws_close_free_wsi(wsi2, reason);
170                         wsi2 = wsi1;
171                 }
172                 wsi->child_list = NULL;
173         }
174
175 #ifdef LWS_WITH_CGI
176         if (wsi->mode == LWSCM_CGI) {
177                 /* we are not a network connection, but a handler for CGI io */
178                 if (wsi->parent && wsi->parent->cgi)
179                         /* end the binding between us and master */
180                         wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
181                 wsi->socket_is_permanently_unusable = 1;
182
183                 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
184                 goto just_kill_connection;
185         }
186
187         if (wsi->cgi) {
188                 /* we have a cgi going, we must kill it */
189                 wsi->cgi->being_closed = 1;
190                 lws_cgi_kill(wsi);
191         }
192 #endif
193
194         if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
195             wsi->u.http.fd != LWS_INVALID_FILE) {
196                 lws_plat_file_close(wsi, wsi->u.http.fd);
197                 wsi->u.http.fd = LWS_INVALID_FILE;
198                 wsi->vhost->protocols[0].callback(wsi,
199                         LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
200         }
201         if (wsi->socket_is_permanently_unusable ||
202             reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
203             wsi->state == LWSS_SHUTDOWN)
204                 goto just_kill_connection;
205
206         wsi->state_pre_close = wsi->state;
207
208         switch (wsi->state_pre_close) {
209         case LWSS_DEAD_SOCKET:
210                 return;
211
212         /* we tried the polite way... */
213         case LWSS_AWAITING_CLOSE_ACK:
214                 goto just_kill_connection;
215
216         case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
217                 if (wsi->trunc_len) {
218                         lws_callback_on_writable(wsi);
219                         return;
220                 }
221                 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
222                 goto just_kill_connection;
223         default:
224                 if (wsi->trunc_len) {
225                         lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
226                         wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
227                         lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
228                         return;
229                 }
230                 break;
231         }
232
233         if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
234             wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
235                 goto just_kill_connection;
236
237         if (wsi->mode == LWSCM_HTTP_SERVING)
238                 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
239                                                wsi->user_space, NULL, 0);
240         if (wsi->mode == LWSCM_HTTP_CLIENT)
241                 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
242                                                wsi->user_space, NULL, 0);
243
244         /*
245          * are his extensions okay with him closing?  Eg he might be a mux
246          * parent and just his ch1 aspect is closing?
247          */
248
249         if (lws_ext_cb_active(wsi,
250                       LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
251                 lwsl_ext("extension vetoed close\n");
252                 return;
253         }
254
255         /*
256          * flush any tx pending from extensions, since we may send close packet
257          * if there are problems with send, just nuke the connection
258          */
259
260         do {
261                 ret = 0;
262                 eff_buf.token = NULL;
263                 eff_buf.token_len = 0;
264
265                 /* show every extension the new incoming data */
266
267                 m = lws_ext_cb_active(wsi,
268                           LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
269                 if (m < 0) {
270                         lwsl_ext("Extension reports fatal error\n");
271                         goto just_kill_connection;
272                 }
273                 if (m)
274                         /*
275                          * at least one extension told us he has more
276                          * to spill, so we will go around again after
277                          */
278                         ret = 1;
279
280                 /* assuming they left us something to send, send it */
281
282                 if (eff_buf.token_len)
283                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
284                                           eff_buf.token_len) !=
285                             eff_buf.token_len) {
286                                 lwsl_debug("close: ext spill failed\n");
287                                 goto just_kill_connection;
288                         }
289         } while (ret);
290
291         /*
292          * signal we are closing, lws_write will
293          * add any necessary version-specific stuff.  If the write fails,
294          * no worries we are closing anyway.  If we didn't initiate this
295          * close, then our state has been changed to
296          * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
297          *
298          * Likewise if it's a second call to close this connection after we
299          * sent the close indication to the peer already, we are in state
300          * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
301          */
302
303         if (wsi->state_pre_close == LWSS_ESTABLISHED &&
304             (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
305              (reason != LWS_CLOSE_STATUS_NOSTATUS &&
306              (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
307                 lwsl_debug("sending close indication...\n");
308
309                 /* if no prepared close reason, use 1000 and no aux data */
310                 if (!wsi->u.ws.close_in_ping_buffer_len) {
311                         wsi->u.ws.close_in_ping_buffer_len = 2;
312                         wsi->u.ws.ping_payload_buf[LWS_PRE] =
313                                 (reason >> 16) & 0xff;
314                         wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
315                                 reason & 0xff;
316                 }
317
318                 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
319                               wsi->u.ws.close_in_ping_buffer_len,
320                               LWS_WRITE_CLOSE);
321                 if (n >= 0) {
322                         /*
323                          * we have sent a nice protocol level indication we
324                          * now wish to close, we should not send anything more
325                          */
326                         wsi->state = LWSS_AWAITING_CLOSE_ACK;
327
328                         /*
329                          * ...and we should wait for a reply for a bit
330                          * out of politeness
331                          */
332                         lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
333                         lwsl_debug("sent close indication, awaiting ack\n");
334
335                         return;
336                 }
337
338                 lwsl_info("close: sending close packet failed, hanging up\n");
339
340                 /* else, the send failed and we should just hang up */
341         }
342
343 just_kill_connection:
344         if (wsi->parent) {
345                 /* detach ourselves from parent's child list */
346                 pwsi = &wsi->parent->child_list;
347                 while (*pwsi) {
348                         if (*pwsi == wsi) {
349                                 lwsl_notice("%s: detach %p from parent %p\n",
350                                                 __func__, wsi, wsi->parent);
351                                 *pwsi = wsi->sibling_list;
352                                 break;
353                         }
354                         pwsi = &(*pwsi)->sibling_list;
355                 }
356                 if (*pwsi)
357                         lwsl_err("%s: failed to detach from parent\n",
358                                         __func__);
359         }
360
361 #if LWS_POSIX
362         /*
363          * Testing with ab shows that we have to stage the socket close when
364          * the system is under stress... shutdown any further TX, change the
365          * state to one that won't emit anything more, and wait with a timeout
366          * for the POLLIN to show a zero-size rx before coming back and doing
367          * the actual close.
368          */
369         if (wsi->state != LWSS_SHUTDOWN &&
370             reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
371             !wsi->socket_is_permanently_unusable) {
372                 lwsl_info("%s: shutting down connection: %p (sock %d)\n", __func__, wsi, wsi->sock);
373                 n = shutdown(wsi->sock, SHUT_WR);
374                 if (n)
375                         lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
376
377 // This causes problems with disconnection when the events are half closing connection
378 // FD_READ | FD_CLOSE (33)
379 #ifndef _WIN32_WCE
380                 /* libuv: no event available to guarantee completion */
381                 if (!LWS_LIBUV_ENABLED(context)) {
382
383                         lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
384                         wsi->state = LWSS_SHUTDOWN;
385                         lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
386                                         context->timeout_secs);
387                         return;
388                 }
389 #endif
390         }
391 #endif
392
393         lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
394                   wsi, wsi->sock);
395 #ifdef LWS_WITH_HTTP_PROXY
396         if (wsi->rw) {
397                 lws_rewrite_destroy(wsi->rw);
398                 wsi->rw = NULL;
399         }
400 #endif
401         /*
402          * we won't be servicing or receiving anything further from this guy
403          * delete socket from the internal poll list if still present
404          */
405         lws_ssl_remove_wsi_from_buffered_list(wsi);
406         lws_remove_from_timeout_list(wsi);
407
408         /* checking return redundant since we anyway close */
409         remove_wsi_socket_from_fds(wsi);
410
411         wsi->state = LWSS_DEAD_SOCKET;
412
413         lws_free_set_NULL(wsi->rxflow_buffer);
414
415         if (wsi->state_pre_close == LWSS_ESTABLISHED ||
416             wsi->mode == LWSCM_WS_SERVING ||
417             wsi->mode == LWSCM_WS_CLIENT) {
418
419                 if (wsi->u.ws.rx_draining_ext) {
420                         struct lws **w = &pt->rx_draining_ext_list;
421
422                         wsi->u.ws.rx_draining_ext = 0;
423                         /* remove us from context draining ext list */
424                         while (*w) {
425                                 if (*w == wsi) {
426                                         *w = wsi->u.ws.rx_draining_ext_list;
427                                         break;
428                                 }
429                                 w = &((*w)->u.ws.rx_draining_ext_list);
430                         }
431                         wsi->u.ws.rx_draining_ext_list = NULL;
432                 }
433
434                 if (wsi->u.ws.tx_draining_ext) {
435                         struct lws **w = &pt->tx_draining_ext_list;
436
437                         wsi->u.ws.tx_draining_ext = 0;
438                         /* remove us from context draining ext list */
439                         while (*w) {
440                                 if (*w == wsi) {
441                                         *w = wsi->u.ws.tx_draining_ext_list;
442                                         break;
443                                 }
444                                 w = &((*w)->u.ws.tx_draining_ext_list);
445                         }
446                         wsi->u.ws.tx_draining_ext_list = NULL;
447                 }
448                 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
449
450                 if (wsi->trunc_alloc)
451                         /* not going to be completed... nuke it */
452                         lws_free_set_NULL(wsi->trunc_alloc);
453
454                 wsi->u.ws.ping_payload_len = 0;
455                 wsi->u.ws.ping_pending_flag = 0;
456         }
457
458         /* tell the user it's all over for this guy */
459
460         if (wsi->protocol && wsi->protocol->callback &&
461             ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
462             (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
463             (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
464             (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
465             (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
466             (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
467                 lwsl_debug("calling back CLOSED\n");
468                 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
469                                         wsi->user_space, NULL, 0);
470         } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
471                 lwsl_debug("calling back CLOSED_HTTP\n");
472                 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
473                                                wsi->user_space, NULL, 0 );
474         } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
475                    wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
476                 lwsl_debug("Connection closed before server reply\n");
477                 wsi->vhost->protocols[0].callback(wsi,
478                                         LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
479                                         wsi->user_space, NULL, 0);
480         } else
481                 lwsl_debug("not calling back closed mode=%d state=%d\n",
482                            wsi->mode, wsi->state_pre_close);
483
484         /* deallocate any active extension contexts */
485
486         if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
487                 lwsl_warn("extension destruction failed\n");
488         /*
489          * inform all extensions in case they tracked this guy out of band
490          * even though not active on him specifically
491          */
492         if (lws_ext_cb_all_exts(context, wsi,
493                        LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
494                 lwsl_warn("ext destroy wsi failed\n");
495
496         wsi->socket_is_permanently_unusable = 1;
497
498 #ifdef LWS_USE_LIBUV
499         if (LWS_LIBUV_ENABLED(context)) {
500                 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
501                 /* libuv has to do his own close handle processing asynchronously */
502                 lws_libuv_closehandle(wsi);
503
504                 return;
505         }
506 #endif
507
508         lws_close_free_wsi_final(wsi);
509 }
510
511 void
512 lws_close_free_wsi_final(struct lws *wsi)
513 {
514         int n;
515
516         if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
517 #if LWS_POSIX
518                 //lwsl_err("*** closing sockfd %d\n", wsi->sock);
519                 n = compatible_close(wsi->sock);
520                 if (n)
521                         lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
522
523 #else
524                 compatible_close(wsi->sock);
525 #endif
526                 wsi->sock = LWS_SOCK_INVALID;
527         }
528
529         /* outermost destroy notification for wsi (user_space still intact) */
530         wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
531                                        wsi->user_space, NULL, 0);
532
533 #ifdef LWS_WITH_CGI
534         if (wsi->cgi) {
535                 for (n = 0; n < 6; n++)
536                         if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0) {
537                                 lwsl_notice("   closing %d\n", wsi->cgi->pipe_fds[n / 2][n & 1]);
538                                 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
539                         }
540                 lws_free(wsi->cgi);
541         }
542 #endif
543
544         lws_free_wsi(wsi);
545 }
546
547 #if LWS_POSIX
548 LWS_VISIBLE int
549 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
550 {
551         int ipv6 = 0;
552 #ifdef LWS_USE_IPV6
553         ipv6 = LWS_IPV6_ENABLED(context);
554 #endif
555         (void)context;
556
557         return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
558 }
559 #endif
560
561 LWS_VISIBLE int
562 lws_get_addresses(struct lws_context *context, void *ads, char *name,
563                   int name_len, char *rip, int rip_len)
564 {
565 #if LWS_POSIX
566         struct addrinfo ai, *res;
567         struct sockaddr_in addr4;
568
569         if (rip)
570                 rip[0] = '\0';
571         name[0] = '\0';
572         addr4.sin_family = AF_UNSPEC;
573
574 #ifdef LWS_USE_IPV6
575         if (LWS_IPV6_ENABLED(context)) {
576                 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
577                         lwsl_err("inet_ntop", strerror(LWS_ERRNO));
578                         return -1;
579                 }
580
581                 // Strip off the IPv4 to IPv6 header if one exists
582                 if (strncmp(rip, "::ffff:", 7) == 0)
583                         memmove(rip, rip + 7, strlen(rip) - 6);
584
585                 getnameinfo((struct sockaddr *)ads,
586                                 sizeof(struct sockaddr_in6), name,
587                                                         name_len, NULL, 0, 0);
588
589                 return 0;
590         } else
591 #endif
592         {
593                 struct addrinfo *result;
594
595                 memset(&ai, 0, sizeof ai);
596                 ai.ai_family = PF_UNSPEC;
597                 ai.ai_socktype = SOCK_STREAM;
598                 ai.ai_flags = AI_CANONNAME;
599
600                 if (getnameinfo((struct sockaddr *)ads,
601                                 sizeof(struct sockaddr_in),
602                                 name, name_len, NULL, 0, 0))
603                         return -1;
604
605                 if (!rip)
606                         return 0;
607
608                 if (getaddrinfo(name, NULL, &ai, &result))
609                         return -1;
610
611                 res = result;
612                 while (addr4.sin_family == AF_UNSPEC && res) {
613                         switch (res->ai_family) {
614                         case AF_INET:
615                                 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
616                                 addr4.sin_family = AF_INET;
617                                 break;
618                         }
619
620                         res = res->ai_next;
621                 }
622                 freeaddrinfo(result);
623         }
624
625         if (addr4.sin_family == AF_UNSPEC)
626                 return -1;
627
628         if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
629                 return -1;
630
631         return 0;
632 #else
633         (void)context;
634         (void)ads;
635         (void)name;
636         (void)name_len;
637         (void)rip;
638         (void)rip_len;
639
640         return -1;
641 #endif
642 }
643
644 /**
645  * lws_get_peer_addresses() - Get client address information
646  * @wsi:        Local struct lws associated with
647  * @fd:         Connection socket descriptor
648  * @name:       Buffer to take client address name
649  * @name_len:   Length of client address name buffer
650  * @rip:        Buffer to take client address IP dotted quad
651  * @rip_len:    Length of client address IP buffer
652  *
653  *      This function fills in @name and @rip with the name and IP of
654  *      the client connected with socket descriptor @fd.  Names may be
655  *      truncated if there is not enough room.  If either cannot be
656  *      determined, they will be returned as valid zero-length strings.
657  */
658
659 LWS_VISIBLE void
660 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
661                        int name_len, char *rip, int rip_len)
662 {
663 #if LWS_POSIX
664         socklen_t len;
665 #ifdef LWS_USE_IPV6
666         struct sockaddr_in6 sin6;
667 #endif
668         struct sockaddr_in sin4;
669         struct lws_context *context = wsi->context;
670         int ret = -1;
671         void *p;
672
673         rip[0] = '\0';
674         name[0] = '\0';
675
676         lws_latency_pre(context, wsi);
677
678 #ifdef LWS_USE_IPV6
679         if (LWS_IPV6_ENABLED(context)) {
680                 len = sizeof(sin6);
681                 p = &sin6;
682         } else
683 #endif
684         {
685                 len = sizeof(sin4);
686                 p = &sin4;
687         }
688
689         if (getpeername(fd, p, &len) < 0) {
690                 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
691                 goto bail;
692         }
693
694         ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
695
696 bail:
697         lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
698 #else
699         (void)wsi;
700         (void)fd;
701         (void)name;
702         (void)name_len;
703         (void)rip;
704         (void)rip_len;
705 #endif
706 }
707
708 /**
709  * lws_context_user() - get the user data associated with the context
710  * @context: Websocket context
711  *
712  *      This returns the optional user allocation that can be attached to
713  *      the context the sockets live in at context_create time.  It's a way
714  *      to let all sockets serviced in the same context share data without
715  *      using globals statics in the user code.
716  */
717 LWS_EXTERN void *
718 lws_context_user(struct lws_context *context)
719 {
720         return context->user_space;
721 }
722
723 LWS_VISIBLE struct lws_vhost *
724 lws_vhost_get(struct lws *wsi)
725 {
726         return wsi->vhost;
727 }
728
729 LWS_VISIBLE const struct lws_protocols *
730 lws_protocol_get(struct lws *wsi)
731 {
732         return wsi->protocol;
733 }
734
735
736 /**
737  * lws_callback_all_protocol() - Callback all connections using
738  *                              the given protocol with the given reason
739  *
740  * @protocol:   Protocol whose connections will get callbacks
741  * @reason:     Callback reason index
742  */
743
744 LWS_VISIBLE int
745 lws_callback_all_protocol(struct lws_context *context,
746                           const struct lws_protocols *protocol, int reason)
747 {
748         struct lws_context_per_thread *pt = &context->pt[0];
749         unsigned int n, m = context->count_threads;
750         struct lws *wsi;
751
752         while (m--) {
753                 for (n = 0; n < pt->fds_count; n++) {
754                         wsi = wsi_from_fd(context, pt->fds[n].fd);
755                         if (!wsi)
756                                 continue;
757                         if (wsi->protocol == protocol)
758                                 protocol->callback(wsi, reason, wsi->user_space,
759                                                    NULL, 0);
760                 }
761                 pt++;
762         }
763
764         return 0;
765 }
766
767 /**
768  * lws_callback_all_protocol_vhost() - Callback all connections using
769  *                              the given protocol with the given reason
770  *
771  * @vh:         Vhost whose connections will get callbacks
772  * @protocol:   Which protocol to match
773  * @reason:     Callback reason index
774  */
775
776 LWS_VISIBLE int
777 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
778                           const struct lws_protocols *protocol, int reason)
779 {
780         struct lws_context *context = vh->context;
781         struct lws_context_per_thread *pt = &context->pt[0];
782         unsigned int n, m = context->count_threads;
783         struct lws *wsi;
784
785         while (m--) {
786                 for (n = 0; n < pt->fds_count; n++) {
787                         wsi = wsi_from_fd(context, pt->fds[n].fd);
788                         if (!wsi)
789                                 continue;
790                         if (wsi->vhost == vh && wsi->protocol == protocol)
791                                 protocol->callback(wsi, reason, wsi->user_space,
792                                                    NULL, 0);
793                 }
794                 pt++;
795         }
796
797         return 0;
798 }
799
800 #if LWS_POSIX
801
802 /**
803  * lws_get_socket_fd() - returns the socket file descriptor
804  *
805  * You will not need this unless you are doing something special
806  *
807  * @wsi:        Websocket connection instance
808  */
809
810 LWS_VISIBLE int
811 lws_get_socket_fd(struct lws *wsi)
812 {
813         return wsi->sock;
814 }
815
816 #endif
817
818 #ifdef LWS_LATENCY
819 void
820 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
821             int ret, int completed)
822 {
823         unsigned long long u;
824         char buf[256];
825
826         u = time_in_microseconds();
827
828         if (!action) {
829                 wsi->latency_start = u;
830                 if (!wsi->action_start)
831                         wsi->action_start = u;
832                 return;
833         }
834         if (completed) {
835                 if (wsi->action_start == wsi->latency_start)
836                         sprintf(buf,
837                           "Completion first try lat %lluus: %p: ret %d: %s\n",
838                                         u - wsi->latency_start,
839                                                       (void *)wsi, ret, action);
840                 else
841                         sprintf(buf,
842                           "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
843                                 u - wsi->action_start,
844                                         u - wsi->latency_start,
845                                                       (void *)wsi, ret, action);
846                 wsi->action_start = 0;
847         } else
848                 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
849                               u - wsi->latency_start, (void *)wsi, ret, action);
850
851         if (u - wsi->latency_start > context->worst_latency) {
852                 context->worst_latency = u - wsi->latency_start;
853                 strcpy(context->worst_latency_info, buf);
854         }
855         lwsl_latency("%s", buf);
856 }
857 #endif
858
859
860
861 /**
862  * lws_rx_flow_control() - Enable and disable socket servicing for
863  *                              received packets.
864  *
865  * If the output side of a server process becomes choked, this allows flow
866  * control for the input side.
867  *
868  * @wsi:        Websocket connection instance to get callback for
869  * @enable:     0 = disable read servicing for this connection, 1 = enable
870  */
871
872 LWS_VISIBLE int
873 lws_rx_flow_control(struct lws *wsi, int enable)
874 {
875         if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
876                 return 0;
877
878         lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
879         wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
880
881         return 0;
882 }
883
884 /**
885  * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
886  *
887  * When the user server code realizes it can accept more input, it can
888  * call this to have the RX flow restriction removed from all connections using
889  * the given protocol.
890  *
891  * @protocol:   all connections using this protocol will be allowed to receive
892  */
893
894 LWS_VISIBLE void
895 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
896                                const struct lws_protocols *protocol)
897 {
898         const struct lws_context_per_thread *pt = &context->pt[0];
899         struct lws *wsi;
900         unsigned int n, m = context->count_threads;
901
902         while (m--) {
903                 for (n = 0; n < pt->fds_count; n++) {
904                         wsi = wsi_from_fd(context, pt->fds[n].fd);
905                         if (!wsi)
906                                 continue;
907                         if (wsi->protocol == protocol)
908                                 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
909                 }
910                 pt++;
911         }
912 }
913
914
915 /**
916  * lws_canonical_hostname() - returns this host's hostname
917  *
918  * This is typically used by client code to fill in the host parameter
919  * when making a client connection.  You can only call it after the context
920  * has been created.
921  *
922  * @context:    Websocket context
923  */
924 LWS_VISIBLE extern const char *
925 lws_canonical_hostname(struct lws_context *context)
926 {
927         return (const char *)context->canonical_hostname;
928 }
929
930 int user_callback_handle_rxflow(lws_callback_function callback_function,
931                                 struct lws *wsi,
932                                 enum lws_callback_reasons reason, void *user,
933                                 void *in, size_t len)
934 {
935         int n;
936
937         n = callback_function(wsi, reason, user, in, len);
938         if (!n)
939                 n = _lws_rx_flow_control(wsi);
940
941         return n;
942 }
943
944
945 /**
946  * lws_set_proxy() - Setups proxy to lws_context.
947  * @context:    pointer to struct lws_context you want set proxy to
948  * @proxy: pointer to c string containing proxy in format address:port
949  *
950  * Returns 0 if proxy string was parsed and proxy was setup.
951  * Returns -1 if @proxy is NULL or has incorrect format.
952  *
953  * This is only required if your OS does not provide the http_proxy
954  * environment variable (eg, OSX)
955  *
956  *   IMPORTANT! You should call this function right after creation of the
957  *   lws_context and before call to connect. If you call this
958  *   function after connect behavior is undefined.
959  *   This function will override proxy settings made on lws_context
960  *   creation with genenv() call.
961  */
962
963 LWS_VISIBLE int
964 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
965 {
966         char *p;
967         char authstring[96];
968
969         if (!proxy)
970                 return -1;
971
972         p = strchr(proxy, '@');
973         if (p) { /* auth is around */
974
975                 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
976                         goto auth_too_long;
977
978                 strncpy(authstring, proxy, p - proxy);
979                 // null termination not needed on input
980                 if (lws_b64_encode_string(authstring, (p - proxy),
981                                 vhost->proxy_basic_auth_token,
982                     sizeof vhost->proxy_basic_auth_token) < 0)
983                         goto auth_too_long;
984
985                 lwsl_notice(" Proxy auth in use\n");
986
987                 proxy = p + 1;
988         } else
989                 vhost->proxy_basic_auth_token[0] = '\0';
990
991         strncpy(vhost->http_proxy_address, proxy,
992                                 sizeof(vhost->http_proxy_address) - 1);
993         vhost->http_proxy_address[
994                                 sizeof(vhost->http_proxy_address) - 1] = '\0';
995
996         p = strchr(vhost->http_proxy_address, ':');
997         if (!p && !vhost->http_proxy_port) {
998                 lwsl_err("http_proxy needs to be ads:port\n");
999
1000                 return -1;
1001         } else {
1002                 if (p) {
1003                         *p = '\0';
1004                         vhost->http_proxy_port = atoi(p + 1);
1005                 }
1006         }
1007
1008         lwsl_notice(" Proxy %s:%u\n", vhost->http_proxy_address,
1009                         vhost->http_proxy_port);
1010
1011         return 0;
1012
1013 auth_too_long:
1014         lwsl_err("proxy auth too long\n");
1015
1016         return -1;
1017 }
1018
1019 /**
1020  * lws_get_protocol() - Returns a protocol pointer from a websocket
1021  *                                connection.
1022  * @wsi:        pointer to struct websocket you want to know the protocol of
1023  *
1024  *
1025  *      Some apis can act on all live connections of a given protocol,
1026  *      this is how you can get a pointer to the active protocol if needed.
1027  */
1028
1029 LWS_VISIBLE const struct lws_protocols *
1030 lws_get_protocol(struct lws *wsi)
1031 {
1032         return wsi->protocol;
1033 }
1034
1035 LWS_VISIBLE int
1036 lws_is_final_fragment(struct lws *wsi)
1037 {
1038         lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
1039                         wsi->u.ws.final, wsi->u.ws.rx_packet_length,
1040                         wsi->u.ws.rx_draining_ext);
1041         return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1042 }
1043
1044 LWS_VISIBLE unsigned char
1045 lws_get_reserved_bits(struct lws *wsi)
1046 {
1047         return wsi->u.ws.rsv;
1048 }
1049
1050 int
1051 lws_ensure_user_space(struct lws *wsi)
1052 {
1053         lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1054         if (!wsi->protocol)
1055                 return 1;
1056
1057         /* allocate the per-connection user memory (if any) */
1058
1059         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1060                 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1061                 if (wsi->user_space  == NULL) {
1062                         lwsl_err("Out of memory for conn user space\n");
1063                         return 1;
1064                 }
1065         } else
1066                 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
1067                           __func__, wsi, wsi->protocol->per_session_data_size,
1068                           wsi->user_space);
1069         return 0;
1070 }
1071
1072 /**
1073  * lwsl_timestamp: generate logging timestamp string
1074  *
1075  * @level:      logging level
1076  * @p:          char * buffer to take timestamp
1077  * @len:        length of p
1078  *
1079  * returns length written in p
1080  */
1081 LWS_VISIBLE int
1082 lwsl_timestamp(int level, char *p, int len)
1083 {
1084         time_t o_now = time(NULL);
1085         unsigned long long now;
1086         struct tm *ptm = NULL;
1087 #ifndef WIN32
1088         struct tm tm;
1089 #endif
1090         int n;
1091
1092 #ifndef _WIN32_WCE
1093 #ifdef WIN32
1094         ptm = localtime(&o_now);
1095 #else
1096         if (localtime_r(&o_now, &tm))
1097                 ptm = &tm;
1098 #endif
1099 #endif
1100         p[0] = '\0';
1101         for (n = 0; n < LLL_COUNT; n++) {
1102                 if (level != (1 << n))
1103                         continue;
1104                 now = time_in_microseconds() / 100;
1105                 if (ptm)
1106                         n = snprintf(p, len,
1107                                 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1108                                 ptm->tm_year + 1900,
1109                                 ptm->tm_mon,
1110                                 ptm->tm_mday,
1111                                 ptm->tm_hour,
1112                                 ptm->tm_min,
1113                                 ptm->tm_sec,
1114                                 (int)(now % 10000), log_level_names[n]);
1115                 else
1116                         n = snprintf(p, len, "[%llu:%04d] %s: ",
1117                                         (unsigned long long) now / 10000,
1118                                         (int)(now % 10000), log_level_names[n]);
1119                 return n;
1120         }
1121
1122         return 0;
1123 }
1124
1125 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1126 {
1127         char buf[50];
1128
1129         lwsl_timestamp(level, buf, sizeof(buf));
1130
1131         fprintf(stderr, "%s%s", buf, line);
1132 }
1133
1134 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1135 {
1136         char buf[256];
1137
1138         if (!(log_level & filter))
1139                 return;
1140
1141         vsnprintf(buf, sizeof(buf), format, vl);
1142         buf[sizeof(buf) - 1] = '\0';
1143
1144         lwsl_emit(filter, buf);
1145 }
1146
1147 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1148 {
1149         va_list ap;
1150
1151         va_start(ap, format);
1152         _lws_logv(filter, format, ap);
1153         va_end(ap);
1154 }
1155
1156 /**
1157  * lws_set_log_level() - Set the logging bitfield
1158  * @level:      OR together the LLL_ debug contexts you want output from
1159  * @log_emit_function:  NULL to leave it as it is, or a user-supplied
1160  *                      function to perform log string emission instead of
1161  *                      the default stderr one.
1162  *
1163  *      log level defaults to "err", "warn" and "notice" contexts enabled and
1164  *      emission on stderr.
1165  */
1166
1167 LWS_VISIBLE void lws_set_log_level(int level,
1168                                    void (*func)(int level, const char *line))
1169 {
1170         log_level = level;
1171         if (func)
1172                 lwsl_emit = func;
1173 }
1174
1175 /**
1176  * lws_use_ssl() - Find out if connection is using SSL
1177  * @wsi:        websocket connection to check
1178  *
1179  *      Returns 0 if the connection is not using SSL, 1 if using SSL and
1180  *      using verified cert, and 2 if using SSL but the cert was not
1181  *      checked (appears for client wsi told to skip check on connection)
1182  */
1183 LWS_VISIBLE int
1184 lws_is_ssl(struct lws *wsi)
1185 {
1186 #ifdef LWS_OPENSSL_SUPPORT
1187         return wsi->use_ssl;
1188 #else
1189         (void)wsi;
1190         return 0;
1191 #endif
1192 }
1193
1194 /**
1195  * lws_partial_buffered() - find out if lws buffered the last write
1196  * @wsi:        websocket connection to check
1197  *
1198  * Returns 1 if you cannot use lws_write because the last
1199  * write on this connection is still buffered, and can't be cleared without
1200  * returning to the service loop and waiting for the connection to be
1201  * writeable again.
1202  *
1203  * If you will try to do >1 lws_write call inside a single
1204  * WRITEABLE callback, you must check this after every write and bail if
1205  * set, ask for a new writeable callback and continue writing from there.
1206  *
1207  * This is never set at the start of a writeable callback, but any write
1208  * may set it.
1209  */
1210
1211 LWS_VISIBLE int
1212 lws_partial_buffered(struct lws *wsi)
1213 {
1214         return !!wsi->trunc_len;
1215 }
1216
1217 void lws_set_protocol_write_pending(struct lws *wsi,
1218                                     enum lws_pending_protocol_send pend)
1219 {
1220         lwsl_info("setting pps %d\n", pend);
1221
1222         if (wsi->pps)
1223                 lwsl_err("pps overwrite\n");
1224         wsi->pps = pend;
1225         lws_rx_flow_control(wsi, 0);
1226         lws_callback_on_writable(wsi);
1227 }
1228
1229 LWS_VISIBLE size_t
1230 lws_get_peer_write_allowance(struct lws *wsi)
1231 {
1232 #ifdef LWS_USE_HTTP2
1233         /* only if we are using HTTP2 on this connection */
1234         if (wsi->mode != LWSCM_HTTP2_SERVING)
1235                 return -1;
1236         /* user is only interested in how much he can send, or that he can't  */
1237         if (wsi->u.http2.tx_credit <= 0)
1238                 return 0;
1239
1240         return wsi->u.http2.tx_credit;
1241 #else
1242         (void)wsi;
1243         return -1;
1244 #endif
1245 }
1246
1247 LWS_VISIBLE void
1248 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1249 {
1250         lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1251         memset(&wsi->u, 0, sizeof(wsi->u));
1252         wsi->mode = mode;
1253 }
1254
1255 LWS_VISIBLE struct lws_plat_file_ops *
1256 lws_get_fops(struct lws_context *context)
1257 {
1258         return &context->fops;
1259 }
1260
1261 LWS_VISIBLE LWS_EXTERN struct lws_context *
1262 lws_get_context(const struct lws *wsi)
1263 {
1264         return wsi->context;
1265 }
1266
1267 LWS_VISIBLE LWS_EXTERN int
1268 lws_get_count_threads(struct lws_context *context)
1269 {
1270         return context->count_threads;
1271 }
1272
1273 LWS_VISIBLE LWS_EXTERN void *
1274 lws_wsi_user(struct lws *wsi)
1275 {
1276         return wsi->user_space;
1277 }
1278
1279 LWS_VISIBLE LWS_EXTERN struct lws *
1280 lws_get_parent(const struct lws *wsi)
1281 {
1282         return wsi->parent;
1283 }
1284
1285 LWS_VISIBLE LWS_EXTERN struct lws *
1286 lws_get_child(const struct lws *wsi)
1287 {
1288         return wsi->child_list;
1289 }
1290
1291 LWS_VISIBLE LWS_EXTERN void
1292 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1293                  unsigned char *buf, size_t len)
1294 {
1295         unsigned char *p, *start;
1296         int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1297
1298         assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1299
1300         start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1301
1302         *p++ = (((int)status) >> 8) & 0xff;
1303         *p++ = ((int)status) & 0xff;
1304
1305         if (buf)
1306                 while (len-- && p < start + budget)
1307                         *p++ = *buf++;
1308
1309         wsi->u.ws.close_in_ping_buffer_len = p - start;
1310 }
1311
1312 LWS_EXTERN int
1313 _lws_rx_flow_control(struct lws *wsi)
1314 {
1315         /* there is no pending change */
1316         if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1317                 lwsl_debug("%s: no pending change\n", __func__);
1318                 return 0;
1319         }
1320
1321         /* stuff is still buffered, not ready to really accept new input */
1322         if (wsi->rxflow_buffer) {
1323                 /* get ourselves called back to deal with stashed buffer */
1324                 lws_callback_on_writable(wsi);
1325                 return 0;
1326         }
1327
1328         /* pending is cleared, we can change rxflow state */
1329
1330         wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1331
1332         lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1333                               wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1334
1335         /* adjust the pollfd for this wsi */
1336
1337         if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1338                 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1339                         lwsl_info("%s: fail\n", __func__);
1340                         return -1;
1341                 }
1342         } else
1343                 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1344                         return -1;
1345
1346         return 0;
1347 }
1348
1349 LWS_EXTERN int
1350 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1351 {
1352         static const unsigned char e0f4[] = {
1353                 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1354                 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1355                 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1356                 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1357                 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1358                 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1359                 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1360                 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1361                 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1362                 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1363                 0x80 | ((4 - 1) << 2) | 1, /* ea */
1364                 0x80 | ((4 - 1) << 2) | 1, /* eb */
1365                 0x80 | ((4 - 1) << 2) | 1, /* ec */
1366                 0x80 | ((2 - 1) << 2) | 1, /* ed */
1367                 0x80 | ((4 - 1) << 2) | 1, /* ee */
1368                 0x80 | ((4 - 1) << 2) | 1, /* ef */
1369                 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1370                 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1371                 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1372                 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1373                 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1374
1375                 0,                         /* s0 */
1376                 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1377                 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1378         };
1379         unsigned char s = *state;
1380
1381         while (len--) {
1382                 unsigned char c = *buf++;
1383
1384                 if (!s) {
1385                         if (c >= 0x80) {
1386                                 if (c < 0xc2 || c > 0xf4)
1387                                         return 1;
1388                                 if (c < 0xe0)
1389                                         s = 0x80 | ((4 - 1) << 2);
1390                                 else
1391                                         s = e0f4[c - 0xe0];
1392                         }
1393                 } else {
1394                         if (c < (s & 0xf0) ||
1395                             c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1396                                 return 1;
1397                         s = e0f4[21 + (s & 3)];
1398                 }
1399         }
1400
1401         *state = s;
1402
1403         return 0;
1404 }
1405
1406 /**
1407  * lws_parse_uri:       cut up prot:/ads:port/path into pieces
1408  *                      Notice it does so by dropping '\0' into input string
1409  *                      and the leading / on the path is consequently lost
1410  *
1411  * @p:                  incoming uri string.. will get written to
1412  * @prot:               result pointer for protocol part (https://)
1413  * @ads:                result pointer for address part
1414  * @port:               result pointer for port part
1415  * @path:               result pointer for path part
1416  */
1417
1418 LWS_VISIBLE LWS_EXTERN int
1419 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1420               const char **path)
1421 {
1422         const char *end;
1423         static const char *slash = "/";
1424
1425         /* cut up the location into address, port and path */
1426         *prot = p;
1427         while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1428                 p++;
1429         if (!*p) {
1430                 end = p;
1431                 p = (char *)*prot;
1432                 *prot = end;
1433         } else {
1434                 *p = '\0';
1435                 p += 3;
1436         }
1437         *ads = p;
1438         if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1439                 *port = 80;
1440         else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1441                 *port = 443;
1442
1443         while (*p && *p != ':' && *p != '/')
1444                 p++;
1445         if (*p == ':') {
1446                 *p++ = '\0';
1447                 *port = atoi(p);
1448                 while (*p && *p != '/')
1449                         p++;
1450         }
1451         *path = slash;
1452         if (*p) {
1453                 *p++ = '\0';
1454                 if (*p)
1455                         *path = p;
1456         }
1457
1458         return 0;
1459 }
1460
1461 #ifdef LWS_NO_EXTENSIONS
1462
1463 /* we need to provide dummy callbacks for internal exts
1464  * so user code runs when faced with a lib compiled with
1465  * extensions disabled.
1466  */
1467
1468 int
1469 lws_extension_callback_pm_deflate(struct lws_context *context,
1470                                   const struct lws_extension *ext,
1471                                   struct lws *wsi,
1472                                   enum lws_extension_callback_reasons reason,
1473                                   void *user, void *in, size_t len)
1474 {
1475         (void)context;
1476         (void)ext;
1477         (void)wsi;
1478         (void)reason;
1479         (void)user;
1480         (void)in;
1481         (void)len;
1482
1483         return 0;
1484 }
1485 #endif
1486
1487 LWS_EXTERN int
1488 lws_socket_bind(struct lws_context *context, int sockfd, int port,
1489                 const char *iface)
1490 {
1491 #if LWS_POSIX
1492 #ifdef LWS_USE_UNIX_SOCK
1493         struct sockaddr_un serv_unix;
1494 #endif
1495 #ifdef LWS_USE_IPV6
1496         struct sockaddr_in6 serv_addr6;
1497 #endif
1498         struct sockaddr_in serv_addr4;
1499         socklen_t len = sizeof(struct sockaddr);
1500         int n;
1501         struct sockaddr_in sin;
1502         struct sockaddr *v;
1503
1504 #ifdef LWS_USE_UNIX_SOCK
1505         if (LWS_UNIX_SOCK_ENABLED(context)) {
1506                 v = (struct sockaddr *)&serv_unix;
1507                 n = sizeof(struct sockaddr_un);
1508                 bzero((char *) &serv_unix, sizeof(serv_unix));
1509                 serv_unix.sun_family = AF_UNIX;
1510                 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1511                         lwsl_err("\"%s\" too long for UNIX domain socket\n",
1512                                  iface);
1513                         return -1;
1514                 }
1515                 strcpy(serv_unix.sun_path, iface);
1516         } else
1517 #endif
1518 #ifdef LWS_USE_IPV6
1519         if (LWS_IPV6_ENABLED(context)) {
1520                 v = (struct sockaddr *)&serv_addr6;
1521                 n = sizeof(struct sockaddr_in6);
1522                 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1523                 serv_addr6.sin6_addr = in6addr_any;
1524                 serv_addr6.sin6_family = AF_INET6;
1525                 serv_addr6.sin6_port = htons(port);
1526         } else
1527 #endif
1528         {
1529                 v = (struct sockaddr *)&serv_addr4;
1530                 n = sizeof(serv_addr4);
1531                 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1532                 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1533                 serv_addr4.sin_family = AF_INET;
1534
1535                 if (iface &&
1536                     interface_to_sa(context, iface,
1537                                     (struct sockaddr_in *)v, n) < 0) {
1538                         lwsl_err("Unable to find interface %s\n", iface);
1539                         return -1;
1540                 }
1541
1542                 serv_addr4.sin_port = htons(port);
1543         } /* ipv4 */
1544
1545         n = bind(sockfd, v, n);
1546 #ifdef LWS_USE_UNIX_SOCK
1547         if (n < 0 && LWS_UNIX_SOCK_ENABLED(context)) {
1548                 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
1549                                 sockfd, iface, n, LWS_ERRNO);
1550                 return -1;
1551         } else
1552 #endif
1553         if (n < 0) {
1554                 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1555                                 sockfd, port, n, LWS_ERRNO);
1556                 return -1;
1557         }
1558
1559         if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1560                 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1561         else
1562                 port = ntohs(sin.sin_port);
1563 #endif
1564
1565         return port;
1566 }
1567
1568 LWS_VISIBLE LWS_EXTERN int
1569 lws_urlencode(const char *in, int inlen, char *out, int outlen)
1570 {
1571         const char *hex = "0123456789ABCDEF";
1572         char *start = out, *end = out + outlen;
1573
1574         while (inlen-- && out < end - 4) {
1575                 if ((*in >= 'A' && *in <= 'Z') ||
1576                     (*in >= 'a' && *in <= 'z') ||
1577                     (*in >= '0' && *in <= '9') ||
1578                     *in == '-' ||
1579                     *in == '_' ||
1580                     *in == '.' ||
1581                     *in == '~')
1582                         *out++ = *in++;
1583                 else {
1584                         *out++ = '%';
1585                         *out++ = hex[(*in) >> 4];
1586                         *out++ = hex[(*in++) & 15];
1587                 }
1588         }
1589         *out = '\0';
1590
1591         if (out >= end - 4)
1592                 return -1;
1593
1594         return out - start;
1595 }
1596
1597 LWS_VISIBLE LWS_EXTERN int
1598 lws_finalize_startup(struct lws_context *context)
1599 {
1600         struct lws_context_creation_info info;
1601
1602         info.uid = context->uid;
1603         info.gid = context->gid;
1604
1605         if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
1606                 lws_plat_drop_app_privileges(&info);
1607
1608         return 0;
1609 }
1610
1611
1612 LWS_VISIBLE LWS_EXTERN int
1613 lws_is_cgi(struct lws *wsi) {
1614 #ifdef LWS_WITH_CGI
1615         return !!wsi->cgi;
1616 #else
1617         return 0;
1618 #endif
1619 }
1620
1621 #ifdef LWS_WITH_CGI
1622
1623 static struct lws *
1624 lws_create_basic_wsi(struct lws_context *context, int tsi)
1625 {
1626         struct lws *new_wsi;
1627
1628         if ((unsigned int)context->pt[tsi].fds_count ==
1629             context->fd_limit_per_thread - 1) {
1630                 lwsl_err("no space for new conn\n");
1631                 return NULL;
1632         }
1633
1634         new_wsi = lws_zalloc(sizeof(struct lws));
1635         if (new_wsi == NULL) {
1636                 lwsl_err("Out of memory for new connection\n");
1637                 return NULL;
1638         }
1639
1640         new_wsi->tsi = tsi;
1641         new_wsi->context = context;
1642         new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1643         new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1644
1645         /* intialize the instance struct */
1646
1647         new_wsi->state = LWSS_CGI;
1648         new_wsi->mode = LWSCM_CGI;
1649         new_wsi->hdr_parsing_completed = 0;
1650         new_wsi->position_in_fds_table = -1;
1651
1652         /*
1653          * these can only be set once the protocol is known
1654          * we set an unestablished connection's protocol pointer
1655          * to the start of the defauly vhost supported list, so it can look
1656          * for matching ones during the handshake
1657          */
1658         new_wsi->protocol = context->vhost_list->protocols;
1659         new_wsi->user_space = NULL;
1660         new_wsi->ietf_spec_revision = 0;
1661         new_wsi->sock = LWS_SOCK_INVALID;
1662         context->count_wsi_allocated++;
1663
1664         return new_wsi;
1665 }
1666
1667 /**
1668  * lws_cgi: spawn network-connected cgi process
1669  *
1670  * @wsi: connection to own the process
1671  * @exec_array: array of "exec-name" "arg1" ... "argn" NULL
1672  */
1673
1674 LWS_VISIBLE LWS_EXTERN int
1675 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
1676         int timeout_secs, struct lws_protocol_vhost_options *mp_cgienv)
1677 {
1678         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1679         char *env_array[30], cgi_path[400], e[1024], *p = e,
1680              *end = p + sizeof(e) - 1, tok[256], *t;
1681         struct lws_cgi *cgi;
1682         int n, m, i, uritok = WSI_TOKEN_GET_URI;
1683
1684         /*
1685          * give the master wsi a cgi struct
1686          */
1687
1688         wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
1689         if (!wsi->cgi) {
1690                 lwsl_err("%s: OOM\n", __func__);
1691                 return -1;
1692         }
1693
1694         cgi = wsi->cgi;
1695         cgi->wsi = wsi; /* set cgi's owning wsi */
1696
1697         /* create pipes for [stdin|stdout] and [stderr] */
1698
1699         for (n = 0; n < 3; n++)
1700                 if (pipe(cgi->pipe_fds[n]) == -1)
1701                         goto bail1;
1702
1703         /* create cgi wsis for each stdin/out/err fd */
1704
1705         for (n = 0; n < 3; n++) {
1706                 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
1707                 if (!cgi->stdwsi[n])
1708                         goto bail2;
1709                 cgi->stdwsi[n]->cgi_channel = n;
1710                 cgi->stdwsi[n]->vhost = wsi->vhost;
1711
1712                 lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
1713                          cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
1714
1715                 /* read side is 0, stdin we want the write side, others read */
1716                 cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
1717                 fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK);
1718         }
1719
1720         for (n = 0; n < 3; n++) {
1721                 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->sock);
1722                 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
1723                         goto bail3;
1724                 cgi->stdwsi[n]->parent = wsi;
1725                 cgi->stdwsi[n]->sibling_list = wsi->child_list;
1726                 wsi->child_list = cgi->stdwsi[n];
1727         }
1728
1729         lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
1730         lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
1731         lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
1732
1733         lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
1734                    cgi->stdwsi[LWS_STDIN]->sock, cgi->stdwsi[LWS_STDOUT]->sock,
1735                    cgi->stdwsi[LWS_STDERR]->sock);
1736
1737         lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
1738
1739         /* the cgi stdout is always sending us http1.x header data first */
1740         wsi->hdr_state = LCHS_HEADER;
1741
1742         /* add us to the pt list of active cgis */
1743         cgi->cgi_list = pt->cgi_list;
1744         pt->cgi_list = cgi;
1745
1746         /* prepare his CGI env */
1747
1748         n = 0;
1749
1750         if (lws_is_ssl(wsi))
1751                 env_array[n++] = "HTTPS=ON";
1752         if (wsi->u.hdr.ah) {
1753                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
1754                         uritok = WSI_TOKEN_POST_URI;
1755                 snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
1756                          lws_hdr_simple_ptr(wsi, uritok));
1757                 cgi_path[sizeof(cgi_path) - 1] = '\0';
1758                 env_array[n++] = cgi_path;
1759                 if (uritok == WSI_TOKEN_POST_URI)
1760                         env_array[n++] = "REQUEST_METHOD=POST";
1761                 else
1762                         env_array[n++] = "REQUEST_METHOD=GET";
1763
1764                 env_array[n++] = p;
1765                 p += snprintf(p, end - p, "QUERY_STRING=");
1766                 /* dump the individual URI Arg parameters */
1767                 m = 0;
1768                 while (1) {
1769                         i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
1770                                              WSI_TOKEN_HTTP_URI_ARGS, m);
1771                         if (i < 0)
1772                                 break;
1773                         t = tok;
1774                         while (*t && *t != '=' && p < end - 4)
1775                                 *p++ = *t++;
1776                         if (*t == '=')
1777                                 *p++ = *t++;
1778                         i = lws_urlencode(t, i- (t - tok), p, end - p);
1779                         if (i > 0) {
1780                                 p += i;
1781                                 *p++ = '&';
1782                         }
1783                         m++;
1784                 }
1785                 if (m)
1786                         p--;
1787                 *p++ = '\0';
1788
1789                 env_array[n++] = p;
1790                 p += snprintf(p, end - p, "PATH_INFO=%s",
1791                               lws_hdr_simple_ptr(wsi, uritok) +
1792                               script_uri_path_len);
1793                 p++;
1794         }
1795         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
1796                 env_array[n++] = p;
1797                 p += snprintf(p, end - p, "HTTP_REFERER=%s",
1798                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
1799                 p++;
1800         }
1801         if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1802                 env_array[n++] = p;
1803                 p += snprintf(p, end - p, "HTTP_HOST=%s",
1804                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1805                 p++;
1806         }
1807         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
1808                 env_array[n++] = p;
1809                 p += snprintf(p, end - p, "HTTP_COOKIE=%s",
1810                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
1811                 p++;
1812         }
1813         if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
1814                 env_array[n++] = p;
1815                 p += snprintf(p, end - p, "USER_AGENT=%s",
1816                               lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
1817                 p++;
1818         }
1819         if (uritok == WSI_TOKEN_POST_URI) {
1820                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
1821                         env_array[n++] = p;
1822                         p += snprintf(p, end - p, "CONTENT_TYPE=%s",
1823                                       lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
1824                         p++;
1825                 }
1826                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
1827                         env_array[n++] = p;
1828                         p += snprintf(p, end - p, "CONTENT_LENGTH=%s",
1829                                       lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
1830                         p++;
1831                 }
1832         }
1833         env_array[n++] = p;
1834         p += snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
1835
1836         while (mp_cgienv) {
1837                 env_array[n++] = p;
1838                 p += snprintf(p, end - p, "%s=%s", mp_cgienv->name,
1839                               mp_cgienv->value);
1840                 lwsl_notice("   Applying mount-specific cgi env '%s'\n",
1841                             env_array[n - 1]);
1842                 p++;
1843                 mp_cgienv = mp_cgienv->next;
1844         }
1845
1846         env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
1847         env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
1848         env_array[n] = NULL;
1849
1850 #if 1
1851         for (m = 0; m < n; m++)
1852                 lwsl_err("    %s\n", env_array[m]);
1853 #endif
1854
1855         /* we are ready with the redirection pipes... run the thing */
1856 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
1857         cgi->pid = fork();
1858 #else
1859         cgi->pid = vfork();
1860 #endif
1861         if (cgi->pid < 0) {
1862                 lwsl_err("fork failed, errno %d", errno);
1863                 goto bail3;
1864         }
1865
1866         if (cgi->pid)
1867                 /* we are the parent process */
1868                 return 0;
1869
1870         /* somewhere we can at least read things and enter it */
1871         if (chdir("/tmp"))
1872                 lwsl_notice("%s: Failed to chdir\n", __func__);
1873
1874         /* We are the forked process, redirect and kill inherited things.
1875          *
1876          * Because of vfork(), we cannot do anything that changes pages in
1877          * the parent environment.  Stuff that changes kernel state for the
1878          * process is OK.  Stuff that happens after the execvpe() is OK.
1879          */
1880
1881         for (n = 0; n < 3; n++)
1882                 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
1883                         lwsl_err("%s: stdin dup2 failed\n", __func__);
1884                         goto bail3;
1885                 }
1886
1887 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
1888         for (m = 0; m < n; m++) {
1889                 p = strchr(env_array[m], '=');
1890                 *p++ = '\0';
1891                 setenv(env_array[m], p, 1);
1892         }
1893         execvp(exec_array[0], (char * const *)&exec_array[0]);
1894 #else
1895         execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
1896 #endif
1897
1898         exit(1);
1899
1900 bail3:
1901         /* drop us from the pt cgi list */
1902         pt->cgi_list = cgi->cgi_list;
1903
1904         while (--n >= 0)
1905                 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
1906 bail2:
1907         for (n = 0; n < 3; n++)
1908                 if (wsi->cgi->stdwsi[n])
1909                         lws_free_wsi(cgi->stdwsi[n]);
1910
1911 bail1:
1912         for (n = 0; n < 3; n++) {
1913                 if (cgi->pipe_fds[n][0])
1914                         close(cgi->pipe_fds[n][0]);
1915                 if (cgi->pipe_fds[n][1])
1916                         close(cgi->pipe_fds[n][1]);
1917         }
1918
1919         lws_free_set_NULL(wsi->cgi);
1920
1921         lwsl_err("%s: failed\n", __func__);
1922
1923         return -1;
1924 }
1925 /**
1926  * lws_cgi_write_split_headers: write cgi output accounting for header part
1927  *
1928  * @wsi: connection to own the process
1929  */
1930 LWS_VISIBLE LWS_EXTERN int
1931 lws_cgi_write_split_stdout_headers(struct lws *wsi)
1932 {
1933         int n, m, match = 0, lp = 0;
1934         static const char * const content_length = "content-length: ";
1935         char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
1936              *end = &buf[sizeof(buf) - 1 - LWS_PRE], c, l[12];
1937
1938         if (!wsi->cgi)
1939                 return -1;
1940
1941         while (wsi->hdr_state != LHCS_PAYLOAD) {
1942                 /* we have to separate header / finalize and
1943                  * payload chunks, since they need to be
1944                  * handled separately
1945                  */
1946                 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
1947                 if (n < 0) {
1948                         if (errno != EAGAIN) {
1949                                 lwsl_debug("%s: read says %d\n", __func__, n);
1950                                 return -1;
1951                         }
1952                         else
1953                                 n = 0;
1954                 }
1955                 if (n) {
1956                         lwsl_debug("-- 0x%02X %c\n", (unsigned char)c, c);
1957                         switch (wsi->hdr_state) {
1958                         case LCHS_HEADER:
1959                                 if (!content_length[match] &&
1960                                     (c >= '0' && c <= '9') &&
1961                                     lp < sizeof(l) - 1) {
1962                                         l[lp++] = c;
1963                                         l[lp] = '\0';
1964                                         wsi->cgi->content_length = atol(l);
1965                                 }
1966                                 if (tolower(c) == content_length[match])
1967                                         match++;
1968                                 else
1969                                         match = 0;
1970
1971                                 /* some cgi only send us \x0a for EOL */
1972                                 if (c == '\x0a') {
1973                                         wsi->hdr_state = LCHS_SINGLE_0A;
1974                                         *p++ = '\x0d';
1975                                 }
1976                                 *p++ = c;
1977                                 if (c == '\x0d') {
1978                                         wsi->hdr_state = LCHS_LF1;
1979                                         break;
1980                                 }
1981
1982                                 break;
1983                         case LCHS_LF1:
1984                                 *p++ = c;
1985                                 if (c == '\x0a') {
1986                                         wsi->hdr_state = LCHS_CR2;
1987                                         break;
1988                                 }
1989                                 /* we got \r[^\n]... it's unreasonable */
1990                                 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
1991                                 return -1;
1992
1993                         case LCHS_CR2:
1994                                 if (c == '\x0d') {
1995                                         /* drop the \x0d */
1996                                         wsi->hdr_state = LCHS_LF2;
1997                                         break;
1998                                 }
1999                                 wsi->hdr_state = LCHS_HEADER;
2000                                 match = 0;
2001                                 *p++ = c;
2002                                 break;
2003                         case LCHS_LF2:
2004                         case LCHS_SINGLE_0A:
2005                                 m = wsi->hdr_state;
2006                                 if (c == '\x0a') {
2007                                         lwsl_err("Content-Length: %ld\n", wsi->cgi->content_length);
2008                                         wsi->hdr_state = LHCS_PAYLOAD;
2009                                         /* drop the \0xa ... finalize will add it if needed */
2010                                         lws_finalize_http_header(wsi,
2011                                                         (unsigned char **)&p,
2012                                                         (unsigned char *)end);
2013                                         break;
2014                                 }
2015                                 if (m == LCHS_LF2)
2016                                         /* we got \r\n\r[^\n]... it's unreasonable */
2017                                         return -1;
2018                                 /* we got \x0anext header, it's reasonable */
2019                                 *p++ = c;
2020                                 wsi->hdr_state = LCHS_HEADER;
2021                                 break;
2022                         case LHCS_PAYLOAD:
2023                                 break;
2024                         }
2025                 }
2026
2027                 /* ran out of input, ended the headers, or filled up the headers buf */
2028                 if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
2029
2030                         m = lws_write(wsi, (unsigned char *)start,
2031                                       p - start, LWS_WRITE_HTTP_HEADERS);
2032                         if (m < 0) {
2033                                 lwsl_debug("%s: write says %d\n", __func__, m);
2034                                 return -1;
2035                         }
2036                         /* writeability becomes uncertain now we wrote
2037                          * something, we must return to the event loop
2038                          */
2039
2040                         return 0;
2041                 }
2042         }
2043
2044         n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2045                  start, sizeof(buf) - LWS_PRE);
2046
2047         if (n < 0 && errno != EAGAIN) {
2048                 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2049                 return -1;
2050         }
2051         if (n > 0) {
2052                 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2053                 //lwsl_notice("write %d\n", m);
2054                 if (m < 0) {
2055                         lwsl_debug("%s: stdout write says %d\n", __func__, m);
2056                         return -1;
2057                 }
2058                 wsi->cgi->content_length_seen += m;
2059         }
2060
2061         return 0;
2062 }
2063
2064 /**
2065  * lws_cgi_kill: terminate cgi process associated with wsi
2066  *
2067  * @wsi: connection to own the process
2068  */
2069 LWS_VISIBLE LWS_EXTERN int
2070 lws_cgi_kill(struct lws *wsi)
2071 {
2072         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2073         struct lws_cgi **pcgi = &pt->cgi_list;
2074         struct lws_cgi_args args;
2075         int n, status, do_close = 0;
2076
2077         lwsl_debug("!!!!! %s: %p\n", __func__, wsi);
2078
2079         if (!wsi->cgi)
2080                 return 0;
2081
2082         if (wsi->cgi->pid > 0) {
2083                 /* kill the process */
2084                 n = kill(wsi->cgi->pid, SIGTERM);
2085                 if (n < 0) {
2086                         lwsl_err("%s: failed\n", __func__);
2087                         return 1;
2088                 }
2089                 waitpid(wsi->cgi->pid, &status, 0); /* !!! may hang !!! */
2090         }
2091
2092         args.stdwsi = &wsi->cgi->stdwsi[0];
2093
2094         if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
2095                         wsi->protocol->callback,
2096                         wsi, LWS_CALLBACK_CGI_TERMINATED,
2097                         wsi->user_space,
2098                         (void *)&args, 0)) {
2099                 wsi->cgi->pid = -1;
2100                 do_close = !wsi->cgi->being_closed;
2101         }
2102
2103         /* remove us from the cgi list */
2104         while (*pcgi) {
2105                 if (*pcgi == wsi->cgi) {
2106                         /* drop us from the pt cgi list */
2107                         *pcgi = (*pcgi)->cgi_list;
2108                         break;
2109                 }
2110                 pcgi = &(*pcgi)->cgi_list;
2111         }
2112
2113         if (do_close) {
2114                 lwsl_debug("!!!!! %s: do_close\n", __func__);
2115                 lws_close_free_wsi(wsi, 0);
2116         }
2117
2118         return 0;
2119 }
2120
2121 LWS_EXTERN int
2122 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2123 {
2124         struct lws_cgi **pcgi = &pt->cgi_list, *cgi;
2125         int status;
2126
2127         /* check all the subprocesses on the cgi list for termination */
2128         while (*pcgi) {
2129                 /* get the next one because we may close current one next */
2130                 cgi = *pcgi;
2131                 pcgi = &(*pcgi)->cgi_list;
2132
2133                 if (cgi->pid <= 0)
2134                         continue;
2135
2136                 /* wait for stdout to be drained */
2137                 if (cgi->content_length > cgi->content_length_seen)
2138                         continue;
2139
2140                 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
2141                         lwsl_notice("content length seen: %ld\n", cgi->content_length_seen);
2142                         cgi->pid = 0;
2143                         lws_cgi_kill(cgi->wsi);
2144                         pcgi = &pt->cgi_list;
2145                 }
2146         }
2147
2148         return 0;
2149 }
2150 #endif
2151
2152 #ifdef LWS_NO_EXTENSIONS
2153 LWS_EXTERN int
2154 lws_set_extension_option(struct lws *wsi, const char *ext_name,
2155                          const char *opt_name, const char *opt_val)
2156 {
2157         return -1;
2158 }
2159 #endif