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