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>
35 #include <sys/socket.h>
39 #ifdef LWS_OPENSSL_SUPPORT
40 int openssl_websocket_private_data_index;
44 #include "../win32port/win32helpers/websock-w32.c"
47 #include "../win32port/win32helpers/websock-w32.c"
51 static int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
52 static void lwsl_emit_stderr(int level, const char *line);
53 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
55 static const char *log_level_names[] = {
68 insert_wsi_socket_into_fds(struct libwebsocket_context *context, struct libwebsocket *wsi)
70 if (context->fds_count >= context->max_fds) {
71 lwsl_err("Reached limit of fds tracking (%d)\n", context->max_fds);
75 if (wsi->sock > context->max_fds) {
76 lwsl_err("Socket fd %d is beyond what we can index (%d)\n", wsi->sock, context->max_fds);
83 lwsl_info("insert_wsi_socket_into_fds: wsi=%p, sock=%d, fds pos=%d\n", wsi, wsi->sock, context->fds_count);
85 context->lws_lookup[wsi->sock] = wsi;
86 wsi->position_in_fds_table = context->fds_count;
87 context->fds[context->fds_count].fd = wsi->sock;
88 context->fds[context->fds_count].events = POLLIN;
89 context->fds[context->fds_count++].revents = 0;
91 /* external POLL support via protocol 0 */
92 context->protocols[0].callback(context, wsi,
93 LWS_CALLBACK_ADD_POLL_FD,
94 (void *)(long)wsi->sock, NULL, POLLIN);
100 remove_wsi_socket_from_fds(struct libwebsocket_context *context, struct libwebsocket *wsi)
104 if (!--context->fds_count)
107 if (wsi->sock > context->max_fds) {
108 lwsl_err("Socket fd %d is beyond what we can index (%d)\n", wsi->sock, context->max_fds);
112 lwsl_info("remove_wsi_socket_from_fds: wsi=%p, sock=%d, fds pos=%d\n", wsi, wsi->sock, wsi->position_in_fds_table);
114 m = wsi->position_in_fds_table; /* replace the contents for this */
116 /* have the last guy take up the vacant slot */
117 context->fds[m] = context->fds[context->fds_count]; /* vacant fds slot filled with end one */
118 /* end guy's fds_lookup entry remains unchanged (still same fd pointing to same wsi) */
119 /* end guy's "position in fds table" changed */
120 context->lws_lookup[context->fds[context->fds_count].fd]->position_in_fds_table = m;
121 /* deletion guy's lws_lookup entry needs nuking */
122 context->lws_lookup[wsi->sock] = NULL; /* no WSI for the socket of the wsi being removed*/
123 wsi->position_in_fds_table = -1; /* removed wsi has no position any more */
126 /* remove also from external POLL support via protocol 0 */
128 context->protocols[0].callback(context, wsi,
129 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
136 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
137 struct libwebsocket *wsi, enum lws_close_status reason)
141 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
142 LWS_SEND_BUFFER_POST_PADDING];
145 struct lws_tokens eff_buf;
146 struct libwebsocket_extension *ext;
151 old_state = wsi->state;
153 if (old_state == WSI_STATE_DEAD_SOCKET)
156 wsi->close_reason = reason;
159 * are his extensions okay with him closing? Eg he might be a mux
160 * parent and just his ch1 aspect is closing?
164 for (n = 0; n < wsi->count_active_extensions; n++) {
165 if (!wsi->active_extensions[n]->callback)
168 m = wsi->active_extensions[n]->callback(context,
169 wsi->active_extensions[n], wsi,
170 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
171 wsi->active_extensions_user[n], NULL, 0);
174 * if somebody vetoed actually closing him at this time....
175 * up to the extension to track the attempted close, let's
180 lwsl_ext("extension vetoed close\n");
188 * flush any tx pending from extensions, since we may send close packet
189 * if there are problems with send, just nuke the connection
195 /* default to nobody has more to spill */
198 eff_buf.token = NULL;
199 eff_buf.token_len = 0;
201 /* show every extension the new incoming data */
203 for (n = 0; n < wsi->count_active_extensions; n++) {
204 m = wsi->active_extensions[n]->callback(
205 wsi->protocol->owning_server,
206 wsi->active_extensions[n], wsi,
207 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
208 wsi->active_extensions_user[n], &eff_buf, 0);
210 lwsl_ext("Extension reports fatal error\n");
211 goto just_kill_connection;
215 * at least one extension told us he has more
216 * to spill, so we will go around again after
221 /* assuming they left us something to send, send it */
223 if (eff_buf.token_len)
224 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
225 eff_buf.token_len)) {
226 lwsl_debug("close: sending final extension spill had problems\n");
227 goto just_kill_connection;
232 * signal we are closing, libsocket_write will
233 * add any necessary version-specific stuff. If the write fails,
234 * no worries we are closing anyway. If we didn't initiate this
235 * close, then our state has been changed to
236 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
238 * Likewise if it's a second call to close this connection after we
239 * sent the close indication to the peer already, we are in state
240 * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
243 if (old_state == WSI_STATE_ESTABLISHED &&
244 reason != LWS_CLOSE_STATUS_NOSTATUS) {
246 lwsl_debug("sending close indication...\n");
248 n = libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING],
252 * we have sent a nice protocol level indication we
253 * now wish to close, we should not send anything more
256 wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
258 /* and we should wait for a reply for a bit out of politeness */
260 libwebsocket_set_timeout(wsi,
261 PENDING_TIMEOUT_CLOSE_ACK, 1);
263 lwsl_debug("sent close indication, awaiting ack\n");
268 lwsl_info("close: sending the close packet failed, hanging up\n");
270 /* else, the send failed and we should just hang up */
273 just_kill_connection:
275 lwsl_debug("libwebsocket_close_and_free_session: just_kill_connection\n");
278 * we won't be servicing or receiving anything further from this guy
279 * delete socket from the internal poll list if still present
282 remove_wsi_socket_from_fds(context, wsi);
284 wsi->state = WSI_STATE_DEAD_SOCKET;
286 /* tell the user it's all over for this guy */
288 if (wsi->protocol && wsi->protocol->callback &&
289 ((old_state == WSI_STATE_ESTABLISHED) ||
290 (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
291 (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
292 lwsl_debug("calling back CLOSED\n");
293 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
294 wsi->user_space, NULL, 0);
296 lwsl_debug("not calling back closed, old_state=%d\n", old_state);
298 /* deallocate any active extension contexts */
300 for (n = 0; n < wsi->count_active_extensions; n++) {
301 if (!wsi->active_extensions[n]->callback)
304 wsi->active_extensions[n]->callback(context,
305 wsi->active_extensions[n], wsi,
306 LWS_EXT_CALLBACK_DESTROY,
307 wsi->active_extensions_user[n], NULL, 0);
309 free(wsi->active_extensions_user[n]);
313 * inform all extensions in case they tracked this guy out of band
314 * even though not active on him specifically
317 ext = context->extensions;
318 while (ext && ext->callback) {
319 ext->callback(context, ext, wsi,
320 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
325 /* free up his parsing allocations */
327 for (n = 0; n < WSI_TOKEN_COUNT; n++)
328 if (wsi->utf8_token[n].token)
329 free(wsi->utf8_token[n].token);
330 #ifndef LWS_NO_CLIENT
332 free(wsi->c_address);
334 if (wsi->rxflow_buffer)
335 free(wsi->rxflow_buffer);
337 /* lwsl_info("closing fd=%d\n", wsi->sock); */
339 #ifdef LWS_OPENSSL_SUPPORT
341 n = SSL_get_fd(wsi->ssl);
342 SSL_shutdown(wsi->ssl);
348 n = shutdown(wsi->sock, SHUT_RDWR);
350 lwsl_debug("closing: shutdown returned %d\n", errno);
352 n = compatible_close(wsi->sock);
354 lwsl_debug("closing: close returned %d\n", errno);
356 #ifdef LWS_OPENSSL_SUPPORT
359 if (wsi->protocol && wsi->protocol->per_session_data_size && wsi->user_space) /* user code may own */
360 free(wsi->user_space);
366 * libwebsockets_hangup_on_client() - Server calls to terminate client
368 * @context: libwebsockets context
369 * @fd: Connection socket descriptor
373 libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
375 struct libwebsocket *wsi = context->lws_lookup[fd];
378 libwebsocket_close_and_free_session(context,
379 wsi, LWS_CLOSE_STATUS_NOSTATUS);
386 * libwebsockets_get_peer_addresses() - Get client address information
387 * @fd: Connection socket descriptor
388 * @name: Buffer to take client address name
389 * @name_len: Length of client address name buffer
390 * @rip: Buffer to take client address IP qotted quad
391 * @rip_len: Length of client address IP buffer
393 * This function fills in @name and @rip with the name and IP of
394 * the client connected with socket descriptor @fd. Names may be
395 * truncated if there is not enough room. If either cannot be
396 * determined, they will be returned as valid zero-length strings.
400 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
401 char *rip, int rip_len)
404 struct sockaddr_in sin;
405 struct hostent *host;
406 struct hostent *host1;
411 struct sockaddr_un *un;
418 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
419 perror("getpeername");
423 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
426 perror("gethostbyaddr");
430 strncpy(name, host->h_name, name_len);
431 name[name_len - 1] = '\0';
433 host1 = gethostbyname(host->h_name);
436 p = (unsigned char *)host1;
439 p = (unsigned char *)host1->h_addr_list[n++];
442 if ((host1->h_addrtype != AF_INET)
444 && (host1->h_addrtype != AF_LOCAL)
449 if (host1->h_addrtype == AF_INET)
450 sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
453 un = (struct sockaddr_un *)p;
454 strncpy(ip, un->sun_path, sizeof(ip) - 1);
455 ip[sizeof(ip) - 1] = '\0';
459 strncpy(rip, ip, rip_len);
460 rip[rip_len - 1] = '\0';
464 int libwebsockets_get_random(struct libwebsocket_context *context,
468 char *p = (char *)buf;
471 for (n = 0; n < len; n++)
472 p[n] = (unsigned char)rand();
474 n = read(context->fd_random, p, len);
481 libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md)
483 return SHA1(d, n, md);
486 int lws_send_pipe_choked(struct libwebsocket *wsi)
491 fds.events = POLLOUT;
494 if (poll(&fds, 1, 0) != 1)
497 if ((fds.revents & POLLOUT) == 0)
500 /* okay to send another packet without blocking */
506 lws_handle_POLLOUT_event(struct libwebsocket_context *context,
507 struct libwebsocket *wsi, struct pollfd *pollfd)
509 struct lws_tokens eff_buf;
515 for (n = 0; n < wsi->count_active_extensions; n++) {
516 if (!wsi->active_extensions[n]->callback)
519 m = wsi->active_extensions[n]->callback(context,
520 wsi->active_extensions[n], wsi,
521 LWS_EXT_CALLBACK_IS_WRITEABLE,
522 wsi->active_extensions_user[n], NULL, 0);
530 if (!wsi->extension_data_pending || handled == 2)
534 * check in on the active extensions, see if they
535 * had pending stuff to spill... they need to get the
536 * first look-in otherwise sequence will be disordered
538 * NULL, zero-length eff_buf means just spill pending
544 /* default to nobody has more to spill */
547 eff_buf.token = NULL;
548 eff_buf.token_len = 0;
550 /* give every extension a chance to spill */
552 for (n = 0; n < wsi->count_active_extensions; n++) {
553 m = wsi->active_extensions[n]->callback(
554 wsi->protocol->owning_server,
555 wsi->active_extensions[n], wsi,
556 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
557 wsi->active_extensions_user[n], &eff_buf, 0);
559 lwsl_err("ext reports fatal error\n");
564 * at least one extension told us he has more
565 * to spill, so we will go around again after
570 /* assuming they gave us something to send, send it */
572 if (eff_buf.token_len) {
573 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
579 /* no extension has more to spill */
585 * There's more to spill from an extension, but we just sent
586 * something... did that leave the pipe choked?
589 if (!lws_send_pipe_choked(wsi))
590 /* no we could add more */
593 lwsl_info("choked in POLLOUT service\n");
596 * Yes, he's choked. Leave the POLLOUT masked on so we will
597 * come back here when he is unchoked. Don't call the user
598 * callback to enforce ordering of spilling, he'll get called
599 * when we come back here and there's nothing more to spill.
605 wsi->extension_data_pending = 0;
611 pollfd->events &= ~POLLOUT;
613 /* external POLL support via protocol 0 */
614 context->protocols[0].callback(context, wsi,
615 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
616 (void *)(long)wsi->sock, NULL, POLLOUT);
621 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
622 n = LWS_CALLBACK_CLIENT_WRITEABLE;
624 n = LWS_CALLBACK_SERVER_WRITEABLE;
626 user_callback_handle_rxflow(wsi->protocol->callback, context,
627 wsi, (enum libwebsocket_callback_reasons) n, wsi->user_space, NULL, 0);
635 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
636 struct libwebsocket *wsi, unsigned int sec)
641 * if extensions want in on it (eg, we are a mux parent)
642 * give them a chance to service child timeouts
645 for (n = 0; n < wsi->count_active_extensions; n++)
646 wsi->active_extensions[n]->callback(
647 context, wsi->active_extensions[n],
648 wsi, LWS_EXT_CALLBACK_1HZ,
649 wsi->active_extensions_user[n], NULL, sec);
651 if (!wsi->pending_timeout)
655 * if we went beyond the allowed time, kill the
659 if (sec > wsi->pending_timeout_limit) {
660 lwsl_info("TIMEDOUT WAITING\n");
661 libwebsocket_close_and_free_session(context,
662 wsi, LWS_CLOSE_STATUS_NOSTATUS);
667 * libwebsocket_service_fd() - Service polled socket with something waiting
668 * @context: Websocket context
669 * @pollfd: The pollfd entry describing the socket fd and which events
672 * This function closes any active connections and then frees the
673 * context. After calling this, any further use of the context is
678 libwebsocket_service_fd(struct libwebsocket_context *context,
679 struct pollfd *pollfd)
681 struct libwebsocket *wsi;
682 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
683 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
688 struct lws_tokens eff_buf;
689 #ifndef LWS_NO_CLIENT
690 extern int lws_client_socket_service(struct libwebsocket_context *context, struct libwebsocket *wsi, struct pollfd *pollfd);
692 #ifndef LWS_NO_SERVER
693 extern int lws_server_socket_service(struct libwebsocket_context *context, struct libwebsocket *wsi, struct pollfd *pollfd);
696 * you can call us with pollfd = NULL to just allow the once-per-second
697 * global timeout checks; if less than a second since the last check
698 * it returns immediately then.
701 gettimeofday(&tv, NULL);
703 if (context->last_timeout_check_s != tv.tv_sec) {
704 context->last_timeout_check_s = tv.tv_sec;
706 /* global timeout check once per second */
708 for (n = 0; n < context->fds_count; n++) {
709 struct libwebsocket *new_wsi = context->lws_lookup[context->fds[n].fd];
712 libwebsocket_service_timeout_check(context,
717 /* just here for timeout management? */
722 /* no, here to service a socket descriptor */
725 * deal with listen service piggybacking
726 * every listen_service_modulo services of other fds, we
727 * sneak one in to service the listen socket if there's anything waiting
729 * To handle connection storms, as found in ab, if we previously saw a
730 * pending connection here, it causes us to check again next time.
733 if (context->listen_service_fd && pollfd->fd != context->listen_service_fd) {
734 context->listen_service_count++;
735 if (context->listen_service_extraseen ||
736 context->listen_service_count == context->listen_service_modulo) {
737 context->listen_service_count = 0;
739 if (context->listen_service_extraseen > 5)
742 /* even with extpoll, we prepared this internal fds for listen */
743 n = poll(&context->fds[0], 1, 0);
744 if (n > 0) { /* there's a connection waiting for us */
745 libwebsocket_service_fd(context, &context->fds[0]);
746 context->listen_service_extraseen++;
748 if (context->listen_service_extraseen)
749 context->listen_service_extraseen--;
757 /* okay, what we came here to do... */
759 wsi = context->lws_lookup[pollfd->fd];
762 lwsl_err("unexpected NULL wsi fd=%d fds_count=%d\n", pollfd->fd, context->fds_count);
768 #ifndef LWS_NO_SERVER
769 case LWS_CONNMODE_HTTP_SERVING:
770 case LWS_CONNMODE_SERVER_LISTENER:
771 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
772 case LWS_CONNMODE_BROADCAST_PROXY:
773 return lws_server_socket_service(context, wsi, pollfd);
776 case LWS_CONNMODE_WS_SERVING:
777 case LWS_CONNMODE_WS_CLIENT:
779 /* handle session socket closed */
781 if (pollfd->revents & (POLLERR | POLLHUP)) {
783 lwsl_debug("Session Socket %p (fd=%d) dead\n",
784 (void *)wsi, pollfd->fd);
786 libwebsocket_close_and_free_session(context, wsi,
787 LWS_CLOSE_STATUS_NOSTATUS);
791 /* the guy requested a callback when it was OK to write */
793 if ((pollfd->revents & POLLOUT) &&
794 wsi->state == WSI_STATE_ESTABLISHED)
795 if (lws_handle_POLLOUT_event(context, wsi,
797 libwebsocket_close_and_free_session(
798 context, wsi, LWS_CLOSE_STATUS_NORMAL);
803 /* any incoming data ready? */
805 if (!(pollfd->revents & POLLIN))
808 #ifdef LWS_OPENSSL_SUPPORT
811 eff_buf.token_len = SSL_read(wsi->ssl, buf, sizeof buf);
815 recv(pollfd->fd, buf, sizeof buf, 0);
817 if (eff_buf.token_len < 0) {
818 lwsl_debug("Socket read returned %d\n",
820 if (errno != EINTR && errno != EAGAIN)
821 libwebsocket_close_and_free_session(context,
822 wsi, LWS_CLOSE_STATUS_NOSTATUS);
825 if (!eff_buf.token_len) {
826 libwebsocket_close_and_free_session(context, wsi,
827 LWS_CLOSE_STATUS_NOSTATUS);
832 * give any active extensions a chance to munge the buffer
833 * before parse. We pass in a pointer to an lws_tokens struct
834 * prepared with the default buffer and content length that's in
835 * there. Rather than rewrite the default buffer, extensions
836 * that expect to grow the buffer can adapt .token to
837 * point to their own per-connection buffer in the extension
838 * user allocation. By default with no extensions or no
839 * extension callback handling, just the normal input buffer is
840 * used then so it is efficient.
843 eff_buf.token = (char *)buf;
850 for (n = 0; n < wsi->count_active_extensions; n++) {
851 m = wsi->active_extensions[n]->callback(context,
852 wsi->active_extensions[n], wsi,
853 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
854 wsi->active_extensions_user[n],
858 "Extension reports fatal error\n");
859 libwebsocket_close_and_free_session(
861 LWS_CLOSE_STATUS_NOSTATUS);
868 /* service incoming data */
870 if (eff_buf.token_len) {
871 n = libwebsocket_read(context, wsi,
872 (unsigned char *)eff_buf.token,
879 eff_buf.token = NULL;
880 eff_buf.token_len = 0;
883 #ifdef LWS_OPENSSL_SUPPORT
884 if (wsi->ssl && SSL_pending(wsi->ssl))
893 return lws_client_socket_service(context, wsi, pollfd);
902 * libwebsocket_context_destroy() - Destroy the websocket context
903 * @context: Websocket context
905 * This function closes any active connections and then frees the
906 * context. After calling this, any further use of the context is
910 libwebsocket_context_destroy(struct libwebsocket_context *context)
914 struct libwebsocket_extension *ext;
916 for (n = 0; n < context->fds_count; n++) {
917 struct libwebsocket *wsi = context->lws_lookup[context->fds[n].fd];
918 libwebsocket_close_and_free_session(context,
919 wsi, LWS_CLOSE_STATUS_GOINGAWAY);
923 * give all extensions a chance to clean up any per-context
924 * allocations they might have made
927 ext = context->extensions;
928 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
929 if (context->listen_port)
930 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
931 while (ext && ext->callback) {
932 ext->callback(context, ext, NULL, (enum libwebsocket_extension_callback_reasons)m, NULL, NULL, 0);
938 close(context->fd_random);
941 #ifdef LWS_OPENSSL_SUPPORT
942 if (context->ssl_ctx)
943 SSL_CTX_free(context->ssl_ctx);
944 if (context->ssl_client_ctx)
945 SSL_CTX_free(context->ssl_client_ctx);
956 libwebsocket_context_user(struct libwebsocket_context *context)
958 return context->user_space;
962 * libwebsocket_service() - Service any pending websocket activity
963 * @context: Websocket context
964 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
965 * service otherwise block and service immediately, returning
966 * after the timeout if nothing needed service.
968 * This function deals with any pending websocket traffic, for three
969 * kinds of event. It handles these events on both server and client
970 * types of connection the same.
972 * 1) Accept new connections to our context's server
974 * 2) Perform pending broadcast writes initiated from other forked
975 * processes (effectively serializing asynchronous broadcasts)
977 * 3) Call the receive callback for incoming frame data received by
978 * server or client connections.
980 * You need to call this service function periodically to all the above
981 * functions to happen; if your application is single-threaded you can
982 * just call it in your main event loop.
984 * Alternatively you can fork a new process that asynchronously handles
985 * calling this service in a loop. In that case you are happy if this
986 * call blocks your thread until it needs to take care of something and
987 * would call it with a large nonzero timeout. Your loop then takes no
988 * CPU while there is nothing happening.
990 * If you are calling it in a single-threaded app, you don't want it to
991 * wait around blocking other things in your loop from happening, so you
992 * would call it with a timeout_ms of 0, so it returns immediately if
993 * nothing is pending, or as soon as it services whatever was pending.
998 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
1002 /* stay dead once we are dead */
1004 if (context == NULL)
1007 /* wait for something to need service */
1009 n = poll(context->fds, context->fds_count, timeout_ms);
1010 if (n == 0) /* poll timeout */
1016 /* any socket with events to service? */
1018 for (n = 0; n < context->fds_count; n++)
1019 if (context->fds[n].revents)
1020 if (libwebsocket_service_fd(context,
1021 &context->fds[n]) < 0)
1027 lws_any_extension_handled(struct libwebsocket_context *context,
1028 struct libwebsocket *wsi,
1029 enum libwebsocket_extension_callback_reasons r,
1030 void *v, size_t len)
1035 /* maybe an extension will take care of it for us */
1037 for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
1038 if (!wsi->active_extensions[n]->callback)
1041 handled |= wsi->active_extensions[n]->callback(context,
1042 wsi->active_extensions[n], wsi,
1043 r, wsi->active_extensions_user[n], v, len);
1051 lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
1052 struct libwebsocket_extension *ext)
1059 while (n < wsi->count_active_extensions) {
1060 if (wsi->active_extensions[n] != ext) {
1064 return wsi->active_extensions_user[n];
1071 * libwebsocket_callback_on_writable() - Request a callback when this socket
1072 * becomes able to be written to without
1075 * @context: libwebsockets context
1076 * @wsi: Websocket connection instance to get callback for
1080 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
1081 struct libwebsocket *wsi)
1086 /* maybe an extension will take care of it for us */
1088 for (n = 0; n < wsi->count_active_extensions; n++) {
1089 if (!wsi->active_extensions[n]->callback)
1092 handled |= wsi->active_extensions[n]->callback(context,
1093 wsi->active_extensions[n], wsi,
1094 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
1095 wsi->active_extensions_user[n], NULL, 0);
1101 if (wsi->position_in_fds_table < 0) {
1102 lwsl_err("libwebsocket_callback_on_writable: "
1103 "failed to find socket %d\n", wsi->sock);
1107 context->fds[wsi->position_in_fds_table].events |= POLLOUT;
1109 /* external POLL support via protocol 0 */
1110 context->protocols[0].callback(context, wsi,
1111 LWS_CALLBACK_SET_MODE_POLL_FD,
1112 (void *)(long)wsi->sock, NULL, POLLOUT);
1118 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1119 * all connections using the given protocol when it
1120 * becomes possible to write to each socket without
1123 * @protocol: Protocol whose connections will get callbacks
1127 libwebsocket_callback_on_writable_all_protocol(
1128 const struct libwebsocket_protocols *protocol)
1130 struct libwebsocket_context *context = protocol->owning_server;
1132 struct libwebsocket *wsi;
1134 for (n = 0; n < context->fds_count; n++) {
1135 wsi = context->lws_lookup[context->fds[n].fd];
1138 if (wsi->protocol == protocol)
1139 libwebsocket_callback_on_writable(context, wsi);
1146 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1148 * You will not need this unless you are doing something special
1150 * @wsi: Websocket connection instance
1151 * @reason: timeout reason
1152 * @secs: how many seconds
1156 libwebsocket_set_timeout(struct libwebsocket *wsi,
1157 enum pending_timeout reason, int secs)
1161 gettimeofday(&tv, NULL);
1163 wsi->pending_timeout_limit = tv.tv_sec + secs;
1164 wsi->pending_timeout = reason;
1169 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1171 * You will not need this unless you are doing something special
1173 * @wsi: Websocket connection instance
1177 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1182 #ifdef LWS_NO_SERVER
1184 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1190 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1192 struct libwebsocket_context *context = wsi->protocol->owning_server;
1195 if (!(wsi->rxflow_change_to & 2))
1198 wsi->rxflow_change_to &= ~2;
1200 lwsl_info("rxflow: wsi %p change_to %d\n", wsi, wsi->rxflow_change_to);
1202 /* if we're letting it come again, did we interrupt anything? */
1203 if ((wsi->rxflow_change_to & 1) && wsi->rxflow_buffer) {
1204 n = libwebsocket_interpret_incoming_packet(wsi, NULL, 0);
1206 libwebsocket_close_and_free_session(context, wsi, LWS_CLOSE_STATUS_NOSTATUS);
1210 /* oh he stuck again, do nothing */
1214 if (wsi->rxflow_change_to & 1)
1215 context->fds[wsi->position_in_fds_table].events |= POLLIN;
1217 context->fds[wsi->position_in_fds_table].events &= ~POLLIN;
1219 if (wsi->rxflow_change_to & 1)
1220 /* external POLL support via protocol 0 */
1221 context->protocols[0].callback(context, wsi,
1222 LWS_CALLBACK_SET_MODE_POLL_FD,
1223 (void *)(long)wsi->sock, NULL, POLLIN);
1225 /* external POLL support via protocol 0 */
1226 context->protocols[0].callback(context, wsi,
1227 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1228 (void *)(long)wsi->sock, NULL, POLLIN);
1235 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1236 * receieved packets.
1238 * If the output side of a server process becomes choked, this allows flow
1239 * control for the input side.
1241 * @wsi: Websocket connection instance to get callback for
1242 * @enable: 0 = disable read servicing for this connection, 1 = enable
1246 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1248 wsi->rxflow_change_to = 2 | !!enable;
1255 * libwebsocket_canonical_hostname() - returns this host's hostname
1257 * This is typically used by client code to fill in the host parameter
1258 * when making a client connection. You can only call it after the context
1261 * @context: Websocket context
1266 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
1268 return (const char *)context->canonical_hostname;
1272 static void sigpipe_handler(int x)
1276 #ifdef LWS_OPENSSL_SUPPORT
1278 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1283 struct libwebsocket_context *context;
1285 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1286 SSL_get_ex_data_X509_STORE_CTX_idx());
1289 * !!! nasty openssl requires the index to come as a library-scope
1292 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
1294 n = context->protocols[0].callback(NULL, NULL,
1295 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1296 x509_ctx, ssl, preverify_ok);
1298 /* convert return code from 0 = OK to 1 = OK */
1309 int user_callback_handle_rxflow(callback_function callback_function,
1310 struct libwebsocket_context * context,
1311 struct libwebsocket *wsi,
1312 enum libwebsocket_callback_reasons reason, void *user,
1313 void *in, size_t len)
1317 n = callback_function(context, wsi, reason, user, in, len);
1321 _libwebsocket_rx_flow_control(wsi);
1328 * libwebsocket_create_context() - Create the websocket handler
1329 * @port: Port to listen on... you can use 0 to suppress listening on
1330 * any port, that's what you want if you are not running a
1331 * websocket server at all but just using it as a client
1332 * @interf: NULL to bind the listen socket to all interfaces, or the
1333 * interface name, eg, "eth2"
1334 * @protocols: Array of structures listing supported protocols and a protocol-
1335 * specific callback for each one. The list is ended with an
1336 * entry that has a NULL callback pointer.
1337 * It's not const because we write the owning_server member
1338 * @extensions: NULL or array of libwebsocket_extension structs listing the
1339 * extensions this context supports
1340 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
1341 * to listen using SSL, set to the filepath to fetch the
1342 * server cert from, otherwise NULL for unencrypted
1343 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
1345 * @ssl_ca_filepath: CA certificate filepath or NULL
1346 * @gid: group id to change to after setting listen socket, or -1.
1347 * @uid: user id to change to after setting listen socket, or -1.
1348 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
1349 * @user: optional user pointer that can be recovered via the context
1350 * pointer using libwebsocket_context_user
1352 * This function creates the listening socket and takes care
1353 * of all initialization in one step.
1355 * After initialization, it returns a struct libwebsocket_context * that
1356 * represents this server. After calling, user code needs to take care
1357 * of calling libwebsocket_service() with the context pointer to get the
1358 * server's sockets serviced. This can be done in the same process context
1359 * or a forked process, or another thread,
1361 * The protocol callback functions are called for a handful of events
1362 * including http requests coming in, websocket connections becoming
1363 * established, and data arriving; it's also called periodically to allow
1364 * async transmission.
1366 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1367 * at that time websocket protocol has not been negotiated. Other
1368 * protocols after the first one never see any HTTP callack activity.
1370 * The server created is a simple http server by default; part of the
1371 * websocket standard is upgrading this http connection to a websocket one.
1373 * This allows the same server to provide files like scripts and favicon /
1374 * images or whatever over http and dynamic data over websockets all in
1375 * one place; they're all handled in the user callback.
1378 struct libwebsocket_context *
1379 libwebsocket_create_context(int port, const char *interf,
1380 struct libwebsocket_protocols *protocols,
1381 struct libwebsocket_extension *extensions,
1382 const char *ssl_cert_filepath,
1383 const char *ssl_private_key_filepath,
1384 const char *ssl_ca_filepath,
1385 int gid, int uid, unsigned int options,
1391 struct sockaddr_in serv_addr, cli_addr;
1393 struct libwebsocket_context *context = NULL;
1396 struct libwebsocket *wsi;
1398 #ifdef LWS_OPENSSL_SUPPORT
1400 char ssl_err_buf[512];
1403 lwsl_notice("Initial logging level %d\n", log_level);
1404 lwsl_info(" LWS_MAX_HEADER_NAME_LENGTH: %u\n", LWS_MAX_HEADER_NAME_LENGTH);
1405 lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN);
1406 lwsl_info(" LWS_INITIAL_HDR_ALLOC: %u\n", LWS_INITIAL_HDR_ALLOC);
1407 lwsl_info(" LWS_ADDITIONAL_HDR_ALLOC: %u\n", LWS_ADDITIONAL_HDR_ALLOC);
1408 lwsl_info(" MAX_USER_RX_BUFFER: %u\n", MAX_USER_RX_BUFFER);
1409 lwsl_info(" MAX_BROADCAST_PAYLOAD: %u\n", MAX_BROADCAST_PAYLOAD);
1410 lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS);
1411 lwsl_info(" LWS_MAX_EXTENSIONS_ACTIVE: %u\n", LWS_MAX_EXTENSIONS_ACTIVE);
1412 lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED);
1413 lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT);
1414 lwsl_info(" CIPHERS_LIST_STRING: '%s'\n", CIPHERS_LIST_STRING);
1415 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
1416 lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER);
1420 WORD wVersionRequested;
1425 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1426 wVersionRequested = MAKEWORD(2, 2);
1428 err = WSAStartup(wVersionRequested, &wsaData);
1430 /* Tell the user that we could not find a usable */
1432 lwsl_err("WSAStartup failed with error: %d\n", err);
1436 /* default to a poll() made out of select() */
1437 poll = emulated_poll;
1439 /* if windows socket lib available, use his WSAPoll */
1440 wsdll = GetModuleHandle(_T("Ws2_32.dll"));
1442 poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
1447 context = (struct libwebsocket_context *) malloc(sizeof(struct libwebsocket_context));
1449 lwsl_err("No memory for websocket context\n");
1452 context->protocols = protocols;
1453 context->listen_port = port;
1454 context->http_proxy_port = 0;
1455 context->http_proxy_address[0] = '\0';
1456 context->options = options;
1457 /* to reduce this allocation, */
1458 context->max_fds = getdtablesize();
1459 lwsl_notice(" max fd tracked: %u\n", context->max_fds);
1461 context->fds = (struct pollfd *)malloc(sizeof(struct pollfd) * context->max_fds);
1462 if (context->fds == NULL) {
1463 lwsl_err("Unable to allocate fds array for %d connections\n", context->max_fds);
1467 context->lws_lookup = (struct libwebsocket **)malloc(sizeof(struct libwebsocke *) * context->max_fds);
1468 if (context->lws_lookup == NULL) {
1469 lwsl_err("Unable to allocate lws_lookup array for %d connections\n", context->max_fds);
1474 context->fds_count = 0;
1475 context->extensions = extensions;
1476 context->last_timeout_check_s = 0;
1477 context->user_space = user;
1480 context->fd_random = 0;
1482 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1483 if (context->fd_random < 0) {
1485 lwsl_err("Unable to open random device %s %d\n",
1486 SYSTEM_RANDOM_FILEPATH, context->fd_random);
1491 #ifdef LWS_OPENSSL_SUPPORT
1492 context->use_ssl = 0;
1493 context->ssl_ctx = NULL;
1494 context->ssl_client_ctx = NULL;
1495 openssl_websocket_private_data_index = 0;
1498 strcpy(context->canonical_hostname, "unknown");
1500 #ifndef LWS_NO_SERVER
1501 if (!(options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)) {
1503 char hostname[1024] = "";
1505 /* find canonical hostname */
1507 hostname[(sizeof hostname) - 1] = '\0';
1508 memset(&sa, 0, sizeof(sa));
1509 sa.sa_family = AF_INET;
1510 sa.sa_data[(sizeof sa.sa_data) - 1] = '\0';
1511 gethostname(hostname, (sizeof hostname) - 1);
1515 if (strlen(hostname) < sizeof(sa.sa_data) - 1) {
1516 strcpy(sa.sa_data, hostname);
1517 // lwsl_debug("my host name is %s\n", sa.sa_data);
1518 n = getnameinfo(&sa, sizeof(sa), hostname,
1519 (sizeof hostname) - 1, NULL, 0, 0);
1523 strncpy(context->canonical_hostname, hostname,
1524 sizeof context->canonical_hostname - 1);
1525 context->canonical_hostname[
1526 sizeof context->canonical_hostname - 1] = '\0';
1528 strncpy(context->canonical_hostname, hostname,
1529 sizeof context->canonical_hostname - 1);
1531 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
1535 /* split the proxy ads:port if given */
1537 p = getenv("http_proxy");
1539 strncpy(context->http_proxy_address, p,
1540 sizeof context->http_proxy_address - 1);
1541 context->http_proxy_address[
1542 sizeof context->http_proxy_address - 1] = '\0';
1544 p = strchr(context->http_proxy_address, ':');
1546 lwsl_err("http_proxy needs to be ads:port\n");
1550 context->http_proxy_port = atoi(p + 1);
1552 lwsl_notice(" Proxy %s:%u\n",
1553 context->http_proxy_address,
1554 context->http_proxy_port);
1557 #ifndef LWS_NO_SERVER
1560 #ifdef LWS_OPENSSL_SUPPORT
1561 context->use_ssl = ssl_cert_filepath != NULL &&
1562 ssl_private_key_filepath != NULL;
1563 if (context->use_ssl)
1564 lwsl_notice(" Compiled with SSL support, using it\n");
1566 lwsl_notice(" Compiled with SSL support, not using it\n");
1569 if (ssl_cert_filepath != NULL &&
1570 ssl_private_key_filepath != NULL) {
1571 lwsl_notice(" Not compiled for OpenSSl support!\n");
1574 lwsl_notice(" Compiled without SSL support, "
1575 "serving unencrypted\n");
1580 /* ignore SIGPIPE */
1583 signal(SIGPIPE, sigpipe_handler);
1587 #ifdef LWS_OPENSSL_SUPPORT
1589 /* basic openssl init */
1593 OpenSSL_add_all_algorithms();
1594 SSL_load_error_strings();
1596 openssl_websocket_private_data_index =
1597 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1600 * Firefox insists on SSLv23 not SSLv3
1601 * Konq disables SSLv2 by default now, SSLv23 works
1604 method = (SSL_METHOD *)SSLv23_server_method();
1606 lwsl_err("problem creating ssl method: %s\n",
1607 ERR_error_string(ERR_get_error(), ssl_err_buf));
1610 context->ssl_ctx = SSL_CTX_new(method); /* create context */
1611 if (!context->ssl_ctx) {
1612 lwsl_err("problem creating ssl context: %s\n",
1613 ERR_error_string(ERR_get_error(), ssl_err_buf));
1617 #ifdef SSL_OP_NO_COMPRESSION
1618 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
1620 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
1621 SSL_CTX_set_cipher_list(context->ssl_ctx, CIPHERS_LIST_STRING);
1623 #ifndef LWS_NO_CLIENT
1625 /* client context */
1627 if (port == CONTEXT_PORT_NO_LISTEN) {
1628 method = (SSL_METHOD *)SSLv23_client_method();
1630 lwsl_err("problem creating ssl method: %s\n",
1631 ERR_error_string(ERR_get_error(), ssl_err_buf));
1634 /* create context */
1635 context->ssl_client_ctx = SSL_CTX_new(method);
1636 if (!context->ssl_client_ctx) {
1637 lwsl_err("problem creating ssl context: %s\n",
1638 ERR_error_string(ERR_get_error(), ssl_err_buf));
1642 #ifdef SSL_OP_NO_COMPRESSION
1643 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_NO_COMPRESSION);
1645 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
1646 SSL_CTX_set_cipher_list(context->ssl_client_ctx, CIPHERS_LIST_STRING);
1648 /* openssl init for cert verification (for client sockets) */
1649 if (!ssl_ca_filepath) {
1650 if (!SSL_CTX_load_verify_locations(
1651 context->ssl_client_ctx, NULL,
1652 LWS_OPENSSL_CLIENT_CERTS))
1654 "Unable to load SSL Client certs from %s "
1655 "(set by --with-client-cert-dir= in configure) -- "
1656 " client ssl isn't going to work",
1657 LWS_OPENSSL_CLIENT_CERTS);
1659 if (!SSL_CTX_load_verify_locations(
1660 context->ssl_client_ctx, ssl_ca_filepath,
1663 "Unable to load SSL Client certs "
1664 "file from %s -- client ssl isn't "
1665 "going to work", ssl_ca_filepath);
1668 * callback allowing user code to load extra verification certs
1669 * helping the client to verify server identity
1672 context->protocols[0].callback(context, NULL,
1673 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1674 context->ssl_client_ctx, NULL, 0);
1678 /* as a server, are we requiring clients to identify themselves? */
1680 if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1682 /* absolutely require the client cert */
1684 SSL_CTX_set_verify(context->ssl_ctx,
1685 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1686 OpenSSL_verify_callback);
1689 * give user code a chance to load certs into the server
1690 * allowing it to verify incoming client certs
1693 context->protocols[0].callback(context, NULL,
1694 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
1695 context->ssl_ctx, NULL, 0);
1698 if (context->use_ssl) {
1700 /* openssl init for server sockets */
1702 /* set the local certificate from CertFile */
1703 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
1706 lwsl_err("problem getting cert '%s': %s\n",
1708 ERR_error_string(ERR_get_error(), ssl_err_buf));
1711 /* set the private key from KeyFile */
1712 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
1713 ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
1714 lwsl_err("ssl problem getting key '%s': %s\n",
1715 ssl_private_key_filepath,
1716 ERR_error_string(ERR_get_error(), ssl_err_buf));
1719 /* verify private key */
1720 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
1721 lwsl_err("Private SSL key doesn't match cert\n");
1725 /* SSL is happy and has a cert it's content with */
1731 if (lws_b64_selftest())
1734 #ifndef LWS_NO_SERVER
1735 /* set up our external listening socket we serve on */
1738 extern int interface_to_sa(const char *ifname, struct sockaddr_in *addr, size_t addrlen);
1741 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1743 lwsl_err("ERROR opening socket\n");
1747 /* allow us to restart even if old sockets in TIME_WAIT */
1748 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
1749 (const void *)&opt, sizeof(opt));
1753 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
1754 (const void *)&opt, sizeof(opt));
1756 bzero((char *) &serv_addr, sizeof(serv_addr));
1757 serv_addr.sin_family = AF_INET;
1759 serv_addr.sin_addr.s_addr = INADDR_ANY;
1761 interface_to_sa(interf, &serv_addr,
1763 serv_addr.sin_port = htons(port);
1765 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1768 lwsl_err("ERROR on binding to port %d (%d %d)\n",
1774 wsi = (struct libwebsocket *)malloc(sizeof(struct libwebsocket));
1776 lwsl_err("Out of mem\n");
1780 memset(wsi, 0, sizeof (struct libwebsocket));
1782 wsi->count_active_extensions = 0;
1783 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1785 insert_wsi_socket_into_fds(context, wsi);
1787 context->listen_service_modulo = LWS_LISTEN_SERVICE_MODULO;
1788 context->listen_service_count = 0;
1789 context->listen_service_fd = sockfd;
1791 listen(sockfd, LWS_SOMAXCONN);
1792 lwsl_notice(" Listening on port %d\n", port);
1797 * drop any root privs for this process
1798 * to listen on port < 1023 we would have needed root, but now we are
1799 * listening, we don't want the power for anything else
1805 lwsl_warn("setgid: %s\n", strerror(errno));
1808 lwsl_warn("setuid: %s\n", strerror(errno));
1811 /* set up our internal broadcast trigger sockets per-protocol */
1813 for (context->count_protocols = 0;
1814 protocols[context->count_protocols].callback;
1815 context->count_protocols++) {
1817 lwsl_parser(" Protocol: %s\n",
1818 protocols[context->count_protocols].name);
1820 protocols[context->count_protocols].owning_server = context;
1821 protocols[context->count_protocols].protocol_index =
1822 context->count_protocols;
1824 fd = socket(AF_INET, SOCK_STREAM, 0);
1826 lwsl_err("ERROR opening socket\n");
1830 /* allow us to restart even if old sockets in TIME_WAIT */
1831 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt,
1834 bzero((char *) &serv_addr, sizeof(serv_addr));
1835 serv_addr.sin_family = AF_INET;
1836 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1837 serv_addr.sin_port = 0; /* pick the port for us */
1839 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1841 lwsl_err("ERROR on binding to port %d (%d %d)\n",
1846 slen = sizeof cli_addr;
1847 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1849 lwsl_err("getsockname failed\n");
1852 protocols[context->count_protocols].broadcast_socket_port =
1853 ntohs(cli_addr.sin_port);
1856 lwsl_debug(" Protocol %s broadcast socket %d\n",
1857 protocols[context->count_protocols].name,
1858 ntohs(cli_addr.sin_port));
1860 /* dummy wsi per broadcast proxy socket */
1862 wsi = (struct libwebsocket *)malloc(sizeof(struct libwebsocket));
1864 lwsl_err("Out of mem\n");
1868 memset(wsi, 0, sizeof (struct libwebsocket));
1870 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1871 wsi->count_active_extensions = 0;
1872 /* note which protocol we are proxying */
1873 wsi->protocol_index_for_broadcast_proxy =
1874 context->count_protocols;
1876 insert_wsi_socket_into_fds(context, wsi);
1880 * give all extensions a chance to create any per-context
1881 * allocations they need
1884 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
1886 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
1889 while (extensions->callback) {
1890 lwsl_ext(" Extension: %s\n", extensions->name);
1891 extensions->callback(context, extensions, NULL,
1892 (enum libwebsocket_extension_callback_reasons)m,
1905 * libwebsockets_fork_service_loop() - Optional helper function forks off
1906 * a process for the websocket server loop.
1907 * You don't have to use this but if not, you
1908 * have to make sure you are calling
1909 * libwebsocket_service periodically to service
1910 * the websocket traffic
1911 * @context: server context returned by creation function
1915 libwebsockets_fork_service_loop(struct libwebsocket_context *context)
1918 struct sockaddr_in cli_addr;
1928 /* main process context */
1931 * set up the proxy sockets to allow broadcast from
1932 * service process context
1935 for (p = 0; p < context->count_protocols; p++) {
1936 fd = socket(AF_INET, SOCK_STREAM, 0);
1938 lwsl_err("Unable to create socket\n");
1941 cli_addr.sin_family = AF_INET;
1942 cli_addr.sin_port = htons(
1943 context->protocols[p].broadcast_socket_port);
1944 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1945 n = connect(fd, (struct sockaddr *)&cli_addr,
1948 lwsl_err("Unable to connect to "
1949 "broadcast socket %d, %s\n",
1950 n, strerror(errno));
1954 context->protocols[p].broadcast_socket_user_fd = fd;
1960 #ifdef HAVE_SYS_PRCTL_H
1961 /* we want a SIGHUP when our parent goes down */
1962 signal(SIGHUP, SIG_DFL);
1963 prctl(PR_SET_PDEATHSIG, SIGHUP);
1966 /* in this forked process, sit and service websocket connections */
1969 if (libwebsocket_service(context, 1000))
1971 //#ifndef HAVE_SYS_PRCTL_H
1973 * on systems without prctl() (i.e. anything but linux) we can notice that our
1974 * parent is dead if getppid() returns 1. FIXME apparently this is not true for
1975 * solaris, could remember ppid right after fork and wait for it to change.
1990 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
1992 * @wsi: pointer to struct websocket you want to know the protocol of
1995 * This is useful to get the protocol to broadcast back to from inside
1999 const struct libwebsocket_protocols *
2000 libwebsockets_get_protocol(struct libwebsocket *wsi)
2002 return wsi->protocol;
2006 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
2007 * connections of the given protocol.
2008 * @protocol: pointer to the protocol you will broadcast to all members of
2009 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
2010 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
2011 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
2012 * case you are calling this function from callback context.
2013 * @len: length of payload data in buf, starting from buf.
2015 * This function allows bulk sending of a packet to every connection using
2016 * the given protocol. It does not send the data directly; instead it calls
2017 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
2018 * wants to actually send the data for that connection, the callback itself
2019 * should call libwebsocket_write().
2021 * libwebsockets_broadcast() can be called from another fork context without
2022 * having to take any care about data visibility between the processes, it'll
2028 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
2029 unsigned char *buf, size_t len)
2031 struct libwebsocket_context *context = protocol->owning_server;
2033 struct libwebsocket *wsi;
2035 if (!protocol->broadcast_socket_user_fd) {
2037 * We are either running unforked / flat, or we are being
2038 * called from poll thread context
2039 * eg, from a callback. In that case don't use sockets for
2040 * broadcast IPC (since we can't open a socket connection to
2041 * a socket listening on our own thread) but directly do the
2044 * Locking is not needed because we are by definition being
2045 * called in the poll thread context and are serialized.
2048 for (n = 0; n < context->fds_count; n++) {
2050 wsi = context->lws_lookup[context->fds[n].fd];
2054 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
2058 * never broadcast to non-established connections
2060 if (wsi->state != WSI_STATE_ESTABLISHED)
2063 /* only broadcast to guys using
2064 * requested protocol
2066 if (wsi->protocol != protocol)
2069 user_callback_handle_rxflow(wsi->protocol->callback,
2071 LWS_CALLBACK_BROADCAST,
2080 * We're being called from a different process context than the server
2081 * loop. Instead of broadcasting directly, we send our
2082 * payload on a socket to do the IPC; the server process will serialize
2083 * the broadcast action in its main poll() loop.
2085 * There's one broadcast socket listening for each protocol supported
2086 * set up when the websocket server initializes
2089 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
2095 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
2101 libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
2107 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
2109 /* allocate the per-connection user memory (if any) */
2111 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
2112 wsi->user_space = malloc(
2113 wsi->protocol->per_session_data_size);
2114 if (wsi->user_space == NULL) {
2115 lwsl_err("Out of memory for conn user space\n");
2118 memset(wsi->user_space, 0,
2119 wsi->protocol->per_session_data_size);
2121 return wsi->user_space;
2125 * lws_confirm_legit_wsi: returns nonzero if the wsi looks bad
2127 * @wsi: struct libwebsocket to assess
2129 * Performs consistecy checks on what the wsi claims and what the
2130 * polling arrays hold. This'll catch a closed wsi still in use.
2131 * Don't try to use on the listen (nonconnection) wsi as it will
2132 * fail it. Otherwise 0 return == wsi seems consistent.
2135 int lws_confirm_legit_wsi(struct libwebsocket *wsi)
2137 struct libwebsocket_context *context;
2139 if (!(wsi && wsi->protocol && wsi->protocol->owning_server))
2142 context = wsi->protocol->owning_server;
2147 if (!wsi->position_in_fds_table)
2148 return 3; /* position in fds table looks bad */
2149 if (context->fds[wsi->position_in_fds_table].fd != wsi->sock)
2150 return 4; /* pollfd entry does not wait on our socket descriptor */
2151 if (context->lws_lookup[wsi->sock] != wsi)
2152 return 5; /* lookup table does not agree with wsi */
2157 static void lwsl_emit_stderr(int level, const char *line)
2163 gettimeofday(&tv, NULL);
2166 for (n = 0; n < LLL_COUNT; n++)
2167 if (level == (1 << n)) {
2168 sprintf(buf, "[%ld:%04d] %s: ", tv.tv_sec,
2169 (int)(tv.tv_usec / 100), log_level_names[n]);
2173 fprintf(stderr, "%s%s", buf, line);
2176 void lwsl_emit_syslog(int level, const char *line)
2178 int syslog_level = LOG_DEBUG;
2182 syslog_level = LOG_ERR;
2185 syslog_level = LOG_WARNING;
2188 syslog_level = LOG_NOTICE;
2191 syslog_level = LOG_INFO;
2194 syslog(syslog_level, line);
2197 void _lws_log(int filter, const char *format, ...)
2202 if (!(log_level & filter))
2205 va_start(ap, format);
2206 vsnprintf(buf, (sizeof buf), format, ap);
2207 buf[(sizeof buf) - 1] = '\0';
2210 lwsl_emit(filter, buf);
2214 * lws_set_log_level() - Set the logging bitfield
2215 * @level: OR together the LLL_ debug contexts you want output from
2216 * @log_emit_function: NULL to leave it as it is, or a user-supplied
2217 * function to perform log string emission instead of
2218 * the default stderr one.
2220 * log level defaults to "err" and "warn" contexts enabled only and
2221 * emission on stderr.
2224 void lws_set_log_level(int level, void (*log_emit_function)(int level, const char *line))
2227 if (log_emit_function)
2228 lwsl_emit = log_emit_function;