2
* libwebsockets - small server side websockets and web server implementation
4
* Copyright (C) 2010 Andy Green <andy@warmcat.com>
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.
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.
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,
22
#include "private-libwebsockets.h"
29
#ifdef LWS_BUILTIN_GETIFADDRS
30
#include <getifaddrs.h>
36
#include <sys/socket.h>
40
#ifdef LWS_OPENSSL_SUPPORT
41
int openssl_websocket_private_data_index;
45
#include "../win32port/win32helpers/websock-w32.c"
48
#include "../win32port/win32helpers/websock-w32.c"
52
#ifndef LWS_BUILD_HASH
53
#define LWS_BUILD_HASH "unknown-build-hash"
56
static int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
57
static void lwsl_emit_stderr(int level, const char *line);
58
static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
60
static const char *library_version = LWS_LIBRARY_VERSION " " LWS_BUILD_HASH;
62
static const char * const log_level_names[] = {
76
extern int lws_client_socket_service(
77
struct libwebsocket_context *context,
78
struct libwebsocket *wsi, struct pollfd *pollfd);
81
extern int lws_server_socket_service(
82
struct libwebsocket_context *context,
83
struct libwebsocket *wsi, struct pollfd *pollfd);
87
* lws_get_library_version: get version and git hash library built from
89
* returns a const char * to a string like "1.1 178d78c"
90
* representing the library version followed by the git head hash it
95
lws_get_library_version(void)
97
return library_version;
101
insert_wsi_socket_into_fds(struct libwebsocket_context *context,
102
struct libwebsocket *wsi)
104
if (context->fds_count >= context->max_fds) {
105
lwsl_err("Too many fds (%d)\n", context->max_fds);
109
if (wsi->sock > context->max_fds) {
110
lwsl_err("Socket fd %d is too high (%d)\n",
111
wsi->sock, context->max_fds);
118
lwsl_info("insert_wsi_socket_into_fds: wsi=%p, sock=%d, fds pos=%d\n",
119
wsi, wsi->sock, context->fds_count);
121
context->lws_lookup[wsi->sock] = wsi;
122
wsi->position_in_fds_table = context->fds_count;
123
context->fds[context->fds_count].fd = wsi->sock;
124
context->fds[context->fds_count].events = POLLIN;
125
context->fds[context->fds_count++].revents = 0;
127
/* external POLL support via protocol 0 */
128
context->protocols[0].callback(context, wsi,
129
LWS_CALLBACK_ADD_POLL_FD,
130
(void *)(long)wsi->sock, NULL, POLLIN);
136
remove_wsi_socket_from_fds(struct libwebsocket_context *context,
137
struct libwebsocket *wsi)
141
if (!--context->fds_count)
144
if (wsi->sock > context->max_fds) {
145
lwsl_err("Socket fd %d too high (%d)\n",
146
wsi->sock, context->max_fds);
150
lwsl_info("remove_wsi_socket_from_fds: wsi=%p, sock=%d, fds pos=%d\n",
151
wsi, wsi->sock, wsi->position_in_fds_table);
153
m = wsi->position_in_fds_table; /* replace the contents for this */
155
/* have the last guy take up the vacant slot */
156
context->fds[m] = context->fds[context->fds_count];
158
* end guy's fds_lookup entry remains unchanged
159
* (still same fd pointing to same wsi)
161
/* end guy's "position in fds table" changed */
162
context->lws_lookup[context->fds[context->fds_count].fd]->
163
position_in_fds_table = m;
164
/* deletion guy's lws_lookup entry needs nuking */
165
context->lws_lookup[wsi->sock] = NULL;
166
/* removed wsi has no position any more */
167
wsi->position_in_fds_table = -1;
170
/* remove also from external POLL support via protocol 0 */
172
context->protocols[0].callback(context, wsi,
173
LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
180
libwebsocket_close_and_free_session(struct libwebsocket_context *context,
181
struct libwebsocket *wsi, enum lws_close_status reason)
185
unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
186
LWS_SEND_BUFFER_POST_PADDING];
187
#ifndef LWS_NO_EXTENSIONS
190
struct lws_tokens eff_buf;
191
struct libwebsocket_extension *ext;
197
old_state = wsi->state;
199
if (old_state == WSI_STATE_DEAD_SOCKET)
202
wsi->u.ws.close_reason = reason;
204
if (wsi->mode == LWS_CONNMODE_HTTP_SERVING && wsi->u.http.fd) {
205
close(wsi->u.http.fd);
209
#ifndef LWS_NO_EXTENSIONS
211
* are his extensions okay with him closing? Eg he might be a mux
212
* parent and just his ch1 aspect is closing?
215
for (n = 0; n < wsi->count_active_extensions; n++) {
216
if (!wsi->active_extensions[n]->callback)
219
m = wsi->active_extensions[n]->callback(context,
220
wsi->active_extensions[n], wsi,
221
LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
222
wsi->active_extensions_user[n], NULL, 0);
225
* if somebody vetoed actually closing him at this time....
226
* up to the extension to track the attempted close, let's
231
lwsl_ext("extension vetoed close\n");
237
* flush any tx pending from extensions, since we may send close packet
238
* if there are problems with send, just nuke the connection
244
/* default to nobody has more to spill */
247
eff_buf.token = NULL;
248
eff_buf.token_len = 0;
250
/* show every extension the new incoming data */
252
for (n = 0; n < wsi->count_active_extensions; n++) {
253
m = wsi->active_extensions[n]->callback(
254
wsi->protocol->owning_server,
255
wsi->active_extensions[n], wsi,
256
LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
257
wsi->active_extensions_user[n], &eff_buf, 0);
259
lwsl_ext("Extension reports fatal error\n");
260
goto just_kill_connection;
264
* at least one extension told us he has more
265
* to spill, so we will go around again after
270
/* assuming they left us something to send, send it */
272
if (eff_buf.token_len)
273
if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
274
eff_buf.token_len)) {
275
lwsl_debug("close: ext spill failed\n");
276
goto just_kill_connection;
282
* signal we are closing, libsocket_write will
283
* add any necessary version-specific stuff. If the write fails,
284
* no worries we are closing anyway. If we didn't initiate this
285
* close, then our state has been changed to
286
* WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
288
* Likewise if it's a second call to close this connection after we
289
* sent the close indication to the peer already, we are in state
290
* WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
293
if (old_state == WSI_STATE_ESTABLISHED &&
294
reason != LWS_CLOSE_STATUS_NOSTATUS) {
296
lwsl_debug("sending close indication...\n");
298
/* make valgrind happy */
299
memset(buf, 0, sizeof(buf));
300
n = libwebsocket_write(wsi,
301
&buf[LWS_SEND_BUFFER_PRE_PADDING + 2],
305
* we have sent a nice protocol level indication we
306
* now wish to close, we should not send anything more
309
wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
312
* ...and we should wait for a reply for a bit
316
libwebsocket_set_timeout(wsi,
317
PENDING_TIMEOUT_CLOSE_ACK, 1);
319
lwsl_debug("sent close indication, awaiting ack\n");
324
lwsl_info("close: sending close packet failed, hanging up\n");
326
/* else, the send failed and we should just hang up */
329
#ifndef LWS_NO_EXTENSIONS
330
just_kill_connection:
333
lwsl_debug("close: just_kill_connection\n");
336
* we won't be servicing or receiving anything further from this guy
337
* delete socket from the internal poll list if still present
340
remove_wsi_socket_from_fds(context, wsi);
342
wsi->state = WSI_STATE_DEAD_SOCKET;
344
if ((old_state == WSI_STATE_ESTABLISHED ||
345
wsi->mode == LWS_CONNMODE_WS_SERVING ||
346
wsi->mode == LWS_CONNMODE_WS_CLIENT)) {
348
if (wsi->u.ws.rx_user_buffer) {
349
free(wsi->u.ws.rx_user_buffer);
350
wsi->u.ws.rx_user_buffer = NULL;
352
if (wsi->u.ws.rxflow_buffer) {
353
free(wsi->u.ws.rxflow_buffer);
354
wsi->u.ws.rxflow_buffer = NULL;
358
/* tell the user it's all over for this guy */
360
if (wsi->protocol && wsi->protocol->callback &&
361
((old_state == WSI_STATE_ESTABLISHED) ||
362
(old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
363
(old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
364
lwsl_debug("calling back CLOSED\n");
365
wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
366
wsi->user_space, NULL, 0);
368
lwsl_debug("not calling back closed\n");
370
#ifndef LWS_NO_EXTENSIONS
371
/* deallocate any active extension contexts */
373
for (n = 0; n < wsi->count_active_extensions; n++) {
374
if (!wsi->active_extensions[n]->callback)
377
wsi->active_extensions[n]->callback(context,
378
wsi->active_extensions[n], wsi,
379
LWS_EXT_CALLBACK_DESTROY,
380
wsi->active_extensions_user[n], NULL, 0);
382
free(wsi->active_extensions_user[n]);
386
* inform all extensions in case they tracked this guy out of band
387
* even though not active on him specifically
390
ext = context->extensions;
391
while (ext && ext->callback) {
392
ext->callback(context, ext, wsi,
393
LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
399
/* lwsl_info("closing fd=%d\n", wsi->sock); */
401
#ifdef LWS_OPENSSL_SUPPORT
403
n = SSL_get_fd(wsi->ssl);
404
SSL_shutdown(wsi->ssl);
410
n = shutdown(wsi->sock, SHUT_RDWR);
412
lwsl_debug("closing: shutdown returned %d\n",
415
n = compatible_close(wsi->sock);
417
lwsl_debug("closing: close returned %d\n",
420
#ifdef LWS_OPENSSL_SUPPORT
423
if (wsi->protocol && wsi->protocol->per_session_data_size &&
424
wsi->user_space) /* user code may own */
425
free(wsi->user_space);
431
* libwebsockets_get_peer_addresses() - Get client address information
432
* @context: Libwebsockets context
433
* @wsi: Local struct libwebsocket associated with
434
* @fd: Connection socket descriptor
435
* @name: Buffer to take client address name
436
* @name_len: Length of client address name buffer
437
* @rip: Buffer to take client address IP qotted quad
438
* @rip_len: Length of client address IP buffer
440
* This function fills in @name and @rip with the name and IP of
441
* the client connected with socket descriptor @fd. Names may be
442
* truncated if there is not enough room. If either cannot be
443
* determined, they will be returned as valid zero-length strings.
447
libwebsockets_get_peer_addresses(struct libwebsocket_context *context,
448
struct libwebsocket *wsi, int fd, char *name, int name_len,
449
char *rip, int rip_len)
452
struct sockaddr_in sin;
453
struct hostent *host;
454
struct hostent *host1;
460
struct sockaddr_un *un;
466
lws_latency_pre(context, wsi);
469
if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
470
perror("getpeername");
474
host = gethostbyaddr((char *) &sin.sin_addr, sizeof(sin.sin_addr),
477
perror("gethostbyaddr");
481
strncpy(name, host->h_name, name_len);
482
name[name_len - 1] = '\0';
484
host1 = gethostbyname(host->h_name);
487
p = (unsigned char *)host1;
490
p = (unsigned char *)host1->h_addr_list[n++];
493
if ((host1->h_addrtype != AF_INET)
495
&& (host1->h_addrtype != AF_LOCAL)
500
if (host1->h_addrtype == AF_INET)
501
sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
504
un = (struct sockaddr_un *)p;
505
strncpy(ip, un->sun_path, sizeof(ip) - 1);
506
ip[sizeof(ip) - 1] = '\0';
510
strncpy(rip, ip, rip_len);
511
rip[rip_len - 1] = '\0';
516
lws_latency(context, wsi, "libwebsockets_get_peer_addresses", ret, 1);
519
int libwebsockets_get_random(struct libwebsocket_context *context,
523
char *p = (char *)buf;
526
for (n = 0; n < len; n++)
527
p[n] = (unsigned char)rand();
529
n = read(context->fd_random, p, len);
535
int lws_set_socket_options(struct libwebsocket_context *context, int fd)
538
socklen_t optlen = sizeof(optval);
540
unsigned long optl = 0;
542
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
543
struct protoent *tcp_proto;
546
if (context->ka_time) {
547
/* enable keepalive on this socket */
549
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
550
(const void *)&optval, optlen) < 0)
553
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
556
* didn't find a way to set these per-socket, need to
557
* tune kernel systemwide values
562
struct tcp_keepalive alive;
564
alive.keepalivetime = context->ka_time;
565
alive.keepaliveinterval = context->ka_interval;
567
if (WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive),
568
NULL, 0, &dwBytesRet, NULL, NULL))
572
/* set the keepalive conditions we want on it too */
573
optval = context->ka_time;
574
if (setsockopt(fd, IPPROTO_IP, TCP_KEEPIDLE,
575
(const void *)&optval, optlen) < 0)
578
optval = context->ka_interval;
579
if (setsockopt(fd, IPPROTO_IP, TCP_KEEPINTVL,
580
(const void *)&optval, optlen) < 0)
583
optval = context->ka_probes;
584
if (setsockopt(fd, IPPROTO_IP, TCP_KEEPCNT,
585
(const void *)&optval, optlen) < 0)
592
#if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__)
593
setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen);
595
tcp_proto = getprotobyname("TCP");
596
setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen);
599
/* We are nonblocking... */
601
ioctlsocket(fd, FIONBIO, &optl);
603
fcntl(fd, F_SETFL, O_NONBLOCK);
609
int lws_send_pipe_choked(struct libwebsocket *wsi)
614
fds.events = POLLOUT;
617
if (poll(&fds, 1, 0) != 1)
620
if ((fds.revents & POLLOUT) == 0)
623
/* okay to send another packet without blocking */
629
lws_handle_POLLOUT_event(struct libwebsocket_context *context,
630
struct libwebsocket *wsi, struct pollfd *pollfd)
634
#ifndef LWS_NO_EXTENSIONS
635
struct lws_tokens eff_buf;
640
for (n = 0; n < wsi->count_active_extensions; n++) {
641
if (!wsi->active_extensions[n]->callback)
644
m = wsi->active_extensions[n]->callback(context,
645
wsi->active_extensions[n], wsi,
646
LWS_EXT_CALLBACK_IS_WRITEABLE,
647
wsi->active_extensions_user[n], NULL, 0);
655
if (!wsi->extension_data_pending || handled == 2)
659
* check in on the active extensions, see if they
660
* had pending stuff to spill... they need to get the
661
* first look-in otherwise sequence will be disordered
663
* NULL, zero-length eff_buf means just spill pending
669
/* default to nobody has more to spill */
672
eff_buf.token = NULL;
673
eff_buf.token_len = 0;
675
/* give every extension a chance to spill */
677
for (n = 0; n < wsi->count_active_extensions; n++) {
678
m = wsi->active_extensions[n]->callback(
679
wsi->protocol->owning_server,
680
wsi->active_extensions[n], wsi,
681
LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
682
wsi->active_extensions_user[n], &eff_buf, 0);
684
lwsl_err("ext reports fatal error\n");
689
* at least one extension told us he has more
690
* to spill, so we will go around again after
695
/* assuming they gave us something to send, send it */
697
if (eff_buf.token_len) {
698
if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
704
/* no extension has more to spill */
710
* There's more to spill from an extension, but we just sent
711
* something... did that leave the pipe choked?
714
if (!lws_send_pipe_choked(wsi))
715
/* no we could add more */
718
lwsl_info("choked in POLLOUT service\n");
721
* Yes, he's choked. Leave the POLLOUT masked on so we will
722
* come back here when he is unchoked. Don't call the user
723
* callback to enforce ordering of spilling, he'll get called
724
* when we come back here and there's nothing more to spill.
730
wsi->extension_data_pending = 0;
737
pollfd->events &= ~POLLOUT;
739
/* external POLL support via protocol 0 */
740
context->protocols[0].callback(context, wsi,
741
LWS_CALLBACK_CLEAR_MODE_POLL_FD,
742
(void *)(long)wsi->sock, NULL, POLLOUT);
744
#ifndef LWS_NO_EXTENSIONS
748
if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
749
n = LWS_CALLBACK_CLIENT_WRITEABLE;
751
n = LWS_CALLBACK_SERVER_WRITEABLE;
753
return user_callback_handle_rxflow(wsi->protocol->callback, context,
754
wsi, (enum libwebsocket_callback_reasons) n,
755
wsi->user_space, NULL, 0);
761
libwebsocket_service_timeout_check(struct libwebsocket_context *context,
762
struct libwebsocket *wsi, unsigned int sec)
764
#ifndef LWS_NO_EXTENSIONS
768
* if extensions want in on it (eg, we are a mux parent)
769
* give them a chance to service child timeouts
772
for (n = 0; n < wsi->count_active_extensions; n++)
773
wsi->active_extensions[n]->callback(
774
context, wsi->active_extensions[n],
775
wsi, LWS_EXT_CALLBACK_1HZ,
776
wsi->active_extensions_user[n], NULL, sec);
779
if (!wsi->pending_timeout)
783
* if we went beyond the allowed time, kill the
787
if (sec > wsi->pending_timeout_limit) {
788
lwsl_info("TIMEDOUT WAITING\n");
789
libwebsocket_close_and_free_session(context,
790
wsi, LWS_CLOSE_STATUS_NOSTATUS);
795
* libwebsocket_service_fd() - Service polled socket with something waiting
796
* @context: Websocket context
797
* @pollfd: The pollfd entry describing the socket fd and which events
800
* This function takes a pollfd that has POLLIN or POLLOUT activity and
801
* services it according to the state of the associated
802
* struct libwebsocket.
804
* The one call deals with all "service" that might happen on a socket
805
* including listen accepts, http files as well as websocket protocol.
809
libwebsocket_service_fd(struct libwebsocket_context *context,
810
struct pollfd *pollfd)
812
struct libwebsocket *wsi;
815
int listen_socket_fds_index = 0;
818
#ifndef LWS_NO_EXTENSIONS
821
struct lws_tokens eff_buf;
823
if (context->listen_service_fd)
824
listen_socket_fds_index = context->lws_lookup[
825
context->listen_service_fd]->position_in_fds_table;
828
* you can call us with pollfd = NULL to just allow the once-per-second
829
* global timeout checks; if less than a second since the last check
830
* it returns immediately then.
833
gettimeofday(&tv, NULL);
835
if (context->last_timeout_check_s != tv.tv_sec) {
836
context->last_timeout_check_s = tv.tv_sec;
839
/* if our parent went down, don't linger around */
840
if (context->started_with_parent &&
841
kill(context->started_with_parent, 0) < 0)
842
kill(getpid(), SIGTERM);
845
/* global timeout check once per second */
847
for (n = 0; n < context->fds_count; n++) {
848
struct libwebsocket *new_wsi =
849
context->lws_lookup[context->fds[n].fd];
852
libwebsocket_service_timeout_check(context,
857
/* just here for timeout management? */
862
/* no, here to service a socket descriptor */
865
* deal with listen service piggybacking
866
* every listen_service_modulo services of other fds, we
867
* sneak one in to service the listen socket if there's anything waiting
869
* To handle connection storms, as found in ab, if we previously saw a
870
* pending connection here, it causes us to check again next time.
873
if (context->listen_service_fd && pollfd !=
874
&context->fds[listen_socket_fds_index]) {
875
context->listen_service_count++;
876
if (context->listen_service_extraseen ||
877
context->listen_service_count ==
878
context->listen_service_modulo) {
879
context->listen_service_count = 0;
881
if (context->listen_service_extraseen > 5)
885
* even with extpoll, we prepared this
886
* internal fds for listen
888
n = poll(&context->fds[listen_socket_fds_index],
890
if (n > 0) { /* there's a conn waiting for us */
891
libwebsocket_service_fd(context,
893
fds[listen_socket_fds_index]);
894
context->listen_service_extraseen++;
896
if (context->listen_service_extraseen)
898
listen_service_extraseen--;
906
/* okay, what we came here to do... */
908
wsi = context->lws_lookup[pollfd->fd];
911
lwsl_err("unexpected NULL wsi fd=%d fds_count=%d\n",
912
pollfd->fd, context->fds_count);
918
#ifndef LWS_NO_SERVER
919
case LWS_CONNMODE_HTTP_SERVING:
920
case LWS_CONNMODE_SERVER_LISTENER:
921
case LWS_CONNMODE_SSL_ACK_PENDING:
922
return lws_server_socket_service(context, wsi, pollfd);
925
case LWS_CONNMODE_WS_SERVING:
926
case LWS_CONNMODE_WS_CLIENT:
928
/* handle session socket closed */
930
if (pollfd->revents & (POLLERR | POLLHUP)) {
932
lwsl_debug("Session Socket %p (fd=%d) dead\n",
933
(void *)wsi, pollfd->fd);
935
libwebsocket_close_and_free_session(context, wsi,
936
LWS_CLOSE_STATUS_NOSTATUS);
940
/* the guy requested a callback when it was OK to write */
942
if ((pollfd->revents & POLLOUT) &&
943
wsi->state == WSI_STATE_ESTABLISHED)
944
if (lws_handle_POLLOUT_event(context, wsi,
946
lwsl_info("libwebsocket_service_fd: closing\n");
947
libwebsocket_close_and_free_session(
948
context, wsi, LWS_CLOSE_STATUS_NORMAL);
953
/* any incoming data ready? */
955
if (!(pollfd->revents & POLLIN))
958
#ifdef LWS_OPENSSL_SUPPORT
961
eff_buf.token_len = SSL_read(wsi->ssl,
962
context->service_buffer,
963
sizeof(context->service_buffer));
964
if (!eff_buf.token_len) {
965
n = SSL_get_error(wsi->ssl, eff_buf.token_len);
966
lwsl_err("SSL_read returned 0 with reason %s\n",
968
(char *)context->service_buffer));
972
eff_buf.token_len = recv(pollfd->fd,
973
context->service_buffer,
974
sizeof(context->service_buffer), 0);
976
if (eff_buf.token_len < 0) {
977
lwsl_debug("Socket read returned %d\n",
979
if (errno != EINTR && errno != EAGAIN)
980
libwebsocket_close_and_free_session(context,
981
wsi, LWS_CLOSE_STATUS_NOSTATUS);
984
if (!eff_buf.token_len) {
985
lwsl_info("closing connection due to 0 length read\n");
986
libwebsocket_close_and_free_session(context, wsi,
987
LWS_CLOSE_STATUS_NOSTATUS);
992
* give any active extensions a chance to munge the buffer
993
* before parse. We pass in a pointer to an lws_tokens struct
994
* prepared with the default buffer and content length that's in
995
* there. Rather than rewrite the default buffer, extensions
996
* that expect to grow the buffer can adapt .token to
997
* point to their own per-connection buffer in the extension
998
* user allocation. By default with no extensions or no
999
* extension callback handling, just the normal input buffer is
1000
* used then so it is efficient.
1003
eff_buf.token = (char *)context->service_buffer;
1004
#ifndef LWS_NO_EXTENSIONS
1010
for (n = 0; n < wsi->count_active_extensions; n++) {
1011
m = wsi->active_extensions[n]->callback(context,
1012
wsi->active_extensions[n], wsi,
1013
LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
1014
wsi->active_extensions_user[n],
1018
"Extension reports fatal error\n");
1019
libwebsocket_close_and_free_session(
1021
LWS_CLOSE_STATUS_NOSTATUS);
1028
/* service incoming data */
1030
if (eff_buf.token_len) {
1031
n = libwebsocket_read(context, wsi,
1032
(unsigned char *)eff_buf.token,
1038
#ifndef LWS_NO_EXTENSIONS
1039
eff_buf.token = NULL;
1040
eff_buf.token_len = 0;
1044
#ifdef LWS_OPENSSL_SUPPORT
1045
if (wsi->ssl && SSL_pending(wsi->ssl))
1051
#ifdef LWS_NO_CLIENT
1054
return lws_client_socket_service(context, wsi, pollfd);
1063
* libwebsocket_context_destroy() - Destroy the websocket context
1064
* @context: Websocket context
1066
* This function closes any active connections and then frees the
1067
* context. After calling this, any further use of the context is
1071
libwebsocket_context_destroy(struct libwebsocket_context *context)
1073
#ifndef LWS_NO_EXTENSIONS
1076
struct libwebsocket_extension *ext;
1077
struct libwebsocket_protocols *protocol = context->protocols;
1080
if (context->worst_latency_info[0])
1081
lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
1084
for (n = 0; n < context->fds_count; n++) {
1085
struct libwebsocket *wsi =
1086
context->lws_lookup[context->fds[n].fd];
1087
libwebsocket_close_and_free_session(context,
1088
wsi, LWS_CLOSE_STATUS_NOSTATUS /* no protocol close */);
1093
* give all extensions a chance to clean up any per-context
1094
* allocations they might have made
1097
ext = context->extensions;
1098
m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
1099
if (context->listen_port)
1100
m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
1101
while (ext && ext->callback) {
1102
ext->callback(context, ext, NULL,
1103
(enum libwebsocket_extension_callback_reasons)m,
1109
* inform all the protocols that they are done and will have no more
1113
while (protocol->callback) {
1114
protocol->callback(context, NULL, LWS_CALLBACK_PROTOCOL_DESTROY,
1123
close(context->fd_random);
1126
#ifdef LWS_OPENSSL_SUPPORT
1127
if (context->ssl_ctx)
1128
SSL_CTX_free(context->ssl_ctx);
1129
if (context->ssl_client_ctx)
1130
SSL_CTX_free(context->ssl_client_ctx);
1132
ERR_remove_state(0);
1135
CRYPTO_cleanup_all_ex_data();
1140
if (context->lws_lookup)
1141
free(context->lws_lookup);
1151
* libwebsocket_context_user() - get the user data associated with the context
1152
* @context: Websocket context
1154
* This returns the optional user allocation that can be attached to
1155
* the context the sockets live in at context_create time. It's a way
1156
* to let all sockets serviced in the same context share data without
1157
* using globals statics in the user code.
1160
libwebsocket_context_user(struct libwebsocket_context *context)
1162
return context->user_space;
1166
* libwebsocket_service() - Service any pending websocket activity
1167
* @context: Websocket context
1168
* @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1169
* service otherwise block and service immediately, returning
1170
* after the timeout if nothing needed service.
1172
* This function deals with any pending websocket traffic, for three
1173
* kinds of event. It handles these events on both server and client
1174
* types of connection the same.
1176
* 1) Accept new connections to our context's server
1178
* 2) Call the receive callback for incoming frame data received by
1179
* server or client connections.
1181
* You need to call this service function periodically to all the above
1182
* functions to happen; if your application is single-threaded you can
1183
* just call it in your main event loop.
1185
* Alternatively you can fork a new process that asynchronously handles
1186
* calling this service in a loop. In that case you are happy if this
1187
* call blocks your thread until it needs to take care of something and
1188
* would call it with a large nonzero timeout. Your loop then takes no
1189
* CPU while there is nothing happening.
1191
* If you are calling it in a single-threaded app, you don't want it to
1192
* wait around blocking other things in your loop from happening, so you
1193
* would call it with a timeout_ms of 0, so it returns immediately if
1194
* nothing is pending, or as soon as it services whatever was pending.
1198
libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
1202
/* stay dead once we are dead */
1204
if (context == NULL)
1207
/* wait for something to need service */
1209
n = poll(context->fds, context->fds_count, timeout_ms);
1210
if (n == 0) /* poll timeout */
1216
/* any socket with events to service? */
1218
for (n = 0; n < context->fds_count; n++)
1219
if (context->fds[n].revents)
1220
if (libwebsocket_service_fd(context,
1221
&context->fds[n]) < 0)
1226
#ifndef LWS_NO_EXTENSIONS
1228
lws_any_extension_handled(struct libwebsocket_context *context,
1229
struct libwebsocket *wsi,
1230
enum libwebsocket_extension_callback_reasons r,
1231
void *v, size_t len)
1236
/* maybe an extension will take care of it for us */
1238
for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
1239
if (!wsi->active_extensions[n]->callback)
1242
handled |= wsi->active_extensions[n]->callback(context,
1243
wsi->active_extensions[n], wsi,
1244
r, wsi->active_extensions_user[n], v, len);
1252
lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
1253
struct libwebsocket_extension *ext)
1260
while (n < wsi->count_active_extensions) {
1261
if (wsi->active_extensions[n] != ext) {
1265
return wsi->active_extensions_user[n];
1273
* libwebsocket_callback_on_writable() - Request a callback when this socket
1274
* becomes able to be written to without
1277
* @context: libwebsockets context
1278
* @wsi: Websocket connection instance to get callback for
1282
libwebsocket_callback_on_writable(struct libwebsocket_context *context,
1283
struct libwebsocket *wsi)
1285
#ifndef LWS_NO_EXTENSIONS
1289
/* maybe an extension will take care of it for us */
1291
for (n = 0; n < wsi->count_active_extensions; n++) {
1292
if (!wsi->active_extensions[n]->callback)
1295
handled |= wsi->active_extensions[n]->callback(context,
1296
wsi->active_extensions[n], wsi,
1297
LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
1298
wsi->active_extensions_user[n], NULL, 0);
1304
if (wsi->position_in_fds_table < 0) {
1305
lwsl_err("libwebsocket_callback_on_writable: failed to find socket %d\n",
1310
context->fds[wsi->position_in_fds_table].events |= POLLOUT;
1312
/* external POLL support via protocol 0 */
1313
context->protocols[0].callback(context, wsi,
1314
LWS_CALLBACK_SET_MODE_POLL_FD,
1315
(void *)(long)wsi->sock, NULL, POLLOUT);
1321
* libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1322
* all connections using the given protocol when it
1323
* becomes possible to write to each socket without
1326
* @protocol: Protocol whose connections will get callbacks
1330
libwebsocket_callback_on_writable_all_protocol(
1331
const struct libwebsocket_protocols *protocol)
1333
struct libwebsocket_context *context = protocol->owning_server;
1335
struct libwebsocket *wsi;
1337
for (n = 0; n < context->fds_count; n++) {
1338
wsi = context->lws_lookup[context->fds[n].fd];
1341
if (wsi->protocol == protocol)
1342
libwebsocket_callback_on_writable(context, wsi);
1349
* libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1351
* You will not need this unless you are doing something special
1353
* @wsi: Websocket connection instance
1354
* @reason: timeout reason
1355
* @secs: how many seconds
1359
libwebsocket_set_timeout(struct libwebsocket *wsi,
1360
enum pending_timeout reason, int secs)
1364
gettimeofday(&tv, NULL);
1366
wsi->pending_timeout_limit = tv.tv_sec + secs;
1367
wsi->pending_timeout = reason;
1372
* libwebsocket_get_socket_fd() - returns the socket file descriptor
1374
* You will not need this unless you are doing something special
1376
* @wsi: Websocket connection instance
1380
libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1387
lws_latency(struct libwebsocket_context *context, struct libwebsocket *wsi,
1388
const char *action, int ret, int completed)
1394
gettimeofday(&tv, NULL);
1396
u = (tv.tv_sec * 1000000) + tv.tv_usec;
1400
if (wsi->action_start == wsi->latency_start)
1402
"Completion first try lat %luus: %p: ret %d: %s\n",
1403
u - wsi->latency_start,
1404
(void *)wsi, ret, action);
1407
"Completion %luus: lat %luus: %p: ret %d: %s\n",
1408
u - wsi->action_start,
1409
u - wsi->latency_start,
1410
(void *)wsi, ret, action);
1411
wsi->action_start = 0;
1413
sprintf(buf, "lat %luus: %p: ret %d: %s\n",
1414
u - wsi->latency_start,
1415
(void *)wsi, ret, action);
1416
if (u - wsi->latency_start > context->worst_latency) {
1417
context->worst_latency = u - wsi->latency_start;
1418
strcpy(context->worst_latency_info, buf);
1420
lwsl_latency("%s", buf);
1422
wsi->latency_start = u;
1423
if (!wsi->action_start)
1424
wsi->action_start = u;
1429
#ifdef LWS_NO_SERVER
1431
_libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1437
_libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1439
struct libwebsocket_context *context = wsi->protocol->owning_server;
1442
if (!(wsi->u.ws.rxflow_change_to & 2))
1445
wsi->u.ws.rxflow_change_to &= ~2;
1447
lwsl_info("rxflow: wsi %p change_to %d\n",
1448
wsi, wsi->u.ws.rxflow_change_to);
1450
/* if we're letting it come again, did we interrupt anything? */
1451
if ((wsi->u.ws.rxflow_change_to & 1) && wsi->u.ws.rxflow_buffer) {
1452
n = libwebsocket_interpret_incoming_packet(wsi, NULL, 0);
1454
lwsl_info("libwebsocket_rx_flow_control: close req\n");
1458
/* oh he stuck again, do nothing */
1462
if (wsi->u.ws.rxflow_change_to & 1)
1463
context->fds[wsi->position_in_fds_table].events |= POLLIN;
1465
context->fds[wsi->position_in_fds_table].events &= ~POLLIN;
1467
if (wsi->u.ws.rxflow_change_to & 1)
1468
/* external POLL support via protocol 0 */
1469
context->protocols[0].callback(context, wsi,
1470
LWS_CALLBACK_SET_MODE_POLL_FD,
1471
(void *)(long)wsi->sock, NULL, POLLIN);
1473
/* external POLL support via protocol 0 */
1474
context->protocols[0].callback(context, wsi,
1475
LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1476
(void *)(long)wsi->sock, NULL, POLLIN);
1483
* libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1484
* receieved packets.
1486
* If the output side of a server process becomes choked, this allows flow
1487
* control for the input side.
1489
* @wsi: Websocket connection instance to get callback for
1490
* @enable: 0 = disable read servicing for this connection, 1 = enable
1494
libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1496
wsi->u.ws.rxflow_change_to = 2 | !!enable;
1503
* libwebsocket_canonical_hostname() - returns this host's hostname
1505
* This is typically used by client code to fill in the host parameter
1506
* when making a client connection. You can only call it after the context
1509
* @context: Websocket context
1514
libwebsocket_canonical_hostname(struct libwebsocket_context *context)
1516
return (const char *)context->canonical_hostname;
1520
static void sigpipe_handler(int x)
1524
#ifdef LWS_OPENSSL_SUPPORT
1526
OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1531
struct libwebsocket_context *context;
1533
ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1534
SSL_get_ex_data_X509_STORE_CTX_idx());
1537
* !!! nasty openssl requires the index to come as a library-scope
1540
context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
1542
n = context->protocols[0].callback(NULL, NULL,
1543
LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1544
x509_ctx, ssl, preverify_ok);
1546
/* convert return code from 0 = OK to 1 = OK */
1557
int user_callback_handle_rxflow(callback_function callback_function,
1558
struct libwebsocket_context *context,
1559
struct libwebsocket *wsi,
1560
enum libwebsocket_callback_reasons reason, void *user,
1561
void *in, size_t len)
1565
n = callback_function(context, wsi, reason, user, in, len);
1567
n = _libwebsocket_rx_flow_control(wsi);
1574
* libwebsocket_create_context() - Create the websocket handler
1575
* @info: pointer to struct with parameters
1577
* This function creates the listening socket (if serving) and takes care
1578
* of all initialization in one step.
1580
* After initialization, it returns a struct libwebsocket_context * that
1581
* represents this server. After calling, user code needs to take care
1582
* of calling libwebsocket_service() with the context pointer to get the
1583
* server's sockets serviced. This can be done in the same process context
1584
* or a forked process, or another thread,
1586
* The protocol callback functions are called for a handful of events
1587
* including http requests coming in, websocket connections becoming
1588
* established, and data arriving; it's also called periodically to allow
1589
* async transmission.
1591
* HTTP requests are sent always to the FIRST protocol in @protocol, since
1592
* at that time websocket protocol has not been negotiated. Other
1593
* protocols after the first one never see any HTTP callack activity.
1595
* The server created is a simple http server by default; part of the
1596
* websocket standard is upgrading this http connection to a websocket one.
1598
* This allows the same server to provide files like scripts and favicon /
1599
* images or whatever over http and dynamic data over websockets all in
1600
* one place; they're all handled in the user callback.
1603
struct libwebsocket_context *
1604
libwebsocket_create_context(struct lws_context_creation_info *info)
1606
struct libwebsocket_context *context = NULL;
1608
#ifndef LWS_NO_SERVER
1611
struct libwebsocket *wsi;
1612
struct sockaddr_in serv_addr;
1614
#ifndef LWS_NO_EXTENSIONS
1616
struct libwebsocket_extension *ext;
1619
#ifdef LWS_OPENSSL_SUPPORT
1623
#ifndef LWS_NO_DAEMONIZE
1624
int pid_daemon = get_daemonize_pid();
1627
lwsl_notice("Initial logging level %d\n", log_level);
1628
lwsl_notice("Library version: %s\n", library_version);
1629
lwsl_info(" LWS_MAX_HEADER_NAME_LENGTH: %u\n",
1630
LWS_MAX_HEADER_NAME_LENGTH);
1631
lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN);
1632
lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS);
1633
#ifndef LWS_NO_EXTENSIONS
1634
lwsl_info(" LWS_MAX_EXTENSIONS_ACTIVE: %u\n",
1635
LWS_MAX_EXTENSIONS_ACTIVE);
1637
lwsl_notice(" Configured without extension support\n");
1639
lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED);
1640
lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT);
1641
lwsl_info(" CIPHERS_LIST_STRING: '%s'\n", CIPHERS_LIST_STRING);
1642
lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
1643
lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER);
1647
WORD wVersionRequested;
1652
/* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1653
wVersionRequested = MAKEWORD(2, 2);
1655
err = WSAStartup(wVersionRequested, &wsaData);
1657
/* Tell the user that we could not find a usable */
1659
lwsl_err("WSAStartup failed with error: %d\n", err);
1663
/* default to a poll() made out of select() */
1664
poll = emulated_poll;
1666
/* if windows socket lib available, use his WSAPoll */
1667
wsdll = GetModuleHandle(_T("Ws2_32.dll"));
1669
poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
1671
/* Finally fall back to emulated poll if all else fails */
1673
poll = emulated_poll;
1677
context = (struct libwebsocket_context *)
1678
malloc(sizeof(struct libwebsocket_context));
1680
lwsl_err("No memory for websocket context\n");
1683
memset(context, 0, sizeof(*context));
1684
#ifndef LWS_NO_DAEMONIZE
1685
context->started_with_parent = pid_daemon;
1686
lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
1689
context->listen_service_extraseen = 0;
1690
context->protocols = info->protocols;
1691
context->listen_port = info->port;
1692
context->http_proxy_port = 0;
1693
context->http_proxy_address[0] = '\0';
1694
context->options = info->options;
1695
/* to reduce this allocation, */
1696
context->max_fds = getdtablesize();
1697
lwsl_notice(" static allocation: %u + (%u x %u fds) = %u bytes\n",
1698
sizeof(struct libwebsocket_context),
1699
sizeof(struct pollfd) + sizeof(struct libwebsocket *),
1701
sizeof(struct libwebsocket_context) +
1702
((sizeof(struct pollfd) + sizeof(struct libwebsocket *)) *
1705
context->fds = (struct pollfd *)malloc(sizeof(struct pollfd) *
1707
if (context->fds == NULL) {
1708
lwsl_err("Unable to allocate fds array for %d connections\n",
1713
context->lws_lookup = (struct libwebsocket **)
1714
malloc(sizeof(struct libwebsocket *) * context->max_fds);
1715
if (context->lws_lookup == NULL) {
1717
"Unable to allocate lws_lookup array for %d connections\n",
1724
context->fds_count = 0;
1725
#ifndef LWS_NO_EXTENSIONS
1726
context->extensions = info->extensions;
1728
context->last_timeout_check_s = 0;
1729
context->user_space = info->user;
1732
context->fd_random = 0;
1734
context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1735
if (context->fd_random < 0) {
1736
lwsl_err("Unable to open random device %s %d\n",
1737
SYSTEM_RANDOM_FILEPATH, context->fd_random);
1742
#ifdef LWS_OPENSSL_SUPPORT
1743
context->use_ssl = 0;
1744
context->ssl_ctx = NULL;
1745
context->ssl_client_ctx = NULL;
1746
openssl_websocket_private_data_index = 0;
1749
strcpy(context->canonical_hostname, "unknown");
1751
#ifndef LWS_NO_SERVER
1752
if (!(info->options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)) {
1753
/* find canonical hostname */
1754
gethostname((char *)context->canonical_hostname,
1755
sizeof(context->canonical_hostname) - 1);
1757
lwsl_notice(" canonical_hostname = %s\n",
1758
context->canonical_hostname);
1762
/* split the proxy ads:port if given */
1764
p = getenv("http_proxy");
1766
strncpy(context->http_proxy_address, p,
1767
sizeof(context->http_proxy_address) - 1);
1768
context->http_proxy_address[
1769
sizeof(context->http_proxy_address) - 1] = '\0';
1771
p = strchr(context->http_proxy_address, ':');
1773
lwsl_err("http_proxy needs to be ads:port\n");
1777
context->http_proxy_port = atoi(p + 1);
1779
lwsl_notice(" Proxy %s:%u\n",
1780
context->http_proxy_address,
1781
context->http_proxy_port);
1784
#ifndef LWS_NO_SERVER
1787
#ifdef LWS_OPENSSL_SUPPORT
1788
context->use_ssl = info->ssl_cert_filepath != NULL &&
1789
info->ssl_private_key_filepath != NULL;
1791
lwsl_notice(" Compiled with CYASSL support\n");
1793
lwsl_notice(" Compiled with OpenSSL support\n");
1795
if (context->use_ssl)
1796
lwsl_notice(" Using SSL mode\n");
1798
lwsl_notice(" Using non-SSL mode\n");
1801
if (info->ssl_cert_filepath != NULL &&
1802
info->ssl_private_key_filepath != NULL) {
1803
lwsl_notice(" Not compiled for OpenSSl support!\n");
1806
lwsl_notice(" Compiled without SSL support\n");
1810
" per-conn mem: %u + %u headers + protocol rx buf\n",
1811
sizeof(struct libwebsocket),
1812
sizeof(struct allocated_headers));
1816
/* ignore SIGPIPE */
1819
signal(SIGPIPE, sigpipe_handler);
1823
#ifdef LWS_OPENSSL_SUPPORT
1825
/* basic openssl init */
1829
OpenSSL_add_all_algorithms();
1830
SSL_load_error_strings();
1832
openssl_websocket_private_data_index =
1833
SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1836
* Firefox insists on SSLv23 not SSLv3
1837
* Konq disables SSLv2 by default now, SSLv23 works
1840
method = (SSL_METHOD *)SSLv23_server_method();
1842
lwsl_err("problem creating ssl method: %s\n",
1843
ERR_error_string(ERR_get_error(),
1844
(char *)context->service_buffer));
1847
context->ssl_ctx = SSL_CTX_new(method); /* create context */
1848
if (!context->ssl_ctx) {
1849
lwsl_err("problem creating ssl context: %s\n",
1850
ERR_error_string(ERR_get_error(),
1851
(char *)context->service_buffer));
1855
#ifdef SSL_OP_NO_COMPRESSION
1856
SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
1858
SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
1859
SSL_CTX_set_cipher_list(context->ssl_ctx, CIPHERS_LIST_STRING);
1861
#ifndef LWS_NO_CLIENT
1863
/* client context */
1865
if (info->port == CONTEXT_PORT_NO_LISTEN) {
1866
method = (SSL_METHOD *)SSLv23_client_method();
1868
lwsl_err("problem creating ssl method: %s\n",
1869
ERR_error_string(ERR_get_error(),
1870
(char *)context->service_buffer));
1873
/* create context */
1874
context->ssl_client_ctx = SSL_CTX_new(method);
1875
if (!context->ssl_client_ctx) {
1876
lwsl_err("problem creating ssl context: %s\n",
1877
ERR_error_string(ERR_get_error(),
1878
(char *)context->service_buffer));
1882
#ifdef SSL_OP_NO_COMPRESSION
1883
SSL_CTX_set_options(context->ssl_client_ctx,
1884
SSL_OP_NO_COMPRESSION);
1886
SSL_CTX_set_options(context->ssl_client_ctx,
1887
SSL_OP_CIPHER_SERVER_PREFERENCE);
1888
SSL_CTX_set_cipher_list(context->ssl_client_ctx,
1889
CIPHERS_LIST_STRING);
1891
/* openssl init for cert verification (for client sockets) */
1892
if (!info->ssl_ca_filepath) {
1893
if (!SSL_CTX_load_verify_locations(
1894
context->ssl_client_ctx, NULL,
1895
LWS_OPENSSL_CLIENT_CERTS))
1897
"Unable to load SSL Client certs from %s "
1898
"(set by --with-client-cert-dir= "
1899
"in configure) -- client ssl isn't "
1900
"going to work", LWS_OPENSSL_CLIENT_CERTS);
1902
if (!SSL_CTX_load_verify_locations(
1903
context->ssl_client_ctx, info->ssl_ca_filepath,
1906
"Unable to load SSL Client certs "
1907
"file from %s -- client ssl isn't "
1908
"going to work", info->ssl_ca_filepath);
1911
* callback allowing user code to load extra verification certs
1912
* helping the client to verify server identity
1915
context->protocols[0].callback(context, NULL,
1916
LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1917
context->ssl_client_ctx, NULL, 0);
1921
/* as a server, are we requiring clients to identify themselves? */
1924
LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1926
/* absolutely require the client cert */
1928
SSL_CTX_set_verify(context->ssl_ctx,
1929
SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1930
OpenSSL_verify_callback);
1933
* give user code a chance to load certs into the server
1934
* allowing it to verify incoming client certs
1937
context->protocols[0].callback(context, NULL,
1938
LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
1939
context->ssl_ctx, NULL, 0);
1942
if (context->use_ssl) {
1944
/* openssl init for server sockets */
1946
/* set the local certificate from CertFile */
1947
n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
1948
info->ssl_cert_filepath);
1950
lwsl_err("problem getting cert '%s': %s\n",
1951
info->ssl_cert_filepath,
1952
ERR_error_string(ERR_get_error(),
1953
(char *)context->service_buffer));
1956
/* set the private key from KeyFile */
1957
if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
1958
info->ssl_private_key_filepath,
1959
SSL_FILETYPE_PEM) != 1) {
1960
lwsl_err("ssl problem getting key '%s': %s\n",
1961
info->ssl_private_key_filepath,
1962
ERR_error_string(ERR_get_error(),
1963
(char *)context->service_buffer));
1966
/* verify private key */
1967
if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
1968
lwsl_err("Private SSL key doesn't match cert\n");
1972
/* SSL is happy and has a cert it's content with */
1978
if (lws_b64_selftest())
1981
#ifndef LWS_NO_SERVER
1982
/* set up our external listening socket we serve on */
1987
sockfd = socket(AF_INET, SOCK_STREAM, 0);
1989
lwsl_err("ERROR opening socket\n");
1995
* allow us to restart even if old sockets in TIME_WAIT
1996
* (REUSEADDR on Unix means, "don't hang on to this
1997
* address after the listener is closed." On Windows, though,
1998
* it means "don't keep other processes from binding to
1999
* this address while we're using it)
2001
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
2002
(const void *)&opt, sizeof(opt));
2007
setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
2008
(const void *)&opt, sizeof(opt));
2012
ioctlsocket(sockfd, FIONBIO, (unsigned long *)&opt);
2014
fcntl(sockfd, F_SETFL, O_NONBLOCK);
2017
bzero((char *) &serv_addr, sizeof(serv_addr));
2018
serv_addr.sin_family = AF_INET;
2019
if (info->iface == NULL)
2020
serv_addr.sin_addr.s_addr = INADDR_ANY;
2022
interface_to_sa(info->iface, &serv_addr,
2024
serv_addr.sin_port = htons(info->port);
2026
n = bind(sockfd, (struct sockaddr *) &serv_addr,
2029
lwsl_err("ERROR on binding to port %d (%d %d)\n",
2030
info->port, n, errno);
2035
wsi = (struct libwebsocket *)malloc(
2036
sizeof(struct libwebsocket));
2038
lwsl_err("Out of mem\n");
2042
memset(wsi, 0, sizeof(struct libwebsocket));
2044
#ifndef LWS_NO_EXTENSIONS
2045
wsi->count_active_extensions = 0;
2047
wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
2049
insert_wsi_socket_into_fds(context, wsi);
2051
context->listen_service_modulo = LWS_LISTEN_SERVICE_MODULO;
2052
context->listen_service_count = 0;
2053
context->listen_service_fd = sockfd;
2055
listen(sockfd, LWS_SOMAXCONN);
2056
lwsl_notice(" Listening on port %d\n", info->port);
2061
* drop any root privs for this process
2062
* to listen on port < 1023 we would have needed root, but now we are
2063
* listening, we don't want the power for anything else
2067
if (info->gid != -1)
2068
if (setgid(info->gid))
2069
lwsl_warn("setgid: %s\n", strerror(errno));
2070
if (info->uid != -1)
2071
if (setuid(info->uid))
2072
lwsl_warn("setuid: %s\n", strerror(errno));
2075
/* initialize supported protocols */
2077
for (context->count_protocols = 0;
2078
info->protocols[context->count_protocols].callback;
2079
context->count_protocols++) {
2081
lwsl_parser(" Protocol: %s\n",
2082
info->protocols[context->count_protocols].name);
2084
info->protocols[context->count_protocols].owning_server =
2086
info->protocols[context->count_protocols].protocol_index =
2087
context->count_protocols;
2090
* inform all the protocols that they are doing their one-time
2091
* initialization if they want to
2093
info->protocols[context->count_protocols].callback(context,
2094
NULL, LWS_CALLBACK_PROTOCOL_INIT, NULL, NULL, 0);
2097
#ifndef LWS_NO_EXTENSIONS
2099
* give all extensions a chance to create any per-context
2100
* allocations they need
2103
m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
2105
m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
2107
if (info->extensions) {
2108
ext = info->extensions;
2109
while (ext->callback) {
2110
lwsl_ext(" Extension: %s\n", ext->name);
2111
ext->callback(context, ext, NULL,
2112
(enum libwebsocket_extension_callback_reasons)m,
2121
libwebsocket_context_destroy(context);
2126
* libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2128
* @wsi: pointer to struct websocket you want to know the protocol of
2131
* Some apis can act on all live connections of a given protocol,
2132
* this is how you can get a pointer to the active protocol if needed.
2135
const struct libwebsocket_protocols *
2136
libwebsockets_get_protocol(struct libwebsocket *wsi)
2138
return wsi->protocol;
2142
libwebsocket_is_final_fragment(struct libwebsocket *wsi)
2144
return wsi->u.ws.final;
2148
libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
2150
return wsi->u.ws.rsv;
2154
libwebsocket_ensure_user_space(struct libwebsocket *wsi)
2156
/* allocate the per-connection user memory (if any) */
2158
if (wsi->protocol->per_session_data_size && !wsi->user_space) {
2159
wsi->user_space = malloc(
2160
wsi->protocol->per_session_data_size);
2161
if (wsi->user_space == NULL) {
2162
lwsl_err("Out of memory for conn user space\n");
2165
memset(wsi->user_space, 0,
2166
wsi->protocol->per_session_data_size);
2168
return wsi->user_space;
2171
static void lwsl_emit_stderr(int level, const char *line)
2177
gettimeofday(&tv, NULL);
2180
for (n = 0; n < LLL_COUNT; n++)
2181
if (level == (1 << n)) {
2182
sprintf(buf, "[%ld:%04d] %s: ", tv.tv_sec,
2183
(int)(tv.tv_usec / 100), log_level_names[n]);
2187
fprintf(stderr, "%s%s", buf, line);
2191
void lwsl_emit_syslog(int level, const char *line)
2193
lwsl_emit_stderr(level, line);
2196
void lwsl_emit_syslog(int level, const char *line)
2198
int syslog_level = LOG_DEBUG;
2202
syslog_level = LOG_ERR;
2205
syslog_level = LOG_WARNING;
2208
syslog_level = LOG_NOTICE;
2211
syslog_level = LOG_INFO;
2214
syslog(syslog_level, "%s", line);
2218
void _lws_log(int filter, const char *format, ...)
2223
if (!(log_level & filter))
2226
va_start(ap, format);
2227
vsnprintf(buf, sizeof(buf), format, ap);
2228
buf[sizeof(buf) - 1] = '\0';
2231
lwsl_emit(filter, buf);
2235
* lws_set_log_level() - Set the logging bitfield
2236
* @level: OR together the LLL_ debug contexts you want output from
2237
* @log_emit_function: NULL to leave it as it is, or a user-supplied
2238
* function to perform log string emission instead of
2239
* the default stderr one.
2241
* log level defaults to "err" and "warn" contexts enabled only and
2242
* emission on stderr.
2245
void lws_set_log_level(int level, void (*log_emit_function)(int level,
2249
if (log_emit_function)
2250
lwsl_emit = log_emit_function;