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);
397 /* true if still partial pending */
398 if (lws_send_pipe_choked(wsi)) {
399 libwebsocket_callback_on_writable(context, wsi);
408 * callback for confirming to continue with client IP appear in
409 * protocol 0 callback since no websocket protocol has been agreed
410 * yet. You can just ignore this if you won't filter on client IP
411 * since the default uhandled callback return is 0 meaning let the
412 * connection continue.
415 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
417 libwebsockets_get_peer_addresses(context, wsi, (int)(long)in, client_name,
418 sizeof(client_name), client_ip, sizeof(client_ip));
420 fprintf(stderr, "Received network connect from %s (%s)\n",
421 client_name, client_ip);
423 /* if we returned non-zero from here, we kill the connection */
428 * callbacks for managing the external poll() array appear in
429 * protocol 0 callback
432 case LWS_CALLBACK_ADD_POLL_FD:
434 if (count_pollfds >= max_poll_elements) {
435 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
439 fd_lookup[fd] = count_pollfds;
440 pollfds[count_pollfds].fd = fd;
441 pollfds[count_pollfds].events = (int)(long)len;
442 pollfds[count_pollfds++].revents = 0;
445 case LWS_CALLBACK_DEL_POLL_FD:
446 if (!--count_pollfds)
449 /* have the last guy take up the vacant slot */
450 pollfds[m] = pollfds[count_pollfds];
451 fd_lookup[pollfds[count_pollfds].fd] = m;
454 case LWS_CALLBACK_SET_MODE_POLL_FD:
455 pollfds[fd_lookup[fd]].events |= (int)(long)len;
458 case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
459 pollfds[fd_lookup[fd]].events &= ~(int)(long)len;
471 /* dumb_increment protocol */
474 * one of these is auto-created for each connection and a pointer to the
475 * appropriate instance is passed to the callback in the user parameter
477 * for this example protocol we use it to individualize the count for each
481 struct per_session_data__dumb_increment {
486 callback_dumb_increment(struct libwebsocket_context *context,
487 struct libwebsocket *wsi,
488 enum libwebsocket_callback_reasons reason,
489 void *user, void *in, size_t len)
492 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
493 LWS_SEND_BUFFER_POST_PADDING];
494 unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
495 struct per_session_data__dumb_increment *pss = (struct per_session_data__dumb_increment *)user;
499 case LWS_CALLBACK_ESTABLISHED:
500 lwsl_info("callback_dumb_increment: "
501 "LWS_CALLBACK_ESTABLISHED\n");
505 case LWS_CALLBACK_SERVER_WRITEABLE:
506 n = sprintf((char *)p, "%d", pss->number++);
507 m = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
509 lwsl_err("ERROR %d writing to di socket\n", n);
512 if (close_testing && pss->number == 50) {
513 lwsl_info("close tesing limit, closing\n");
518 case LWS_CALLBACK_RECEIVE:
519 // fprintf(stderr, "rx %d\n", (int)len);
522 if (strcmp((const char *)in, "reset\n") == 0)
526 * this just demonstrates how to use the protocol filter. If you won't
527 * study and reject connections based on header content, you don't need
528 * to handle this callback
531 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
532 dump_handshake_info(wsi);
533 /* you could return non-zero here and kill the connection */
544 /* lws-mirror_protocol */
546 #define MAX_MESSAGE_QUEUE 32
548 struct per_session_data__lws_mirror {
549 struct libwebsocket *wsi;
558 static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
559 static int ringbuffer_head;
562 callback_lws_mirror(struct libwebsocket_context *context,
563 struct libwebsocket *wsi,
564 enum libwebsocket_callback_reasons reason,
565 void *user, void *in, size_t len)
568 struct per_session_data__lws_mirror *pss = (struct per_session_data__lws_mirror *)user;
572 case LWS_CALLBACK_ESTABLISHED:
573 lwsl_info("callback_lws_mirror: LWS_CALLBACK_ESTABLISHED\n");
574 pss->ringbuffer_tail = ringbuffer_head;
578 case LWS_CALLBACK_PROTOCOL_DESTROY:
579 lwsl_notice("mirror protocol cleaning up\n");
580 for (n = 0; n < sizeof ringbuffer / sizeof ringbuffer[0]; n++)
581 if (ringbuffer[n].payload)
582 free(ringbuffer[n].payload);
585 case LWS_CALLBACK_SERVER_WRITEABLE:
588 while (pss->ringbuffer_tail != ringbuffer_head) {
590 n = libwebsocket_write(wsi, (unsigned char *)
591 ringbuffer[pss->ringbuffer_tail].payload +
592 LWS_SEND_BUFFER_PRE_PADDING,
593 ringbuffer[pss->ringbuffer_tail].len,
596 lwsl_err("ERROR %d writing to mirror socket\n", n);
599 if (n < ringbuffer[pss->ringbuffer_tail].len)
600 lwsl_err("mirror partial write %d vs %d\n",
601 n, ringbuffer[pss->ringbuffer_tail].len);
603 if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
604 pss->ringbuffer_tail = 0;
606 pss->ringbuffer_tail++;
608 if (((ringbuffer_head - pss->ringbuffer_tail) &
609 (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 15))
610 libwebsocket_rx_flow_allow_all_protocol(
611 libwebsockets_get_protocol(wsi));
613 // lwsl_debug("tx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1));
615 if (lws_send_pipe_choked(wsi)) {
616 libwebsocket_callback_on_writable(context, wsi);
620 * for tests with chrome on same machine as client and
621 * server, this is needed to stop chrome choking
627 case LWS_CALLBACK_RECEIVE:
629 if (((ringbuffer_head - pss->ringbuffer_tail) &
630 (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 1)) {
631 lwsl_err("dropping!\n");
635 if (ringbuffer[ringbuffer_head].payload)
636 free(ringbuffer[ringbuffer_head].payload);
638 ringbuffer[ringbuffer_head].payload =
639 malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
640 LWS_SEND_BUFFER_POST_PADDING);
641 ringbuffer[ringbuffer_head].len = len;
642 memcpy((char *)ringbuffer[ringbuffer_head].payload +
643 LWS_SEND_BUFFER_PRE_PADDING, in, len);
644 if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
649 if (((ringbuffer_head - pss->ringbuffer_tail) &
650 (MAX_MESSAGE_QUEUE - 1)) != (MAX_MESSAGE_QUEUE - 2))
654 lwsl_debug("LWS_CALLBACK_RECEIVE: throttling %p\n", wsi);
655 libwebsocket_rx_flow_control(wsi, 0);
657 // lwsl_debug("rx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1));
659 libwebsocket_callback_on_writable_all_protocol(
660 libwebsockets_get_protocol(wsi));
664 * this just demonstrates how to use the protocol filter. If you won't
665 * study and reject connections based on header content, you don't need
666 * to handle this callback
669 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
670 dump_handshake_info(wsi);
671 /* you could return non-zero here and kill the connection */
682 /* list of supported protocols and callbacks */
684 static struct libwebsocket_protocols protocols[] = {
685 /* first protocol must always be HTTP handler */
688 "http-only", /* name */
689 callback_http, /* callback */
690 sizeof (struct per_session_data__http), /* per_session_data_size */
691 0, /* max frame size / rx buffer */
694 "dumb-increment-protocol",
695 callback_dumb_increment,
696 sizeof(struct per_session_data__dumb_increment),
700 "lws-mirror-protocol",
702 sizeof(struct per_session_data__lws_mirror),
705 { NULL, NULL, 0, 0 } /* terminator */
708 void sighandler(int sig)
713 static struct option options[] = {
714 { "help", no_argument, NULL, 'h' },
715 { "debug", required_argument, NULL, 'd' },
716 { "port", required_argument, NULL, 'p' },
717 { "ssl", no_argument, NULL, 's' },
718 { "allow-non-ssl", no_argument, NULL, 'a' },
719 { "interface", required_argument, NULL, 'i' },
720 { "closetest", no_argument, NULL, 'c' },
721 #ifndef LWS_NO_DAEMONIZE
722 { "daemonize", no_argument, NULL, 'D' },
724 { "resource_path", required_argument, NULL, 'r' },
728 int main(int argc, char **argv)
730 char cert_path[1024];
734 struct libwebsocket_context *context;
736 char interface_name[128] = "";
737 const char *iface = NULL;
739 int syslog_options = LOG_PID | LOG_PERROR;
741 unsigned int oldus = 0;
742 struct lws_context_creation_info info;
745 #ifndef LWS_NO_DAEMONIZE
749 memset(&info, 0, sizeof info);
753 n = getopt_long(argc, argv, "ci:hsap:d:Dr:", options, NULL);
757 #ifndef LWS_NO_DAEMONIZE
761 syslog_options &= ~LOG_PERROR;
766 debug_level = atoi(optarg);
772 opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
775 info.port = atoi(optarg);
778 strncpy(interface_name, optarg, sizeof interface_name);
779 interface_name[(sizeof interface_name) - 1] = '\0';
780 iface = interface_name;
784 fprintf(stderr, " Close testing mode -- closes on "
785 "client after 50 dumb increments"
786 "and suppresses lws_mirror spam\n");
789 resource_path = optarg;
790 printf("Setting resource path to \"%s\"\n", resource_path);
793 fprintf(stderr, "Usage: test-server "
794 "[--port=<p>] [--ssl] "
795 "[-d <log bitfield>] "
796 "[--resource_path <path>]\n");
801 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
803 * normally lock path would be /var/lock/lwsts or similar, to
804 * simplify getting started without having to take care about
805 * permissions or running as root, set to /tmp/.lwsts-lock
807 if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
808 fprintf(stderr, "Failed to daemonize\n");
813 signal(SIGINT, sighandler);
816 /* we will only try to log things according to our debug_level */
817 setlogmask(LOG_UPTO (LOG_DEBUG));
818 openlog("lwsts", syslog_options, LOG_DAEMON);
821 /* tell the library what debug level to emit and to send it to syslog */
822 lws_set_log_level(debug_level, lwsl_emit_syslog);
824 lwsl_notice("libwebsockets test server - "
825 "(C) Copyright 2010-2013 Andy Green <andy@warmcat.com> - "
826 "licensed under LGPL2.1\n");
828 max_poll_elements = getdtablesize();
829 pollfds = malloc(max_poll_elements * sizeof (struct pollfd));
830 fd_lookup = malloc(max_poll_elements * sizeof (int));
831 if (pollfds == NULL || fd_lookup == NULL) {
832 lwsl_err("Out of memory pollfds=%d\n", max_poll_elements);
838 info.protocols = protocols;
839 #ifndef LWS_NO_EXTENSIONS
840 info.extensions = libwebsocket_get_internal_extensions();
843 info.ssl_cert_filepath = NULL;
844 info.ssl_private_key_filepath = NULL;
846 if (strlen(resource_path) > sizeof(cert_path) - 32) {
847 lwsl_err("resource path too long\n");
850 sprintf(cert_path, "%s/libwebsockets-test-server.pem",
852 if (strlen(resource_path) > sizeof(key_path) - 32) {
853 lwsl_err("resource path too long\n");
856 sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
859 info.ssl_cert_filepath = cert_path;
860 info.ssl_private_key_filepath = key_path;
866 context = libwebsocket_create_context(&info);
867 if (context == NULL) {
868 lwsl_err("libwebsocket init failed\n");
873 while (n >= 0 && !force_exit) {
876 gettimeofday(&tv, NULL);
879 * This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every
880 * live websocket connection using the DUMB_INCREMENT protocol,
881 * as soon as it can take more packets (usually immediately)
884 if (((unsigned int)tv.tv_usec - oldus) > 50000) {
885 libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_DUMB_INCREMENT]);
892 * this represents an existing server's single poll action
893 * which also includes libwebsocket sockets
896 n = poll(pollfds, count_pollfds, 50);
902 for (n = 0; n < count_pollfds; n++)
903 if (pollfds[n].revents)
905 * returns immediately if the fd does not
906 * match anything under libwebsockets
909 if (libwebsocket_service_fd(context,
914 * If libwebsockets sockets are all we care about,
915 * you can use this api which takes care of the poll()
916 * and looping through finding who needed service.
918 * If no socket needs service, it'll return anyway after
919 * the number of ms in the second argument.
922 n = libwebsocket_service(context, 50);
930 libwebsocket_context_destroy(context);
932 lwsl_notice("libwebsockets-test-server exited cleanly\n");