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"
52 static int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
53 static void lwsl_emit_stderr(int level, const char *line);
54 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
56 static const char *log_level_names[] = {
69 insert_wsi_socket_into_fds(struct libwebsocket_context *context, struct libwebsocket *wsi)
71 if (context->fds_count >= context->max_fds) {
72 lwsl_err("Reached limit of fds tracking (%d)\n", context->max_fds);
76 if (wsi->sock > context->max_fds) {
77 lwsl_err("Socket fd %d is beyond what we can index (%d)\n", wsi->sock, context->max_fds);
84 lwsl_info("insert_wsi_socket_into_fds: wsi=%p, sock=%d, fds pos=%d\n", wsi, wsi->sock, context->fds_count);
86 context->lws_lookup[wsi->sock] = wsi;
87 wsi->position_in_fds_table = context->fds_count;
88 context->fds[context->fds_count].fd = wsi->sock;
89 context->fds[context->fds_count].events = POLLIN;
90 context->fds[context->fds_count++].revents = 0;
92 /* external POLL support via protocol 0 */
93 context->protocols[0].callback(context, wsi,
94 LWS_CALLBACK_ADD_POLL_FD,
95 (void *)(long)wsi->sock, NULL, POLLIN);
101 remove_wsi_socket_from_fds(struct libwebsocket_context *context, struct libwebsocket *wsi)
105 if (!--context->fds_count)
108 if (wsi->sock > context->max_fds) {
109 lwsl_err("Socket fd %d is beyond what we can index (%d)\n", wsi->sock, context->max_fds);
113 lwsl_info("remove_wsi_socket_from_fds: wsi=%p, sock=%d, fds pos=%d\n", wsi, wsi->sock, wsi->position_in_fds_table);
115 m = wsi->position_in_fds_table; /* replace the contents for this */
117 /* have the last guy take up the vacant slot */
118 context->fds[m] = context->fds[context->fds_count]; /* vacant fds slot filled with end one */
119 /* end guy's fds_lookup entry remains unchanged (still same fd pointing to same wsi) */
120 /* end guy's "position in fds table" changed */
121 context->lws_lookup[context->fds[context->fds_count].fd]->position_in_fds_table = m;
122 /* deletion guy's lws_lookup entry needs nuking */
123 context->lws_lookup[wsi->sock] = NULL; /* no WSI for the socket of the wsi being removed*/
124 wsi->position_in_fds_table = -1; /* removed wsi has no position any more */
127 /* remove also from external POLL support via protocol 0 */
129 context->protocols[0].callback(context, wsi,
130 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
137 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
138 struct libwebsocket *wsi, enum lws_close_status reason)
142 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
143 LWS_SEND_BUFFER_POST_PADDING];
144 #ifndef LWS_NO_EXTENSIONS
147 struct lws_tokens eff_buf;
148 struct libwebsocket_extension *ext;
154 old_state = wsi->state;
156 if (old_state == WSI_STATE_DEAD_SOCKET)
159 wsi->close_reason = reason;
161 #ifndef LWS_NO_EXTENSIONS
163 * are his extensions okay with him closing? Eg he might be a mux
164 * parent and just his ch1 aspect is closing?
167 for (n = 0; n < wsi->count_active_extensions; n++) {
168 if (!wsi->active_extensions[n]->callback)
171 m = wsi->active_extensions[n]->callback(context,
172 wsi->active_extensions[n], wsi,
173 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
174 wsi->active_extensions_user[n], NULL, 0);
177 * if somebody vetoed actually closing him at this time....
178 * up to the extension to track the attempted close, let's
183 lwsl_ext("extension vetoed close\n");
189 * flush any tx pending from extensions, since we may send close packet
190 * if there are problems with send, just nuke the connection
196 /* default to nobody has more to spill */
199 eff_buf.token = NULL;
200 eff_buf.token_len = 0;
202 /* show every extension the new incoming data */
204 for (n = 0; n < wsi->count_active_extensions; n++) {
205 m = wsi->active_extensions[n]->callback(
206 wsi->protocol->owning_server,
207 wsi->active_extensions[n], wsi,
208 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
209 wsi->active_extensions_user[n], &eff_buf, 0);
211 lwsl_ext("Extension reports fatal error\n");
212 goto just_kill_connection;
216 * at least one extension told us he has more
217 * to spill, so we will go around again after
222 /* assuming they left us something to send, send it */
224 if (eff_buf.token_len)
225 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
226 eff_buf.token_len)) {
227 lwsl_debug("close: sending final extension spill had problems\n");
228 goto just_kill_connection;
234 * signal we are closing, libsocket_write will
235 * add any necessary version-specific stuff. If the write fails,
236 * no worries we are closing anyway. If we didn't initiate this
237 * close, then our state has been changed to
238 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
240 * Likewise if it's a second call to close this connection after we
241 * sent the close indication to the peer already, we are in state
242 * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
245 if (old_state == WSI_STATE_ESTABLISHED &&
246 reason != LWS_CLOSE_STATUS_NOSTATUS) {
248 lwsl_debug("sending close indication...\n");
250 n = libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING],
254 * we have sent a nice protocol level indication we
255 * now wish to close, we should not send anything more
258 wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
260 /* and we should wait for a reply for a bit out of politeness */
262 libwebsocket_set_timeout(wsi,
263 PENDING_TIMEOUT_CLOSE_ACK, 1);
265 lwsl_debug("sent close indication, awaiting ack\n");
270 lwsl_info("close: sending the close packet failed, hanging up\n");
272 /* else, the send failed and we should just hang up */
275 #ifndef LWS_NO_EXTENSIONS
276 just_kill_connection:
279 lwsl_debug("libwebsocket_close_and_free_session: just_kill_connection\n");
282 * we won't be servicing or receiving anything further from this guy
283 * delete socket from the internal poll list if still present
286 remove_wsi_socket_from_fds(context, wsi);
288 wsi->state = WSI_STATE_DEAD_SOCKET;
290 /* tell the user it's all over for this guy */
292 if (wsi->protocol && wsi->protocol->callback &&
293 ((old_state == WSI_STATE_ESTABLISHED) ||
294 (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
295 (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
296 lwsl_debug("calling back CLOSED\n");
297 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
298 wsi->user_space, NULL, 0);
300 lwsl_debug("not calling back closed, old_state=%d\n", old_state);
302 #ifndef LWS_NO_EXTENSIONS
303 /* deallocate any active extension contexts */
305 for (n = 0; n < wsi->count_active_extensions; n++) {
306 if (!wsi->active_extensions[n]->callback)
309 wsi->active_extensions[n]->callback(context,
310 wsi->active_extensions[n], wsi,
311 LWS_EXT_CALLBACK_DESTROY,
312 wsi->active_extensions_user[n], NULL, 0);
314 free(wsi->active_extensions_user[n]);
318 * inform all extensions in case they tracked this guy out of band
319 * even though not active on him specifically
322 ext = context->extensions;
323 while (ext && ext->callback) {
324 ext->callback(context, ext, wsi,
325 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
331 /* free up his parsing allocations */
333 for (n = 0; n < WSI_TOKEN_COUNT; n++)
334 if (wsi->utf8_token[n].token)
335 free(wsi->utf8_token[n].token);
336 #ifndef LWS_NO_CLIENT
338 free(wsi->c_address);
340 if (wsi->rxflow_buffer)
341 free(wsi->rxflow_buffer);
343 /* lwsl_info("closing fd=%d\n", wsi->sock); */
345 #ifdef LWS_OPENSSL_SUPPORT
347 n = SSL_get_fd(wsi->ssl);
348 SSL_shutdown(wsi->ssl);
354 n = shutdown(wsi->sock, SHUT_RDWR);
356 lwsl_debug("closing: shutdown returned %d\n", errno);
358 n = compatible_close(wsi->sock);
360 lwsl_debug("closing: close returned %d\n", errno);
362 #ifdef LWS_OPENSSL_SUPPORT
365 if (wsi->protocol && wsi->protocol->per_session_data_size && wsi->user_space) /* user code may own */
366 free(wsi->user_space);
372 * libwebsockets_hangup_on_client() - Server calls to terminate client
374 * @context: libwebsockets context
375 * @fd: Connection socket descriptor
379 libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
381 struct libwebsocket *wsi = context->lws_lookup[fd];
384 libwebsocket_close_and_free_session(context,
385 wsi, LWS_CLOSE_STATUS_NOSTATUS);
392 * libwebsockets_get_peer_addresses() - Get client address information
393 * @fd: Connection socket descriptor
394 * @name: Buffer to take client address name
395 * @name_len: Length of client address name buffer
396 * @rip: Buffer to take client address IP qotted quad
397 * @rip_len: Length of client address IP buffer
399 * This function fills in @name and @rip with the name and IP of
400 * the client connected with socket descriptor @fd. Names may be
401 * truncated if there is not enough room. If either cannot be
402 * determined, they will be returned as valid zero-length strings.
406 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
407 char *rip, int rip_len)
410 struct sockaddr_in sin;
411 struct hostent *host;
412 struct hostent *host1;
417 struct sockaddr_un *un;
424 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
425 perror("getpeername");
429 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
432 perror("gethostbyaddr");
436 strncpy(name, host->h_name, name_len);
437 name[name_len - 1] = '\0';
439 host1 = gethostbyname(host->h_name);
442 p = (unsigned char *)host1;
445 p = (unsigned char *)host1->h_addr_list[n++];
448 if ((host1->h_addrtype != AF_INET)
450 && (host1->h_addrtype != AF_LOCAL)
455 if (host1->h_addrtype == AF_INET)
456 sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
459 un = (struct sockaddr_un *)p;
460 strncpy(ip, un->sun_path, sizeof(ip) - 1);
461 ip[sizeof(ip) - 1] = '\0';
465 strncpy(rip, ip, rip_len);
466 rip[rip_len - 1] = '\0';
470 int libwebsockets_get_random(struct libwebsocket_context *context,
474 char *p = (char *)buf;
477 for (n = 0; n < len; n++)
478 p[n] = (unsigned char)rand();
480 n = read(context->fd_random, p, len);
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)
510 #ifndef LWS_NO_EXTENSIONS
511 struct lws_tokens eff_buf;
516 for (n = 0; n < wsi->count_active_extensions; n++) {
517 if (!wsi->active_extensions[n]->callback)
520 m = wsi->active_extensions[n]->callback(context,
521 wsi->active_extensions[n], wsi,
522 LWS_EXT_CALLBACK_IS_WRITEABLE,
523 wsi->active_extensions_user[n], NULL, 0);
531 if (!wsi->extension_data_pending || handled == 2)
535 * check in on the active extensions, see if they
536 * had pending stuff to spill... they need to get the
537 * first look-in otherwise sequence will be disordered
539 * NULL, zero-length eff_buf means just spill pending
545 /* default to nobody has more to spill */
548 eff_buf.token = NULL;
549 eff_buf.token_len = 0;
551 /* give every extension a chance to spill */
553 for (n = 0; n < wsi->count_active_extensions; n++) {
554 m = wsi->active_extensions[n]->callback(
555 wsi->protocol->owning_server,
556 wsi->active_extensions[n], wsi,
557 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
558 wsi->active_extensions_user[n], &eff_buf, 0);
560 lwsl_err("ext reports fatal error\n");
565 * at least one extension told us he has more
566 * to spill, so we will go around again after
571 /* assuming they gave us something to send, send it */
573 if (eff_buf.token_len) {
574 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
580 /* no extension has more to spill */
586 * There's more to spill from an extension, but we just sent
587 * something... did that leave the pipe choked?
590 if (!lws_send_pipe_choked(wsi))
591 /* no we could add more */
594 lwsl_info("choked in POLLOUT service\n");
597 * Yes, he's choked. Leave the POLLOUT masked on so we will
598 * come back here when he is unchoked. Don't call the user
599 * callback to enforce ordering of spilling, he'll get called
600 * when we come back here and there's nothing more to spill.
606 wsi->extension_data_pending = 0;
613 pollfd->events &= ~POLLOUT;
615 /* external POLL support via protocol 0 */
616 context->protocols[0].callback(context, wsi,
617 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
618 (void *)(long)wsi->sock, NULL, POLLOUT);
620 #ifndef LWS_NO_EXTENSIONS
624 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
625 n = LWS_CALLBACK_CLIENT_WRITEABLE;
627 n = LWS_CALLBACK_SERVER_WRITEABLE;
629 user_callback_handle_rxflow(wsi->protocol->callback, context,
630 wsi, (enum libwebsocket_callback_reasons) n, wsi->user_space, NULL, 0);
638 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
639 struct libwebsocket *wsi, unsigned int sec)
641 #ifndef LWS_NO_EXTENSIONS
645 * if extensions want in on it (eg, we are a mux parent)
646 * give them a chance to service child timeouts
649 for (n = 0; n < wsi->count_active_extensions; n++)
650 wsi->active_extensions[n]->callback(
651 context, wsi->active_extensions[n],
652 wsi, LWS_EXT_CALLBACK_1HZ,
653 wsi->active_extensions_user[n], NULL, sec);
656 if (!wsi->pending_timeout)
660 * if we went beyond the allowed time, kill the
664 if (sec > wsi->pending_timeout_limit) {
665 lwsl_info("TIMEDOUT WAITING\n");
666 libwebsocket_close_and_free_session(context,
667 wsi, LWS_CLOSE_STATUS_NOSTATUS);
672 * libwebsocket_service_fd() - Service polled socket with something waiting
673 * @context: Websocket context
674 * @pollfd: The pollfd entry describing the socket fd and which events
677 * This function closes any active connections and then frees the
678 * context. After calling this, any further use of the context is
683 libwebsocket_service_fd(struct libwebsocket_context *context,
684 struct pollfd *pollfd)
686 struct libwebsocket *wsi;
687 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
688 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
692 #ifndef LWS_NO_EXTENSIONS
695 struct lws_tokens eff_buf;
696 #ifndef LWS_NO_CLIENT
697 extern int lws_client_socket_service(struct libwebsocket_context *context, struct libwebsocket *wsi, struct pollfd *pollfd);
699 #ifndef LWS_NO_SERVER
700 extern int lws_server_socket_service(struct libwebsocket_context *context, struct libwebsocket *wsi, struct pollfd *pollfd);
703 * you can call us with pollfd = NULL to just allow the once-per-second
704 * global timeout checks; if less than a second since the last check
705 * it returns immediately then.
708 gettimeofday(&tv, NULL);
710 if (context->last_timeout_check_s != tv.tv_sec) {
711 context->last_timeout_check_s = tv.tv_sec;
713 /* if our parent went down, don't linger around */
714 if (context->started_with_parent && kill(context->started_with_parent, 0) < 0)
715 kill(getpid(), SIGTERM);
717 /* global timeout check once per second */
719 for (n = 0; n < context->fds_count; n++) {
720 struct libwebsocket *new_wsi = context->lws_lookup[context->fds[n].fd];
723 libwebsocket_service_timeout_check(context,
728 /* just here for timeout management? */
733 /* no, here to service a socket descriptor */
736 * deal with listen service piggybacking
737 * every listen_service_modulo services of other fds, we
738 * sneak one in to service the listen socket if there's anything waiting
740 * To handle connection storms, as found in ab, if we previously saw a
741 * pending connection here, it causes us to check again next time.
744 if (context->listen_service_fd && pollfd->fd != context->listen_service_fd) {
745 context->listen_service_count++;
746 if (context->listen_service_extraseen ||
747 context->listen_service_count == context->listen_service_modulo) {
748 context->listen_service_count = 0;
750 if (context->listen_service_extraseen > 5)
753 /* even with extpoll, we prepared this internal fds for listen */
754 n = poll(&context->fds[0], 1, 0);
755 if (n > 0) { /* there's a connection waiting for us */
756 libwebsocket_service_fd(context, &context->fds[0]);
757 context->listen_service_extraseen++;
759 if (context->listen_service_extraseen)
760 context->listen_service_extraseen--;
768 /* okay, what we came here to do... */
770 wsi = context->lws_lookup[pollfd->fd];
773 lwsl_err("unexpected NULL wsi fd=%d fds_count=%d\n", pollfd->fd, context->fds_count);
779 #ifndef LWS_NO_SERVER
780 case LWS_CONNMODE_HTTP_SERVING:
781 case LWS_CONNMODE_SERVER_LISTENER:
782 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
783 case LWS_CONNMODE_BROADCAST_PROXY:
784 return lws_server_socket_service(context, wsi, pollfd);
787 case LWS_CONNMODE_WS_SERVING:
788 case LWS_CONNMODE_WS_CLIENT:
790 /* handle session socket closed */
792 if (pollfd->revents & (POLLERR | POLLHUP)) {
794 lwsl_debug("Session Socket %p (fd=%d) dead\n",
795 (void *)wsi, pollfd->fd);
797 libwebsocket_close_and_free_session(context, wsi,
798 LWS_CLOSE_STATUS_NOSTATUS);
802 /* the guy requested a callback when it was OK to write */
804 if ((pollfd->revents & POLLOUT) &&
805 wsi->state == WSI_STATE_ESTABLISHED)
806 if (lws_handle_POLLOUT_event(context, wsi,
808 libwebsocket_close_and_free_session(
809 context, wsi, LWS_CLOSE_STATUS_NORMAL);
814 /* any incoming data ready? */
816 if (!(pollfd->revents & POLLIN))
819 #ifdef LWS_OPENSSL_SUPPORT
822 eff_buf.token_len = SSL_read(wsi->ssl, buf, sizeof buf);
826 recv(pollfd->fd, buf, sizeof buf, 0);
828 if (eff_buf.token_len < 0) {
829 lwsl_debug("Socket read returned %d\n",
831 if (errno != EINTR && errno != EAGAIN)
832 libwebsocket_close_and_free_session(context,
833 wsi, LWS_CLOSE_STATUS_NOSTATUS);
836 if (!eff_buf.token_len) {
837 libwebsocket_close_and_free_session(context, wsi,
838 LWS_CLOSE_STATUS_NOSTATUS);
843 * give any active extensions a chance to munge the buffer
844 * before parse. We pass in a pointer to an lws_tokens struct
845 * prepared with the default buffer and content length that's in
846 * there. Rather than rewrite the default buffer, extensions
847 * that expect to grow the buffer can adapt .token to
848 * point to their own per-connection buffer in the extension
849 * user allocation. By default with no extensions or no
850 * extension callback handling, just the normal input buffer is
851 * used then so it is efficient.
854 eff_buf.token = (char *)buf;
855 #ifndef LWS_NO_EXTENSIONS
861 for (n = 0; n < wsi->count_active_extensions; n++) {
862 m = wsi->active_extensions[n]->callback(context,
863 wsi->active_extensions[n], wsi,
864 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
865 wsi->active_extensions_user[n],
869 "Extension reports fatal error\n");
870 libwebsocket_close_and_free_session(
872 LWS_CLOSE_STATUS_NOSTATUS);
879 /* service incoming data */
881 if (eff_buf.token_len) {
882 n = libwebsocket_read(context, wsi,
883 (unsigned char *)eff_buf.token,
889 #ifndef LWS_NO_EXTENSIONS
890 eff_buf.token = NULL;
891 eff_buf.token_len = 0;
895 #ifdef LWS_OPENSSL_SUPPORT
896 if (wsi->ssl && SSL_pending(wsi->ssl))
905 return lws_client_socket_service(context, wsi, pollfd);
914 * libwebsocket_context_destroy() - Destroy the websocket context
915 * @context: Websocket context
917 * This function closes any active connections and then frees the
918 * context. After calling this, any further use of the context is
922 libwebsocket_context_destroy(struct libwebsocket_context *context)
924 #ifndef LWS_NO_EXTENSIONS
927 struct libwebsocket_extension *ext;
929 for (n = 0; n < context->fds_count; n++) {
930 struct libwebsocket *wsi = context->lws_lookup[context->fds[n].fd];
931 libwebsocket_close_and_free_session(context,
932 wsi, LWS_CLOSE_STATUS_GOINGAWAY);
936 * give all extensions a chance to clean up any per-context
937 * allocations they might have made
940 ext = context->extensions;
941 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
942 if (context->listen_port)
943 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
944 while (ext && ext->callback) {
945 ext->callback(context, ext, NULL, (enum libwebsocket_extension_callback_reasons)m, NULL, NULL, 0);
952 close(context->fd_random);
955 #ifdef LWS_OPENSSL_SUPPORT
956 if (context->ssl_ctx)
957 SSL_CTX_free(context->ssl_ctx);
958 if (context->ssl_client_ctx)
959 SSL_CTX_free(context->ssl_client_ctx);
970 libwebsocket_context_user(struct libwebsocket_context *context)
972 return context->user_space;
976 * libwebsocket_service() - Service any pending websocket activity
977 * @context: Websocket context
978 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
979 * service otherwise block and service immediately, returning
980 * after the timeout if nothing needed service.
982 * This function deals with any pending websocket traffic, for three
983 * kinds of event. It handles these events on both server and client
984 * types of connection the same.
986 * 1) Accept new connections to our context's server
988 * 2) Perform pending broadcast writes initiated from other forked
989 * processes (effectively serializing asynchronous broadcasts)
991 * 3) Call the receive callback for incoming frame data received by
992 * server or client connections.
994 * You need to call this service function periodically to all the above
995 * functions to happen; if your application is single-threaded you can
996 * just call it in your main event loop.
998 * Alternatively you can fork a new process that asynchronously handles
999 * calling this service in a loop. In that case you are happy if this
1000 * call blocks your thread until it needs to take care of something and
1001 * would call it with a large nonzero timeout. Your loop then takes no
1002 * CPU while there is nothing happening.
1004 * If you are calling it in a single-threaded app, you don't want it to
1005 * wait around blocking other things in your loop from happening, so you
1006 * would call it with a timeout_ms of 0, so it returns immediately if
1007 * nothing is pending, or as soon as it services whatever was pending.
1012 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
1016 /* stay dead once we are dead */
1018 if (context == NULL)
1021 /* wait for something to need service */
1023 n = poll(context->fds, context->fds_count, timeout_ms);
1024 if (n == 0) /* poll timeout */
1030 /* any socket with events to service? */
1032 for (n = 0; n < context->fds_count; n++)
1033 if (context->fds[n].revents)
1034 if (libwebsocket_service_fd(context,
1035 &context->fds[n]) < 0)
1040 #ifndef LWS_NO_EXTENSIONS
1042 lws_any_extension_handled(struct libwebsocket_context *context,
1043 struct libwebsocket *wsi,
1044 enum libwebsocket_extension_callback_reasons r,
1045 void *v, size_t len)
1050 /* maybe an extension will take care of it for us */
1052 for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
1053 if (!wsi->active_extensions[n]->callback)
1056 handled |= wsi->active_extensions[n]->callback(context,
1057 wsi->active_extensions[n], wsi,
1058 r, wsi->active_extensions_user[n], v, len);
1066 lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
1067 struct libwebsocket_extension *ext)
1074 while (n < wsi->count_active_extensions) {
1075 if (wsi->active_extensions[n] != ext) {
1079 return wsi->active_extensions_user[n];
1087 * libwebsocket_callback_on_writable() - Request a callback when this socket
1088 * becomes able to be written to without
1091 * @context: libwebsockets context
1092 * @wsi: Websocket connection instance to get callback for
1096 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
1097 struct libwebsocket *wsi)
1099 #ifndef LWS_NO_EXTENSIONS
1103 /* maybe an extension will take care of it for us */
1105 for (n = 0; n < wsi->count_active_extensions; n++) {
1106 if (!wsi->active_extensions[n]->callback)
1109 handled |= wsi->active_extensions[n]->callback(context,
1110 wsi->active_extensions[n], wsi,
1111 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
1112 wsi->active_extensions_user[n], NULL, 0);
1118 if (wsi->position_in_fds_table < 0) {
1119 lwsl_err("libwebsocket_callback_on_writable: "
1120 "failed to find socket %d\n", wsi->sock);
1124 context->fds[wsi->position_in_fds_table].events |= POLLOUT;
1126 /* external POLL support via protocol 0 */
1127 context->protocols[0].callback(context, wsi,
1128 LWS_CALLBACK_SET_MODE_POLL_FD,
1129 (void *)(long)wsi->sock, NULL, POLLOUT);
1135 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1136 * all connections using the given protocol when it
1137 * becomes possible to write to each socket without
1140 * @protocol: Protocol whose connections will get callbacks
1144 libwebsocket_callback_on_writable_all_protocol(
1145 const struct libwebsocket_protocols *protocol)
1147 struct libwebsocket_context *context = protocol->owning_server;
1149 struct libwebsocket *wsi;
1151 for (n = 0; n < context->fds_count; n++) {
1152 wsi = context->lws_lookup[context->fds[n].fd];
1155 if (wsi->protocol == protocol)
1156 libwebsocket_callback_on_writable(context, wsi);
1163 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1165 * You will not need this unless you are doing something special
1167 * @wsi: Websocket connection instance
1168 * @reason: timeout reason
1169 * @secs: how many seconds
1173 libwebsocket_set_timeout(struct libwebsocket *wsi,
1174 enum pending_timeout reason, int secs)
1178 gettimeofday(&tv, NULL);
1180 wsi->pending_timeout_limit = tv.tv_sec + secs;
1181 wsi->pending_timeout = reason;
1186 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1188 * You will not need this unless you are doing something special
1190 * @wsi: Websocket connection instance
1194 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1199 #ifdef LWS_NO_SERVER
1201 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1207 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1209 struct libwebsocket_context *context = wsi->protocol->owning_server;
1212 if (!(wsi->rxflow_change_to & 2))
1215 wsi->rxflow_change_to &= ~2;
1217 lwsl_info("rxflow: wsi %p change_to %d\n", wsi, wsi->rxflow_change_to);
1219 /* if we're letting it come again, did we interrupt anything? */
1220 if ((wsi->rxflow_change_to & 1) && wsi->rxflow_buffer) {
1221 n = libwebsocket_interpret_incoming_packet(wsi, NULL, 0);
1223 libwebsocket_close_and_free_session(context, wsi, LWS_CLOSE_STATUS_NOSTATUS);
1227 /* oh he stuck again, do nothing */
1231 if (wsi->rxflow_change_to & 1)
1232 context->fds[wsi->position_in_fds_table].events |= POLLIN;
1234 context->fds[wsi->position_in_fds_table].events &= ~POLLIN;
1236 if (wsi->rxflow_change_to & 1)
1237 /* external POLL support via protocol 0 */
1238 context->protocols[0].callback(context, wsi,
1239 LWS_CALLBACK_SET_MODE_POLL_FD,
1240 (void *)(long)wsi->sock, NULL, POLLIN);
1242 /* external POLL support via protocol 0 */
1243 context->protocols[0].callback(context, wsi,
1244 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1245 (void *)(long)wsi->sock, NULL, POLLIN);
1252 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1253 * receieved packets.
1255 * If the output side of a server process becomes choked, this allows flow
1256 * control for the input side.
1258 * @wsi: Websocket connection instance to get callback for
1259 * @enable: 0 = disable read servicing for this connection, 1 = enable
1263 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1265 wsi->rxflow_change_to = 2 | !!enable;
1272 * libwebsocket_canonical_hostname() - returns this host's hostname
1274 * This is typically used by client code to fill in the host parameter
1275 * when making a client connection. You can only call it after the context
1278 * @context: Websocket context
1283 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
1285 return (const char *)context->canonical_hostname;
1289 static void sigpipe_handler(int x)
1293 #ifdef LWS_OPENSSL_SUPPORT
1295 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1300 struct libwebsocket_context *context;
1302 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1303 SSL_get_ex_data_X509_STORE_CTX_idx());
1306 * !!! nasty openssl requires the index to come as a library-scope
1309 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
1311 n = context->protocols[0].callback(NULL, NULL,
1312 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1313 x509_ctx, ssl, preverify_ok);
1315 /* convert return code from 0 = OK to 1 = OK */
1326 int user_callback_handle_rxflow(callback_function callback_function,
1327 struct libwebsocket_context * context,
1328 struct libwebsocket *wsi,
1329 enum libwebsocket_callback_reasons reason, void *user,
1330 void *in, size_t len)
1334 n = callback_function(context, wsi, reason, user, in, len);
1338 _libwebsocket_rx_flow_control(wsi);
1345 * libwebsocket_create_context() - Create the websocket handler
1346 * @port: Port to listen on... you can use 0 to suppress listening on
1347 * any port, that's what you want if you are not running a
1348 * websocket server at all but just using it as a client
1349 * @interf: NULL to bind the listen socket to all interfaces, or the
1350 * interface name, eg, "eth2"
1351 * @protocols: Array of structures listing supported protocols and a protocol-
1352 * specific callback for each one. The list is ended with an
1353 * entry that has a NULL callback pointer.
1354 * It's not const because we write the owning_server member
1355 * @extensions: NULL or array of libwebsocket_extension structs listing the
1356 * extensions this context supports. If you configured with
1357 * --without-extensions, you should give NULL here.
1358 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
1359 * to listen using SSL, set to the filepath to fetch the
1360 * server cert from, otherwise NULL for unencrypted
1361 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
1363 * @ssl_ca_filepath: CA certificate filepath or NULL
1364 * @gid: group id to change to after setting listen socket, or -1.
1365 * @uid: user id to change to after setting listen socket, or -1.
1366 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
1367 * @user: optional user pointer that can be recovered via the context
1368 * pointer using libwebsocket_context_user
1370 * This function creates the listening socket and takes care
1371 * of all initialization in one step.
1373 * After initialization, it returns a struct libwebsocket_context * that
1374 * represents this server. After calling, user code needs to take care
1375 * of calling libwebsocket_service() with the context pointer to get the
1376 * server's sockets serviced. This can be done in the same process context
1377 * or a forked process, or another thread,
1379 * The protocol callback functions are called for a handful of events
1380 * including http requests coming in, websocket connections becoming
1381 * established, and data arriving; it's also called periodically to allow
1382 * async transmission.
1384 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1385 * at that time websocket protocol has not been negotiated. Other
1386 * protocols after the first one never see any HTTP callack activity.
1388 * The server created is a simple http server by default; part of the
1389 * websocket standard is upgrading this http connection to a websocket one.
1391 * This allows the same server to provide files like scripts and favicon /
1392 * images or whatever over http and dynamic data over websockets all in
1393 * one place; they're all handled in the user callback.
1396 struct libwebsocket_context *
1397 libwebsocket_create_context(int port, const char *interf,
1398 struct libwebsocket_protocols *protocols,
1399 struct libwebsocket_extension *extensions,
1400 const char *ssl_cert_filepath,
1401 const char *ssl_private_key_filepath,
1402 const char *ssl_ca_filepath,
1403 int gid, int uid, unsigned int options,
1407 struct sockaddr_in serv_addr;
1409 struct libwebsocket_context *context = NULL;
1412 struct sockaddr_in cli_addr;
1416 struct libwebsocket *wsi;
1417 #ifndef LWS_NO_EXTENSIONS
1421 #ifdef LWS_OPENSSL_SUPPORT
1423 char ssl_err_buf[512];
1426 lwsl_notice("Initial logging level %d\n", log_level);
1427 lwsl_info(" LWS_MAX_HEADER_NAME_LENGTH: %u\n", LWS_MAX_HEADER_NAME_LENGTH);
1428 lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN);
1429 lwsl_info(" LWS_INITIAL_HDR_ALLOC: %u\n", LWS_INITIAL_HDR_ALLOC);
1430 lwsl_info(" LWS_ADDITIONAL_HDR_ALLOC: %u\n", LWS_ADDITIONAL_HDR_ALLOC);
1431 lwsl_info(" MAX_USER_RX_BUFFER: %u\n", MAX_USER_RX_BUFFER);
1432 lwsl_info(" MAX_BROADCAST_PAYLOAD: %u\n", MAX_BROADCAST_PAYLOAD);
1433 lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS);
1434 #ifndef LWS_NO_EXTENSIONS
1435 lwsl_info(" LWS_MAX_EXTENSIONS_ACTIVE: %u\n", LWS_MAX_EXTENSIONS_ACTIVE);
1437 lwsl_notice(" Configured without extension support\n");
1439 lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED);
1440 lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT);
1441 lwsl_info(" CIPHERS_LIST_STRING: '%s'\n", CIPHERS_LIST_STRING);
1442 lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
1443 lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER);
1447 WORD wVersionRequested;
1452 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1453 wVersionRequested = MAKEWORD(2, 2);
1455 err = WSAStartup(wVersionRequested, &wsaData);
1457 /* Tell the user that we could not find a usable */
1459 lwsl_err("WSAStartup failed with error: %d\n", err);
1463 /* default to a poll() made out of select() */
1464 poll = emulated_poll;
1466 /* if windows socket lib available, use his WSAPoll */
1467 wsdll = GetModuleHandle(_T("Ws2_32.dll"));
1469 poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
1473 context = (struct libwebsocket_context *) malloc(sizeof(struct libwebsocket_context));
1475 lwsl_err("No memory for websocket context\n");
1478 #ifndef NO_DAEMONIZE
1479 extern int pid_daemon;
1480 context->started_with_parent = pid_daemon;
1481 lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
1484 context->protocols = protocols;
1485 context->listen_port = port;
1486 context->http_proxy_port = 0;
1487 context->http_proxy_address[0] = '\0';
1488 context->options = options;
1489 /* to reduce this allocation, */
1490 context->max_fds = getdtablesize();
1491 lwsl_notice(" max fd tracked: %u\n", context->max_fds);
1492 lwsl_notice(" static allocation: %u bytes\n",
1493 (sizeof(struct pollfd) * context->max_fds) +
1494 (sizeof(struct libwebsocket *) * context->max_fds));
1496 context->fds = (struct pollfd *)malloc(sizeof(struct pollfd) * context->max_fds);
1497 if (context->fds == NULL) {
1498 lwsl_err("Unable to allocate fds array for %d connections\n", context->max_fds);
1502 context->lws_lookup = (struct libwebsocket **)malloc(sizeof(struct libwebsocket *) * context->max_fds);
1503 if (context->lws_lookup == NULL) {
1504 lwsl_err("Unable to allocate lws_lookup array for %d connections\n", context->max_fds);
1510 context->fds_count = 0;
1511 #ifndef LWS_NO_EXTENSIONS
1512 context->extensions = extensions;
1514 context->last_timeout_check_s = 0;
1515 context->user_space = user;
1518 context->fd_random = 0;
1520 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1521 if (context->fd_random < 0) {
1523 lwsl_err("Unable to open random device %s %d\n",
1524 SYSTEM_RANDOM_FILEPATH, context->fd_random);
1529 #ifdef LWS_OPENSSL_SUPPORT
1530 context->use_ssl = 0;
1531 context->ssl_ctx = NULL;
1532 context->ssl_client_ctx = NULL;
1533 openssl_websocket_private_data_index = 0;
1536 strcpy(context->canonical_hostname, "unknown");
1538 #ifndef LWS_NO_SERVER
1539 if (!(options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)) {
1541 char hostname[1024] = "";
1543 /* find canonical hostname */
1545 hostname[(sizeof hostname) - 1] = '\0';
1546 memset(&sa, 0, sizeof(sa));
1547 sa.sa_family = AF_INET;
1548 sa.sa_data[(sizeof sa.sa_data) - 1] = '\0';
1549 gethostname(hostname, (sizeof hostname) - 1);
1553 if (strlen(hostname) < sizeof(sa.sa_data) - 1) {
1554 strcpy(sa.sa_data, hostname);
1555 // lwsl_debug("my host name is %s\n", sa.sa_data);
1556 n = getnameinfo(&sa, sizeof(sa), hostname,
1557 (sizeof hostname) - 1, NULL, 0, 0);
1561 strncpy(context->canonical_hostname, hostname,
1562 sizeof context->canonical_hostname - 1);
1563 context->canonical_hostname[
1564 sizeof context->canonical_hostname - 1] = '\0';
1566 strncpy(context->canonical_hostname, hostname,
1567 sizeof context->canonical_hostname - 1);
1569 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
1573 /* split the proxy ads:port if given */
1575 p = getenv("http_proxy");
1577 strncpy(context->http_proxy_address, p,
1578 sizeof context->http_proxy_address - 1);
1579 context->http_proxy_address[
1580 sizeof context->http_proxy_address - 1] = '\0';
1582 p = strchr(context->http_proxy_address, ':');
1584 lwsl_err("http_proxy needs to be ads:port\n");
1588 context->http_proxy_port = atoi(p + 1);
1590 lwsl_notice(" Proxy %s:%u\n",
1591 context->http_proxy_address,
1592 context->http_proxy_port);
1595 #ifndef LWS_NO_SERVER
1598 #ifdef LWS_OPENSSL_SUPPORT
1599 context->use_ssl = ssl_cert_filepath != NULL &&
1600 ssl_private_key_filepath != NULL;
1601 if (context->use_ssl)
1602 lwsl_notice(" Compiled with SSL support, using it\n");
1604 lwsl_notice(" Compiled with SSL support, not using it\n");
1607 if (ssl_cert_filepath != NULL &&
1608 ssl_private_key_filepath != NULL) {
1609 lwsl_notice(" Not compiled for OpenSSl support!\n");
1612 lwsl_notice(" Compiled without SSL support, "
1613 "serving unencrypted\n");
1616 lwsl_notice(" per-connection allocation: %u + headers\n", sizeof(struct libwebsocket));
1620 /* ignore SIGPIPE */
1623 signal(SIGPIPE, sigpipe_handler);
1627 #ifdef LWS_OPENSSL_SUPPORT
1629 /* basic openssl init */
1633 OpenSSL_add_all_algorithms();
1634 SSL_load_error_strings();
1636 openssl_websocket_private_data_index =
1637 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1640 * Firefox insists on SSLv23 not SSLv3
1641 * Konq disables SSLv2 by default now, SSLv23 works
1644 method = (SSL_METHOD *)SSLv23_server_method();
1646 lwsl_err("problem creating ssl method: %s\n",
1647 ERR_error_string(ERR_get_error(), ssl_err_buf));
1650 context->ssl_ctx = SSL_CTX_new(method); /* create context */
1651 if (!context->ssl_ctx) {
1652 lwsl_err("problem creating ssl context: %s\n",
1653 ERR_error_string(ERR_get_error(), ssl_err_buf));
1657 #ifdef SSL_OP_NO_COMPRESSION
1658 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
1660 SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
1661 SSL_CTX_set_cipher_list(context->ssl_ctx, CIPHERS_LIST_STRING);
1663 #ifndef LWS_NO_CLIENT
1665 /* client context */
1667 if (port == CONTEXT_PORT_NO_LISTEN) {
1668 method = (SSL_METHOD *)SSLv23_client_method();
1670 lwsl_err("problem creating ssl method: %s\n",
1671 ERR_error_string(ERR_get_error(), ssl_err_buf));
1674 /* create context */
1675 context->ssl_client_ctx = SSL_CTX_new(method);
1676 if (!context->ssl_client_ctx) {
1677 lwsl_err("problem creating ssl context: %s\n",
1678 ERR_error_string(ERR_get_error(), ssl_err_buf));
1682 #ifdef SSL_OP_NO_COMPRESSION
1683 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_NO_COMPRESSION);
1685 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
1686 SSL_CTX_set_cipher_list(context->ssl_client_ctx, CIPHERS_LIST_STRING);
1688 /* openssl init for cert verification (for client sockets) */
1689 if (!ssl_ca_filepath) {
1690 if (!SSL_CTX_load_verify_locations(
1691 context->ssl_client_ctx, NULL,
1692 LWS_OPENSSL_CLIENT_CERTS))
1694 "Unable to load SSL Client certs from %s "
1695 "(set by --with-client-cert-dir= in configure) -- "
1696 " client ssl isn't going to work",
1697 LWS_OPENSSL_CLIENT_CERTS);
1699 if (!SSL_CTX_load_verify_locations(
1700 context->ssl_client_ctx, ssl_ca_filepath,
1703 "Unable to load SSL Client certs "
1704 "file from %s -- client ssl isn't "
1705 "going to work", ssl_ca_filepath);
1708 * callback allowing user code to load extra verification certs
1709 * helping the client to verify server identity
1712 context->protocols[0].callback(context, NULL,
1713 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1714 context->ssl_client_ctx, NULL, 0);
1718 /* as a server, are we requiring clients to identify themselves? */
1720 if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1722 /* absolutely require the client cert */
1724 SSL_CTX_set_verify(context->ssl_ctx,
1725 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1726 OpenSSL_verify_callback);
1729 * give user code a chance to load certs into the server
1730 * allowing it to verify incoming client certs
1733 context->protocols[0].callback(context, NULL,
1734 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
1735 context->ssl_ctx, NULL, 0);
1738 if (context->use_ssl) {
1740 /* openssl init for server sockets */
1742 /* set the local certificate from CertFile */
1743 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
1746 lwsl_err("problem getting cert '%s': %s\n",
1748 ERR_error_string(ERR_get_error(), ssl_err_buf));
1751 /* set the private key from KeyFile */
1752 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
1753 ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
1754 lwsl_err("ssl problem getting key '%s': %s\n",
1755 ssl_private_key_filepath,
1756 ERR_error_string(ERR_get_error(), ssl_err_buf));
1759 /* verify private key */
1760 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
1761 lwsl_err("Private SSL key doesn't match cert\n");
1765 /* SSL is happy and has a cert it's content with */
1771 if (lws_b64_selftest())
1774 #ifndef LWS_NO_SERVER
1775 /* set up our external listening socket we serve on */
1778 extern int interface_to_sa(const char *ifname, struct sockaddr_in *addr, size_t addrlen);
1781 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1783 lwsl_err("ERROR opening socket\n");
1787 /* allow us to restart even if old sockets in TIME_WAIT */
1788 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
1789 (const void *)&opt, sizeof(opt));
1793 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
1794 (const void *)&opt, sizeof(opt));
1796 bzero((char *) &serv_addr, sizeof(serv_addr));
1797 serv_addr.sin_family = AF_INET;
1799 serv_addr.sin_addr.s_addr = INADDR_ANY;
1801 interface_to_sa(interf, &serv_addr,
1803 serv_addr.sin_port = htons(port);
1805 n = bind(sockfd, (struct sockaddr *) &serv_addr,
1808 lwsl_err("ERROR on binding to port %d (%d %d)\n",
1814 wsi = (struct libwebsocket *)malloc(sizeof(struct libwebsocket));
1816 lwsl_err("Out of mem\n");
1820 memset(wsi, 0, sizeof (struct libwebsocket));
1822 #ifndef LWS_NO_EXTENSIONS
1823 wsi->count_active_extensions = 0;
1825 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1827 insert_wsi_socket_into_fds(context, wsi);
1829 context->listen_service_modulo = LWS_LISTEN_SERVICE_MODULO;
1830 context->listen_service_count = 0;
1831 context->listen_service_fd = sockfd;
1833 listen(sockfd, LWS_SOMAXCONN);
1834 lwsl_notice(" Listening on port %d\n", port);
1839 * drop any root privs for this process
1840 * to listen on port < 1023 we would have needed root, but now we are
1841 * listening, we don't want the power for anything else
1847 lwsl_warn("setgid: %s\n", strerror(errno));
1850 lwsl_warn("setuid: %s\n", strerror(errno));
1853 /* set up our internal broadcast trigger sockets per-protocol */
1855 for (context->count_protocols = 0;
1856 protocols[context->count_protocols].callback;
1857 context->count_protocols++) {
1859 lwsl_parser(" Protocol: %s\n",
1860 protocols[context->count_protocols].name);
1862 protocols[context->count_protocols].owning_server = context;
1863 protocols[context->count_protocols].protocol_index =
1864 context->count_protocols;
1867 fd = socket(AF_INET, SOCK_STREAM, 0);
1869 lwsl_err("ERROR opening socket\n");
1873 /* allow us to restart even if old sockets in TIME_WAIT */
1874 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt,
1877 bzero((char *) &serv_addr, sizeof(serv_addr));
1878 serv_addr.sin_family = AF_INET;
1879 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1880 serv_addr.sin_port = 0; /* pick the port for us */
1882 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1884 lwsl_err("ERROR on binding to port %d (%d %d)\n",
1889 slen = sizeof cli_addr;
1890 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1892 lwsl_err("getsockname failed\n");
1895 protocols[context->count_protocols].broadcast_socket_port =
1896 ntohs(cli_addr.sin_port);
1899 lwsl_debug(" Protocol %s broadcast socket %d\n",
1900 protocols[context->count_protocols].name,
1901 ntohs(cli_addr.sin_port));
1903 /* dummy wsi per broadcast proxy socket */
1905 wsi = (struct libwebsocket *)malloc(sizeof(struct libwebsocket));
1907 lwsl_err("Out of mem\n");
1911 memset(wsi, 0, sizeof (struct libwebsocket));
1913 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1914 #ifndef LWS_NO_EXTENSIONS
1915 wsi->count_active_extensions = 0;
1917 /* note which protocol we are proxying */
1918 wsi->protocol_index_for_broadcast_proxy =
1919 context->count_protocols;
1921 insert_wsi_socket_into_fds(context, wsi);
1925 #ifndef LWS_NO_EXTENSIONS
1927 * give all extensions a chance to create any per-context
1928 * allocations they need
1931 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
1933 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
1936 while (extensions->callback) {
1937 lwsl_ext(" Extension: %s\n", extensions->name);
1938 extensions->callback(context, extensions, NULL,
1939 (enum libwebsocket_extension_callback_reasons)m,
1952 * libwebsockets_fork_service_loop() - Optional helper function forks off
1953 * a process for the websocket server loop.
1954 * You don't have to use this but if not, you
1955 * have to make sure you are calling
1956 * libwebsocket_service periodically to service
1957 * the websocket traffic
1958 * @context: server context returned by creation function
1962 libwebsockets_fork_service_loop(struct libwebsocket_context *context)
1965 struct sockaddr_in cli_addr;
1975 /* main process context */
1978 * set up the proxy sockets to allow broadcast from
1979 * service process context
1982 for (p = 0; p < context->count_protocols; p++) {
1983 fd = socket(AF_INET, SOCK_STREAM, 0);
1985 lwsl_err("Unable to create socket\n");
1988 cli_addr.sin_family = AF_INET;
1989 cli_addr.sin_port = htons(
1990 context->protocols[p].broadcast_socket_port);
1991 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1992 n = connect(fd, (struct sockaddr *)&cli_addr,
1995 lwsl_err("Unable to connect to "
1996 "broadcast socket %d, %s\n",
1997 n, strerror(errno));
2001 context->protocols[p].broadcast_socket_user_fd = fd;
2007 #ifdef HAVE_SYS_PRCTL_H
2008 /* we want a SIGHUP when our parent goes down */
2009 signal(SIGHUP, SIG_DFL);
2010 prctl(PR_SET_PDEATHSIG, SIGHUP);
2013 /* in this forked process, sit and service websocket connections */
2016 if (libwebsocket_service(context, 1000))
2018 //#ifndef HAVE_SYS_PRCTL_H
2020 * on systems without prctl() (i.e. anything but linux) we can notice that our
2021 * parent is dead if getppid() returns 1. FIXME apparently this is not true for
2022 * solaris, could remember ppid right after fork and wait for it to change.
2025 /* if our parent went down, don't linger around */
2026 if (context->started_with_parent && kill(context->started_with_parent, 0) < 0)
2027 kill(getpid(), SIGTERM);
2041 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2043 * @wsi: pointer to struct websocket you want to know the protocol of
2046 * This is useful to get the protocol to broadcast back to from inside
2050 const struct libwebsocket_protocols *
2051 libwebsockets_get_protocol(struct libwebsocket *wsi)
2053 return wsi->protocol;
2057 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
2058 * connections of the given protocol.
2059 * @protocol: pointer to the protocol you will broadcast to all members of
2060 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
2061 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
2062 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
2063 * case you are calling this function from callback context.
2064 * @len: length of payload data in buf, starting from buf.
2066 * This function allows bulk sending of a packet to every connection using
2067 * the given protocol. It does not send the data directly; instead it calls
2068 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
2069 * wants to actually send the data for that connection, the callback itself
2070 * should call libwebsocket_write().
2072 * libwebsockets_broadcast() can be called from another fork context without
2073 * having to take any care about data visibility between the processes, it'll
2079 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
2080 unsigned char *buf, size_t len)
2082 struct libwebsocket_context *context = protocol->owning_server;
2084 struct libwebsocket *wsi;
2090 if (!protocol->broadcast_socket_user_fd) {
2093 * We are either running unforked / flat, or we are being
2094 * called from poll thread context
2095 * eg, from a callback. In that case don't use sockets for
2096 * broadcast IPC (since we can't open a socket connection to
2097 * a socket listening on our own thread) but directly do the
2100 * Locking is not needed because we are by definition being
2101 * called in the poll thread context and are serialized.
2104 for (n = 0; n < context->fds_count; n++) {
2106 wsi = context->lws_lookup[context->fds[n].fd];
2110 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
2114 * never broadcast to non-established connections
2116 if (wsi->state != WSI_STATE_ESTABLISHED)
2119 /* only broadcast to guys using
2120 * requested protocol
2122 if (wsi->protocol != protocol)
2125 user_callback_handle_rxflow(wsi->protocol->callback,
2127 LWS_CALLBACK_BROADCAST,
2137 * We're being called from a different process context than the server
2138 * loop. Instead of broadcasting directly, we send our
2139 * payload on a socket to do the IPC; the server process will serialize
2140 * the broadcast action in its main poll() loop.
2142 * There's one broadcast socket listening for each protocol supported
2143 * set up when the websocket server initializes
2146 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
2153 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
2159 libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
2165 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
2167 /* allocate the per-connection user memory (if any) */
2169 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
2170 wsi->user_space = malloc(
2171 wsi->protocol->per_session_data_size);
2172 if (wsi->user_space == NULL) {
2173 lwsl_err("Out of memory for conn user space\n");
2176 memset(wsi->user_space, 0,
2177 wsi->protocol->per_session_data_size);
2179 return wsi->user_space;
2183 * lws_confirm_legit_wsi: returns nonzero if the wsi looks bad
2185 * @wsi: struct libwebsocket to assess
2187 * Performs consistecy checks on what the wsi claims and what the
2188 * polling arrays hold. This'll catch a closed wsi still in use.
2189 * Don't try to use on the listen (nonconnection) wsi as it will
2190 * fail it. Otherwise 0 return == wsi seems consistent.
2193 int lws_confirm_legit_wsi(struct libwebsocket *wsi)
2195 struct libwebsocket_context *context;
2197 if (!(wsi && wsi->protocol && wsi->protocol->owning_server))
2200 context = wsi->protocol->owning_server;
2205 if (!wsi->position_in_fds_table)
2206 return 3; /* position in fds table looks bad */
2207 if (context->fds[wsi->position_in_fds_table].fd != wsi->sock)
2208 return 4; /* pollfd entry does not wait on our socket descriptor */
2209 if (context->lws_lookup[wsi->sock] != wsi)
2210 return 5; /* lookup table does not agree with wsi */
2215 static void lwsl_emit_stderr(int level, const char *line)
2221 gettimeofday(&tv, NULL);
2224 for (n = 0; n < LLL_COUNT; n++)
2225 if (level == (1 << n)) {
2226 sprintf(buf, "[%ld:%04d] %s: ", tv.tv_sec,
2227 (int)(tv.tv_usec / 100), log_level_names[n]);
2231 fprintf(stderr, "%s%s", buf, line);
2234 void lwsl_emit_syslog(int level, const char *line)
2236 int syslog_level = LOG_DEBUG;
2240 syslog_level = LOG_ERR;
2243 syslog_level = LOG_WARNING;
2246 syslog_level = LOG_NOTICE;
2249 syslog_level = LOG_INFO;
2252 syslog(syslog_level, "%s", line);
2255 void _lws_log(int filter, const char *format, ...)
2260 if (!(log_level & filter))
2263 va_start(ap, format);
2264 vsnprintf(buf, (sizeof buf), format, ap);
2265 buf[(sizeof buf) - 1] = '\0';
2268 lwsl_emit(filter, buf);
2272 * lws_set_log_level() - Set the logging bitfield
2273 * @level: OR together the LLL_ debug contexts you want output from
2274 * @log_emit_function: NULL to leave it as it is, or a user-supplied
2275 * function to perform log string emission instead of
2276 * the default stderr one.
2278 * log level defaults to "err" and "warn" contexts enabled only and
2279 * emission on stderr.
2282 void lws_set_log_level(int level, void (*log_emit_function)(int level, const char *line))
2285 if (log_emit_function)
2286 lwsl_emit = log_emit_function;