gethostbyname removal from lws get peer addresses
[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)
96                 context->protocols[0].callback(context, wsi,
97                         LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
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, libwebsocket_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         lws_free2(wsi->rxflow_buffer);
217
218         if (wsi->mode == LWS_CONNMODE_HTTP2_SERVING && wsi->u.hdr.ah) {
219                 lws_free2(wsi->u.hdr.ah);
220         }
221
222         if ((old_state == WSI_STATE_ESTABLISHED ||
223              wsi->mode == LWS_CONNMODE_WS_SERVING ||
224              wsi->mode == LWS_CONNMODE_WS_CLIENT)) {
225
226                 lws_free2(wsi->u.ws.rx_user_buffer);
227
228                 if (wsi->truncated_send_malloc) {
229                         /* not going to be completed... nuke it */
230                         lws_free2(wsi->truncated_send_malloc);
231                         wsi->truncated_send_len = 0;
232                 }
233                 if (wsi->u.ws.ping_payload_buf) {
234                         lws_free2(wsi->u.ws.ping_payload_buf);
235                         wsi->u.ws.ping_payload_alloc = 0;
236                         wsi->u.ws.ping_payload_len = 0;
237                 }
238         }
239
240         /* tell the user it's all over for this guy */
241
242         if (wsi->protocol && wsi->protocol->callback &&
243                         ((old_state == WSI_STATE_ESTABLISHED) ||
244                          (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
245                          (old_state == WSI_STATE_AWAITING_CLOSE_ACK) ||
246                          (old_state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE))) {
247                 lwsl_debug("calling back CLOSED\n");
248                 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
249                                                       wsi->user_space, NULL, 0);
250         } else if (wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED) {
251                 lwsl_debug("calling back CLOSED_HTTP\n");
252                 context->protocols[0].callback(context, wsi,
253                         LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0 );
254         } else
255                 lwsl_debug("not calling back closed\n");
256
257         /* deallocate any active extension contexts */
258         
259         if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_DESTROY, NULL, 0) < 0)
260                 lwsl_warn("extension destruction failed\n");
261 #ifndef LWS_NO_EXTENSIONS
262         for (n = 0; n < wsi->count_active_extensions; n++)
263                 lws_free(wsi->active_extensions_user[n]);
264 #endif
265         /*
266          * inform all extensions in case they tracked this guy out of band
267          * even though not active on him specifically
268          */
269         if (lws_ext_callback_for_each_extension_type(context, wsi,
270                        LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
271                 lwsl_warn("ext destroy wsi failed\n");
272
273 /*      lwsl_info("closing fd=%d\n", wsi->sock); */
274
275         if (!lws_ssl_close(wsi) && wsi->sock >= 0) {
276                 n = shutdown(wsi->sock, SHUT_RDWR);
277                 if (n)
278                         lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
279
280                 n = compatible_close(wsi->sock);
281                 if (n)
282                         lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
283         }
284
285         /* outermost destroy notification for wsi (user_space still intact) */
286         context->protocols[0].callback(context, wsi,
287                         LWS_CALLBACK_WSI_DESTROY, wsi->user_space, NULL, 0);
288
289         if (wsi->protocol && wsi->protocol->per_session_data_size &&
290             wsi->user_space && !wsi->user_space_externally_allocated)
291                 lws_free(wsi->user_space);
292
293         /* As a precaution, free the header table in case it lingered: */
294         lws_free_header_table(wsi);
295         lws_free(wsi);
296 }
297
298 LWS_VISIBLE int
299 libwebsockets_get_addresses(struct libwebsocket_context *context,
300                             void *ads, char *name, int name_len,
301                             char *rip, int rip_len)
302 {
303         struct addrinfo ai, *res;
304         void *p = NULL;
305
306         rip[0] = '\0';
307         name[0] = '\0';
308
309 #ifdef LWS_USE_IPV6
310         if (LWS_IPV6_ENABLED(context)) {
311                 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
312                         lwsl_err("inet_ntop", strerror(LWS_ERRNO));
313                         return -1;
314                 }
315
316                 // Strip off the IPv4 to IPv6 header if one exists
317                 if (strncmp(rip, "::ffff:", 7) == 0)
318                         memmove(rip, rip + 7, strlen(rip) - 6);
319
320                 getnameinfo((struct sockaddr *)ads,
321                                 sizeof(struct sockaddr_in6), name,
322                                                         name_len, NULL, 0, 0);
323                 
324                 return 0;
325         } else
326 #endif
327         {
328                 memset(&ai, 0, sizeof ai);
329                 ai.ai_family = PF_UNSPEC;
330                 ai.ai_socktype = SOCK_STREAM;
331                 ai.ai_flags = AI_CANONNAME;
332
333                 if (getnameinfo((struct sockaddr *)ads,
334                                 sizeof(struct sockaddr_in),
335                                 name, name_len, NULL, 0, 0))
336                         return -1;
337
338                 if (!rip)
339                         return 0;
340
341                 if (getaddrinfo(name, NULL, &ai, &res))
342                         return -1;
343
344                 while (!p && res) {
345                         switch (res->ai_family) {
346                         case AF_INET:
347                                 p = &((struct sockaddr_in *)res->ai_addr)->sin_addr;
348                                 break;
349                         }
350
351                         res = res->ai_next;
352                 }
353         }
354
355         if (!p)
356                 return -1;
357
358         inet_ntop(AF_INET, p, rip, rip_len);
359
360         return 0;
361 }
362
363 /**
364  * libwebsockets_get_peer_addresses() - Get client address information
365  * @context:    Libwebsockets context
366  * @wsi:        Local struct libwebsocket associated with
367  * @fd:         Connection socket descriptor
368  * @name:       Buffer to take client address name
369  * @name_len:   Length of client address name buffer
370  * @rip:        Buffer to take client address IP dotted quad
371  * @rip_len:    Length of client address IP buffer
372  *
373  *      This function fills in @name and @rip with the name and IP of
374  *      the client connected with socket descriptor @fd.  Names may be
375  *      truncated if there is not enough room.  If either cannot be
376  *      determined, they will be returned as valid zero-length strings.
377  */
378
379 LWS_VISIBLE void
380 libwebsockets_get_peer_addresses(struct libwebsocket_context *context,
381         struct libwebsocket *wsi, int fd, char *name, int name_len,
382                                         char *rip, int rip_len)
383 {
384         socklen_t len;
385 #ifdef LWS_USE_IPV6
386         struct sockaddr_in6 sin6;
387 #endif
388         struct sockaddr_in sin4;
389         int ret = -1;
390         void *p;
391
392         rip[0] = '\0';
393         name[0] = '\0';
394
395         lws_latency_pre(context, wsi);
396
397 #ifdef LWS_USE_IPV6
398         if (LWS_IPV6_ENABLED(context)) {
399                 len = sizeof(sin6);
400                 p = &sin6;
401         } else
402 #endif
403         {
404                 len = sizeof(sin4);
405                 p = &sin4;
406         }
407
408         if (getpeername(fd, p, &len) < 0) {
409                 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
410                 goto bail;
411         }
412         
413         ret = libwebsockets_get_addresses(context, p, name, name_len, rip, rip_len);
414
415 bail:
416         lws_latency(context, wsi, "libwebsockets_get_peer_addresses", ret, 1);
417 }
418
419 /**
420  * libwebsocket_context_user() - get the user data associated with the context
421  * @context: Websocket context
422  *
423  *      This returns the optional user allocation that can be attached to
424  *      the context the sockets live in at context_create time.  It's a way
425  *      to let all sockets serviced in the same context share data without
426  *      using globals statics in the user code.
427  */
428 LWS_EXTERN void *
429 libwebsocket_context_user(struct libwebsocket_context *context)
430 {
431         return context->user_space;
432 }
433
434
435 /**
436  * libwebsocket_callback_all_protocol() - Callback all connections using
437  *                              the given protocol with the given reason
438  *
439  * @protocol:   Protocol whose connections will get callbacks
440  * @reason:     Callback reason index
441  */
442
443 LWS_VISIBLE int
444 libwebsocket_callback_all_protocol(
445                 const struct libwebsocket_protocols *protocol, int reason)
446 {
447         struct libwebsocket_context *context = protocol->owning_server;
448         int n;
449         struct libwebsocket *wsi;
450
451         for (n = 0; n < context->fds_count; n++) {
452                 wsi = context->lws_lookup[context->fds[n].fd];
453                 if (!wsi)
454                         continue;
455                 if (wsi->protocol == protocol)
456                         protocol->callback(context, wsi,
457                                         reason, wsi->user_space, NULL, 0);
458         }
459
460         return 0;
461 }
462
463 /**
464  * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
465  *
466  * You will not need this unless you are doing something special
467  *
468  * @wsi:        Websocket connection instance
469  * @reason:     timeout reason
470  * @secs:       how many seconds
471  */
472
473 LWS_VISIBLE void
474 libwebsocket_set_timeout(struct libwebsocket *wsi,
475                                           enum pending_timeout reason, int secs)
476 {
477         time_t now;
478
479         time(&now);
480
481         wsi->pending_timeout_limit = now + secs;
482         wsi->pending_timeout = reason;
483 }
484
485
486 /**
487  * libwebsocket_get_socket_fd() - returns the socket file descriptor
488  *
489  * You will not need this unless you are doing something special
490  *
491  * @wsi:        Websocket connection instance
492  */
493
494 LWS_VISIBLE int
495 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
496 {
497         return wsi->sock;
498 }
499
500 #ifdef LWS_LATENCY
501 void
502 lws_latency(struct libwebsocket_context *context, struct libwebsocket *wsi,
503                                      const char *action, int ret, int completed)
504 {
505         unsigned long long u;
506         char buf[256];
507
508         u = time_in_microseconds();
509
510         if (!action) {
511                 wsi->latency_start = u;
512                 if (!wsi->action_start)
513                         wsi->action_start = u;
514                 return;
515         }
516         if (completed) {
517                 if (wsi->action_start == wsi->latency_start)
518                         sprintf(buf,
519                           "Completion first try lat %lluus: %p: ret %d: %s\n",
520                                         u - wsi->latency_start,
521                                                       (void *)wsi, ret, action);
522                 else
523                         sprintf(buf,
524                           "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
525                                 u - wsi->action_start,
526                                         u - wsi->latency_start,
527                                                       (void *)wsi, ret, action);
528                 wsi->action_start = 0;
529         } else
530                 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
531                               u - wsi->latency_start, (void *)wsi, ret, action);
532
533         if (u - wsi->latency_start > context->worst_latency) {
534                 context->worst_latency = u - wsi->latency_start;
535                 strcpy(context->worst_latency_info, buf);
536         }
537         lwsl_latency("%s", buf);
538 }
539 #endif
540
541
542
543 /**
544  * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
545  *                              received packets.
546  *
547  * If the output side of a server process becomes choked, this allows flow
548  * control for the input side.
549  *
550  * @wsi:        Websocket connection instance to get callback for
551  * @enable:     0 = disable read servicing for this connection, 1 = enable
552  */
553
554 LWS_VISIBLE int
555 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
556 {
557         if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
558                 return 0;
559
560         lwsl_info("libwebsocket_rx_flow_control(0x%p, %d)\n", wsi, enable);
561         wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
562
563         return 0;
564 }
565
566 /**
567  * libwebsocket_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
568  *
569  * When the user server code realizes it can accept more input, it can
570  * call this to have the RX flow restriction removed from all connections using
571  * the given protocol.
572  *
573  * @protocol:   all connections using this protocol will be allowed to receive
574  */
575
576 LWS_VISIBLE void
577 libwebsocket_rx_flow_allow_all_protocol(
578                                 const struct libwebsocket_protocols *protocol)
579 {
580         struct libwebsocket_context *context = protocol->owning_server;
581         int n;
582         struct libwebsocket *wsi;
583
584         for (n = 0; n < context->fds_count; n++) {
585                 wsi = context->lws_lookup[context->fds[n].fd];
586                 if (!wsi)
587                         continue;
588                 if (wsi->protocol == protocol)
589                         libwebsocket_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
590         }
591 }
592
593
594 /**
595  * libwebsocket_canonical_hostname() - returns this host's hostname
596  *
597  * This is typically used by client code to fill in the host parameter
598  * when making a client connection.  You can only call it after the context
599  * has been created.
600  *
601  * @context:    Websocket context
602  */
603 LWS_VISIBLE extern const char *
604 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
605 {
606         return (const char *)context->canonical_hostname;
607 }
608
609 int user_callback_handle_rxflow(callback_function callback_function,
610                 struct libwebsocket_context *context,
611                         struct libwebsocket *wsi,
612                          enum libwebsocket_callback_reasons reason, void *user,
613                                                           void *in, size_t len)
614 {
615         int n;
616
617         n = callback_function(context, wsi, reason, user, in, len);
618         if (!n)
619                 n = _libwebsocket_rx_flow_control(wsi);
620
621         return n;
622 }
623
624
625 /**
626  * libwebsocket_set_proxy() - Setups proxy to libwebsocket_context.
627  * @context:    pointer to struct libwebsocket_context you want set proxy to
628  * @proxy: pointer to c string containing proxy in format address:port
629  *
630  * Returns 0 if proxy string was parsed and proxy was setup. 
631  * Returns -1 if @proxy is NULL or has incorrect format.
632  *
633  * This is only required if your OS does not provide the http_proxy
634  * environment variable (eg, OSX)
635  *
636  *   IMPORTANT! You should call this function right after creation of the
637  *   libwebsocket_context and before call to connect. If you call this
638  *   function after connect behavior is undefined.
639  *   This function will override proxy settings made on libwebsocket_context
640  *   creation with genenv() call.
641  */
642
643 LWS_VISIBLE int
644 libwebsocket_set_proxy(struct libwebsocket_context *context, const char *proxy)
645 {
646         char *p;
647         
648         if (!proxy)
649                 return -1;
650
651         strncpy(context->http_proxy_address, proxy,
652                                 sizeof(context->http_proxy_address) - 1);
653         context->http_proxy_address[
654                                 sizeof(context->http_proxy_address) - 1] = '\0';
655         
656         p = strchr(context->http_proxy_address, ':');
657         if (!p) {
658                 lwsl_err("http_proxy needs to be ads:port\n");
659
660                 return -1;
661         }
662         *p = '\0';
663         context->http_proxy_port = atoi(p + 1);
664         
665         lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
666                                                 context->http_proxy_port);
667
668         return 0;
669 }
670
671 /**
672  * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
673  *                                connection.
674  * @wsi:        pointer to struct websocket you want to know the protocol of
675  *
676  *
677  *      Some apis can act on all live connections of a given protocol,
678  *      this is how you can get a pointer to the active protocol if needed.
679  */
680
681 LWS_VISIBLE const struct libwebsocket_protocols *
682 libwebsockets_get_protocol(struct libwebsocket *wsi)
683 {
684         return wsi->protocol;
685 }
686
687 LWS_VISIBLE int
688 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
689 {
690         return wsi->u.ws.final;
691 }
692
693 LWS_VISIBLE unsigned char
694 libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
695 {
696         return wsi->u.ws.rsv;
697 }
698
699 int
700 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
701 {
702         lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
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 = lws_zalloc(wsi->protocol->per_session_data_size);
710                 if (wsi->user_space  == NULL) {
711                         lwsl_err("Out of memory for conn user space\n");
712                         return 1;
713                 }
714         } else
715                 lwsl_info("%s: %p protocol pss %u, user_space=%d\n", __func__, wsi, wsi->protocol->per_session_data_size, wsi->user_space);
716         return 0;
717 }
718
719 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
720 {
721         char buf[300];
722         unsigned long long now;
723         int n;
724
725         buf[0] = '\0';
726         for (n = 0; n < LLL_COUNT; n++)
727                 if (level == (1 << n)) {
728                         now = time_in_microseconds() / 100;
729                         sprintf(buf, "[%llu:%04d] %s: ", (unsigned long long) now / 10000,
730                                 (int)(now % 10000), log_level_names[n]);
731                         break;
732                 }
733
734         fprintf(stderr, "%s%s", buf, line);
735 }
736
737
738 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
739 {
740         char buf[256];
741
742         if (!(log_level & filter))
743                 return;
744
745         vsnprintf(buf, sizeof(buf), format, vl);
746         buf[sizeof(buf) - 1] = '\0';
747
748         lwsl_emit(filter, buf);
749 }
750
751 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
752 {
753         va_list ap;
754
755         va_start(ap, format);
756         _lws_logv(filter, format, ap);
757         va_end(ap);
758 }
759
760 /**
761  * lws_set_log_level() - Set the logging bitfield
762  * @level:      OR together the LLL_ debug contexts you want output from
763  * @log_emit_function:  NULL to leave it as it is, or a user-supplied
764  *                      function to perform log string emission instead of
765  *                      the default stderr one.
766  *
767  *      log level defaults to "err", "warn" and "notice" contexts enabled and
768  *      emission on stderr.
769  */
770
771 LWS_VISIBLE void lws_set_log_level(int level, void (*log_emit_function)(int level,
772                                                               const char *line))
773 {
774         log_level = level;
775         if (log_emit_function)
776                 lwsl_emit = log_emit_function;
777 }
778
779 /**
780  * lws_use_ssl() - Find out if connection is using SSL
781  * @wsi:        websocket connection to check
782  *
783  *      Returns 0 if the connection is not using SSL, 1 if using SSL and
784  *      using verified cert, and 2 if using SSL but the cert was not
785  *      checked (appears for client wsi told to skip check on connection)
786  */
787 LWS_VISIBLE int
788 lws_is_ssl(struct libwebsocket *wsi)
789 {
790 #ifdef LWS_OPENSSL_SUPPORT
791         return wsi->use_ssl;
792 #else
793         return 0;
794 #endif
795 }
796
797 /**
798  * lws_partial_buffered() - find out if lws buffered the last write
799  * @wsi:        websocket connection to check
800  *
801  * Returns 1 if you cannot use libwebsocket_write because the last
802  * write on this connection is still buffered, and can't be cleared without
803  * returning to the service loop and waiting for the connection to be
804  * writeable again.
805  * 
806  * If you will try to do >1 libwebsocket_write call inside a single
807  * WRITEABLE callback, you must check this after every write and bail if
808  * set, ask for a new writeable callback and continue writing from there.
809  * 
810  * This is never set at the start of a writeable callback, but any write
811  * may set it.
812  */
813
814 LWS_VISIBLE int
815 lws_partial_buffered(struct libwebsocket *wsi)
816 {
817         return !!wsi->truncated_send_len;       
818 }
819
820 void lws_set_protocol_write_pending(struct libwebsocket_context *context,
821                                     struct libwebsocket *wsi,
822                                     enum lws_pending_protocol_send pend)
823 {
824         lwsl_info("setting pps %d\n", pend);
825         
826         if (wsi->pps)
827                 lwsl_err("pps overwrite\n");
828         wsi->pps = pend;
829         libwebsocket_rx_flow_control(wsi, 0);
830         libwebsocket_callback_on_writable(context, wsi);
831 }
832
833 LWS_VISIBLE size_t
834 lws_get_peer_write_allowance(struct libwebsocket *wsi)
835 {
836 #ifdef LWS_USE_HTTP2
837         /* only if we are using HTTP2 on this connection */
838         if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING)
839                 return -1;
840         /* user is only interested in how much he can send, or that he can't  */
841         if (wsi->u.http2.tx_credit <= 0)
842                 return 0;
843         
844         return wsi->u.http2.tx_credit;
845 #else
846         return -1;
847 #endif
848 }
849
850 LWS_VISIBLE void
851 lws_union_transition(struct libwebsocket *wsi, enum connection_mode mode)
852 {
853         memset(&wsi->u, 0, sizeof(wsi->u));
854         wsi->mode = mode;
855 }