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