cleanups after api changes and mbed update
[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_free2(wsi->rxflow_buffer);
54         lws_free2(wsi->truncated_send_malloc);
55         lws_free_header_table(wsi);
56         lws_free(wsi);
57 }
58
59 void
60 lws_close_and_free_session(struct lws_context *context,
61                            struct lws *wsi, enum lws_close_status reason)
62 {
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 == LWS_CONNMODE_HTTP_SERVING_ACCEPTED &&
74             wsi->u.http.fd != LWS_INVALID_FILE) {
75                 lwsl_debug("closing http file\n");
76                 compatible_file_close(wsi->u.http.fd);
77                 wsi->u.http.fd = LWS_INVALID_FILE;
78                 context->protocols[0].callback(context, wsi,
79                         LWS_CALLBACK_CLOSED_HTTP, 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 WSI_STATE_DEAD_SOCKET:
87                 return;
88
89         /* we tried the polite way... */
90         case WSI_STATE_AWAITING_CLOSE_ACK:
91                 goto just_kill_connection;
92
93         case WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE:
94                 if (wsi->truncated_send_len) {
95                         lws_callback_on_writable(context, wsi);
96                         return;
97                 }
98                 lwsl_info("wsi %p completed WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
99                 goto just_kill_connection;
100         default:
101                 if (wsi->truncated_send_len) {
102                         lwsl_info("wsi %p entering WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
103                         wsi->state = WSI_STATE_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 == LWS_CONNMODE_WS_CLIENT_WAITING_CONNECT ||
113             wsi->mode == LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE)
114                 goto just_kill_connection;
115
116         if (wsi->mode == LWS_CONNMODE_HTTP_SERVING)
117                 context->protocols[0].callback(context, wsi,
118                         LWS_CALLBACK_CLOSED_HTTP, 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_callback_for_each_active(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_callback_for_each_active(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          * WSI_STATE_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          * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
177          */
178
179         if (old_state == WSI_STATE_ESTABLISHED &&
180             reason != LWS_CLOSE_STATUS_NOSTATUS &&
181             reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY) {
182
183                 lwsl_debug("sending close indication...\n");
184
185                 /* make valgrind happy */
186                 memset(buf, 0, sizeof(buf));
187                 n = lws_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING + 2],
188                               0, LWS_WRITE_CLOSE);
189                 if (n >= 0) {
190                         /*
191                          * we have sent a nice protocol level indication we
192                          * now wish to close, we should not send anything more
193                          */
194                         wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
195
196                         /*
197                          * ...and we should wait for a reply for a bit
198                          * out of politeness
199                          */
200                         lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
201                         lwsl_debug("sent close indication, awaiting ack\n");
202
203                         return;
204                 }
205
206                 lwsl_info("close: sending close packet failed, hanging up\n");
207
208                 /* else, the send failed and we should just hang up */
209         }
210
211 just_kill_connection:
212
213         lwsl_debug("close: just_kill_connection\n");
214
215         /*
216          * we won't be servicing or receiving anything further from this guy
217          * delete socket from the internal poll list if still present
218          */
219         lws_ssl_remove_wsi_from_buffered_list(context, wsi);
220
221         /* checking return redundant since we anyway close */
222         remove_wsi_socket_from_fds(context, wsi);
223
224         wsi->state = WSI_STATE_DEAD_SOCKET;
225
226         lws_free2(wsi->rxflow_buffer);
227         lws_free_header_table(wsi);
228
229         if ((old_state == WSI_STATE_ESTABLISHED ||
230              wsi->mode == LWS_CONNMODE_WS_SERVING ||
231              wsi->mode == LWS_CONNMODE_WS_CLIENT)) {
232
233                 lws_free2(wsi->u.ws.rx_user_buffer);
234
235                 if (wsi->truncated_send_malloc)
236                         /* not going to be completed... nuke it */
237                         lws_free2(wsi->truncated_send_malloc);
238
239                 if (wsi->u.ws.ping_payload_buf) {
240                         lws_free2(wsi->u.ws.ping_payload_buf);
241                         wsi->u.ws.ping_payload_alloc = 0;
242                         wsi->u.ws.ping_payload_len = 0;
243                         wsi->u.ws.ping_pending_flag = 0;
244                 }
245         }
246
247         /* tell the user it's all over for this guy */
248
249         if (wsi->protocol && wsi->protocol->callback &&
250             ((old_state == WSI_STATE_ESTABLISHED) ||
251             (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
252             (old_state == WSI_STATE_AWAITING_CLOSE_ACK) ||
253             (old_state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE))) {
254                 lwsl_debug("calling back CLOSED\n");
255                 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
256                                         wsi->user_space, NULL, 0);
257         } else if (wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED) {
258                 lwsl_debug("calling back CLOSED_HTTP\n");
259                 context->protocols[0].callback(context, wsi,
260                         LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0 );
261         } else if (wsi->mode == LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY ||
262                    wsi->mode == LWS_CONNMODE_WS_CLIENT_WAITING_CONNECT) {
263                 lwsl_debug("Connection closed before server reply\n");
264                 context->protocols[0].callback(context, wsi,
265                                         LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
266                                         wsi->user_space, NULL, 0);
267         } else
268                 lwsl_debug("not calling back closed mode=%d state=%d\n",
269                            wsi->mode, old_state);
270
271         /* deallocate any active extension contexts */
272         
273         if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_DESTROY,
274                                              NULL, 0) < 0)
275                 lwsl_warn("extension destruction failed\n");
276 #ifndef LWS_NO_EXTENSIONS
277         for (n = 0; n < wsi->count_active_extensions; n++)
278                 lws_free(wsi->active_extensions_user[n]);
279 #endif
280         /*
281          * inform all extensions in case they tracked this guy out of band
282          * even though not active on him specifically
283          */
284         if (lws_ext_callback_for_each_extension_type(context, wsi,
285                        LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
286                 lwsl_warn("ext destroy wsi failed\n");
287
288         if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
289 #if LWS_POSIX
290                 n = shutdown(wsi->sock, SHUT_RDWR);
291                 if (n)
292                         lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
293
294                 n = compatible_close(wsi->sock);
295                 if (n)
296                         lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
297
298 #else
299                 compatible_close(wsi->sock);
300 #endif
301                 wsi->sock = LWS_SOCK_INVALID;
302         }
303
304         /* outermost destroy notification for wsi (user_space still intact) */
305         context->protocols[0].callback(context, wsi, LWS_CALLBACK_WSI_DESTROY,
306                                        wsi->user_space, NULL, 0);
307
308         lws_free_wsi(wsi);
309 }
310
311 LWS_VISIBLE int
312 lws_get_addresses(struct lws_context *context, void *ads, char *name,
313                   int name_len, char *rip, int rip_len)
314 {
315 #if LWS_POSIX
316         struct addrinfo ai, *res;
317         struct sockaddr_in addr4;
318
319         rip[0] = '\0';
320         name[0] = '\0';
321         addr4.sin_family = AF_UNSPEC;
322
323 #ifdef LWS_USE_IPV6
324         if (LWS_IPV6_ENABLED(context)) {
325                 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
326                         lwsl_err("inet_ntop", strerror(LWS_ERRNO));
327                         return -1;
328                 }
329
330                 // Strip off the IPv4 to IPv6 header if one exists
331                 if (strncmp(rip, "::ffff:", 7) == 0)
332                         memmove(rip, rip + 7, strlen(rip) - 6);
333
334                 getnameinfo((struct sockaddr *)ads,
335                                 sizeof(struct sockaddr_in6), name,
336                                                         name_len, NULL, 0, 0);
337                 
338                 return 0;
339         } else
340 #endif
341         {
342                 struct addrinfo *result;
343
344                 memset(&ai, 0, sizeof ai);
345                 ai.ai_family = PF_UNSPEC;
346                 ai.ai_socktype = SOCK_STREAM;
347                 ai.ai_flags = AI_CANONNAME;
348
349                 if (getnameinfo((struct sockaddr *)ads,
350                                 sizeof(struct sockaddr_in),
351                                 name, name_len, NULL, 0, 0))
352                         return -1;
353
354                 if (!rip)
355                         return 0;
356
357                 if (getaddrinfo(name, NULL, &ai, &result))
358                         return -1;
359
360                 res = result;
361                 while (addr4.sin_family == AF_UNSPEC && res) {
362                         switch (res->ai_family) {
363                         case AF_INET:
364                                 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
365                                 addr4.sin_family = AF_INET;
366                                 break;
367                         }
368
369                         res = res->ai_next;
370                 }
371                 freeaddrinfo(result);
372         }
373
374         if (addr4.sin_family == AF_UNSPEC)
375                 return -1;
376
377         lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len);
378
379         return 0;
380 #else
381         (void)context;
382         (void)ads;
383         (void)name;
384         (void)name_len;
385         (void)rip;
386         (void)rip_len;
387
388         return -1;
389 #endif
390 }
391
392 /**
393  * lws_get_peer_addresses() - Get client address information
394  * @context:    Libwebsockets context
395  * @wsi:        Local struct lws associated with
396  * @fd:         Connection socket descriptor
397  * @name:       Buffer to take client address name
398  * @name_len:   Length of client address name buffer
399  * @rip:        Buffer to take client address IP dotted quad
400  * @rip_len:    Length of client address IP buffer
401  *
402  *      This function fills in @name and @rip with the name and IP of
403  *      the client connected with socket descriptor @fd.  Names may be
404  *      truncated if there is not enough room.  If either cannot be
405  *      determined, they will be returned as valid zero-length strings.
406  */
407
408 LWS_VISIBLE void
409 lws_get_peer_addresses(struct lws_context *context, struct lws *wsi,
410                        lws_sockfd_type fd, char *name, int name_len,
411                        char *rip, int rip_len)
412 {
413 #if LWS_POSIX
414         socklen_t len;
415 #ifdef LWS_USE_IPV6
416         struct sockaddr_in6 sin6;
417 #endif
418         struct sockaddr_in sin4;
419         int ret = -1;
420         void *p;
421
422         rip[0] = '\0';
423         name[0] = '\0';
424
425         lws_latency_pre(context, wsi);
426
427 #ifdef LWS_USE_IPV6
428         if (LWS_IPV6_ENABLED(context)) {
429                 len = sizeof(sin6);
430                 p = &sin6;
431         } else
432 #endif
433         {
434                 len = sizeof(sin4);
435                 p = &sin4;
436         }
437
438         if (getpeername(fd, p, &len) < 0) {
439                 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
440                 goto bail;
441         }
442         
443         ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
444
445 bail:
446         lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
447 #else
448         (void)context;
449         (void)wsi;
450         (void)fd;
451         (void)name;
452         (void)name_len;
453         (void)rip;
454         (void)rip_len;
455 #endif
456 }
457
458 /**
459  * lws_context_user() - get the user data associated with the context
460  * @context: Websocket context
461  *
462  *      This returns the optional user allocation that can be attached to
463  *      the context the sockets live in at context_create time.  It's a way
464  *      to let all sockets serviced in the same context share data without
465  *      using globals statics in the user code.
466  */
467 LWS_EXTERN void *
468 lws_context_user(struct lws_context *context)
469 {
470         return context->user_space;
471 }
472
473
474 /**
475  * lws_callback_all_protocol() - Callback all connections using
476  *                              the given protocol with the given reason
477  *
478  * @protocol:   Protocol whose connections will get callbacks
479  * @reason:     Callback reason index
480  */
481
482 LWS_VISIBLE int
483 lws_callback_all_protocol(const struct lws_protocols *protocol, int reason)
484 {
485         struct lws_context *context = protocol->owning_server;
486         struct lws *wsi;
487         int n;
488
489         for (n = 0; n < context->fds_count; n++) {
490                 wsi = wsi_from_fd(context, context->fds[n].fd);
491                 if (!wsi)
492                         continue;
493                 if (wsi->protocol == protocol)
494                         protocol->callback(context, wsi,
495                                            reason, wsi->user_space, NULL, 0);
496         }
497
498         return 0;
499 }
500
501 /**
502  * lws_set_timeout() - marks the wsi as subject to a timeout
503  *
504  * You will not need this unless you are doing something special
505  *
506  * @wsi:        Websocket connection instance
507  * @reason:     timeout reason
508  * @secs:       how many seconds
509  */
510
511 LWS_VISIBLE void
512 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
513 {
514         time_t now;
515
516         time(&now);
517
518         wsi->pending_timeout_limit = now + secs;
519         wsi->pending_timeout = reason;
520 }
521
522
523 #if LWS_POSIX
524
525 /**
526  * lws_get_socket_fd() - returns the socket file descriptor
527  *
528  * You will not need this unless you are doing something special
529  *
530  * @wsi:        Websocket connection instance
531  */
532
533 LWS_VISIBLE int
534 lws_get_socket_fd(struct lws *wsi)
535 {
536         return wsi->sock;
537 }
538
539 #endif
540
541 #ifdef LWS_LATENCY
542 void
543 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
544             int ret, int completed)
545 {
546         unsigned long long u;
547         char buf[256];
548
549         u = time_in_microseconds();
550
551         if (!action) {
552                 wsi->latency_start = u;
553                 if (!wsi->action_start)
554                         wsi->action_start = u;
555                 return;
556         }
557         if (completed) {
558                 if (wsi->action_start == wsi->latency_start)
559                         sprintf(buf,
560                           "Completion first try lat %lluus: %p: ret %d: %s\n",
561                                         u - wsi->latency_start,
562                                                       (void *)wsi, ret, action);
563                 else
564                         sprintf(buf,
565                           "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
566                                 u - wsi->action_start,
567                                         u - wsi->latency_start,
568                                                       (void *)wsi, ret, action);
569                 wsi->action_start = 0;
570         } else
571                 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
572                               u - wsi->latency_start, (void *)wsi, ret, action);
573
574         if (u - wsi->latency_start > context->worst_latency) {
575                 context->worst_latency = u - wsi->latency_start;
576                 strcpy(context->worst_latency_info, buf);
577         }
578         lwsl_latency("%s", buf);
579 }
580 #endif
581
582
583
584 /**
585  * lws_rx_flow_control() - Enable and disable socket servicing for
586  *                              received packets.
587  *
588  * If the output side of a server process becomes choked, this allows flow
589  * control for the input side.
590  *
591  * @wsi:        Websocket connection instance to get callback for
592  * @enable:     0 = disable read servicing for this connection, 1 = enable
593  */
594
595 LWS_VISIBLE int
596 lws_rx_flow_control(struct lws *wsi, int enable)
597 {
598         if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
599                 return 0;
600
601         lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
602         wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
603
604         return 0;
605 }
606
607 /**
608  * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
609  *
610  * When the user server code realizes it can accept more input, it can
611  * call this to have the RX flow restriction removed from all connections using
612  * the given protocol.
613  *
614  * @protocol:   all connections using this protocol will be allowed to receive
615  */
616
617 LWS_VISIBLE void
618 lws_rx_flow_allow_all_protocol(const struct lws_protocols *protocol)
619 {
620         struct lws_context *context = protocol->owning_server;
621         int n;
622         struct lws *wsi;
623
624         for (n = 0; n < context->fds_count; n++) {
625                 wsi = wsi_from_fd(context, context->fds[n].fd);
626                 if (!wsi)
627                         continue;
628                 if (wsi->protocol == protocol)
629                         lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
630         }
631 }
632
633
634 /**
635  * lws_canonical_hostname() - returns this host's hostname
636  *
637  * This is typically used by client code to fill in the host parameter
638  * when making a client connection.  You can only call it after the context
639  * has been created.
640  *
641  * @context:    Websocket context
642  */
643 LWS_VISIBLE extern const char *
644 lws_canonical_hostname(struct lws_context *context)
645 {
646         return (const char *)context->canonical_hostname;
647 }
648
649 int user_callback_handle_rxflow(callback_function callback_function,
650                                 struct lws_context *context, struct lws *wsi,
651                                 enum lws_callback_reasons reason, void *user,
652                                 void *in, size_t len)
653 {
654         int n;
655
656         n = callback_function(context, wsi, reason, user, in, len);
657         if (!n)
658                 n = _lws_rx_flow_control(wsi);
659
660         return n;
661 }
662
663
664 /**
665  * lws_set_proxy() - Setups proxy to lws_context.
666  * @context:    pointer to struct lws_context you want set proxy to
667  * @proxy: pointer to c string containing proxy in format address:port
668  *
669  * Returns 0 if proxy string was parsed and proxy was setup. 
670  * Returns -1 if @proxy is NULL or has incorrect format.
671  *
672  * This is only required if your OS does not provide the http_proxy
673  * environment variable (eg, OSX)
674  *
675  *   IMPORTANT! You should call this function right after creation of the
676  *   lws_context and before call to connect. If you call this
677  *   function after connect behavior is undefined.
678  *   This function will override proxy settings made on lws_context
679  *   creation with genenv() call.
680  */
681
682 LWS_VISIBLE int
683 lws_set_proxy(struct lws_context *context, const char *proxy)
684 {
685         char *p;
686         char authstring[96];
687         
688         if (!proxy)
689                 return -1;
690
691         p = strchr(proxy, '@');
692         if (p) { /* auth is around */
693
694                 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
695                         goto auth_too_long;
696
697                 strncpy(authstring, proxy, p - proxy);
698                 // null termination not needed on input
699                 if (lws_b64_encode_string(authstring, (p - proxy),
700                     context->proxy_basic_auth_token,
701                     sizeof context->proxy_basic_auth_token) < 0)
702                         goto auth_too_long;
703
704                 lwsl_notice(" Proxy auth in use\n");
705                         
706                 proxy = p + 1;
707         } else
708                 context->proxy_basic_auth_token[0] = '\0';
709
710         strncpy(context->http_proxy_address, proxy,
711                                 sizeof(context->http_proxy_address) - 1);
712         context->http_proxy_address[
713                                 sizeof(context->http_proxy_address) - 1] = '\0';
714
715         p = strchr(context->http_proxy_address, ':');
716         if (!p && !context->http_proxy_port) {
717                 lwsl_err("http_proxy needs to be ads:port\n");
718
719                 return -1;
720         } else {
721                 *p = '\0';
722                 context->http_proxy_port = atoi(p + 1);
723         }
724
725         lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
726                                                 context->http_proxy_port);
727
728         return 0;
729
730 auth_too_long:
731         lwsl_err("proxy auth too long\n");
732
733         return -1;
734 }
735
736 /**
737  * lws_get_protocol() - Returns a protocol pointer from a websocket
738  *                                connection.
739  * @wsi:        pointer to struct websocket you want to know the protocol of
740  *
741  *
742  *      Some apis can act on all live connections of a given protocol,
743  *      this is how you can get a pointer to the active protocol if needed.
744  */
745
746 LWS_VISIBLE const struct lws_protocols *
747 lws_get_protocol(struct lws *wsi)
748 {
749         return wsi->protocol;
750 }
751
752 LWS_VISIBLE int
753 lws_is_final_fragment(struct lws *wsi)
754 {
755         return wsi->u.ws.final;
756 }
757
758 LWS_VISIBLE unsigned char
759 lws_get_reserved_bits(struct lws *wsi)
760 {
761         return wsi->u.ws.rsv;
762 }
763
764 int
765 lws_ensure_user_space(struct lws *wsi)
766 {
767         lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
768         if (!wsi->protocol)
769                 return 1;
770
771         /* allocate the per-connection user memory (if any) */
772
773         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
774                 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
775                 if (wsi->user_space  == NULL) {
776                         lwsl_err("Out of memory for conn user space\n");
777                         return 1;
778                 }
779         } else
780                 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
781                           __func__, wsi, wsi->protocol->per_session_data_size,
782                           wsi->user_space);
783         return 0;
784 }
785
786 #if LWS_POSIX
787 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
788 {
789         unsigned long long now;
790         char buf[300];
791         int n;
792
793         buf[0] = '\0';
794         for (n = 0; n < LLL_COUNT; n++) {
795                 if (level != (1 << n))
796                         continue;
797                 now = time_in_microseconds() / 100;
798                 sprintf(buf, "[%llu:%04d] %s: ",
799                         (unsigned long long) now / 10000,
800                         (int)(now % 10000), log_level_names[n]);
801                 break;
802         }
803
804         fprintf(stderr, "%s%s", buf, line);
805 }
806 #endif
807
808 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
809 {
810         char buf[256];
811
812         if (!(log_level & filter))
813                 return;
814
815         vsnprintf(buf, sizeof(buf), format, vl);
816         buf[sizeof(buf) - 1] = '\0';
817
818         lwsl_emit(filter, buf);
819 }
820
821 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
822 {
823         va_list ap;
824
825         va_start(ap, format);
826         _lws_logv(filter, format, ap);
827         va_end(ap);
828 }
829
830 /**
831  * lws_set_log_level() - Set the logging bitfield
832  * @level:      OR together the LLL_ debug contexts you want output from
833  * @log_emit_function:  NULL to leave it as it is, or a user-supplied
834  *                      function to perform log string emission instead of
835  *                      the default stderr one.
836  *
837  *      log level defaults to "err", "warn" and "notice" contexts enabled and
838  *      emission on stderr.
839  */
840
841 LWS_VISIBLE void lws_set_log_level(int level,
842                                    void (*func)(int level, const char *line))
843 {
844         log_level = level;
845         if (func)
846                 lwsl_emit = func;
847 }
848
849 /**
850  * lws_use_ssl() - Find out if connection is using SSL
851  * @wsi:        websocket connection to check
852  *
853  *      Returns 0 if the connection is not using SSL, 1 if using SSL and
854  *      using verified cert, and 2 if using SSL but the cert was not
855  *      checked (appears for client wsi told to skip check on connection)
856  */
857 LWS_VISIBLE int
858 lws_is_ssl(struct lws *wsi)
859 {
860 #ifdef LWS_OPENSSL_SUPPORT
861         return wsi->use_ssl;
862 #else
863         (void)wsi;
864         return 0;
865 #endif
866 }
867
868 /**
869  * lws_partial_buffered() - find out if lws buffered the last write
870  * @wsi:        websocket connection to check
871  *
872  * Returns 1 if you cannot use lws_write because the last
873  * write on this connection is still buffered, and can't be cleared without
874  * returning to the service loop and waiting for the connection to be
875  * writeable again.
876  * 
877  * If you will try to do >1 lws_write call inside a single
878  * WRITEABLE callback, you must check this after every write and bail if
879  * set, ask for a new writeable callback and continue writing from there.
880  * 
881  * This is never set at the start of a writeable callback, but any write
882  * may set it.
883  */
884
885 LWS_VISIBLE int
886 lws_partial_buffered(struct lws *wsi)
887 {
888         return !!wsi->truncated_send_len;       
889 }
890
891 void lws_set_protocol_write_pending(struct lws_context *context,
892                                     struct lws *wsi,
893                                     enum lws_pending_protocol_send pend)
894 {
895         lwsl_info("setting pps %d\n", pend);
896         
897         if (wsi->pps)
898                 lwsl_err("pps overwrite\n");
899         wsi->pps = pend;
900         lws_rx_flow_control(wsi, 0);
901         lws_callback_on_writable(context, wsi);
902 }
903
904 LWS_VISIBLE size_t
905 lws_get_peer_write_allowance(struct lws *wsi)
906 {
907 #ifdef LWS_USE_HTTP2
908         /* only if we are using HTTP2 on this connection */
909         if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING)
910                 return -1;
911         /* user is only interested in how much he can send, or that he can't  */
912         if (wsi->u.http2.tx_credit <= 0)
913                 return 0;
914         
915         return wsi->u.http2.tx_credit;
916 #else
917         (void)wsi;
918         return -1;
919 #endif
920 }
921
922 LWS_VISIBLE void
923 lws_union_transition(struct lws *wsi, enum connection_mode mode)
924 {
925         memset(&wsi->u, 0, sizeof(wsi->u));
926         wsi->mode = mode;
927 }
928
929
930 #ifdef LWS_WITH_OLD_API_WRAPPERS
931
932 /*
933  * To maintain .so abi, also produce wrappers using old api naming.
934  *
935  * This is disabled by default, use "LWS_WITH_OLD_API_WRAPPERS" on cmake to
936  * enable.
937  *
938  * You only need these if you have existing binary applications using the old
939  * api names and you don't want to / can't recompile them against new lws.
940  * With these new lws .so is compatible with old and new api names.
941  *
942  * If you can recompile your application (using old api names still) against
943  * current lws, you don't need these compatibility helpers since
944  * libwebsockets.h will map them at compile time.
945  */
946
947 #undef libwebsocket
948
949 #undef libwebsocket_create_context
950 LWS_VISIBLE LWS_EXTERN struct lws_context *
951 libwebsocket_create_context(struct lws_context_creation_info *info)
952 {
953         return lws_create_context(info);
954 }
955
956 #undef libwebsocket_set_proxy
957 LWS_VISIBLE LWS_EXTERN int
958 libwebsocket_set_proxy(struct lws_context *context, const char *proxy)
959 {
960         return lws_set_proxy(context, proxy);
961 }
962
963 #undef libwebsocket_context_destroy
964 LWS_VISIBLE LWS_EXTERN void
965 libwebsocket_context_destroy(struct lws_context *context)
966 {
967         lws_context_destroy(context);
968 }
969
970 #undef libwebsocket_service
971 LWS_VISIBLE LWS_EXTERN int
972 libwebsocket_service(struct lws_context *context, int timeout_ms)
973 {
974         return lws_service(context, timeout_ms);
975 }
976
977 #undef libwebsocket_cancel_service
978 LWS_VISIBLE LWS_EXTERN void
979 libwebsocket_cancel_service(struct lws_context *context)
980 {
981         lws_cancel_service(context);
982 }
983
984 #ifdef LWS_USE_LIBEV
985 #undef libwebsocket_sigint_cfg
986 LWS_VISIBLE LWS_EXTERN int
987 libwebsocket_sigint_cfg(struct lws_context *context, int use_ev_sigint,
988                         lws_ev_signal_cb* cb)
989 {
990         return lws_sigint_cfg(context, use_ev_sigint, cb);
991 }
992
993 #undef libwebsocket_initloop
994 LWS_VISIBLE LWS_EXTERN int
995 libwebsocket_initloop(struct lws_context *context, struct ev_loop *loop)
996 {
997         return lws_initloop(context, loop);
998 }
999
1000 #undef libwebsocket_sigint_cb
1001 LWS_VISIBLE void
1002 libwebsocket_sigint_cb(
1003         struct ev_loop *loop, struct ev_signal *watcher, int revents)
1004 {
1005         lws_sigint_cb(loop, watcher, revents);
1006 }
1007 #endif /* LWS_USE_LIBEV */
1008
1009 #undef libwebsocket_service_fd
1010 LWS_VISIBLE LWS_EXTERN int
1011 libwebsocket_service_fd(struct lws_context *context,
1012                 struct lws_pollfd *pollfd)
1013 {
1014         return lws_service_fd(context, pollfd);
1015 }
1016
1017 #undef libwebsocket_context_user
1018 LWS_VISIBLE LWS_EXTERN void *
1019 libwebsocket_context_user(struct lws_context *context)
1020 {
1021         return lws_context_user(context);
1022 }
1023
1024 #undef libwebsocket_set_timeout
1025 LWS_VISIBLE LWS_EXTERN void
1026 libwebsocket_set_timeout(struct lws *wsi,
1027                                          enum pending_timeout reason, int secs)
1028 {
1029         lws_set_timeout(wsi, reason, secs);
1030 }
1031
1032 #undef libwebsocket_write
1033 LWS_VISIBLE LWS_EXTERN int
1034 libwebsocket_write(struct lws *wsi, unsigned char *buf, size_t len,
1035                                      enum lws_write_protocol protocol)
1036 {
1037         return lws_write(wsi, buf, len, protocol);
1038 }
1039
1040 #undef libwebsockets_serve_http_file_fragment
1041 LWS_VISIBLE LWS_EXTERN int
1042 libwebsockets_serve_http_file_fragment(struct lws_context *context,
1043                         struct lws *wsi)
1044 {
1045         return lws_serve_http_file_fragment(context, wsi);
1046 }
1047
1048 #undef libwebsockets_serve_http_file
1049 LWS_VISIBLE LWS_EXTERN int
1050 libwebsockets_serve_http_file(struct lws_context *context,
1051                         struct lws *wsi, const char *file,
1052                         const char *content_type, const char *other_headers,
1053                         int other_headers_len)
1054 {
1055         return lws_serve_http_file(context, wsi, file, content_type,
1056                         other_headers, other_headers_len);
1057 }
1058
1059 #undef libwebsockets_return_http_status
1060 LWS_VISIBLE LWS_EXTERN int
1061 libwebsockets_return_http_status(
1062                 struct lws_context *context,
1063                         struct lws *wsi, unsigned int code,
1064                                                         const char *html_body)
1065 {
1066         return lws_return_http_status(context, wsi, code, html_body);
1067 }
1068
1069 #undef libwebsockets_get_protocol
1070 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1071 libwebsockets_get_protocol(struct lws *wsi)
1072 {
1073         return lws_get_protocol(wsi);
1074 }
1075
1076 #undef libwebsocket_callback_on_writable_all_protocol
1077 LWS_VISIBLE LWS_EXTERN int
1078 libwebsocket_callback_on_writable_all_protocol(
1079                                  const struct lws_protocols *protocol)
1080 {
1081         return lws_callback_on_writable_all_protocol(protocol);
1082 }
1083
1084 #undef libwebsocket_callback_on_writable
1085 LWS_VISIBLE LWS_EXTERN int
1086 libwebsocket_callback_on_writable(struct lws_context *context,
1087                                                       struct lws *wsi)
1088 {
1089         return lws_callback_on_writable(context, wsi);
1090 }
1091
1092 #undef libwebsocket_callback_all_protocol
1093 LWS_VISIBLE LWS_EXTERN int
1094 libwebsocket_callback_all_protocol(
1095                 const struct lws_protocols *protocol, int reason)
1096 {
1097         return lws_callback_all_protocol(protocol, reason);
1098 }
1099
1100 #undef libwebsocket_get_socket_fd
1101 LWS_VISIBLE LWS_EXTERN int
1102 libwebsocket_get_socket_fd(struct lws *wsi)
1103 {
1104         return lws_get_socket_fd(wsi);
1105 }
1106
1107 #undef libwebsocket_is_final_fragment
1108 LWS_VISIBLE LWS_EXTERN int
1109 libwebsocket_is_final_fragment(struct lws *wsi)
1110 {
1111         return lws_is_final_fragment(wsi);
1112 }
1113
1114 #undef libwebsocket_get_reserved_bits
1115 LWS_VISIBLE LWS_EXTERN unsigned char
1116 libwebsocket_get_reserved_bits(struct lws *wsi)
1117 {
1118         return lws_get_reserved_bits(wsi);
1119 }
1120
1121 #undef libwebsocket_rx_flow_control
1122 LWS_VISIBLE LWS_EXTERN int
1123 libwebsocket_rx_flow_control(struct lws *wsi, int enable)
1124 {
1125         return lws_rx_flow_control(wsi, enable);
1126 }
1127
1128 #undef libwebsocket_rx_flow_allow_all_protocol
1129 LWS_VISIBLE LWS_EXTERN void
1130 libwebsocket_rx_flow_allow_all_protocol(const struct lws_protocols *protocol)
1131 {
1132         lws_rx_flow_allow_all_protocol(protocol);
1133 }
1134
1135 #undef libwebsockets_remaining_packet_payload
1136 LWS_VISIBLE LWS_EXTERN size_t
1137 libwebsockets_remaining_packet_payload(struct lws *wsi)
1138 {
1139         return lws_remaining_packet_payload(wsi);
1140 }
1141
1142 #undef libwebsocket_client_connect
1143 LWS_VISIBLE LWS_EXTERN struct lws *
1144 libwebsocket_client_connect(struct lws_context *clients,
1145                               const char *address,
1146                               int port,
1147                               int ssl_connection,
1148                               const char *path,
1149                               const char *host,
1150                               const char *origin,
1151                               const char *protocol,
1152                               int ietf_version_or_minus_one)
1153 {
1154         return lws_client_connect(clients, address, port, ssl_connection,
1155                         path, host, origin, protocol, ietf_version_or_minus_one);
1156 }
1157 LWS_VISIBLE LWS_EXTERN struct lws *
1158 libwebsocket_client_connect_extended(struct lws_context *clients,
1159                               const char *address,
1160                               int port,
1161                               int ssl_connection,
1162                               const char *path,
1163                               const char *host,
1164                               const char *origin,
1165                               const char *protocol,
1166                               int ietf_version_or_minus_one, void *userdata)
1167 {
1168         return lws_client_connect_extended(clients, address, port, ssl_connection,
1169                         path, host, origin, protocol, ietf_version_or_minus_one,
1170                         userdata);
1171 }
1172
1173 #undef libwebsocket_canonical_hostname
1174 LWS_VISIBLE LWS_EXTERN const char *
1175 libwebsocket_canonical_hostname(struct lws_context *context)
1176 {
1177         return lws_canonical_hostname(context);
1178 }
1179
1180 #undef libwebsockets_get_peer_addresses
1181 LWS_VISIBLE LWS_EXTERN void
1182 libwebsockets_get_peer_addresses(struct lws_context *context,
1183                 struct lws *wsi, lws_sockfd_type fd, char *name,
1184                 int name_len, char *rip, int rip_len)
1185 {
1186         lws_get_peer_addresses(context, wsi, fd, name, name_len, rip, rip_len);
1187 }
1188
1189 #undef libwebsockets_get_random
1190 LWS_VISIBLE LWS_EXTERN int
1191 libwebsockets_get_random(struct lws_context *context, void *buf, int len)
1192 {
1193         return lws_get_random(context, buf, len);
1194 }
1195
1196 #ifndef LWS_SHA1_USE_OPENSSL_NAME
1197 #undef libwebsockets_SHA1
1198 LWS_VISIBLE LWS_EXTERN unsigned char *
1199 libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md)
1200 {
1201         return lws_SHA1(d, n, md);
1202 }
1203 #endif
1204
1205 #undef libwebsocket_read
1206 LWS_VISIBLE LWS_EXTERN int
1207 libwebsocket_read(struct lws_context *context, struct lws *wsi,
1208          unsigned char *buf, size_t len)
1209 {
1210         return lws_read(context, wsi, buf, len);
1211 }
1212
1213 #ifndef LWS_NO_EXTENSIONS
1214 #undef libwebsocket_get_internal_extensions
1215 LWS_VISIBLE LWS_EXTERN struct lws_extension *
1216 libwebsocket_get_internal_extensions()
1217 {
1218         return lws_get_internal_extensions();
1219 }
1220 #endif
1221
1222 #endif
1223