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