2 * libwebsockets-test-server - libwebsockets test implementation
4 * Copyright (C) 2010-2011 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 "lws_config.h"
37 #ifndef WIN32_LEAN_AND_MEAN
38 #define WIN32_LEAN_AND_MEAN
44 #include "websock-w32.h"
53 #include "../lib/libwebsockets.h"
55 static int close_testing;
56 int max_poll_elements;
58 struct pollfd *pollfds;
64 * This demo server shows how to use libwebsockets for one or more
65 * websocket protocols in the same server
67 * It defines the following websocket protocols:
69 * dumb-increment-protocol: once the socket is opened, an incrementing
70 * ascii string is sent down it every 50ms.
71 * If you send "reset\n" on the websocket, then
72 * the incrementing number is reset to 0.
74 * lws-mirror-protocol: copies any received packet to every connection also
75 * using this protocol, including the sender
82 PROTOCOL_DUMB_INCREMENT,
90 #define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
91 char *resource_path = LOCAL_RESOURCE_PATH;
94 * We take a strict whitelist approach to stop ../ attacks
102 struct per_session_data__http {
107 * this is just an example of parsing handshake headers, you don't need this
108 * in your code unless you will filter allowing connections by the header
113 dump_handshake_info(struct libwebsocket *wsi)
116 static const char *token_names[] = {
117 /*[WSI_TOKEN_GET_URI] =*/ "GET URI",
118 /*[WSI_TOKEN_POST_URI] =*/ "POST URI",
119 /*[WSI_TOKEN_HOST] =*/ "Host",
120 /*[WSI_TOKEN_CONNECTION] =*/ "Connection",
121 /*[WSI_TOKEN_KEY1] =*/ "key 1",
122 /*[WSI_TOKEN_KEY2] =*/ "key 2",
123 /*[WSI_TOKEN_PROTOCOL] =*/ "Protocol",
124 /*[WSI_TOKEN_UPGRADE] =*/ "Upgrade",
125 /*[WSI_TOKEN_ORIGIN] =*/ "Origin",
126 /*[WSI_TOKEN_DRAFT] =*/ "Draft",
127 /*[WSI_TOKEN_CHALLENGE] =*/ "Challenge",
130 /*[WSI_TOKEN_KEY] =*/ "Key",
131 /*[WSI_TOKEN_VERSION] =*/ "Version",
132 /*[WSI_TOKEN_SWORIGIN] =*/ "Sworigin",
135 /*[WSI_TOKEN_EXTENSIONS] =*/ "Extensions",
137 /* client receives these */
138 /*[WSI_TOKEN_ACCEPT] =*/ "Accept",
139 /*[WSI_TOKEN_NONCE] =*/ "Nonce",
140 /*[WSI_TOKEN_HTTP] =*/ "Http",
143 "If-Modified-Since:",
157 /*[WSI_TOKEN_MUXURL] =*/ "MuxURL",
161 for (n = 0; n < sizeof(token_names) / sizeof(token_names[0]); n++) {
162 if (!lws_hdr_total_length(wsi, n))
165 lws_hdr_copy(wsi, buf, sizeof buf, n);
167 fprintf(stderr, " %s = %s\n", token_names[n], buf);
171 const char * get_mimetype(const char *file)
173 int n = strlen(file);
178 if (!strcmp(&file[n - 4], ".ico"))
179 return "image/x-icon";
181 if (!strcmp(&file[n - 4], ".png"))
184 if (!strcmp(&file[n - 5], ".html"))
190 /* this protocol server (always the first one) just knows how to do HTTP */
192 static int callback_http(struct libwebsocket_context *context,
193 struct libwebsocket *wsi,
194 enum libwebsocket_callback_reasons reason, void *user,
195 void *in, size_t len)
198 char client_name[128];
202 char leaf_path[1024];
208 static unsigned char buffer[4096];
209 struct stat stat_buf;
210 struct per_session_data__http *pss =
211 (struct per_session_data__http *)user;
212 const char *mimetype;
214 int fd = (int)(long)in;
218 case LWS_CALLBACK_HTTP:
220 dump_handshake_info(wsi);
223 libwebsockets_return_http_status(context, wsi,
224 HTTP_STATUS_BAD_REQUEST, NULL);
228 /* this server has no concept of directories */
229 if (strchr((const char *)in + 1, '/')) {
230 libwebsockets_return_http_status(context, wsi,
231 HTTP_STATUS_FORBIDDEN, NULL);
235 /* if a legal POST URL, let it continue and accept data */
236 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
239 /* check for the "send a big file by hand" example case */
241 if (!strcmp((const char *)in, "/leaf.jpg")) {
242 if (strlen(resource_path) > sizeof(leaf_path) - 10)
244 sprintf(leaf_path, "%s/leaf.jpg", resource_path);
246 /* well, let's demonstrate how to send the hard way */
251 pss->fd = open(leaf_path, O_RDONLY | _O_BINARY);
253 pss->fd = open(leaf_path, O_RDONLY);
259 fstat(pss->fd, &stat_buf);
262 * we will send a big jpeg file, but it could be
263 * anything. Set the Content-Type: appropriately
264 * so the browser knows what to do with it.
267 p += sprintf((char *)p,
268 "HTTP/1.0 200 OK\x0d\x0a"
269 "Server: libwebsockets\x0d\x0a"
270 "Content-Type: image/jpeg\x0d\x0a"
271 "Content-Length: %u\x0d\x0a\x0d\x0a",
272 (unsigned int)stat_buf.st_size);
275 * send the http headers...
276 * this won't block since it's the first payload sent
277 * on the connection since it was established
278 * (too small for partial)
281 n = libwebsocket_write(wsi, buffer,
282 p - buffer, LWS_WRITE_HTTP);
289 * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
291 libwebsocket_callback_on_writable(context, wsi);
295 /* if not, send a file the easy way */
296 strcpy(buf, resource_path);
297 if (strcmp(in, "/")) {
298 if (*((const char *)in) != '/')
300 strncat(buf, in, sizeof(buf) - strlen(resource_path));
301 } else /* default file to serve */
302 strcat(buf, "/test.html");
303 buf[sizeof(buf) - 1] = '\0';
305 /* refuse to serve files we don't understand */
306 mimetype = get_mimetype(buf);
308 lwsl_err("Unknown mimetype for %s\n", buf);
309 libwebsockets_return_http_status(context, wsi,
310 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
314 /* demostrates how to set a cookie on / */
316 other_headers = NULL;
317 if (!strcmp((const char *)in, "/") &&
318 !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
319 /* this isn't very unguessable but it'll do for us */
320 gettimeofday(&tv, NULL);
321 sprintf(b64, "LWS_%u_%u_COOKIE",
322 (unsigned int)tv.tv_sec,
323 (unsigned int)tv.tv_usec);
326 "Set-Cookie: test=LWS_%u_%u_COOKIE;Max-Age=360000\x0d\x0a",
327 (unsigned int)tv.tv_sec, (unsigned int)tv.tv_usec);
328 other_headers = leaf_path;
329 lwsl_err(other_headers);
332 if (libwebsockets_serve_http_file(context, wsi, buf,
333 mimetype, other_headers))
334 return -1; /* through completion or error, close the socket */
337 * notice that the sending of the file completes asynchronously,
338 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
344 case LWS_CALLBACK_HTTP_BODY:
345 strncpy(buf, in, 20);
350 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
351 (const char *)buf, (int)len);
355 case LWS_CALLBACK_HTTP_BODY_COMPLETION:
356 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
357 /* the whole of the sent body arried, close the connection */
358 libwebsockets_return_http_status(context, wsi,
359 HTTP_STATUS_OK, NULL);
363 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
364 // lwsl_info("LWS_CALLBACK_HTTP_FILE_COMPLETION seen\n");
365 /* kill the connection after we sent one file */
368 case LWS_CALLBACK_HTTP_WRITEABLE:
370 * we can send more of whatever it is we were sending
374 n = read(pss->fd, buffer, sizeof buffer);
375 /* problem reading, close conn */
378 /* sent it all, close conn */
382 * because it's HTTP and not websocket, don't need to take
383 * care about pre and postamble
385 m = libwebsocket_write(wsi, buffer, n, LWS_WRITE_HTTP);
387 /* write failed, close conn */
390 /* partial write, adjust */
391 lseek(pss->fd, m - n, SEEK_CUR);
393 } while (!lws_send_pipe_choked(wsi));
394 libwebsocket_callback_on_writable(context, wsi);
402 * callback for confirming to continue with client IP appear in
403 * protocol 0 callback since no websocket protocol has been agreed
404 * yet. You can just ignore this if you won't filter on client IP
405 * since the default uhandled callback return is 0 meaning let the
406 * connection continue.
409 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
411 libwebsockets_get_peer_addresses(context, wsi, (int)(long)in, client_name,
412 sizeof(client_name), client_ip, sizeof(client_ip));
414 fprintf(stderr, "Received network connect from %s (%s)\n",
415 client_name, client_ip);
417 /* if we returned non-zero from here, we kill the connection */
422 * callbacks for managing the external poll() array appear in
423 * protocol 0 callback
426 case LWS_CALLBACK_ADD_POLL_FD:
428 if (count_pollfds >= max_poll_elements) {
429 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
433 fd_lookup[fd] = count_pollfds;
434 pollfds[count_pollfds].fd = fd;
435 pollfds[count_pollfds].events = (int)(long)len;
436 pollfds[count_pollfds++].revents = 0;
439 case LWS_CALLBACK_DEL_POLL_FD:
440 if (!--count_pollfds)
443 /* have the last guy take up the vacant slot */
444 pollfds[m] = pollfds[count_pollfds];
445 fd_lookup[pollfds[count_pollfds].fd] = m;
448 case LWS_CALLBACK_SET_MODE_POLL_FD:
449 pollfds[fd_lookup[fd]].events |= (int)(long)len;
452 case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
453 pollfds[fd_lookup[fd]].events &= ~(int)(long)len;
465 /* dumb_increment protocol */
468 * one of these is auto-created for each connection and a pointer to the
469 * appropriate instance is passed to the callback in the user parameter
471 * for this example protocol we use it to individualize the count for each
475 struct per_session_data__dumb_increment {
480 callback_dumb_increment(struct libwebsocket_context *context,
481 struct libwebsocket *wsi,
482 enum libwebsocket_callback_reasons reason,
483 void *user, void *in, size_t len)
486 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
487 LWS_SEND_BUFFER_POST_PADDING];
488 unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
489 struct per_session_data__dumb_increment *pss = (struct per_session_data__dumb_increment *)user;
493 case LWS_CALLBACK_ESTABLISHED:
494 lwsl_info("callback_dumb_increment: "
495 "LWS_CALLBACK_ESTABLISHED\n");
499 case LWS_CALLBACK_SERVER_WRITEABLE:
500 n = sprintf((char *)p, "%d", pss->number++);
501 m = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
503 lwsl_err("ERROR %d writing to di socket\n", n);
506 if (close_testing && pss->number == 50) {
507 lwsl_info("close tesing limit, closing\n");
512 case LWS_CALLBACK_RECEIVE:
513 // fprintf(stderr, "rx %d\n", (int)len);
516 if (strcmp((const char *)in, "reset\n") == 0)
520 * this just demonstrates how to use the protocol filter. If you won't
521 * study and reject connections based on header content, you don't need
522 * to handle this callback
525 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
526 dump_handshake_info(wsi);
527 /* you could return non-zero here and kill the connection */
538 /* lws-mirror_protocol */
540 #define MAX_MESSAGE_QUEUE 32
542 struct per_session_data__lws_mirror {
543 struct libwebsocket *wsi;
552 static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
553 static int ringbuffer_head;
556 callback_lws_mirror(struct libwebsocket_context *context,
557 struct libwebsocket *wsi,
558 enum libwebsocket_callback_reasons reason,
559 void *user, void *in, size_t len)
562 struct per_session_data__lws_mirror *pss = (struct per_session_data__lws_mirror *)user;
566 case LWS_CALLBACK_ESTABLISHED:
567 lwsl_info("callback_lws_mirror: LWS_CALLBACK_ESTABLISHED\n");
568 pss->ringbuffer_tail = ringbuffer_head;
572 case LWS_CALLBACK_PROTOCOL_DESTROY:
573 lwsl_notice("mirror protocol cleaning up\n");
574 for (n = 0; n < sizeof ringbuffer / sizeof ringbuffer[0]; n++)
575 if (ringbuffer[n].payload)
576 free(ringbuffer[n].payload);
579 case LWS_CALLBACK_SERVER_WRITEABLE:
582 while (pss->ringbuffer_tail != ringbuffer_head) {
584 n = libwebsocket_write(wsi, (unsigned char *)
585 ringbuffer[pss->ringbuffer_tail].payload +
586 LWS_SEND_BUFFER_PRE_PADDING,
587 ringbuffer[pss->ringbuffer_tail].len,
589 if (n < ringbuffer[pss->ringbuffer_tail].len) {
590 lwsl_err("ERROR %d writing to mirror socket\n", n);
593 if (n < ringbuffer[pss->ringbuffer_tail].len)
594 lwsl_err("mirror partial write %d vs %d\n",
595 n, ringbuffer[pss->ringbuffer_tail].len);
597 if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
598 pss->ringbuffer_tail = 0;
600 pss->ringbuffer_tail++;
602 if (((ringbuffer_head - pss->ringbuffer_tail) &
603 (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 15))
604 libwebsocket_rx_flow_allow_all_protocol(
605 libwebsockets_get_protocol(wsi));
607 // lwsl_debug("tx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1));
609 if (lws_send_pipe_choked(wsi)) {
610 libwebsocket_callback_on_writable(context, wsi);
614 * for tests with chrome on same machine as client and
615 * server, this is needed to stop chrome choking
621 case LWS_CALLBACK_RECEIVE:
623 if (((ringbuffer_head - pss->ringbuffer_tail) &
624 (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 1)) {
625 lwsl_err("dropping!\n");
629 if (ringbuffer[ringbuffer_head].payload)
630 free(ringbuffer[ringbuffer_head].payload);
632 ringbuffer[ringbuffer_head].payload =
633 malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
634 LWS_SEND_BUFFER_POST_PADDING);
635 ringbuffer[ringbuffer_head].len = len;
636 memcpy((char *)ringbuffer[ringbuffer_head].payload +
637 LWS_SEND_BUFFER_PRE_PADDING, in, len);
638 if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
643 if (((ringbuffer_head - pss->ringbuffer_tail) &
644 (MAX_MESSAGE_QUEUE - 1)) != (MAX_MESSAGE_QUEUE - 2))
648 lwsl_debug("LWS_CALLBACK_RECEIVE: throttling %p\n", wsi);
649 libwebsocket_rx_flow_control(wsi, 0);
651 // lwsl_debug("rx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1));
653 libwebsocket_callback_on_writable_all_protocol(
654 libwebsockets_get_protocol(wsi));
658 * this just demonstrates how to use the protocol filter. If you won't
659 * study and reject connections based on header content, you don't need
660 * to handle this callback
663 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
664 dump_handshake_info(wsi);
665 /* you could return non-zero here and kill the connection */
676 /* list of supported protocols and callbacks */
678 static struct libwebsocket_protocols protocols[] = {
679 /* first protocol must always be HTTP handler */
682 "http-only", /* name */
683 callback_http, /* callback */
684 sizeof (struct per_session_data__http), /* per_session_data_size */
685 0, /* max frame size / rx buffer */
688 "dumb-increment-protocol",
689 callback_dumb_increment,
690 sizeof(struct per_session_data__dumb_increment),
694 "lws-mirror-protocol",
696 sizeof(struct per_session_data__lws_mirror),
699 { NULL, NULL, 0, 0 } /* terminator */
702 void sighandler(int sig)
707 static struct option options[] = {
708 { "help", no_argument, NULL, 'h' },
709 { "debug", required_argument, NULL, 'd' },
710 { "port", required_argument, NULL, 'p' },
711 { "ssl", no_argument, NULL, 's' },
712 { "interface", required_argument, NULL, 'i' },
713 { "closetest", no_argument, NULL, 'c' },
714 #ifndef LWS_NO_DAEMONIZE
715 { "daemonize", no_argument, NULL, 'D' },
717 { "resource_path", required_argument, NULL, 'r' },
721 int main(int argc, char **argv)
723 char cert_path[1024];
727 struct libwebsocket_context *context;
729 char interface_name[128] = "";
730 const char *iface = NULL;
732 int syslog_options = LOG_PID | LOG_PERROR;
734 unsigned int oldus = 0;
735 struct lws_context_creation_info info;
738 #ifndef LWS_NO_DAEMONIZE
742 memset(&info, 0, sizeof info);
746 n = getopt_long(argc, argv, "ci:hsp:d:Dr:", options, NULL);
750 #ifndef LWS_NO_DAEMONIZE
754 syslog_options &= ~LOG_PERROR;
759 debug_level = atoi(optarg);
765 info.port = atoi(optarg);
768 strncpy(interface_name, optarg, sizeof interface_name);
769 interface_name[(sizeof interface_name) - 1] = '\0';
770 iface = interface_name;
774 fprintf(stderr, " Close testing mode -- closes on "
775 "client after 50 dumb increments"
776 "and suppresses lws_mirror spam\n");
779 resource_path = optarg;
780 printf("Setting resource path to \"%s\"\n", resource_path);
783 fprintf(stderr, "Usage: test-server "
784 "[--port=<p>] [--ssl] "
785 "[-d <log bitfield>] "
786 "[--resource_path <path>]\n");
791 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
793 * normally lock path would be /var/lock/lwsts or similar, to
794 * simplify getting started without having to take care about
795 * permissions or running as root, set to /tmp/.lwsts-lock
797 if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
798 fprintf(stderr, "Failed to daemonize\n");
803 signal(SIGINT, sighandler);
806 /* we will only try to log things according to our debug_level */
807 setlogmask(LOG_UPTO (LOG_DEBUG));
808 openlog("lwsts", syslog_options, LOG_DAEMON);
811 /* tell the library what debug level to emit and to send it to syslog */
812 lws_set_log_level(debug_level, lwsl_emit_syslog);
814 lwsl_notice("libwebsockets test server - "
815 "(C) Copyright 2010-2013 Andy Green <andy@warmcat.com> - "
816 "licensed under LGPL2.1\n");
818 max_poll_elements = getdtablesize();
819 pollfds = malloc(max_poll_elements * sizeof (struct pollfd));
820 fd_lookup = malloc(max_poll_elements * sizeof (int));
821 if (pollfds == NULL || fd_lookup == NULL) {
822 lwsl_err("Out of memory pollfds=%d\n", max_poll_elements);
828 info.protocols = protocols;
829 #ifndef LWS_NO_EXTENSIONS
830 info.extensions = libwebsocket_get_internal_extensions();
833 info.ssl_cert_filepath = NULL;
834 info.ssl_private_key_filepath = NULL;
836 if (strlen(resource_path) > sizeof(cert_path) - 32) {
837 lwsl_err("resource path too long\n");
840 sprintf(cert_path, "%s/libwebsockets-test-server.pem",
842 if (strlen(resource_path) > sizeof(key_path) - 32) {
843 lwsl_err("resource path too long\n");
846 sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
849 info.ssl_cert_filepath = cert_path;
850 info.ssl_private_key_filepath = key_path;
856 context = libwebsocket_create_context(&info);
857 if (context == NULL) {
858 lwsl_err("libwebsocket init failed\n");
863 while (n >= 0 && !force_exit) {
866 gettimeofday(&tv, NULL);
869 * This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every
870 * live websocket connection using the DUMB_INCREMENT protocol,
871 * as soon as it can take more packets (usually immediately)
874 if (((unsigned int)tv.tv_usec - oldus) > 50000) {
875 libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_DUMB_INCREMENT]);
882 * this represents an existing server's single poll action
883 * which also includes libwebsocket sockets
886 n = poll(pollfds, count_pollfds, 50);
892 for (n = 0; n < count_pollfds; n++)
893 if (pollfds[n].revents)
895 * returns immediately if the fd does not
896 * match anything under libwebsockets
899 if (libwebsocket_service_fd(context,
904 * If libwebsockets sockets are all we care about,
905 * you can use this api which takes care of the poll()
906 * and looping through finding who needed service.
908 * If no socket needs service, it'll return anyway after
909 * the number of ms in the second argument.
912 n = libwebsocket_service(context, 50);
920 libwebsocket_context_destroy(context);
922 lwsl_notice("libwebsockets-test-server exited cleanly\n");