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