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