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