client error on timeout before connection
[platform/upstream/libwebsockets.git] / lib / libwebsockets.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2014 Andy Green <andy@warmcat.com>
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public
8  *  License as published by the Free Software Foundation:
9  *  version 2.1 of the License.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23
24 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
25 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
26
27 static const char * const log_level_names[] = {
28         "ERR",
29         "WARN",
30         "NOTICE",
31         "INFO",
32         "DEBUG",
33         "PARSER",
34         "HEADER",
35         "EXTENSION",
36         "CLIENT",
37         "LATENCY",
38 };
39
40 void
41 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
42                          struct libwebsocket *wsi, enum lws_close_status reason)
43 {
44         int n, m, ret;
45         int old_state;
46         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
47                                                   LWS_SEND_BUFFER_POST_PADDING];
48         struct lws_tokens eff_buf;
49
50         if (!wsi)
51                 return;
52
53         old_state = wsi->state;
54
55         if (wsi->socket_is_permanently_unusable ||
56             reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)
57                 goto just_kill_connection;
58
59         switch (old_state) {
60         case WSI_STATE_DEAD_SOCKET:
61                 return;
62
63         /* we tried the polite way... */
64         case WSI_STATE_AWAITING_CLOSE_ACK:
65                 goto just_kill_connection;
66
67         case WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE:
68                 if (wsi->truncated_send_len) {
69                         libwebsocket_callback_on_writable(context, wsi);
70                         return;
71                 }
72                 lwsl_info("wsi %p completed WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
73                 goto just_kill_connection;
74         default:
75                 if (wsi->truncated_send_len) {
76                         lwsl_info("wsi %p entering WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
77                         wsi->state = WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE;
78                         libwebsocket_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
79                         return;
80                 }
81                 break;
82         }
83
84         wsi->u.ws.close_reason = reason;
85
86         if (wsi->mode == LWS_CONNMODE_WS_CLIENT_WAITING_CONNECT ||
87                         wsi->mode == LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE) {
88
89                 context->protocols[0].callback(context, wsi,
90                         LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, NULL, 0);
91
92                 lws_free_header_table(wsi);
93                 goto just_kill_connection;
94         }
95
96         if (wsi->mode == LWS_CONNMODE_HTTP_SERVING)
97                 context->protocols[0].callback(context, wsi,
98                         LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
99
100         if (wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED) {
101                 if (wsi->u.http.fd != LWS_INVALID_FILE) {
102                         lwsl_debug("closing http file\n");
103                         compatible_file_close(wsi->u.http.fd);
104                         wsi->u.http.fd = LWS_INVALID_FILE;
105                         context->protocols[0].callback(context, wsi,
106                                 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
107                 }
108         }
109
110         /*
111          * are his extensions okay with him closing?  Eg he might be a mux
112          * parent and just his ch1 aspect is closing?
113          */
114         
115         if (lws_ext_callback_for_each_active(wsi,
116                       LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
117                 lwsl_ext("extension vetoed close\n");
118                 return;
119         }
120
121         /*
122          * flush any tx pending from extensions, since we may send close packet
123          * if there are problems with send, just nuke the connection
124          */
125
126         do {
127                 ret = 0;
128                 eff_buf.token = NULL;
129                 eff_buf.token_len = 0;
130
131                 /* show every extension the new incoming data */
132
133                 m = lws_ext_callback_for_each_active(wsi,
134                           LWS_EXT_CALLBACK_FLUSH_PENDING_TX, &eff_buf, 0);
135                 if (m < 0) {
136                         lwsl_ext("Extension reports fatal error\n");
137                         goto just_kill_connection;
138                 }
139                 if (m)
140                         /*
141                          * at least one extension told us he has more
142                          * to spill, so we will go around again after
143                          */
144                         ret = 1;
145
146                 /* assuming they left us something to send, send it */
147
148                 if (eff_buf.token_len)
149                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
150                                       eff_buf.token_len) != eff_buf.token_len) {
151                                 lwsl_debug("close: ext spill failed\n");
152                                 goto just_kill_connection;
153                         }
154         } while (ret);
155
156         /*
157          * signal we are closing, libwebsocket_write will
158          * add any necessary version-specific stuff.  If the write fails,
159          * no worries we are closing anyway.  If we didn't initiate this
160          * close, then our state has been changed to
161          * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
162          *
163          * Likewise if it's a second call to close this connection after we
164          * sent the close indication to the peer already, we are in state
165          * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
166          */
167
168         if (old_state == WSI_STATE_ESTABLISHED &&
169             reason != LWS_CLOSE_STATUS_NOSTATUS &&
170             reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY) {
171
172                 lwsl_debug("sending close indication...\n");
173
174                 /* make valgrind happy */
175                 memset(buf, 0, sizeof(buf));
176                 n = libwebsocket_write(wsi,
177                                 &buf[LWS_SEND_BUFFER_PRE_PADDING + 2],
178                                                             0, LWS_WRITE_CLOSE);
179                 if (n >= 0) {
180                         /*
181                          * we have sent a nice protocol level indication we
182                          * now wish to close, we should not send anything more
183                          */
184
185                         wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
186
187                         /*
188                          * ...and we should wait for a reply for a bit
189                          * out of politeness
190                          */
191
192                         libwebsocket_set_timeout(wsi,
193                                                   PENDING_TIMEOUT_CLOSE_ACK, 1);
194
195                         lwsl_debug("sent close indication, awaiting ack\n");
196
197                         return;
198                 }
199
200                 lwsl_info("close: sending close packet failed, hanging up\n");
201
202                 /* else, the send failed and we should just hang up */
203         }
204
205 just_kill_connection:
206
207         lwsl_debug("close: just_kill_connection\n");
208
209         /*
210          * we won't be servicing or receiving anything further from this guy
211          * delete socket from the internal poll list if still present
212          */
213
214         lws_ssl_remove_wsi_from_buffered_list(context, wsi);
215
216         remove_wsi_socket_from_fds(context, wsi);
217
218         wsi->state = WSI_STATE_DEAD_SOCKET;
219
220         lws_free2(wsi->rxflow_buffer);
221
222         if (wsi->mode == LWS_CONNMODE_HTTP2_SERVING && wsi->u.hdr.ah) {
223                 lws_free2(wsi->u.hdr.ah);
224         }
225
226         if ((old_state == WSI_STATE_ESTABLISHED ||
227              wsi->mode == LWS_CONNMODE_WS_SERVING ||
228              wsi->mode == LWS_CONNMODE_WS_CLIENT)) {
229
230                 lws_free2(wsi->u.ws.rx_user_buffer);
231
232                 if (wsi->truncated_send_malloc) {
233                         /* not going to be completed... nuke it */
234                         lws_free2(wsi->truncated_send_malloc);
235                         wsi->truncated_send_len = 0;
236                 }
237                 if (wsi->u.ws.ping_payload_buf) {
238                         lws_free2(wsi->u.ws.ping_payload_buf);
239                         wsi->u.ws.ping_payload_alloc = 0;
240                         wsi->u.ws.ping_payload_len = 0;
241                         wsi->u.ws.ping_pending_flag = 0;
242                 }
243         }
244
245         /* tell the user it's all over for this guy */
246
247         if (wsi->protocol && wsi->protocol->callback &&
248                         ((old_state == WSI_STATE_ESTABLISHED) ||
249                          (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
250                          (old_state == WSI_STATE_AWAITING_CLOSE_ACK) ||
251                          (old_state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE))) {
252                 lwsl_debug("calling back CLOSED\n");
253                 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
254                                                       wsi->user_space, NULL, 0);
255         } else if (wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED) {
256                 lwsl_debug("calling back CLOSED_HTTP\n");
257                 context->protocols[0].callback(context, wsi,
258                         LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0 );
259         } else if (wsi->mode == LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY) {
260                 lwsl_debug("Connection closed before server reply\n");
261                 context->protocols[0].callback(context, wsi,
262                                 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
263                                 wsi->user_space, NULL, 0 );
264         } else
265                 lwsl_debug("not calling back closed mode=%d state=%d\n",
266                            wsi->mode, old_state);
267
268         /* deallocate any active extension contexts */
269         
270         if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_DESTROY, NULL, 0) < 0)
271                 lwsl_warn("extension destruction failed\n");
272 #ifndef LWS_NO_EXTENSIONS
273         for (n = 0; n < wsi->count_active_extensions; n++)
274                 lws_free(wsi->active_extensions_user[n]);
275 #endif
276         /*
277          * inform all extensions in case they tracked this guy out of band
278          * even though not active on him specifically
279          */
280         if (lws_ext_callback_for_each_extension_type(context, wsi,
281                        LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
282                 lwsl_warn("ext destroy wsi failed\n");
283
284 /*      lwsl_info("closing fd=%d\n", wsi->sock); */
285
286         if (!lws_ssl_close(wsi) && wsi->sock >= 0) {
287                 n = shutdown(wsi->sock, SHUT_RDWR);
288                 if (n)
289                         lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
290
291                 n = compatible_close(wsi->sock);
292                 if (n)
293                         lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
294         }
295
296         /* outermost destroy notification for wsi (user_space still intact) */
297         context->protocols[0].callback(context, wsi,
298                         LWS_CALLBACK_WSI_DESTROY, wsi->user_space, NULL, 0);
299
300         if (wsi->protocol && wsi->protocol->per_session_data_size &&
301             wsi->user_space && !wsi->user_space_externally_allocated)
302                 lws_free(wsi->user_space);
303
304         /* As a precaution, free the header table in case it lingered: */
305         lws_free_header_table(wsi);
306         lws_free(wsi);
307 }
308
309 LWS_VISIBLE int
310 libwebsockets_get_addresses(struct libwebsocket_context *context,
311                             void *ads, char *name, int name_len,
312                             char *rip, int rip_len)
313 {
314         struct addrinfo ai, *res;
315         void *p = NULL;
316
317         rip[0] = '\0';
318         name[0] = '\0';
319
320 #ifdef LWS_USE_IPV6
321         if (LWS_IPV6_ENABLED(context)) {
322                 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
323                         lwsl_err("inet_ntop", strerror(LWS_ERRNO));
324                         return -1;
325                 }
326
327                 // Strip off the IPv4 to IPv6 header if one exists
328                 if (strncmp(rip, "::ffff:", 7) == 0)
329                         memmove(rip, rip + 7, strlen(rip) - 6);
330
331                 getnameinfo((struct sockaddr *)ads,
332                                 sizeof(struct sockaddr_in6), name,
333                                                         name_len, NULL, 0, 0);
334                 
335                 return 0;
336         } else
337 #endif
338         {
339                 memset(&ai, 0, sizeof ai);
340                 ai.ai_family = PF_UNSPEC;
341                 ai.ai_socktype = SOCK_STREAM;
342                 ai.ai_flags = AI_CANONNAME;
343
344                 if (getnameinfo((struct sockaddr *)ads,
345                                 sizeof(struct sockaddr_in),
346                                 name, name_len, NULL, 0, 0))
347                         return -1;
348
349                 if (!rip)
350                         return 0;
351
352                 if (getaddrinfo(name, NULL, &ai, &res))
353                         return -1;
354
355                 while (!p && res) {
356                         switch (res->ai_family) {
357                         case AF_INET:
358                                 p = &((struct sockaddr_in *)res->ai_addr)->sin_addr;
359                                 break;
360                         }
361
362                         res = res->ai_next;
363                 }
364         }
365
366         if (!p)
367                 return -1;
368
369         lws_plat_inet_ntop(AF_INET, p, rip, rip_len);
370
371         return 0;
372 }
373
374 /**
375  * libwebsockets_get_peer_addresses() - Get client address information
376  * @context:    Libwebsockets context
377  * @wsi:        Local struct libwebsocket associated with
378  * @fd:         Connection socket descriptor
379  * @name:       Buffer to take client address name
380  * @name_len:   Length of client address name buffer
381  * @rip:        Buffer to take client address IP dotted quad
382  * @rip_len:    Length of client address IP buffer
383  *
384  *      This function fills in @name and @rip with the name and IP of
385  *      the client connected with socket descriptor @fd.  Names may be
386  *      truncated if there is not enough room.  If either cannot be
387  *      determined, they will be returned as valid zero-length strings.
388  */
389
390 LWS_VISIBLE void
391 libwebsockets_get_peer_addresses(struct libwebsocket_context *context,
392         struct libwebsocket *wsi, int fd, char *name, int name_len,
393                                         char *rip, int rip_len)
394 {
395         socklen_t len;
396 #ifdef LWS_USE_IPV6
397         struct sockaddr_in6 sin6;
398 #endif
399         struct sockaddr_in sin4;
400         int ret = -1;
401         void *p;
402
403         rip[0] = '\0';
404         name[0] = '\0';
405
406         lws_latency_pre(context, wsi);
407
408 #ifdef LWS_USE_IPV6
409         if (LWS_IPV6_ENABLED(context)) {
410                 len = sizeof(sin6);
411                 p = &sin6;
412         } else
413 #endif
414         {
415                 len = sizeof(sin4);
416                 p = &sin4;
417         }
418
419         if (getpeername(fd, p, &len) < 0) {
420                 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
421                 goto bail;
422         }
423         
424         ret = libwebsockets_get_addresses(context, p, name, name_len, rip, rip_len);
425
426 bail:
427         lws_latency(context, wsi, "libwebsockets_get_peer_addresses", ret, 1);
428 }
429
430 /**
431  * libwebsocket_context_user() - get the user data associated with the context
432  * @context: Websocket context
433  *
434  *      This returns the optional user allocation that can be attached to
435  *      the context the sockets live in at context_create time.  It's a way
436  *      to let all sockets serviced in the same context share data without
437  *      using globals statics in the user code.
438  */
439 LWS_EXTERN void *
440 libwebsocket_context_user(struct libwebsocket_context *context)
441 {
442         return context->user_space;
443 }
444
445
446 /**
447  * libwebsocket_callback_all_protocol() - Callback all connections using
448  *                              the given protocol with the given reason
449  *
450  * @protocol:   Protocol whose connections will get callbacks
451  * @reason:     Callback reason index
452  */
453
454 LWS_VISIBLE int
455 libwebsocket_callback_all_protocol(
456                 const struct libwebsocket_protocols *protocol, int reason)
457 {
458         struct libwebsocket_context *context = protocol->owning_server;
459         int n;
460         struct libwebsocket *wsi;
461
462         for (n = 0; n < context->fds_count; n++) {
463                 wsi = wsi_from_fd(context, context->fds[n].fd);
464                 if (!wsi)
465                         continue;
466                 if (wsi->protocol == protocol)
467                         protocol->callback(context, wsi,
468                                         reason, wsi->user_space, NULL, 0);
469         }
470
471         return 0;
472 }
473
474 /**
475  * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
476  *
477  * You will not need this unless you are doing something special
478  *
479  * @wsi:        Websocket connection instance
480  * @reason:     timeout reason
481  * @secs:       how many seconds
482  */
483
484 LWS_VISIBLE void
485 libwebsocket_set_timeout(struct libwebsocket *wsi,
486                                           enum pending_timeout reason, int secs)
487 {
488         time_t now;
489
490         time(&now);
491
492         wsi->pending_timeout_limit = now + secs;
493         wsi->pending_timeout = reason;
494 }
495
496
497 /**
498  * libwebsocket_get_socket_fd() - returns the socket file descriptor
499  *
500  * You will not need this unless you are doing something special
501  *
502  * @wsi:        Websocket connection instance
503  */
504
505 LWS_VISIBLE int
506 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
507 {
508         return wsi->sock;
509 }
510
511 #ifdef LWS_LATENCY
512 void
513 lws_latency(struct libwebsocket_context *context, struct libwebsocket *wsi,
514                                      const char *action, int ret, int completed)
515 {
516         unsigned long long u;
517         char buf[256];
518
519         u = time_in_microseconds();
520
521         if (!action) {
522                 wsi->latency_start = u;
523                 if (!wsi->action_start)
524                         wsi->action_start = u;
525                 return;
526         }
527         if (completed) {
528                 if (wsi->action_start == wsi->latency_start)
529                         sprintf(buf,
530                           "Completion first try lat %lluus: %p: ret %d: %s\n",
531                                         u - wsi->latency_start,
532                                                       (void *)wsi, ret, action);
533                 else
534                         sprintf(buf,
535                           "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
536                                 u - wsi->action_start,
537                                         u - wsi->latency_start,
538                                                       (void *)wsi, ret, action);
539                 wsi->action_start = 0;
540         } else
541                 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
542                               u - wsi->latency_start, (void *)wsi, ret, action);
543
544         if (u - wsi->latency_start > context->worst_latency) {
545                 context->worst_latency = u - wsi->latency_start;
546                 strcpy(context->worst_latency_info, buf);
547         }
548         lwsl_latency("%s", buf);
549 }
550 #endif
551
552
553
554 /**
555  * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
556  *                              received packets.
557  *
558  * If the output side of a server process becomes choked, this allows flow
559  * control for the input side.
560  *
561  * @wsi:        Websocket connection instance to get callback for
562  * @enable:     0 = disable read servicing for this connection, 1 = enable
563  */
564
565 LWS_VISIBLE int
566 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
567 {
568         if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
569                 return 0;
570
571         lwsl_info("libwebsocket_rx_flow_control(0x%p, %d)\n", wsi, enable);
572         wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
573
574         return 0;
575 }
576
577 /**
578  * libwebsocket_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
579  *
580  * When the user server code realizes it can accept more input, it can
581  * call this to have the RX flow restriction removed from all connections using
582  * the given protocol.
583  *
584  * @protocol:   all connections using this protocol will be allowed to receive
585  */
586
587 LWS_VISIBLE void
588 libwebsocket_rx_flow_allow_all_protocol(
589                                 const struct libwebsocket_protocols *protocol)
590 {
591         struct libwebsocket_context *context = protocol->owning_server;
592         int n;
593         struct libwebsocket *wsi;
594
595         for (n = 0; n < context->fds_count; n++) {
596                 wsi = wsi_from_fd(context, context->fds[n].fd);
597                 if (!wsi)
598                         continue;
599                 if (wsi->protocol == protocol)
600                         libwebsocket_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
601         }
602 }
603
604
605 /**
606  * libwebsocket_canonical_hostname() - returns this host's hostname
607  *
608  * This is typically used by client code to fill in the host parameter
609  * when making a client connection.  You can only call it after the context
610  * has been created.
611  *
612  * @context:    Websocket context
613  */
614 LWS_VISIBLE extern const char *
615 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
616 {
617         return (const char *)context->canonical_hostname;
618 }
619
620 int user_callback_handle_rxflow(callback_function callback_function,
621                 struct libwebsocket_context *context,
622                         struct libwebsocket *wsi,
623                          enum libwebsocket_callback_reasons reason, void *user,
624                                                           void *in, size_t len)
625 {
626         int n;
627
628         n = callback_function(context, wsi, reason, user, in, len);
629         if (!n)
630                 n = _libwebsocket_rx_flow_control(wsi);
631
632         return n;
633 }
634
635
636 /**
637  * libwebsocket_set_proxy() - Setups proxy to libwebsocket_context.
638  * @context:    pointer to struct libwebsocket_context you want set proxy to
639  * @proxy: pointer to c string containing proxy in format address:port
640  *
641  * Returns 0 if proxy string was parsed and proxy was setup. 
642  * Returns -1 if @proxy is NULL or has incorrect format.
643  *
644  * This is only required if your OS does not provide the http_proxy
645  * environment variable (eg, OSX)
646  *
647  *   IMPORTANT! You should call this function right after creation of the
648  *   libwebsocket_context and before call to connect. If you call this
649  *   function after connect behavior is undefined.
650  *   This function will override proxy settings made on libwebsocket_context
651  *   creation with genenv() call.
652  */
653
654 LWS_VISIBLE int
655 libwebsocket_set_proxy(struct libwebsocket_context *context, const char *proxy)
656 {
657         char *p;
658         
659         if (!proxy)
660                 return -1;
661
662         strncpy(context->http_proxy_address, proxy,
663                                 sizeof(context->http_proxy_address) - 1);
664         context->http_proxy_address[
665                                 sizeof(context->http_proxy_address) - 1] = '\0';
666         
667         p = strchr(context->http_proxy_address, ':');
668         if (!p) {
669                 lwsl_err("http_proxy needs to be ads:port\n");
670
671                 return -1;
672         }
673         *p = '\0';
674         context->http_proxy_port = atoi(p + 1);
675         
676         lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
677                                                 context->http_proxy_port);
678
679         return 0;
680 }
681
682 /**
683  * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
684  *                                connection.
685  * @wsi:        pointer to struct websocket you want to know the protocol of
686  *
687  *
688  *      Some apis can act on all live connections of a given protocol,
689  *      this is how you can get a pointer to the active protocol if needed.
690  */
691
692 LWS_VISIBLE const struct libwebsocket_protocols *
693 libwebsockets_get_protocol(struct libwebsocket *wsi)
694 {
695         return wsi->protocol;
696 }
697
698 LWS_VISIBLE int
699 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
700 {
701         return wsi->u.ws.final;
702 }
703
704 LWS_VISIBLE unsigned char
705 libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
706 {
707         return wsi->u.ws.rsv;
708 }
709
710 int
711 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
712 {
713         lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
714         if (!wsi->protocol)
715                 return 1;
716
717         /* allocate the per-connection user memory (if any) */
718
719         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
720                 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
721                 if (wsi->user_space  == NULL) {
722                         lwsl_err("Out of memory for conn user space\n");
723                         return 1;
724                 }
725         } else
726                 lwsl_info("%s: %p protocol pss %u, user_space=%d\n", __func__, wsi, wsi->protocol->per_session_data_size, wsi->user_space);
727         return 0;
728 }
729
730 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
731 {
732         char buf[300];
733         unsigned long long now;
734         int n;
735
736         buf[0] = '\0';
737         for (n = 0; n < LLL_COUNT; n++)
738                 if (level == (1 << n)) {
739                         now = time_in_microseconds() / 100;
740                         sprintf(buf, "[%llu:%04d] %s: ", (unsigned long long) now / 10000,
741                                 (int)(now % 10000), log_level_names[n]);
742                         break;
743                 }
744
745         fprintf(stderr, "%s%s", buf, line);
746 }
747
748
749 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
750 {
751         char buf[256];
752
753         if (!(log_level & filter))
754                 return;
755
756         vsnprintf(buf, sizeof(buf), format, vl);
757         buf[sizeof(buf) - 1] = '\0';
758
759         lwsl_emit(filter, buf);
760 }
761
762 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
763 {
764         va_list ap;
765
766         va_start(ap, format);
767         _lws_logv(filter, format, ap);
768         va_end(ap);
769 }
770
771 /**
772  * lws_set_log_level() - Set the logging bitfield
773  * @level:      OR together the LLL_ debug contexts you want output from
774  * @log_emit_function:  NULL to leave it as it is, or a user-supplied
775  *                      function to perform log string emission instead of
776  *                      the default stderr one.
777  *
778  *      log level defaults to "err", "warn" and "notice" contexts enabled and
779  *      emission on stderr.
780  */
781
782 LWS_VISIBLE void lws_set_log_level(int level, void (*log_emit_function)(int level,
783                                                               const char *line))
784 {
785         log_level = level;
786         if (log_emit_function)
787                 lwsl_emit = log_emit_function;
788 }
789
790 /**
791  * lws_use_ssl() - Find out if connection is using SSL
792  * @wsi:        websocket connection to check
793  *
794  *      Returns 0 if the connection is not using SSL, 1 if using SSL and
795  *      using verified cert, and 2 if using SSL but the cert was not
796  *      checked (appears for client wsi told to skip check on connection)
797  */
798 LWS_VISIBLE int
799 lws_is_ssl(struct libwebsocket *wsi)
800 {
801 #ifdef LWS_OPENSSL_SUPPORT
802         return wsi->use_ssl;
803 #else
804         return 0;
805 #endif
806 }
807
808 /**
809  * lws_partial_buffered() - find out if lws buffered the last write
810  * @wsi:        websocket connection to check
811  *
812  * Returns 1 if you cannot use libwebsocket_write because the last
813  * write on this connection is still buffered, and can't be cleared without
814  * returning to the service loop and waiting for the connection to be
815  * writeable again.
816  * 
817  * If you will try to do >1 libwebsocket_write call inside a single
818  * WRITEABLE callback, you must check this after every write and bail if
819  * set, ask for a new writeable callback and continue writing from there.
820  * 
821  * This is never set at the start of a writeable callback, but any write
822  * may set it.
823  */
824
825 LWS_VISIBLE int
826 lws_partial_buffered(struct libwebsocket *wsi)
827 {
828         return !!wsi->truncated_send_len;       
829 }
830
831 void lws_set_protocol_write_pending(struct libwebsocket_context *context,
832                                     struct libwebsocket *wsi,
833                                     enum lws_pending_protocol_send pend)
834 {
835         lwsl_info("setting pps %d\n", pend);
836         
837         if (wsi->pps)
838                 lwsl_err("pps overwrite\n");
839         wsi->pps = pend;
840         libwebsocket_rx_flow_control(wsi, 0);
841         libwebsocket_callback_on_writable(context, wsi);
842 }
843
844 LWS_VISIBLE size_t
845 lws_get_peer_write_allowance(struct libwebsocket *wsi)
846 {
847 #ifdef LWS_USE_HTTP2
848         /* only if we are using HTTP2 on this connection */
849         if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING)
850                 return -1;
851         /* user is only interested in how much he can send, or that he can't  */
852         if (wsi->u.http2.tx_credit <= 0)
853                 return 0;
854         
855         return wsi->u.http2.tx_credit;
856 #else
857         return -1;
858 #endif
859 }
860
861 LWS_VISIBLE void
862 lws_union_transition(struct libwebsocket *wsi, enum connection_mode mode)
863 {
864         memset(&wsi->u, 0, sizeof(wsi->u));
865         wsi->mode = mode;
866 }