extension permessage deflate
[platform/upstream/libwebsockets.git] / lib / libwebsockets.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2014 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 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
25 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
26
27 static const char * const log_level_names[] = {
28         "ERR",
29         "WARN",
30         "NOTICE",
31         "INFO",
32         "DEBUG",
33         "PARSER",
34         "HEADER",
35         "EXTENSION",
36         "CLIENT",
37         "LATENCY",
38 };
39
40 void
41 lws_free_wsi(struct lws *wsi)
42 {
43         if (!wsi)
44                 return;
45
46         /* Protocol user data may be allocated either internally by lws
47          * or by specified the user.
48          * We should only free what we allocated. */
49         if (wsi->protocol && wsi->protocol->per_session_data_size &&
50             wsi->user_space && !wsi->user_space_externally_allocated)
51                 lws_free(wsi->user_space);
52
53         lws_free_set_NULL(wsi->rxflow_buffer);
54         lws_free_set_NULL(wsi->trunc_alloc);
55         /*
56          * These union members have an ah at the start
57          *
58          *      struct _lws_http_mode_related http;
59          *      struct _lws_http2_related http2;
60          *      struct _lws_header_related hdr;
61          *
62          * basically ws-related union member does not
63          */
64         if (wsi->mode != LWSCM_WS_CLIENT &&
65             wsi->mode != LWSCM_WS_SERVING)
66                 if (wsi->u.hdr.ah)
67                         lws_free_header_table(wsi);
68         lws_free(wsi);
69 }
70
71 void
72 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
73 {
74         struct lws_context *context = wsi->context;
75         int n, m, ret, old_state;
76         struct lws_tokens eff_buf;
77
78         if (!wsi)
79                 return;
80
81         old_state = wsi->state;
82
83         if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
84             wsi->u.http.fd != LWS_INVALID_FILE) {
85                 lwsl_debug("closing http file\n");
86                 lws_plat_file_close(wsi, wsi->u.http.fd);
87                 wsi->u.http.fd = LWS_INVALID_FILE;
88                 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
89                                                wsi->user_space, NULL, 0);
90         }
91         if (wsi->socket_is_permanently_unusable ||
92             reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)
93                 goto just_kill_connection;
94
95         switch (old_state) {
96         case LWSS_DEAD_SOCKET:
97                 return;
98
99         /* we tried the polite way... */
100         case LWSS_AWAITING_CLOSE_ACK:
101                 goto just_kill_connection;
102
103         case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
104                 if (wsi->trunc_len) {
105                         lws_callback_on_writable(wsi);
106                         return;
107                 }
108                 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
109                 goto just_kill_connection;
110         default:
111                 if (wsi->trunc_len) {
112                         lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
113                         wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
114                         lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
115                         return;
116                 }
117                 break;
118         }
119
120         if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
121             wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
122                 goto just_kill_connection;
123
124         if (wsi->mode == LWSCM_HTTP_SERVING)
125                 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
126                                                wsi->user_space, NULL, 0);
127
128         /*
129          * are his extensions okay with him closing?  Eg he might be a mux
130          * parent and just his ch1 aspect is closing?
131          */
132
133         if (lws_ext_cb_active(wsi,
134                       LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
135                 lwsl_ext("extension vetoed close\n");
136                 return;
137         }
138
139         /*
140          * flush any tx pending from extensions, since we may send close packet
141          * if there are problems with send, just nuke the connection
142          */
143
144         do {
145                 ret = 0;
146                 eff_buf.token = NULL;
147                 eff_buf.token_len = 0;
148
149                 /* show every extension the new incoming data */
150
151                 m = lws_ext_cb_active(wsi,
152                           LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
153                 if (m < 0) {
154                         lwsl_ext("Extension reports fatal error\n");
155                         goto just_kill_connection;
156                 }
157                 if (m)
158                         /*
159                          * at least one extension told us he has more
160                          * to spill, so we will go around again after
161                          */
162                         ret = 1;
163
164                 /* assuming they left us something to send, send it */
165
166                 if (eff_buf.token_len)
167                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
168                                           eff_buf.token_len) !=
169                             eff_buf.token_len) {
170                                 lwsl_debug("close: ext spill failed\n");
171                                 goto just_kill_connection;
172                         }
173         } while (ret);
174
175         /*
176          * signal we are closing, lws_write will
177          * add any necessary version-specific stuff.  If the write fails,
178          * no worries we are closing anyway.  If we didn't initiate this
179          * close, then our state has been changed to
180          * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
181          *
182          * Likewise if it's a second call to close this connection after we
183          * sent the close indication to the peer already, we are in state
184          * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
185          */
186
187         if (old_state == LWSS_ESTABLISHED &&
188             (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
189              (reason != LWS_CLOSE_STATUS_NOSTATUS &&
190              (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
191                 lwsl_debug("sending close indication...\n");
192
193                 /* if no prepared close reason, use 1000 and no aux data */
194                 if (!wsi->u.ws.close_in_ping_buffer_len) {
195                         wsi->u.ws.close_in_ping_buffer_len = 2;
196                         wsi->u.ws.ping_payload_buf[LWS_PRE] =
197                                 (reason >> 16) & 0xff;
198                         wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
199                                 reason & 0xff;
200                 }
201
202                 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[
203                                                 LWS_PRE],
204                               wsi->u.ws.close_in_ping_buffer_len,
205                               LWS_WRITE_CLOSE);
206                 if (n >= 0) {
207                         /*
208                          * we have sent a nice protocol level indication we
209                          * now wish to close, we should not send anything more
210                          */
211                         wsi->state = LWSS_AWAITING_CLOSE_ACK;
212
213                         /*
214                          * ...and we should wait for a reply for a bit
215                          * out of politeness
216                          */
217                         lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
218                         lwsl_debug("sent close indication, awaiting ack\n");
219
220                         return;
221                 }
222
223                 lwsl_info("close: sending close packet failed, hanging up\n");
224
225                 /* else, the send failed and we should just hang up */
226         }
227
228 just_kill_connection:
229
230         lwsl_debug("close: just_kill_connection: %p\n", wsi);
231
232         /*
233          * we won't be servicing or receiving anything further from this guy
234          * delete socket from the internal poll list if still present
235          */
236         lws_ssl_remove_wsi_from_buffered_list(wsi);
237
238         /* checking return redundant since we anyway close */
239         remove_wsi_socket_from_fds(wsi);
240
241         wsi->state = LWSS_DEAD_SOCKET;
242
243         lws_free_set_NULL(wsi->rxflow_buffer);
244
245         if (old_state == LWSS_ESTABLISHED ||
246             wsi->mode == LWSCM_WS_SERVING ||
247             wsi->mode == LWSCM_WS_CLIENT) {
248
249                 if (wsi->u.ws.rx_draining_ext) {
250                         struct lws **w = &wsi->context->rx_draining_ext_list;
251
252                         wsi->u.ws.rx_draining_ext = 0;
253                         /* remove us from context draining ext list */
254                         while (*w) {
255                                 if (*w == wsi) {
256                                         *w = wsi->u.ws.rx_draining_ext_list;
257                                         break;
258                                 }
259                                 w = &((*w)->u.ws.rx_draining_ext_list);
260                         }
261                         wsi->u.ws.rx_draining_ext_list = NULL;
262                 }
263
264                 if (wsi->u.ws.tx_draining_ext) {
265                         struct lws **w = &wsi->context->tx_draining_ext_list;
266
267                         wsi->u.ws.tx_draining_ext = 0;
268                         /* remove us from context draining ext list */
269                         while (*w) {
270                                 if (*w == wsi) {
271                                         *w = wsi->u.ws.tx_draining_ext_list;
272                                         break;
273                                 }
274                                 w = &((*w)->u.ws.tx_draining_ext_list);
275                         }
276                         wsi->u.ws.tx_draining_ext_list = NULL;
277                 }
278                 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
279
280                 if (wsi->trunc_alloc)
281                         /* not going to be completed... nuke it */
282                         lws_free_set_NULL(wsi->trunc_alloc);
283
284                 wsi->u.ws.ping_payload_len = 0;
285                 wsi->u.ws.ping_pending_flag = 0;
286         }
287
288         /* tell the user it's all over for this guy */
289
290         if (wsi->protocol && wsi->protocol->callback &&
291             ((old_state == LWSS_ESTABLISHED) ||
292             (old_state == LWSS_RETURNED_CLOSE_ALREADY) ||
293             (old_state == LWSS_AWAITING_CLOSE_ACK) ||
294             (old_state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE))) {
295                 lwsl_debug("calling back CLOSED\n");
296                 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
297                                         wsi->user_space, NULL, 0);
298         } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
299                 lwsl_debug("calling back CLOSED_HTTP\n");
300                 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
301                                                wsi->user_space, NULL, 0 );
302         } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
303                    wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
304                 lwsl_debug("Connection closed before server reply\n");
305                 context->protocols[0].callback(wsi,
306                                         LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
307                                         wsi->user_space, NULL, 0);
308         } else
309                 lwsl_debug("not calling back closed mode=%d state=%d\n",
310                            wsi->mode, old_state);
311
312         /* deallocate any active extension contexts */
313
314         if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
315                 lwsl_warn("extension destruction failed\n");
316         /*
317          * inform all extensions in case they tracked this guy out of band
318          * even though not active on him specifically
319          */
320         if (lws_ext_cb_all_exts(context, wsi,
321                        LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
322                 lwsl_warn("ext destroy wsi failed\n");
323
324         if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
325 #if LWS_POSIX
326                 n = shutdown(wsi->sock, SHUT_RDWR);
327                 if (n)
328                         lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
329
330                 n = compatible_close(wsi->sock);
331                 if (n)
332                         lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
333
334 #else
335                 compatible_close(wsi->sock);
336 #endif
337                 wsi->sock = LWS_SOCK_INVALID;
338         }
339
340         /* outermost destroy notification for wsi (user_space still intact) */
341         context->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
342                                        wsi->user_space, NULL, 0);
343
344         lws_free_wsi(wsi);
345 }
346
347 LWS_VISIBLE int
348 lws_get_addresses(struct lws_context *context, void *ads, char *name,
349                   int name_len, char *rip, int rip_len)
350 {
351 #if LWS_POSIX
352         struct addrinfo ai, *res;
353         struct sockaddr_in addr4;
354
355         if (rip)
356                 rip[0] = '\0';
357         name[0] = '\0';
358         addr4.sin_family = AF_UNSPEC;
359
360 #ifdef LWS_USE_IPV6
361         if (LWS_IPV6_ENABLED(context)) {
362                 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
363                         lwsl_err("inet_ntop", strerror(LWS_ERRNO));
364                         return -1;
365                 }
366
367                 // Strip off the IPv4 to IPv6 header if one exists
368                 if (strncmp(rip, "::ffff:", 7) == 0)
369                         memmove(rip, rip + 7, strlen(rip) - 6);
370
371                 getnameinfo((struct sockaddr *)ads,
372                                 sizeof(struct sockaddr_in6), name,
373                                                         name_len, NULL, 0, 0);
374
375                 return 0;
376         } else
377 #endif
378         {
379                 struct addrinfo *result;
380
381                 memset(&ai, 0, sizeof ai);
382                 ai.ai_family = PF_UNSPEC;
383                 ai.ai_socktype = SOCK_STREAM;
384                 ai.ai_flags = AI_CANONNAME;
385
386                 if (getnameinfo((struct sockaddr *)ads,
387                                 sizeof(struct sockaddr_in),
388                                 name, name_len, NULL, 0, 0))
389                         return -1;
390
391                 if (!rip)
392                         return 0;
393
394                 if (getaddrinfo(name, NULL, &ai, &result))
395                         return -1;
396
397                 res = result;
398                 while (addr4.sin_family == AF_UNSPEC && res) {
399                         switch (res->ai_family) {
400                         case AF_INET:
401                                 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
402                                 addr4.sin_family = AF_INET;
403                                 break;
404                         }
405
406                         res = res->ai_next;
407                 }
408                 freeaddrinfo(result);
409         }
410
411         if (addr4.sin_family == AF_UNSPEC)
412                 return -1;
413
414         lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len);
415
416         return 0;
417 #else
418         (void)context;
419         (void)ads;
420         (void)name;
421         (void)name_len;
422         (void)rip;
423         (void)rip_len;
424
425         return -1;
426 #endif
427 }
428
429 /**
430  * lws_get_peer_addresses() - Get client address information
431  * @wsi:        Local struct lws associated with
432  * @fd:         Connection socket descriptor
433  * @name:       Buffer to take client address name
434  * @name_len:   Length of client address name buffer
435  * @rip:        Buffer to take client address IP dotted quad
436  * @rip_len:    Length of client address IP buffer
437  *
438  *      This function fills in @name and @rip with the name and IP of
439  *      the client connected with socket descriptor @fd.  Names may be
440  *      truncated if there is not enough room.  If either cannot be
441  *      determined, they will be returned as valid zero-length strings.
442  */
443
444 LWS_VISIBLE void
445 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
446                        int name_len, char *rip, int rip_len)
447 {
448 #if LWS_POSIX
449         socklen_t len;
450 #ifdef LWS_USE_IPV6
451         struct sockaddr_in6 sin6;
452 #endif
453         struct sockaddr_in sin4;
454         struct lws_context *context = wsi->context;
455         int ret = -1;
456         void *p;
457
458         rip[0] = '\0';
459         name[0] = '\0';
460
461         lws_latency_pre(context, wsi);
462
463 #ifdef LWS_USE_IPV6
464         if (LWS_IPV6_ENABLED(context)) {
465                 len = sizeof(sin6);
466                 p = &sin6;
467         } else
468 #endif
469         {
470                 len = sizeof(sin4);
471                 p = &sin4;
472         }
473
474         if (getpeername(fd, p, &len) < 0) {
475                 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
476                 goto bail;
477         }
478
479         ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
480
481 bail:
482         lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
483 #else
484         (void)wsi;
485         (void)fd;
486         (void)name;
487         (void)name_len;
488         (void)rip;
489         (void)rip_len;
490 #endif
491 }
492
493 /**
494  * lws_context_user() - get the user data associated with the context
495  * @context: Websocket context
496  *
497  *      This returns the optional user allocation that can be attached to
498  *      the context the sockets live in at context_create time.  It's a way
499  *      to let all sockets serviced in the same context share data without
500  *      using globals statics in the user code.
501  */
502 LWS_EXTERN void *
503 lws_context_user(struct lws_context *context)
504 {
505         return context->user_space;
506 }
507
508
509 /**
510  * lws_callback_all_protocol() - Callback all connections using
511  *                              the given protocol with the given reason
512  *
513  * @protocol:   Protocol whose connections will get callbacks
514  * @reason:     Callback reason index
515  */
516
517 LWS_VISIBLE int
518 lws_callback_all_protocol(struct lws_context *context,
519                           const struct lws_protocols *protocol, int reason)
520 {
521         struct lws *wsi;
522         int n;
523
524         for (n = 0; n < context->fds_count; n++) {
525                 wsi = wsi_from_fd(context, context->fds[n].fd);
526                 if (!wsi)
527                         continue;
528                 if (wsi->protocol == protocol)
529                         protocol->callback(wsi, reason, wsi->user_space, NULL, 0);
530         }
531
532         return 0;
533 }
534
535 /**
536  * lws_set_timeout() - marks the wsi as subject to a timeout
537  *
538  * You will not need this unless you are doing something special
539  *
540  * @wsi:        Websocket connection instance
541  * @reason:     timeout reason
542  * @secs:       how many seconds
543  */
544
545 LWS_VISIBLE void
546 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
547 {
548         time_t now;
549
550         time(&now);
551
552         wsi->pending_timeout_limit = now + secs;
553         wsi->pending_timeout = reason;
554 }
555
556
557 #if LWS_POSIX
558
559 /**
560  * lws_get_socket_fd() - returns the socket file descriptor
561  *
562  * You will not need this unless you are doing something special
563  *
564  * @wsi:        Websocket connection instance
565  */
566
567 LWS_VISIBLE int
568 lws_get_socket_fd(struct lws *wsi)
569 {
570         return wsi->sock;
571 }
572
573 #endif
574
575 #ifdef LWS_LATENCY
576 void
577 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
578             int ret, int completed)
579 {
580         unsigned long long u;
581         char buf[256];
582
583         u = time_in_microseconds();
584
585         if (!action) {
586                 wsi->latency_start = u;
587                 if (!wsi->action_start)
588                         wsi->action_start = u;
589                 return;
590         }
591         if (completed) {
592                 if (wsi->action_start == wsi->latency_start)
593                         sprintf(buf,
594                           "Completion first try lat %lluus: %p: ret %d: %s\n",
595                                         u - wsi->latency_start,
596                                                       (void *)wsi, ret, action);
597                 else
598                         sprintf(buf,
599                           "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
600                                 u - wsi->action_start,
601                                         u - wsi->latency_start,
602                                                       (void *)wsi, ret, action);
603                 wsi->action_start = 0;
604         } else
605                 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
606                               u - wsi->latency_start, (void *)wsi, ret, action);
607
608         if (u - wsi->latency_start > context->worst_latency) {
609                 context->worst_latency = u - wsi->latency_start;
610                 strcpy(context->worst_latency_info, buf);
611         }
612         lwsl_latency("%s", buf);
613 }
614 #endif
615
616
617
618 /**
619  * lws_rx_flow_control() - Enable and disable socket servicing for
620  *                              received packets.
621  *
622  * If the output side of a server process becomes choked, this allows flow
623  * control for the input side.
624  *
625  * @wsi:        Websocket connection instance to get callback for
626  * @enable:     0 = disable read servicing for this connection, 1 = enable
627  */
628
629 LWS_VISIBLE int
630 lws_rx_flow_control(struct lws *wsi, int enable)
631 {
632         if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
633                 return 0;
634
635         lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
636         wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
637
638         return 0;
639 }
640
641 /**
642  * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
643  *
644  * When the user server code realizes it can accept more input, it can
645  * call this to have the RX flow restriction removed from all connections using
646  * the given protocol.
647  *
648  * @protocol:   all connections using this protocol will be allowed to receive
649  */
650
651 LWS_VISIBLE void
652 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
653                                const struct lws_protocols *protocol)
654 {
655         int n;
656         struct lws *wsi;
657
658         for (n = 0; n < context->fds_count; n++) {
659                 wsi = wsi_from_fd(context, context->fds[n].fd);
660                 if (!wsi)
661                         continue;
662                 if (wsi->protocol == protocol)
663                         lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
664         }
665 }
666
667
668 /**
669  * lws_canonical_hostname() - returns this host's hostname
670  *
671  * This is typically used by client code to fill in the host parameter
672  * when making a client connection.  You can only call it after the context
673  * has been created.
674  *
675  * @context:    Websocket context
676  */
677 LWS_VISIBLE extern const char *
678 lws_canonical_hostname(struct lws_context *context)
679 {
680         return (const char *)context->canonical_hostname;
681 }
682
683 int user_callback_handle_rxflow(lws_callback_function callback_function,
684                                 struct lws *wsi,
685                                 enum lws_callback_reasons reason, void *user,
686                                 void *in, size_t len)
687 {
688         int n;
689
690         n = callback_function(wsi, reason, user, in, len);
691         if (!n)
692                 n = _lws_rx_flow_control(wsi);
693
694         return n;
695 }
696
697
698 /**
699  * lws_set_proxy() - Setups proxy to lws_context.
700  * @context:    pointer to struct lws_context you want set proxy to
701  * @proxy: pointer to c string containing proxy in format address:port
702  *
703  * Returns 0 if proxy string was parsed and proxy was setup.
704  * Returns -1 if @proxy is NULL or has incorrect format.
705  *
706  * This is only required if your OS does not provide the http_proxy
707  * environment variable (eg, OSX)
708  *
709  *   IMPORTANT! You should call this function right after creation of the
710  *   lws_context and before call to connect. If you call this
711  *   function after connect behavior is undefined.
712  *   This function will override proxy settings made on lws_context
713  *   creation with genenv() call.
714  */
715
716 LWS_VISIBLE int
717 lws_set_proxy(struct lws_context *context, const char *proxy)
718 {
719         char *p;
720         char authstring[96];
721
722         if (!proxy)
723                 return -1;
724
725         p = strchr(proxy, '@');
726         if (p) { /* auth is around */
727
728                 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
729                         goto auth_too_long;
730
731                 strncpy(authstring, proxy, p - proxy);
732                 // null termination not needed on input
733                 if (lws_b64_encode_string(authstring, (p - proxy),
734                     context->proxy_basic_auth_token,
735                     sizeof context->proxy_basic_auth_token) < 0)
736                         goto auth_too_long;
737
738                 lwsl_notice(" Proxy auth in use\n");
739
740                 proxy = p + 1;
741         } else
742                 context->proxy_basic_auth_token[0] = '\0';
743
744         strncpy(context->http_proxy_address, proxy,
745                                 sizeof(context->http_proxy_address) - 1);
746         context->http_proxy_address[
747                                 sizeof(context->http_proxy_address) - 1] = '\0';
748
749         p = strchr(context->http_proxy_address, ':');
750         if (!p && !context->http_proxy_port) {
751                 lwsl_err("http_proxy needs to be ads:port\n");
752
753                 return -1;
754         } else {
755                 if (p) {
756                         *p = '\0';
757                         context->http_proxy_port = atoi(p + 1);
758                 }
759         }
760
761         lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
762                                                 context->http_proxy_port);
763
764         return 0;
765
766 auth_too_long:
767         lwsl_err("proxy auth too long\n");
768
769         return -1;
770 }
771
772 /**
773  * lws_get_protocol() - Returns a protocol pointer from a websocket
774  *                                connection.
775  * @wsi:        pointer to struct websocket you want to know the protocol of
776  *
777  *
778  *      Some apis can act on all live connections of a given protocol,
779  *      this is how you can get a pointer to the active protocol if needed.
780  */
781
782 LWS_VISIBLE const struct lws_protocols *
783 lws_get_protocol(struct lws *wsi)
784 {
785         return wsi->protocol;
786 }
787
788 LWS_VISIBLE int
789 lws_is_final_fragment(struct lws *wsi)
790 {
791         lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
792                         wsi->u.ws.final, wsi->u.ws.rx_packet_length, wsi->u.ws.rx_draining_ext);
793         return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
794 }
795
796 LWS_VISIBLE unsigned char
797 lws_get_reserved_bits(struct lws *wsi)
798 {
799         return wsi->u.ws.rsv;
800 }
801
802 int
803 lws_ensure_user_space(struct lws *wsi)
804 {
805         lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
806         if (!wsi->protocol)
807                 return 1;
808
809         /* allocate the per-connection user memory (if any) */
810
811         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
812                 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
813                 if (wsi->user_space  == NULL) {
814                         lwsl_err("Out of memory for conn user space\n");
815                         return 1;
816                 }
817         } else
818                 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
819                           __func__, wsi, wsi->protocol->per_session_data_size,
820                           wsi->user_space);
821         return 0;
822 }
823
824 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
825 {
826         unsigned long long now;
827         char buf[300];
828         int n;
829
830         buf[0] = '\0';
831         for (n = 0; n < LLL_COUNT; n++) {
832                 if (level != (1 << n))
833                         continue;
834                 now = time_in_microseconds() / 100;
835                 sprintf(buf, "[%llu:%04d] %s: ",
836                         (unsigned long long) now / 10000,
837                         (int)(now % 10000), log_level_names[n]);
838                 break;
839         }
840
841         fprintf(stderr, "%s%s", buf, line);
842 }
843
844 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
845 {
846         char buf[256];
847
848         if (!(log_level & filter))
849                 return;
850
851         vsnprintf(buf, sizeof(buf), format, vl);
852         buf[sizeof(buf) - 1] = '\0';
853
854         lwsl_emit(filter, buf);
855 }
856
857 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
858 {
859         va_list ap;
860
861         va_start(ap, format);
862         _lws_logv(filter, format, ap);
863         va_end(ap);
864 }
865
866 /**
867  * lws_set_log_level() - Set the logging bitfield
868  * @level:      OR together the LLL_ debug contexts you want output from
869  * @log_emit_function:  NULL to leave it as it is, or a user-supplied
870  *                      function to perform log string emission instead of
871  *                      the default stderr one.
872  *
873  *      log level defaults to "err", "warn" and "notice" contexts enabled and
874  *      emission on stderr.
875  */
876
877 LWS_VISIBLE void lws_set_log_level(int level,
878                                    void (*func)(int level, const char *line))
879 {
880         log_level = level;
881         if (func)
882                 lwsl_emit = func;
883 }
884
885 /**
886  * lws_use_ssl() - Find out if connection is using SSL
887  * @wsi:        websocket connection to check
888  *
889  *      Returns 0 if the connection is not using SSL, 1 if using SSL and
890  *      using verified cert, and 2 if using SSL but the cert was not
891  *      checked (appears for client wsi told to skip check on connection)
892  */
893 LWS_VISIBLE int
894 lws_is_ssl(struct lws *wsi)
895 {
896 #ifdef LWS_OPENSSL_SUPPORT
897         return wsi->use_ssl;
898 #else
899         (void)wsi;
900         return 0;
901 #endif
902 }
903
904 /**
905  * lws_partial_buffered() - find out if lws buffered the last write
906  * @wsi:        websocket connection to check
907  *
908  * Returns 1 if you cannot use lws_write because the last
909  * write on this connection is still buffered, and can't be cleared without
910  * returning to the service loop and waiting for the connection to be
911  * writeable again.
912  *
913  * If you will try to do >1 lws_write call inside a single
914  * WRITEABLE callback, you must check this after every write and bail if
915  * set, ask for a new writeable callback and continue writing from there.
916  *
917  * This is never set at the start of a writeable callback, but any write
918  * may set it.
919  */
920
921 LWS_VISIBLE int
922 lws_partial_buffered(struct lws *wsi)
923 {
924         return !!wsi->trunc_len;
925 }
926
927 void lws_set_protocol_write_pending(struct lws *wsi,
928                                     enum lws_pending_protocol_send pend)
929 {
930         lwsl_info("setting pps %d\n", pend);
931
932         if (wsi->pps)
933                 lwsl_err("pps overwrite\n");
934         wsi->pps = pend;
935         lws_rx_flow_control(wsi, 0);
936         lws_callback_on_writable(wsi);
937 }
938
939 LWS_VISIBLE size_t
940 lws_get_peer_write_allowance(struct lws *wsi)
941 {
942 #ifdef LWS_USE_HTTP2
943         /* only if we are using HTTP2 on this connection */
944         if (wsi->mode != LWSCM_HTTP2_SERVING)
945                 return -1;
946         /* user is only interested in how much he can send, or that he can't  */
947         if (wsi->u.http2.tx_credit <= 0)
948                 return 0;
949
950         return wsi->u.http2.tx_credit;
951 #else
952         (void)wsi;
953         return -1;
954 #endif
955 }
956
957 LWS_VISIBLE void
958 lws_union_transition(struct lws *wsi, enum connection_mode mode)
959 {
960         lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
961         memset(&wsi->u, 0, sizeof(wsi->u));
962         wsi->mode = mode;
963 }
964
965 LWS_VISIBLE struct lws_plat_file_ops *
966 lws_get_fops(struct lws_context *context)
967 {
968         return &context->fops;
969 }
970
971 LWS_VISIBLE LWS_EXTERN struct lws_context *
972 lws_get_context(const struct lws *wsi)
973 {
974         return wsi->context;
975 }
976
977 LWS_VISIBLE LWS_EXTERN void *
978 lws_wsi_user(struct lws *wsi)
979 {
980         return wsi->user_space;
981 }
982
983 LWS_VISIBLE LWS_EXTERN void
984 lws_close_reason(struct lws *wsi, enum lws_close_status status,
985                  unsigned char *buf, size_t len)
986 {
987         unsigned char *p, *start;
988         int budget = sizeof(wsi->u.ws.ping_payload_buf) -
989                      LWS_PRE;
990
991         assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
992
993         start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
994
995         *p++ = (((int)status) >> 8) & 0xff;
996         *p++ = ((int)status) & 0xff;
997
998         if (buf)
999                 while (len-- && p < start + budget)
1000                         *p++ = *buf++;
1001
1002         wsi->u.ws.close_in_ping_buffer_len = p - start;
1003 }
1004
1005 LWS_EXTERN int
1006 _lws_rx_flow_control(struct lws *wsi)
1007 {
1008         /* there is no pending change */
1009         if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1010                 lwsl_info("%s: no pending change\n", __func__);
1011                 return 0;
1012         }
1013
1014         /* stuff is still buffered, not ready to really accept new input */
1015         if (wsi->rxflow_buffer) {
1016                 /* get ourselves called back to deal with stashed buffer */
1017                 lws_callback_on_writable(wsi);
1018                 return 0;
1019         }
1020
1021         /* pending is cleared, we can change rxflow state */
1022
1023         wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1024
1025         lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1026                               wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1027
1028         /* adjust the pollfd for this wsi */
1029
1030         if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1031                 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1032                         lwsl_info("%s: fail\n", __func__);
1033                         return -1;
1034                 }
1035         } else
1036                 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1037                         return -1;
1038
1039         return 0;
1040 }
1041
1042 LWS_EXTERN int
1043 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1044 {
1045         static const unsigned char e0f4[] = {
1046                 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1047                 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1048                 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1049                 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1050                 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1051                 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1052                 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1053                 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1054                 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1055                 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1056                 0x80 | ((4 - 1) << 2) | 1, /* ea */
1057                 0x80 | ((4 - 1) << 2) | 1, /* eb */
1058                 0x80 | ((4 - 1) << 2) | 1, /* ec */
1059                 0x80 | ((2 - 1) << 2) | 1, /* ed */
1060                 0x80 | ((4 - 1) << 2) | 1, /* ee */
1061                 0x80 | ((4 - 1) << 2) | 1, /* ef */
1062                 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1063                 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1064                 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1065                 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1066                 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1067
1068                 0,                         /* s0 */
1069                 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1070                 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1071         };
1072         unsigned char s = *state;
1073
1074         while (len--) {
1075                 unsigned char c = *buf++;
1076
1077                 if (!s) {
1078                         if (c >= 0x80) {
1079                                 if (c < 0xc2 || c > 0xf4)
1080                                         return 1;
1081                                 if (c < 0xe0)
1082                                         s = 0x80 | ((4 - 1) << 2);
1083                                 else
1084                                         s = e0f4[c - 0xe0];
1085                         }
1086                 } else {
1087                         if (c < (s & 0xf0) ||
1088                             c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1089                                 return 1;
1090                         s = e0f4[21 + (s & 3)];
1091                 }
1092         }
1093
1094         *state = s;
1095
1096         return 0;
1097 }
1098
1099 #ifdef LWS_NO_EXTENSIONS
1100
1101 /* we need to provide dummy callbacks for internal exts
1102  * so user code runs when faced with a lib compiled with
1103  * extensions disabled.
1104  */
1105
1106 int
1107 lws_extension_callback_pm_deflate(struct lws_context *context,
1108                                   const struct lws_extension *ext,
1109                                   struct lws *wsi,
1110                                   enum lws_extension_callback_reasons reason,
1111                                   void *user, void *in, size_t len)
1112 {
1113         return 0;
1114 }
1115 #endif
1116