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