multithread stability
[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         struct lws *wsi;
617         unsigned int n, m = context->count_threads;
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, NULL, 0);
626                 }
627                 pt++;
628         }
629
630         return 0;
631 }
632
633 #if LWS_POSIX
634
635 /**
636  * lws_get_socket_fd() - returns the socket file descriptor
637  *
638  * You will not need this unless you are doing something special
639  *
640  * @wsi:        Websocket connection instance
641  */
642
643 LWS_VISIBLE int
644 lws_get_socket_fd(struct lws *wsi)
645 {
646         return wsi->sock;
647 }
648
649 #endif
650
651 #ifdef LWS_LATENCY
652 void
653 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
654             int ret, int completed)
655 {
656         unsigned long long u;
657         char buf[256];
658
659         u = time_in_microseconds();
660
661         if (!action) {
662                 wsi->latency_start = u;
663                 if (!wsi->action_start)
664                         wsi->action_start = u;
665                 return;
666         }
667         if (completed) {
668                 if (wsi->action_start == wsi->latency_start)
669                         sprintf(buf,
670                           "Completion first try lat %lluus: %p: ret %d: %s\n",
671                                         u - wsi->latency_start,
672                                                       (void *)wsi, ret, action);
673                 else
674                         sprintf(buf,
675                           "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
676                                 u - wsi->action_start,
677                                         u - wsi->latency_start,
678                                                       (void *)wsi, ret, action);
679                 wsi->action_start = 0;
680         } else
681                 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
682                               u - wsi->latency_start, (void *)wsi, ret, action);
683
684         if (u - wsi->latency_start > context->worst_latency) {
685                 context->worst_latency = u - wsi->latency_start;
686                 strcpy(context->worst_latency_info, buf);
687         }
688         lwsl_latency("%s", buf);
689 }
690 #endif
691
692
693
694 /**
695  * lws_rx_flow_control() - Enable and disable socket servicing for
696  *                              received packets.
697  *
698  * If the output side of a server process becomes choked, this allows flow
699  * control for the input side.
700  *
701  * @wsi:        Websocket connection instance to get callback for
702  * @enable:     0 = disable read servicing for this connection, 1 = enable
703  */
704
705 LWS_VISIBLE int
706 lws_rx_flow_control(struct lws *wsi, int enable)
707 {
708         if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
709                 return 0;
710
711         lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
712         wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
713
714         return 0;
715 }
716
717 /**
718  * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
719  *
720  * When the user server code realizes it can accept more input, it can
721  * call this to have the RX flow restriction removed from all connections using
722  * the given protocol.
723  *
724  * @protocol:   all connections using this protocol will be allowed to receive
725  */
726
727 LWS_VISIBLE void
728 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
729                                const struct lws_protocols *protocol)
730 {
731         const struct lws_context_per_thread *pt = &context->pt[0];
732         struct lws *wsi;
733         unsigned int n, m = context->count_threads;
734
735         while (m--) {
736                 for (n = 0; n < pt->fds_count; n++) {
737                         wsi = wsi_from_fd(context, pt->fds[n].fd);
738                         if (!wsi)
739                                 continue;
740                         if (wsi->protocol == protocol)
741                                 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
742                 }
743                 pt++;
744         }
745 }
746
747
748 /**
749  * lws_canonical_hostname() - returns this host's hostname
750  *
751  * This is typically used by client code to fill in the host parameter
752  * when making a client connection.  You can only call it after the context
753  * has been created.
754  *
755  * @context:    Websocket context
756  */
757 LWS_VISIBLE extern const char *
758 lws_canonical_hostname(struct lws_context *context)
759 {
760         return (const char *)context->canonical_hostname;
761 }
762
763 int user_callback_handle_rxflow(lws_callback_function callback_function,
764                                 struct lws *wsi,
765                                 enum lws_callback_reasons reason, void *user,
766                                 void *in, size_t len)
767 {
768         int n;
769
770         n = callback_function(wsi, reason, user, in, len);
771         if (!n)
772                 n = _lws_rx_flow_control(wsi);
773
774         return n;
775 }
776
777
778 /**
779  * lws_set_proxy() - Setups proxy to lws_context.
780  * @context:    pointer to struct lws_context you want set proxy to
781  * @proxy: pointer to c string containing proxy in format address:port
782  *
783  * Returns 0 if proxy string was parsed and proxy was setup.
784  * Returns -1 if @proxy is NULL or has incorrect format.
785  *
786  * This is only required if your OS does not provide the http_proxy
787  * environment variable (eg, OSX)
788  *
789  *   IMPORTANT! You should call this function right after creation of the
790  *   lws_context and before call to connect. If you call this
791  *   function after connect behavior is undefined.
792  *   This function will override proxy settings made on lws_context
793  *   creation with genenv() call.
794  */
795
796 LWS_VISIBLE int
797 lws_set_proxy(struct lws_context *context, const char *proxy)
798 {
799         char *p;
800         char authstring[96];
801
802         if (!proxy)
803                 return -1;
804
805         p = strchr(proxy, '@');
806         if (p) { /* auth is around */
807
808                 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
809                         goto auth_too_long;
810
811                 strncpy(authstring, proxy, p - proxy);
812                 // null termination not needed on input
813                 if (lws_b64_encode_string(authstring, (p - proxy),
814                     context->proxy_basic_auth_token,
815                     sizeof context->proxy_basic_auth_token) < 0)
816                         goto auth_too_long;
817
818                 lwsl_notice(" Proxy auth in use\n");
819
820                 proxy = p + 1;
821         } else
822                 context->proxy_basic_auth_token[0] = '\0';
823
824         strncpy(context->http_proxy_address, proxy,
825                                 sizeof(context->http_proxy_address) - 1);
826         context->http_proxy_address[
827                                 sizeof(context->http_proxy_address) - 1] = '\0';
828
829         p = strchr(context->http_proxy_address, ':');
830         if (!p && !context->http_proxy_port) {
831                 lwsl_err("http_proxy needs to be ads:port\n");
832
833                 return -1;
834         } else {
835                 if (p) {
836                         *p = '\0';
837                         context->http_proxy_port = atoi(p + 1);
838                 }
839         }
840
841         lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
842                                                 context->http_proxy_port);
843
844         return 0;
845
846 auth_too_long:
847         lwsl_err("proxy auth too long\n");
848
849         return -1;
850 }
851
852 /**
853  * lws_get_protocol() - Returns a protocol pointer from a websocket
854  *                                connection.
855  * @wsi:        pointer to struct websocket you want to know the protocol of
856  *
857  *
858  *      Some apis can act on all live connections of a given protocol,
859  *      this is how you can get a pointer to the active protocol if needed.
860  */
861
862 LWS_VISIBLE const struct lws_protocols *
863 lws_get_protocol(struct lws *wsi)
864 {
865         return wsi->protocol;
866 }
867
868 LWS_VISIBLE int
869 lws_is_final_fragment(struct lws *wsi)
870 {
871         lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
872                         wsi->u.ws.final, wsi->u.ws.rx_packet_length, wsi->u.ws.rx_draining_ext);
873         return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
874 }
875
876 LWS_VISIBLE unsigned char
877 lws_get_reserved_bits(struct lws *wsi)
878 {
879         return wsi->u.ws.rsv;
880 }
881
882 int
883 lws_ensure_user_space(struct lws *wsi)
884 {
885         lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
886         if (!wsi->protocol)
887                 return 1;
888
889         /* allocate the per-connection user memory (if any) */
890
891         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
892                 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
893                 if (wsi->user_space  == NULL) {
894                         lwsl_err("Out of memory for conn user space\n");
895                         return 1;
896                 }
897         } else
898                 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
899                           __func__, wsi, wsi->protocol->per_session_data_size,
900                           wsi->user_space);
901         return 0;
902 }
903
904 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
905 {
906         unsigned long long now;
907         char buf[300];
908         int n;
909
910         buf[0] = '\0';
911         for (n = 0; n < LLL_COUNT; n++) {
912                 if (level != (1 << n))
913                         continue;
914                 now = time_in_microseconds() / 100;
915                 sprintf(buf, "[%llu:%04d] %s: ",
916                         (unsigned long long) now / 10000,
917                         (int)(now % 10000), log_level_names[n]);
918                 break;
919         }
920
921         fprintf(stderr, "%s%s", buf, line);
922 }
923
924 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
925 {
926         char buf[256];
927
928         if (!(log_level & filter))
929                 return;
930
931         vsnprintf(buf, sizeof(buf), format, vl);
932         buf[sizeof(buf) - 1] = '\0';
933
934         lwsl_emit(filter, buf);
935 }
936
937 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
938 {
939         va_list ap;
940
941         va_start(ap, format);
942         _lws_logv(filter, format, ap);
943         va_end(ap);
944 }
945
946 /**
947  * lws_set_log_level() - Set the logging bitfield
948  * @level:      OR together the LLL_ debug contexts you want output from
949  * @log_emit_function:  NULL to leave it as it is, or a user-supplied
950  *                      function to perform log string emission instead of
951  *                      the default stderr one.
952  *
953  *      log level defaults to "err", "warn" and "notice" contexts enabled and
954  *      emission on stderr.
955  */
956
957 LWS_VISIBLE void lws_set_log_level(int level,
958                                    void (*func)(int level, const char *line))
959 {
960         log_level = level;
961         if (func)
962                 lwsl_emit = func;
963 }
964
965 /**
966  * lws_use_ssl() - Find out if connection is using SSL
967  * @wsi:        websocket connection to check
968  *
969  *      Returns 0 if the connection is not using SSL, 1 if using SSL and
970  *      using verified cert, and 2 if using SSL but the cert was not
971  *      checked (appears for client wsi told to skip check on connection)
972  */
973 LWS_VISIBLE int
974 lws_is_ssl(struct lws *wsi)
975 {
976 #ifdef LWS_OPENSSL_SUPPORT
977         return wsi->use_ssl;
978 #else
979         (void)wsi;
980         return 0;
981 #endif
982 }
983
984 /**
985  * lws_partial_buffered() - find out if lws buffered the last write
986  * @wsi:        websocket connection to check
987  *
988  * Returns 1 if you cannot use lws_write because the last
989  * write on this connection is still buffered, and can't be cleared without
990  * returning to the service loop and waiting for the connection to be
991  * writeable again.
992  *
993  * If you will try to do >1 lws_write call inside a single
994  * WRITEABLE callback, you must check this after every write and bail if
995  * set, ask for a new writeable callback and continue writing from there.
996  *
997  * This is never set at the start of a writeable callback, but any write
998  * may set it.
999  */
1000
1001 LWS_VISIBLE int
1002 lws_partial_buffered(struct lws *wsi)
1003 {
1004         return !!wsi->trunc_len;
1005 }
1006
1007 void lws_set_protocol_write_pending(struct lws *wsi,
1008                                     enum lws_pending_protocol_send pend)
1009 {
1010         lwsl_info("setting pps %d\n", pend);
1011
1012         if (wsi->pps)
1013                 lwsl_err("pps overwrite\n");
1014         wsi->pps = pend;
1015         lws_rx_flow_control(wsi, 0);
1016         lws_callback_on_writable(wsi);
1017 }
1018
1019 LWS_VISIBLE size_t
1020 lws_get_peer_write_allowance(struct lws *wsi)
1021 {
1022 #ifdef LWS_USE_HTTP2
1023         /* only if we are using HTTP2 on this connection */
1024         if (wsi->mode != LWSCM_HTTP2_SERVING)
1025                 return -1;
1026         /* user is only interested in how much he can send, or that he can't  */
1027         if (wsi->u.http2.tx_credit <= 0)
1028                 return 0;
1029
1030         return wsi->u.http2.tx_credit;
1031 #else
1032         (void)wsi;
1033         return -1;
1034 #endif
1035 }
1036
1037 LWS_VISIBLE void
1038 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1039 {
1040         lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1041         memset(&wsi->u, 0, sizeof(wsi->u));
1042         wsi->mode = mode;
1043 }
1044
1045 LWS_VISIBLE struct lws_plat_file_ops *
1046 lws_get_fops(struct lws_context *context)
1047 {
1048         return &context->fops;
1049 }
1050
1051 LWS_VISIBLE LWS_EXTERN struct lws_context *
1052 lws_get_context(const struct lws *wsi)
1053 {
1054         return wsi->context;
1055 }
1056
1057 LWS_VISIBLE LWS_EXTERN int
1058 lws_get_count_threads(struct lws_context *context)
1059 {
1060         return context->count_threads;
1061 }
1062
1063 LWS_VISIBLE LWS_EXTERN void *
1064 lws_wsi_user(struct lws *wsi)
1065 {
1066         return wsi->user_space;
1067 }
1068
1069 LWS_VISIBLE LWS_EXTERN void
1070 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1071                  unsigned char *buf, size_t len)
1072 {
1073         unsigned char *p, *start;
1074         int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1075
1076         assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1077
1078         start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1079
1080         *p++ = (((int)status) >> 8) & 0xff;
1081         *p++ = ((int)status) & 0xff;
1082
1083         if (buf)
1084                 while (len-- && p < start + budget)
1085                         *p++ = *buf++;
1086
1087         wsi->u.ws.close_in_ping_buffer_len = p - start;
1088 }
1089
1090 LWS_EXTERN int
1091 _lws_rx_flow_control(struct lws *wsi)
1092 {
1093         /* there is no pending change */
1094         if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1095                 lwsl_debug("%s: no pending change\n", __func__);
1096                 return 0;
1097         }
1098
1099         /* stuff is still buffered, not ready to really accept new input */
1100         if (wsi->rxflow_buffer) {
1101                 /* get ourselves called back to deal with stashed buffer */
1102                 lws_callback_on_writable(wsi);
1103                 return 0;
1104         }
1105
1106         /* pending is cleared, we can change rxflow state */
1107
1108         wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1109
1110         lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1111                               wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1112
1113         /* adjust the pollfd for this wsi */
1114
1115         if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1116                 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1117                         lwsl_info("%s: fail\n", __func__);
1118                         return -1;
1119                 }
1120         } else
1121                 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1122                         return -1;
1123
1124         return 0;
1125 }
1126
1127 LWS_EXTERN int
1128 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1129 {
1130         static const unsigned char e0f4[] = {
1131                 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1132                 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1133                 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1134                 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1135                 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1136                 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1137                 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1138                 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1139                 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1140                 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1141                 0x80 | ((4 - 1) << 2) | 1, /* ea */
1142                 0x80 | ((4 - 1) << 2) | 1, /* eb */
1143                 0x80 | ((4 - 1) << 2) | 1, /* ec */
1144                 0x80 | ((2 - 1) << 2) | 1, /* ed */
1145                 0x80 | ((4 - 1) << 2) | 1, /* ee */
1146                 0x80 | ((4 - 1) << 2) | 1, /* ef */
1147                 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1148                 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1149                 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1150                 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1151                 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1152
1153                 0,                         /* s0 */
1154                 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1155                 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1156         };
1157         unsigned char s = *state;
1158
1159         while (len--) {
1160                 unsigned char c = *buf++;
1161
1162                 if (!s) {
1163                         if (c >= 0x80) {
1164                                 if (c < 0xc2 || c > 0xf4)
1165                                         return 1;
1166                                 if (c < 0xe0)
1167                                         s = 0x80 | ((4 - 1) << 2);
1168                                 else
1169                                         s = e0f4[c - 0xe0];
1170                         }
1171                 } else {
1172                         if (c < (s & 0xf0) ||
1173                             c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1174                                 return 1;
1175                         s = e0f4[21 + (s & 3)];
1176                 }
1177         }
1178
1179         *state = s;
1180
1181         return 0;
1182 }
1183
1184 /**
1185  * lws_parse_uri:       cut up https:/xxx:yyy/zzz into pieces
1186  *                      Notice it does so by dropping '\0' into input string
1187  *
1188  * @p:                  incoming uri string.. will get written to
1189  * @prot:               result pointer for protocol part (https://)
1190  * @ads:                result pointer for address part
1191  * @port:               result pointer for port part
1192  * @path:               result pointer for path part
1193  */
1194
1195 LWS_VISIBLE LWS_EXTERN int
1196 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1197               const char **path)
1198 {
1199         const char *end;
1200         static const char *slash = "/";
1201
1202         /* cut up the location into address, port and path */
1203         *prot = p;
1204         while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1205                 p++;
1206         if (!*p) {
1207                 end = p;
1208                 p = (char *)*prot;
1209                 *prot = end;
1210         } else {
1211                 *p = '\0';
1212                 p += 3;
1213         }
1214         *ads = p;
1215         if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1216                 *port = 80;
1217         else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1218                 *port = 443;
1219
1220         while (*p && *p != ':' && *p != '/')
1221                 p++;
1222         if (*p == ':') {
1223                 *p++ = '\0';
1224                 *port = atoi(p);
1225                 while (*p && *p != '/')
1226                         p++;
1227         }
1228         *path = slash;
1229         if (*p) {
1230                 *p++ = '\0';
1231                 if (*p)
1232                         *path = p;
1233         }
1234
1235         return 0;
1236 }
1237
1238 #ifdef LWS_NO_EXTENSIONS
1239
1240 /* we need to provide dummy callbacks for internal exts
1241  * so user code runs when faced with a lib compiled with
1242  * extensions disabled.
1243  */
1244
1245 int
1246 lws_extension_callback_pm_deflate(struct lws_context *context,
1247                                   const struct lws_extension *ext,
1248                                   struct lws *wsi,
1249                                   enum lws_extension_callback_reasons reason,
1250                                   void *user, void *in, size_t len)
1251 {
1252         (void)context;
1253         (void)ext;
1254         (void)wsi;
1255         (void)reason;
1256         (void)user;
1257         (void)in;
1258         (void)len;
1259
1260         return 0;
1261 }
1262 #endif
1263