autobahn report final frag only on final rx bufload
[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_wsi_active_exts(wsi,
134                       LWS_EXT_CALLBACK_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_wsi_active_exts(wsi,
152                           LWS_EXT_CALLBACK_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_SEND_BUFFER_PRE_PADDING] =
197                                 (reason >> 16) & 0xff;
198                         wsi->u.ws.ping_payload_buf[LWS_SEND_BUFFER_PRE_PADDING + 1] =
199                                 reason & 0xff;
200                 }
201
202                 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[
203                                                 LWS_SEND_BUFFER_PRE_PADDING],
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\n");
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                 lws_free_set_NULL(wsi->u.ws.rx_user_buffer);
250
251                 if (wsi->trunc_alloc)
252                         /* not going to be completed... nuke it */
253                         lws_free_set_NULL(wsi->trunc_alloc);
254
255                 wsi->u.ws.ping_payload_len = 0;
256                 wsi->u.ws.ping_pending_flag = 0;
257         }
258
259         /* tell the user it's all over for this guy */
260
261         if (wsi->protocol && wsi->protocol->callback &&
262             ((old_state == LWSS_ESTABLISHED) ||
263             (old_state == LWSS_RETURNED_CLOSE_ALREADY) ||
264             (old_state == LWSS_AWAITING_CLOSE_ACK) ||
265             (old_state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE))) {
266                 lwsl_debug("calling back CLOSED\n");
267                 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
268                                         wsi->user_space, NULL, 0);
269         } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
270                 lwsl_debug("calling back CLOSED_HTTP\n");
271                 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
272                                                wsi->user_space, NULL, 0 );
273         } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
274                    wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
275                 lwsl_debug("Connection closed before server reply\n");
276                 context->protocols[0].callback(wsi,
277                                         LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
278                                         wsi->user_space, NULL, 0);
279         } else
280                 lwsl_debug("not calling back closed mode=%d state=%d\n",
281                            wsi->mode, old_state);
282
283         /* deallocate any active extension contexts */
284
285         if (lws_ext_cb_wsi_active_exts(wsi, LWS_EXT_CALLBACK_DESTROY, NULL, 0) < 0)
286                 lwsl_warn("extension destruction failed\n");
287 #ifndef LWS_NO_EXTENSIONS
288         for (n = 0; n < wsi->count_active_extensions; n++)
289                 lws_free(wsi->active_extensions_user[n]);
290 #endif
291         /*
292          * inform all extensions in case they tracked this guy out of band
293          * even though not active on him specifically
294          */
295         if (lws_ext_cb_all_exts(context, wsi,
296                        LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
297                 lwsl_warn("ext destroy wsi failed\n");
298
299         if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
300 #if LWS_POSIX
301                 n = shutdown(wsi->sock, SHUT_RDWR);
302                 if (n)
303                         lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
304
305                 n = compatible_close(wsi->sock);
306                 if (n)
307                         lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
308
309 #else
310                 compatible_close(wsi->sock);
311 #endif
312                 wsi->sock = LWS_SOCK_INVALID;
313         }
314
315         /* outermost destroy notification for wsi (user_space still intact) */
316         context->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
317                                        wsi->user_space, NULL, 0);
318
319         lws_free_wsi(wsi);
320 }
321
322 LWS_VISIBLE int
323 lws_get_addresses(struct lws_context *context, void *ads, char *name,
324                   int name_len, char *rip, int rip_len)
325 {
326 #if LWS_POSIX
327         struct addrinfo ai, *res;
328         struct sockaddr_in addr4;
329
330         if (rip)
331                 rip[0] = '\0';
332         name[0] = '\0';
333         addr4.sin_family = AF_UNSPEC;
334
335 #ifdef LWS_USE_IPV6
336         if (LWS_IPV6_ENABLED(context)) {
337                 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
338                         lwsl_err("inet_ntop", strerror(LWS_ERRNO));
339                         return -1;
340                 }
341
342                 // Strip off the IPv4 to IPv6 header if one exists
343                 if (strncmp(rip, "::ffff:", 7) == 0)
344                         memmove(rip, rip + 7, strlen(rip) - 6);
345
346                 getnameinfo((struct sockaddr *)ads,
347                                 sizeof(struct sockaddr_in6), name,
348                                                         name_len, NULL, 0, 0);
349
350                 return 0;
351         } else
352 #endif
353         {
354                 struct addrinfo *result;
355
356                 memset(&ai, 0, sizeof ai);
357                 ai.ai_family = PF_UNSPEC;
358                 ai.ai_socktype = SOCK_STREAM;
359                 ai.ai_flags = AI_CANONNAME;
360
361                 if (getnameinfo((struct sockaddr *)ads,
362                                 sizeof(struct sockaddr_in),
363                                 name, name_len, NULL, 0, 0))
364                         return -1;
365
366                 if (!rip)
367                         return 0;
368
369                 if (getaddrinfo(name, NULL, &ai, &result))
370                         return -1;
371
372                 res = result;
373                 while (addr4.sin_family == AF_UNSPEC && res) {
374                         switch (res->ai_family) {
375                         case AF_INET:
376                                 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
377                                 addr4.sin_family = AF_INET;
378                                 break;
379                         }
380
381                         res = res->ai_next;
382                 }
383                 freeaddrinfo(result);
384         }
385
386         if (addr4.sin_family == AF_UNSPEC)
387                 return -1;
388
389         lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len);
390
391         return 0;
392 #else
393         (void)context;
394         (void)ads;
395         (void)name;
396         (void)name_len;
397         (void)rip;
398         (void)rip_len;
399
400         return -1;
401 #endif
402 }
403
404 /**
405  * lws_get_peer_addresses() - Get client address information
406  * @wsi:        Local struct lws associated with
407  * @fd:         Connection socket descriptor
408  * @name:       Buffer to take client address name
409  * @name_len:   Length of client address name buffer
410  * @rip:        Buffer to take client address IP dotted quad
411  * @rip_len:    Length of client address IP buffer
412  *
413  *      This function fills in @name and @rip with the name and IP of
414  *      the client connected with socket descriptor @fd.  Names may be
415  *      truncated if there is not enough room.  If either cannot be
416  *      determined, they will be returned as valid zero-length strings.
417  */
418
419 LWS_VISIBLE void
420 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
421                        int name_len, char *rip, int rip_len)
422 {
423 #if LWS_POSIX
424         socklen_t len;
425 #ifdef LWS_USE_IPV6
426         struct sockaddr_in6 sin6;
427 #endif
428         struct sockaddr_in sin4;
429         struct lws_context *context = wsi->context;
430         int ret = -1;
431         void *p;
432
433         rip[0] = '\0';
434         name[0] = '\0';
435
436         lws_latency_pre(context, wsi);
437
438 #ifdef LWS_USE_IPV6
439         if (LWS_IPV6_ENABLED(context)) {
440                 len = sizeof(sin6);
441                 p = &sin6;
442         } else
443 #endif
444         {
445                 len = sizeof(sin4);
446                 p = &sin4;
447         }
448
449         if (getpeername(fd, p, &len) < 0) {
450                 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
451                 goto bail;
452         }
453
454         ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
455
456 bail:
457         lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
458 #else
459         (void)wsi;
460         (void)fd;
461         (void)name;
462         (void)name_len;
463         (void)rip;
464         (void)rip_len;
465 #endif
466 }
467
468 /**
469  * lws_context_user() - get the user data associated with the context
470  * @context: Websocket context
471  *
472  *      This returns the optional user allocation that can be attached to
473  *      the context the sockets live in at context_create time.  It's a way
474  *      to let all sockets serviced in the same context share data without
475  *      using globals statics in the user code.
476  */
477 LWS_EXTERN void *
478 lws_context_user(struct lws_context *context)
479 {
480         return context->user_space;
481 }
482
483
484 /**
485  * lws_callback_all_protocol() - Callback all connections using
486  *                              the given protocol with the given reason
487  *
488  * @protocol:   Protocol whose connections will get callbacks
489  * @reason:     Callback reason index
490  */
491
492 LWS_VISIBLE int
493 lws_callback_all_protocol(struct lws_context *context,
494                           const struct lws_protocols *protocol, int reason)
495 {
496         struct lws *wsi;
497         int n;
498
499         for (n = 0; n < context->fds_count; n++) {
500                 wsi = wsi_from_fd(context, context->fds[n].fd);
501                 if (!wsi)
502                         continue;
503                 if (wsi->protocol == protocol)
504                         protocol->callback(wsi, reason, wsi->user_space, NULL, 0);
505         }
506
507         return 0;
508 }
509
510 /**
511  * lws_set_timeout() - marks the wsi as subject to a timeout
512  *
513  * You will not need this unless you are doing something special
514  *
515  * @wsi:        Websocket connection instance
516  * @reason:     timeout reason
517  * @secs:       how many seconds
518  */
519
520 LWS_VISIBLE void
521 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
522 {
523         time_t now;
524
525         time(&now);
526
527         wsi->pending_timeout_limit = now + secs;
528         wsi->pending_timeout = reason;
529 }
530
531
532 #if LWS_POSIX
533
534 /**
535  * lws_get_socket_fd() - returns the socket file descriptor
536  *
537  * You will not need this unless you are doing something special
538  *
539  * @wsi:        Websocket connection instance
540  */
541
542 LWS_VISIBLE int
543 lws_get_socket_fd(struct lws *wsi)
544 {
545         return wsi->sock;
546 }
547
548 #endif
549
550 #ifdef LWS_LATENCY
551 void
552 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
553             int ret, int completed)
554 {
555         unsigned long long u;
556         char buf[256];
557
558         u = time_in_microseconds();
559
560         if (!action) {
561                 wsi->latency_start = u;
562                 if (!wsi->action_start)
563                         wsi->action_start = u;
564                 return;
565         }
566         if (completed) {
567                 if (wsi->action_start == wsi->latency_start)
568                         sprintf(buf,
569                           "Completion first try lat %lluus: %p: ret %d: %s\n",
570                                         u - wsi->latency_start,
571                                                       (void *)wsi, ret, action);
572                 else
573                         sprintf(buf,
574                           "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
575                                 u - wsi->action_start,
576                                         u - wsi->latency_start,
577                                                       (void *)wsi, ret, action);
578                 wsi->action_start = 0;
579         } else
580                 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
581                               u - wsi->latency_start, (void *)wsi, ret, action);
582
583         if (u - wsi->latency_start > context->worst_latency) {
584                 context->worst_latency = u - wsi->latency_start;
585                 strcpy(context->worst_latency_info, buf);
586         }
587         lwsl_latency("%s", buf);
588 }
589 #endif
590
591
592
593 /**
594  * lws_rx_flow_control() - Enable and disable socket servicing for
595  *                              received packets.
596  *
597  * If the output side of a server process becomes choked, this allows flow
598  * control for the input side.
599  *
600  * @wsi:        Websocket connection instance to get callback for
601  * @enable:     0 = disable read servicing for this connection, 1 = enable
602  */
603
604 LWS_VISIBLE int
605 lws_rx_flow_control(struct lws *wsi, int enable)
606 {
607         if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
608                 return 0;
609
610         lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
611         wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
612
613         return 0;
614 }
615
616 /**
617  * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
618  *
619  * When the user server code realizes it can accept more input, it can
620  * call this to have the RX flow restriction removed from all connections using
621  * the given protocol.
622  *
623  * @protocol:   all connections using this protocol will be allowed to receive
624  */
625
626 LWS_VISIBLE void
627 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
628                                const struct lws_protocols *protocol)
629 {
630         int n;
631         struct lws *wsi;
632
633         for (n = 0; n < context->fds_count; n++) {
634                 wsi = wsi_from_fd(context, context->fds[n].fd);
635                 if (!wsi)
636                         continue;
637                 if (wsi->protocol == protocol)
638                         lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
639         }
640 }
641
642
643 /**
644  * lws_canonical_hostname() - returns this host's hostname
645  *
646  * This is typically used by client code to fill in the host parameter
647  * when making a client connection.  You can only call it after the context
648  * has been created.
649  *
650  * @context:    Websocket context
651  */
652 LWS_VISIBLE extern const char *
653 lws_canonical_hostname(struct lws_context *context)
654 {
655         return (const char *)context->canonical_hostname;
656 }
657
658 int user_callback_handle_rxflow(callback_function callback_function,
659                                 struct lws *wsi,
660                                 enum lws_callback_reasons reason, void *user,
661                                 void *in, size_t len)
662 {
663         int n;
664
665         n = callback_function(wsi, reason, user, in, len);
666         if (!n)
667                 n = _lws_rx_flow_control(wsi);
668
669         return n;
670 }
671
672
673 /**
674  * lws_set_proxy() - Setups proxy to lws_context.
675  * @context:    pointer to struct lws_context you want set proxy to
676  * @proxy: pointer to c string containing proxy in format address:port
677  *
678  * Returns 0 if proxy string was parsed and proxy was setup.
679  * Returns -1 if @proxy is NULL or has incorrect format.
680  *
681  * This is only required if your OS does not provide the http_proxy
682  * environment variable (eg, OSX)
683  *
684  *   IMPORTANT! You should call this function right after creation of the
685  *   lws_context and before call to connect. If you call this
686  *   function after connect behavior is undefined.
687  *   This function will override proxy settings made on lws_context
688  *   creation with genenv() call.
689  */
690
691 LWS_VISIBLE int
692 lws_set_proxy(struct lws_context *context, const char *proxy)
693 {
694         char *p;
695         char authstring[96];
696
697         if (!proxy)
698                 return -1;
699
700         p = strchr(proxy, '@');
701         if (p) { /* auth is around */
702
703                 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
704                         goto auth_too_long;
705
706                 strncpy(authstring, proxy, p - proxy);
707                 // null termination not needed on input
708                 if (lws_b64_encode_string(authstring, (p - proxy),
709                     context->proxy_basic_auth_token,
710                     sizeof context->proxy_basic_auth_token) < 0)
711                         goto auth_too_long;
712
713                 lwsl_notice(" Proxy auth in use\n");
714
715                 proxy = p + 1;
716         } else
717                 context->proxy_basic_auth_token[0] = '\0';
718
719         strncpy(context->http_proxy_address, proxy,
720                                 sizeof(context->http_proxy_address) - 1);
721         context->http_proxy_address[
722                                 sizeof(context->http_proxy_address) - 1] = '\0';
723
724         p = strchr(context->http_proxy_address, ':');
725         if (!p && !context->http_proxy_port) {
726                 lwsl_err("http_proxy needs to be ads:port\n");
727
728                 return -1;
729         } else {
730                 if (p) {
731                         *p = '\0';
732                         context->http_proxy_port = atoi(p + 1);
733                 }
734         }
735
736         lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
737                                                 context->http_proxy_port);
738
739         return 0;
740
741 auth_too_long:
742         lwsl_err("proxy auth too long\n");
743
744         return -1;
745 }
746
747 /**
748  * lws_get_protocol() - Returns a protocol pointer from a websocket
749  *                                connection.
750  * @wsi:        pointer to struct websocket you want to know the protocol of
751  *
752  *
753  *      Some apis can act on all live connections of a given protocol,
754  *      this is how you can get a pointer to the active protocol if needed.
755  */
756
757 LWS_VISIBLE const struct lws_protocols *
758 lws_get_protocol(struct lws *wsi)
759 {
760         return wsi->protocol;
761 }
762
763 LWS_VISIBLE int
764 lws_is_final_fragment(struct lws *wsi)
765 {
766         return wsi->u.ws.final && !wsi->u.ws.rx_packet_length;
767 }
768
769 LWS_VISIBLE unsigned char
770 lws_get_reserved_bits(struct lws *wsi)
771 {
772         return wsi->u.ws.rsv;
773 }
774
775 int
776 lws_ensure_user_space(struct lws *wsi)
777 {
778         lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
779         if (!wsi->protocol)
780                 return 1;
781
782         /* allocate the per-connection user memory (if any) */
783
784         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
785                 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
786                 if (wsi->user_space  == NULL) {
787                         lwsl_err("Out of memory for conn user space\n");
788                         return 1;
789                 }
790         } else
791                 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
792                           __func__, wsi, wsi->protocol->per_session_data_size,
793                           wsi->user_space);
794         return 0;
795 }
796
797 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
798 {
799         unsigned long long now;
800         char buf[300];
801         int n;
802
803         buf[0] = '\0';
804         for (n = 0; n < LLL_COUNT; n++) {
805                 if (level != (1 << n))
806                         continue;
807                 now = time_in_microseconds() / 100;
808                 sprintf(buf, "[%llu:%04d] %s: ",
809                         (unsigned long long) now / 10000,
810                         (int)(now % 10000), log_level_names[n]);
811                 break;
812         }
813
814         fprintf(stderr, "%s%s", buf, line);
815 }
816
817 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
818 {
819         char buf[256];
820
821         if (!(log_level & filter))
822                 return;
823
824         vsnprintf(buf, sizeof(buf), format, vl);
825         buf[sizeof(buf) - 1] = '\0';
826
827         lwsl_emit(filter, buf);
828 }
829
830 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
831 {
832         va_list ap;
833
834         va_start(ap, format);
835         _lws_logv(filter, format, ap);
836         va_end(ap);
837 }
838
839 /**
840  * lws_set_log_level() - Set the logging bitfield
841  * @level:      OR together the LLL_ debug contexts you want output from
842  * @log_emit_function:  NULL to leave it as it is, or a user-supplied
843  *                      function to perform log string emission instead of
844  *                      the default stderr one.
845  *
846  *      log level defaults to "err", "warn" and "notice" contexts enabled and
847  *      emission on stderr.
848  */
849
850 LWS_VISIBLE void lws_set_log_level(int level,
851                                    void (*func)(int level, const char *line))
852 {
853         log_level = level;
854         if (func)
855                 lwsl_emit = func;
856 }
857
858 /**
859  * lws_use_ssl() - Find out if connection is using SSL
860  * @wsi:        websocket connection to check
861  *
862  *      Returns 0 if the connection is not using SSL, 1 if using SSL and
863  *      using verified cert, and 2 if using SSL but the cert was not
864  *      checked (appears for client wsi told to skip check on connection)
865  */
866 LWS_VISIBLE int
867 lws_is_ssl(struct lws *wsi)
868 {
869 #ifdef LWS_OPENSSL_SUPPORT
870         return wsi->use_ssl;
871 #else
872         (void)wsi;
873         return 0;
874 #endif
875 }
876
877 /**
878  * lws_partial_buffered() - find out if lws buffered the last write
879  * @wsi:        websocket connection to check
880  *
881  * Returns 1 if you cannot use lws_write because the last
882  * write on this connection is still buffered, and can't be cleared without
883  * returning to the service loop and waiting for the connection to be
884  * writeable again.
885  *
886  * If you will try to do >1 lws_write call inside a single
887  * WRITEABLE callback, you must check this after every write and bail if
888  * set, ask for a new writeable callback and continue writing from there.
889  *
890  * This is never set at the start of a writeable callback, but any write
891  * may set it.
892  */
893
894 LWS_VISIBLE int
895 lws_partial_buffered(struct lws *wsi)
896 {
897         return !!wsi->trunc_len;
898 }
899
900 void lws_set_protocol_write_pending(struct lws *wsi,
901                                     enum lws_pending_protocol_send pend)
902 {
903         lwsl_info("setting pps %d\n", pend);
904
905         if (wsi->pps)
906                 lwsl_err("pps overwrite\n");
907         wsi->pps = pend;
908         lws_rx_flow_control(wsi, 0);
909         lws_callback_on_writable(wsi);
910 }
911
912 LWS_VISIBLE size_t
913 lws_get_peer_write_allowance(struct lws *wsi)
914 {
915 #ifdef LWS_USE_HTTP2
916         /* only if we are using HTTP2 on this connection */
917         if (wsi->mode != LWSCM_HTTP2_SERVING)
918                 return -1;
919         /* user is only interested in how much he can send, or that he can't  */
920         if (wsi->u.http2.tx_credit <= 0)
921                 return 0;
922
923         return wsi->u.http2.tx_credit;
924 #else
925         (void)wsi;
926         return -1;
927 #endif
928 }
929
930 LWS_VISIBLE void
931 lws_union_transition(struct lws *wsi, enum connection_mode mode)
932 {
933         lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
934         memset(&wsi->u, 0, sizeof(wsi->u));
935         wsi->mode = mode;
936 }
937
938 LWS_VISIBLE struct lws_plat_file_ops *
939 lws_get_fops(struct lws_context *context)
940 {
941         return &context->fops;
942 }
943
944 LWS_VISIBLE LWS_EXTERN struct lws_context *
945 lws_get_context(const struct lws *wsi)
946 {
947         return wsi->context;
948 }
949
950 LWS_VISIBLE LWS_EXTERN void *
951 lws_wsi_user(struct lws *wsi)
952 {
953         return wsi->user_space;
954 }
955
956 LWS_VISIBLE LWS_EXTERN void
957 lws_close_reason(struct lws *wsi, enum lws_close_status status,
958                  unsigned char *buf, size_t len)
959 {
960         unsigned char *p, *start;
961         int budget = sizeof(wsi->u.ws.ping_payload_buf) -
962                      LWS_SEND_BUFFER_PRE_PADDING;
963
964         assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
965
966         start = p = &wsi->u.ws.ping_payload_buf[LWS_SEND_BUFFER_PRE_PADDING];
967
968         *p++ = (((int)status) >> 8) & 0xff;
969         *p++ = ((int)status) & 0xff;
970
971         if (buf)
972                 while (len-- && p < start + budget)
973                         *p++ = *buf++;
974
975         wsi->u.ws.close_in_ping_buffer_len = p - start;
976 }