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