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