timeout also fixup for0middle guy deletion case
[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         lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len);
449
450         return 0;
451 #else
452         (void)context;
453         (void)ads;
454         (void)name;
455         (void)name_len;
456         (void)rip;
457         (void)rip_len;
458
459         return -1;
460 #endif
461 }
462
463 /**
464  * lws_get_peer_addresses() - Get client address information
465  * @wsi:        Local struct lws associated with
466  * @fd:         Connection socket descriptor
467  * @name:       Buffer to take client address name
468  * @name_len:   Length of client address name buffer
469  * @rip:        Buffer to take client address IP dotted quad
470  * @rip_len:    Length of client address IP buffer
471  *
472  *      This function fills in @name and @rip with the name and IP of
473  *      the client connected with socket descriptor @fd.  Names may be
474  *      truncated if there is not enough room.  If either cannot be
475  *      determined, they will be returned as valid zero-length strings.
476  */
477
478 LWS_VISIBLE void
479 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
480                        int name_len, char *rip, int rip_len)
481 {
482 #if LWS_POSIX
483         socklen_t len;
484 #ifdef LWS_USE_IPV6
485         struct sockaddr_in6 sin6;
486 #endif
487         struct sockaddr_in sin4;
488         struct lws_context *context = wsi->context;
489         int ret = -1;
490         void *p;
491
492         rip[0] = '\0';
493         name[0] = '\0';
494
495         lws_latency_pre(context, wsi);
496
497 #ifdef LWS_USE_IPV6
498         if (LWS_IPV6_ENABLED(context)) {
499                 len = sizeof(sin6);
500                 p = &sin6;
501         } else
502 #endif
503         {
504                 len = sizeof(sin4);
505                 p = &sin4;
506         }
507
508         if (getpeername(fd, p, &len) < 0) {
509                 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
510                 goto bail;
511         }
512
513         ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
514
515 bail:
516         lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
517 #else
518         (void)wsi;
519         (void)fd;
520         (void)name;
521         (void)name_len;
522         (void)rip;
523         (void)rip_len;
524 #endif
525 }
526
527 /**
528  * lws_context_user() - get the user data associated with the context
529  * @context: Websocket context
530  *
531  *      This returns the optional user allocation that can be attached to
532  *      the context the sockets live in at context_create time.  It's a way
533  *      to let all sockets serviced in the same context share data without
534  *      using globals statics in the user code.
535  */
536 LWS_EXTERN void *
537 lws_context_user(struct lws_context *context)
538 {
539         return context->user_space;
540 }
541
542
543 /**
544  * lws_callback_all_protocol() - Callback all connections using
545  *                              the given protocol with the given reason
546  *
547  * @protocol:   Protocol whose connections will get callbacks
548  * @reason:     Callback reason index
549  */
550
551 LWS_VISIBLE int
552 lws_callback_all_protocol(struct lws_context *context,
553                           const struct lws_protocols *protocol, int reason)
554 {
555         struct lws_context_per_thread *pt = &context->pt[0];
556         struct lws *wsi;
557         int n, m = context->count_threads;
558
559         while (m--) {
560                 for (n = 0; n < pt->fds_count; n++) {
561                         wsi = wsi_from_fd(context, pt->fds[n].fd);
562                         if (!wsi)
563                                 continue;
564                         if (wsi->protocol == protocol)
565                                 protocol->callback(wsi, reason, wsi->user_space, NULL, 0);
566                 }
567                 pt++;
568         }
569
570         return 0;
571 }
572
573 /**
574  * lws_set_timeout() - marks the wsi as subject to a timeout
575  *
576  * You will not need this unless you are doing something special
577  *
578  * @wsi:        Websocket connection instance
579  * @reason:     timeout reason
580  * @secs:       how many seconds
581  */
582
583 LWS_VISIBLE void
584 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
585 {
586         time_t now;
587
588         time(&now);
589
590         if (!wsi->pending_timeout) {
591                 wsi->timeout_list = wsi->context->timeout_list;
592                 if (wsi->timeout_list)
593                         wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
594                 wsi->timeout_list_prev = &wsi->context->timeout_list;
595                 *wsi->timeout_list_prev = wsi;
596         }
597
598         wsi->pending_timeout_limit = now + secs;
599         wsi->pending_timeout = reason;
600
601         if (!reason)
602                 lws_remove_from_timeout_list(wsi);
603 }
604
605
606 #if LWS_POSIX
607
608 /**
609  * lws_get_socket_fd() - returns the socket file descriptor
610  *
611  * You will not need this unless you are doing something special
612  *
613  * @wsi:        Websocket connection instance
614  */
615
616 LWS_VISIBLE int
617 lws_get_socket_fd(struct lws *wsi)
618 {
619         return wsi->sock;
620 }
621
622 #endif
623
624 #ifdef LWS_LATENCY
625 void
626 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
627             int ret, int completed)
628 {
629         unsigned long long u;
630         char buf[256];
631
632         u = time_in_microseconds();
633
634         if (!action) {
635                 wsi->latency_start = u;
636                 if (!wsi->action_start)
637                         wsi->action_start = u;
638                 return;
639         }
640         if (completed) {
641                 if (wsi->action_start == wsi->latency_start)
642                         sprintf(buf,
643                           "Completion first try lat %lluus: %p: ret %d: %s\n",
644                                         u - wsi->latency_start,
645                                                       (void *)wsi, ret, action);
646                 else
647                         sprintf(buf,
648                           "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
649                                 u - wsi->action_start,
650                                         u - wsi->latency_start,
651                                                       (void *)wsi, ret, action);
652                 wsi->action_start = 0;
653         } else
654                 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
655                               u - wsi->latency_start, (void *)wsi, ret, action);
656
657         if (u - wsi->latency_start > context->worst_latency) {
658                 context->worst_latency = u - wsi->latency_start;
659                 strcpy(context->worst_latency_info, buf);
660         }
661         lwsl_latency("%s", buf);
662 }
663 #endif
664
665
666
667 /**
668  * lws_rx_flow_control() - Enable and disable socket servicing for
669  *                              received packets.
670  *
671  * If the output side of a server process becomes choked, this allows flow
672  * control for the input side.
673  *
674  * @wsi:        Websocket connection instance to get callback for
675  * @enable:     0 = disable read servicing for this connection, 1 = enable
676  */
677
678 LWS_VISIBLE int
679 lws_rx_flow_control(struct lws *wsi, int enable)
680 {
681         if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
682                 return 0;
683
684         lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
685         wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
686
687         return 0;
688 }
689
690 /**
691  * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
692  *
693  * When the user server code realizes it can accept more input, it can
694  * call this to have the RX flow restriction removed from all connections using
695  * the given protocol.
696  *
697  * @protocol:   all connections using this protocol will be allowed to receive
698  */
699
700 LWS_VISIBLE void
701 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
702                                const struct lws_protocols *protocol)
703 {
704         const struct lws_context_per_thread *pt = &context->pt[0];
705         struct lws *wsi;
706         int n, m = context->count_threads;
707
708         while (m--) {
709                 for (n = 0; n < pt->fds_count; n++) {
710                         wsi = wsi_from_fd(context, pt->fds[n].fd);
711                         if (!wsi)
712                                 continue;
713                         if (wsi->protocol == protocol)
714                                 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
715                 }
716                 pt++;
717         }
718 }
719
720
721 /**
722  * lws_canonical_hostname() - returns this host's hostname
723  *
724  * This is typically used by client code to fill in the host parameter
725  * when making a client connection.  You can only call it after the context
726  * has been created.
727  *
728  * @context:    Websocket context
729  */
730 LWS_VISIBLE extern const char *
731 lws_canonical_hostname(struct lws_context *context)
732 {
733         return (const char *)context->canonical_hostname;
734 }
735
736 int user_callback_handle_rxflow(lws_callback_function callback_function,
737                                 struct lws *wsi,
738                                 enum lws_callback_reasons reason, void *user,
739                                 void *in, size_t len)
740 {
741         int n;
742
743         n = callback_function(wsi, reason, user, in, len);
744         if (!n)
745                 n = _lws_rx_flow_control(wsi);
746
747         return n;
748 }
749
750
751 /**
752  * lws_set_proxy() - Setups proxy to lws_context.
753  * @context:    pointer to struct lws_context you want set proxy to
754  * @proxy: pointer to c string containing proxy in format address:port
755  *
756  * Returns 0 if proxy string was parsed and proxy was setup.
757  * Returns -1 if @proxy is NULL or has incorrect format.
758  *
759  * This is only required if your OS does not provide the http_proxy
760  * environment variable (eg, OSX)
761  *
762  *   IMPORTANT! You should call this function right after creation of the
763  *   lws_context and before call to connect. If you call this
764  *   function after connect behavior is undefined.
765  *   This function will override proxy settings made on lws_context
766  *   creation with genenv() call.
767  */
768
769 LWS_VISIBLE int
770 lws_set_proxy(struct lws_context *context, const char *proxy)
771 {
772         char *p;
773         char authstring[96];
774
775         if (!proxy)
776                 return -1;
777
778         p = strchr(proxy, '@');
779         if (p) { /* auth is around */
780
781                 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
782                         goto auth_too_long;
783
784                 strncpy(authstring, proxy, p - proxy);
785                 // null termination not needed on input
786                 if (lws_b64_encode_string(authstring, (p - proxy),
787                     context->proxy_basic_auth_token,
788                     sizeof context->proxy_basic_auth_token) < 0)
789                         goto auth_too_long;
790
791                 lwsl_notice(" Proxy auth in use\n");
792
793                 proxy = p + 1;
794         } else
795                 context->proxy_basic_auth_token[0] = '\0';
796
797         strncpy(context->http_proxy_address, proxy,
798                                 sizeof(context->http_proxy_address) - 1);
799         context->http_proxy_address[
800                                 sizeof(context->http_proxy_address) - 1] = '\0';
801
802         p = strchr(context->http_proxy_address, ':');
803         if (!p && !context->http_proxy_port) {
804                 lwsl_err("http_proxy needs to be ads:port\n");
805
806                 return -1;
807         } else {
808                 if (p) {
809                         *p = '\0';
810                         context->http_proxy_port = atoi(p + 1);
811                 }
812         }
813
814         lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
815                                                 context->http_proxy_port);
816
817         return 0;
818
819 auth_too_long:
820         lwsl_err("proxy auth too long\n");
821
822         return -1;
823 }
824
825 /**
826  * lws_get_protocol() - Returns a protocol pointer from a websocket
827  *                                connection.
828  * @wsi:        pointer to struct websocket you want to know the protocol of
829  *
830  *
831  *      Some apis can act on all live connections of a given protocol,
832  *      this is how you can get a pointer to the active protocol if needed.
833  */
834
835 LWS_VISIBLE const struct lws_protocols *
836 lws_get_protocol(struct lws *wsi)
837 {
838         return wsi->protocol;
839 }
840
841 LWS_VISIBLE int
842 lws_is_final_fragment(struct lws *wsi)
843 {
844         lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
845                         wsi->u.ws.final, wsi->u.ws.rx_packet_length, wsi->u.ws.rx_draining_ext);
846         return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
847 }
848
849 LWS_VISIBLE unsigned char
850 lws_get_reserved_bits(struct lws *wsi)
851 {
852         return wsi->u.ws.rsv;
853 }
854
855 int
856 lws_ensure_user_space(struct lws *wsi)
857 {
858         lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
859         if (!wsi->protocol)
860                 return 1;
861
862         /* allocate the per-connection user memory (if any) */
863
864         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
865                 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
866                 if (wsi->user_space  == NULL) {
867                         lwsl_err("Out of memory for conn user space\n");
868                         return 1;
869                 }
870         } else
871                 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
872                           __func__, wsi, wsi->protocol->per_session_data_size,
873                           wsi->user_space);
874         return 0;
875 }
876
877 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
878 {
879         unsigned long long now;
880         char buf[300];
881         int n;
882
883         buf[0] = '\0';
884         for (n = 0; n < LLL_COUNT; n++) {
885                 if (level != (1 << n))
886                         continue;
887                 now = time_in_microseconds() / 100;
888                 sprintf(buf, "[%llu:%04d] %s: ",
889                         (unsigned long long) now / 10000,
890                         (int)(now % 10000), log_level_names[n]);
891                 break;
892         }
893
894         fprintf(stderr, "%s%s", buf, line);
895 }
896
897 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
898 {
899         char buf[256];
900
901         if (!(log_level & filter))
902                 return;
903
904         vsnprintf(buf, sizeof(buf), format, vl);
905         buf[sizeof(buf) - 1] = '\0';
906
907         lwsl_emit(filter, buf);
908 }
909
910 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
911 {
912         va_list ap;
913
914         va_start(ap, format);
915         _lws_logv(filter, format, ap);
916         va_end(ap);
917 }
918
919 /**
920  * lws_set_log_level() - Set the logging bitfield
921  * @level:      OR together the LLL_ debug contexts you want output from
922  * @log_emit_function:  NULL to leave it as it is, or a user-supplied
923  *                      function to perform log string emission instead of
924  *                      the default stderr one.
925  *
926  *      log level defaults to "err", "warn" and "notice" contexts enabled and
927  *      emission on stderr.
928  */
929
930 LWS_VISIBLE void lws_set_log_level(int level,
931                                    void (*func)(int level, const char *line))
932 {
933         log_level = level;
934         if (func)
935                 lwsl_emit = func;
936 }
937
938 /**
939  * lws_use_ssl() - Find out if connection is using SSL
940  * @wsi:        websocket connection to check
941  *
942  *      Returns 0 if the connection is not using SSL, 1 if using SSL and
943  *      using verified cert, and 2 if using SSL but the cert was not
944  *      checked (appears for client wsi told to skip check on connection)
945  */
946 LWS_VISIBLE int
947 lws_is_ssl(struct lws *wsi)
948 {
949 #ifdef LWS_OPENSSL_SUPPORT
950         return wsi->use_ssl;
951 #else
952         (void)wsi;
953         return 0;
954 #endif
955 }
956
957 /**
958  * lws_partial_buffered() - find out if lws buffered the last write
959  * @wsi:        websocket connection to check
960  *
961  * Returns 1 if you cannot use lws_write because the last
962  * write on this connection is still buffered, and can't be cleared without
963  * returning to the service loop and waiting for the connection to be
964  * writeable again.
965  *
966  * If you will try to do >1 lws_write call inside a single
967  * WRITEABLE callback, you must check this after every write and bail if
968  * set, ask for a new writeable callback and continue writing from there.
969  *
970  * This is never set at the start of a writeable callback, but any write
971  * may set it.
972  */
973
974 LWS_VISIBLE int
975 lws_partial_buffered(struct lws *wsi)
976 {
977         return !!wsi->trunc_len;
978 }
979
980 void lws_set_protocol_write_pending(struct lws *wsi,
981                                     enum lws_pending_protocol_send pend)
982 {
983         lwsl_info("setting pps %d\n", pend);
984
985         if (wsi->pps)
986                 lwsl_err("pps overwrite\n");
987         wsi->pps = pend;
988         lws_rx_flow_control(wsi, 0);
989         lws_callback_on_writable(wsi);
990 }
991
992 LWS_VISIBLE size_t
993 lws_get_peer_write_allowance(struct lws *wsi)
994 {
995 #ifdef LWS_USE_HTTP2
996         /* only if we are using HTTP2 on this connection */
997         if (wsi->mode != LWSCM_HTTP2_SERVING)
998                 return -1;
999         /* user is only interested in how much he can send, or that he can't  */
1000         if (wsi->u.http2.tx_credit <= 0)
1001                 return 0;
1002
1003         return wsi->u.http2.tx_credit;
1004 #else
1005         (void)wsi;
1006         return -1;
1007 #endif
1008 }
1009
1010 LWS_VISIBLE void
1011 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1012 {
1013         lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1014         memset(&wsi->u, 0, sizeof(wsi->u));
1015         wsi->mode = mode;
1016 }
1017
1018 LWS_VISIBLE struct lws_plat_file_ops *
1019 lws_get_fops(struct lws_context *context)
1020 {
1021         return &context->fops;
1022 }
1023
1024 LWS_VISIBLE LWS_EXTERN struct lws_context *
1025 lws_get_context(const struct lws *wsi)
1026 {
1027         return wsi->context;
1028 }
1029
1030 LWS_VISIBLE LWS_EXTERN int
1031 lws_get_count_threads(struct lws_context *context)
1032 {
1033         return context->count_threads;
1034 }
1035
1036 LWS_VISIBLE LWS_EXTERN void *
1037 lws_wsi_user(struct lws *wsi)
1038 {
1039         return wsi->user_space;
1040 }
1041
1042 LWS_VISIBLE LWS_EXTERN void
1043 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1044                  unsigned char *buf, size_t len)
1045 {
1046         unsigned char *p, *start;
1047         int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1048
1049         assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1050
1051         start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1052
1053         *p++ = (((int)status) >> 8) & 0xff;
1054         *p++ = ((int)status) & 0xff;
1055
1056         if (buf)
1057                 while (len-- && p < start + budget)
1058                         *p++ = *buf++;
1059
1060         wsi->u.ws.close_in_ping_buffer_len = p - start;
1061 }
1062
1063 LWS_EXTERN int
1064 _lws_rx_flow_control(struct lws *wsi)
1065 {
1066         /* there is no pending change */
1067         if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1068                 lwsl_debug("%s: no pending change\n", __func__);
1069                 return 0;
1070         }
1071
1072         /* stuff is still buffered, not ready to really accept new input */
1073         if (wsi->rxflow_buffer) {
1074                 /* get ourselves called back to deal with stashed buffer */
1075                 lws_callback_on_writable(wsi);
1076                 return 0;
1077         }
1078
1079         /* pending is cleared, we can change rxflow state */
1080
1081         wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1082
1083         lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1084                               wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1085
1086         /* adjust the pollfd for this wsi */
1087
1088         if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1089                 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1090                         lwsl_info("%s: fail\n", __func__);
1091                         return -1;
1092                 }
1093         } else
1094                 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1095                         return -1;
1096
1097         return 0;
1098 }
1099
1100 LWS_EXTERN int
1101 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1102 {
1103         static const unsigned char e0f4[] = {
1104                 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1105                 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1106                 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1107                 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1108                 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1109                 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1110                 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1111                 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1112                 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1113                 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1114                 0x80 | ((4 - 1) << 2) | 1, /* ea */
1115                 0x80 | ((4 - 1) << 2) | 1, /* eb */
1116                 0x80 | ((4 - 1) << 2) | 1, /* ec */
1117                 0x80 | ((2 - 1) << 2) | 1, /* ed */
1118                 0x80 | ((4 - 1) << 2) | 1, /* ee */
1119                 0x80 | ((4 - 1) << 2) | 1, /* ef */
1120                 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1121                 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1122                 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1123                 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1124                 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1125
1126                 0,                         /* s0 */
1127                 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1128                 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1129         };
1130         unsigned char s = *state;
1131
1132         while (len--) {
1133                 unsigned char c = *buf++;
1134
1135                 if (!s) {
1136                         if (c >= 0x80) {
1137                                 if (c < 0xc2 || c > 0xf4)
1138                                         return 1;
1139                                 if (c < 0xe0)
1140                                         s = 0x80 | ((4 - 1) << 2);
1141                                 else
1142                                         s = e0f4[c - 0xe0];
1143                         }
1144                 } else {
1145                         if (c < (s & 0xf0) ||
1146                             c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1147                                 return 1;
1148                         s = e0f4[21 + (s & 3)];
1149                 }
1150         }
1151
1152         *state = s;
1153
1154         return 0;
1155 }
1156
1157 /**
1158  * lws_parse_uri:       cut up https:/xxx:yyy/zzz into pieces
1159  *                      Notice it does so by dropping '\0' into input string
1160  *
1161  * @p:                  incoming uri string.. will get written to
1162  * @prot:               result pointer for protocol part (https://)
1163  * @ads:                result pointer for address part
1164  * @port:               result pointer for port part
1165  * @path:               result pointer for path part
1166  */
1167
1168 LWS_VISIBLE LWS_EXTERN int
1169 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1170               const char **path)
1171 {
1172         const char *end;
1173         static const char *slash = "/";
1174
1175         /* cut up the location into address, port and path */
1176         *prot = p;
1177         while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1178                 p++;
1179         if (!*p) {
1180                 end = p;
1181                 p = (char *)*prot;
1182                 *prot = end;
1183         } else {
1184                 *p = '\0';
1185                 p += 3;
1186         }
1187         *ads = p;
1188         if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1189                 *port = 80;
1190         else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1191                 *port = 443;
1192
1193         while (*p && *p != ':' && *p != '/')
1194                 p++;
1195         if (*p == ':') {
1196                 *p++ = '\0';
1197                 *port = atoi(p);
1198                 while (*p && *p != '/')
1199                         p++;
1200         }
1201         *path = slash;
1202         if (*p) {
1203                 *p++ = '\0';
1204                 if (*p)
1205                         *path = p;
1206         }
1207
1208         return 0;
1209 }
1210
1211 #ifdef LWS_NO_EXTENSIONS
1212
1213 /* we need to provide dummy callbacks for internal exts
1214  * so user code runs when faced with a lib compiled with
1215  * extensions disabled.
1216  */
1217
1218 int
1219 lws_extension_callback_pm_deflate(struct lws_context *context,
1220                                   const struct lws_extension *ext,
1221                                   struct lws *wsi,
1222                                   enum lws_extension_callback_reasons reason,
1223                                   void *user, void *in, size_t len)
1224 {
1225         return 0;
1226 }
1227 #endif
1228