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