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