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"
93 * We take a strict whitelist approach to stop ../ attacks
101 static const struct serveable whitelist[] = {
102 { "/favicon.ico", "image/x-icon" },
103 { "/libwebsockets.org-logo.png", "image/png" },
105 /* last one is the default served if no match */
106 { "/test.html", "text/html" },
109 struct per_session_data__http {
113 /* this protocol server (always the first one) just knows how to do HTTP */
115 static int callback_http(struct libwebsocket_context *context,
116 struct libwebsocket *wsi,
117 enum libwebsocket_callback_reasons reason, void *user,
118 void *in, size_t len)
121 char client_name[128];
127 static unsigned char buffer[4096];
128 struct stat stat_buf;
129 struct per_session_data__http *pss = (struct per_session_data__http *)user;
131 int fd = (int)(long)in;
135 case LWS_CALLBACK_HTTP:
137 /* check for the "send a big file by hand" example case */
139 if (!strcmp((const char *)in, "/leaf.jpg")) {
141 /* well, let's demonstrate how to send the hard way */
145 pss->fd = open(LOCAL_RESOURCE_PATH"/leaf.jpg", O_RDONLY);
149 fstat(pss->fd, &stat_buf);
152 * we will send a big jpeg file, but it could be
153 * anything. Set the Content-Type: appropriately
154 * so the browser knows what to do with it.
157 p += sprintf((char *)p,
158 "HTTP/1.0 200 OK\x0d\x0a"
159 "Server: libwebsockets\x0d\x0a"
160 "Content-Type: image/jpeg\x0d\x0a"
161 "Content-Length: %u\x0d\x0a\x0d\x0a",
162 (unsigned int)stat_buf.st_size);
165 * send the http headers...
166 * this won't block since it's the first payload sent
167 * on the connection since it was established
168 * (too small for partial)
171 n = libwebsocket_write(wsi, buffer,
172 p - buffer, LWS_WRITE_HTTP);
179 * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
181 libwebsocket_callback_on_writable(context, wsi);
185 /* if not, send a file the easy way */
187 for (n = 0; n < (sizeof(whitelist) / sizeof(whitelist[0]) - 1); n++)
188 if (in && strcmp((const char *)in, whitelist[n].urlpath) == 0)
191 sprintf(buf, LOCAL_RESOURCE_PATH"%s", whitelist[n].urlpath);
193 if (libwebsockets_serve_http_file(context, wsi, buf, whitelist[n].mimetype))
194 return -1; /* through completion or error, close the socket */
197 * notice that the sending of the file completes asynchronously,
198 * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
204 case LWS_CALLBACK_HTTP_FILE_COMPLETION:
205 // lwsl_info("LWS_CALLBACK_HTTP_FILE_COMPLETION seen\n");
206 /* kill the connection after we sent one file */
209 case LWS_CALLBACK_HTTP_WRITEABLE:
211 * we can send more of whatever it is we were sending
215 n = read(pss->fd, buffer, sizeof buffer);
216 /* problem reading, close conn */
219 /* sent it all, close conn */
223 * because it's HTTP and not websocket, don't need to take
224 * care about pre and postamble
226 m = libwebsocket_write(wsi, buffer, n, LWS_WRITE_HTTP);
228 /* write failed, close conn */
231 /* partial write, adjust */
232 lseek(pss->fd, m - n, SEEK_CUR);
234 } while (!lws_send_pipe_choked(wsi));
235 libwebsocket_callback_on_writable(context, wsi);
243 * callback for confirming to continue with client IP appear in
244 * protocol 0 callback since no websocket protocol has been agreed
245 * yet. You can just ignore this if you won't filter on client IP
246 * since the default uhandled callback return is 0 meaning let the
247 * connection continue.
250 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
252 libwebsockets_get_peer_addresses(context, wsi, (int)(long)in, client_name,
253 sizeof(client_name), client_ip, sizeof(client_ip));
255 fprintf(stderr, "Received network connect from %s (%s)\n",
256 client_name, client_ip);
258 /* if we returned non-zero from here, we kill the connection */
263 * callbacks for managing the external poll() array appear in
264 * protocol 0 callback
267 case LWS_CALLBACK_ADD_POLL_FD:
269 if (count_pollfds >= max_poll_elements) {
270 lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
274 fd_lookup[fd] = count_pollfds;
275 pollfds[count_pollfds].fd = fd;
276 pollfds[count_pollfds].events = (int)(long)len;
277 pollfds[count_pollfds++].revents = 0;
280 case LWS_CALLBACK_DEL_POLL_FD:
281 if (!--count_pollfds)
284 /* have the last guy take up the vacant slot */
285 pollfds[m] = pollfds[count_pollfds];
286 fd_lookup[pollfds[count_pollfds].fd] = m;
289 case LWS_CALLBACK_SET_MODE_POLL_FD:
290 pollfds[fd_lookup[fd]].events |= (int)(long)len;
293 case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
294 pollfds[fd_lookup[fd]].events &= ~(int)(long)len;
306 * this is just an example of parsing handshake headers, you don't need this
307 * in your code unless you will filter allowing connections by the header
312 dump_handshake_info(struct libwebsocket *wsi)
315 static const char *token_names[WSI_TOKEN_COUNT] = {
316 /*[WSI_TOKEN_GET_URI] =*/ "GET URI",
317 /*[WSI_TOKEN_HOST] =*/ "Host",
318 /*[WSI_TOKEN_CONNECTION] =*/ "Connection",
319 /*[WSI_TOKEN_KEY1] =*/ "key 1",
320 /*[WSI_TOKEN_KEY2] =*/ "key 2",
321 /*[WSI_TOKEN_PROTOCOL] =*/ "Protocol",
322 /*[WSI_TOKEN_UPGRADE] =*/ "Upgrade",
323 /*[WSI_TOKEN_ORIGIN] =*/ "Origin",
324 /*[WSI_TOKEN_DRAFT] =*/ "Draft",
325 /*[WSI_TOKEN_CHALLENGE] =*/ "Challenge",
328 /*[WSI_TOKEN_KEY] =*/ "Key",
329 /*[WSI_TOKEN_VERSION] =*/ "Version",
330 /*[WSI_TOKEN_SWORIGIN] =*/ "Sworigin",
333 /*[WSI_TOKEN_EXTENSIONS] =*/ "Extensions",
335 /* client receives these */
336 /*[WSI_TOKEN_ACCEPT] =*/ "Accept",
337 /*[WSI_TOKEN_NONCE] =*/ "Nonce",
338 /*[WSI_TOKEN_HTTP] =*/ "Http",
339 /*[WSI_TOKEN_MUXURL] =*/ "MuxURL",
343 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
344 if (!lws_hdr_total_length(wsi, n))
347 lws_hdr_copy(wsi, buf, sizeof buf, n);
349 fprintf(stderr, " %s = %s\n", token_names[n], buf);
353 /* dumb_increment protocol */
356 * one of these is auto-created for each connection and a pointer to the
357 * appropriate instance is passed to the callback in the user parameter
359 * for this example protocol we use it to individualize the count for each
363 struct per_session_data__dumb_increment {
368 callback_dumb_increment(struct libwebsocket_context *context,
369 struct libwebsocket *wsi,
370 enum libwebsocket_callback_reasons reason,
371 void *user, void *in, size_t len)
374 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
375 LWS_SEND_BUFFER_POST_PADDING];
376 unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
377 struct per_session_data__dumb_increment *pss = (struct per_session_data__dumb_increment *)user;
381 case LWS_CALLBACK_ESTABLISHED:
382 lwsl_info("callback_dumb_increment: "
383 "LWS_CALLBACK_ESTABLISHED\n");
387 case LWS_CALLBACK_SERVER_WRITEABLE:
388 n = sprintf((char *)p, "%d", pss->number++);
389 /* too small for partial */
390 n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
392 lwsl_err("ERROR %d writing to di socket\n", n);
395 if (close_testing && pss->number == 50) {
396 lwsl_info("close tesing limit, closing\n");
401 case LWS_CALLBACK_RECEIVE:
402 // fprintf(stderr, "rx %d\n", (int)len);
405 if (strcmp((const char *)in, "reset\n") == 0)
409 * this just demonstrates how to use the protocol filter. If you won't
410 * study and reject connections based on header content, you don't need
411 * to handle this callback
414 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
415 dump_handshake_info(wsi);
416 /* you could return non-zero here and kill the connection */
427 /* lws-mirror_protocol */
429 #define MAX_MESSAGE_QUEUE 128
431 struct per_session_data__lws_mirror {
432 struct libwebsocket *wsi;
441 static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
442 static int ringbuffer_head;
444 static struct libwebsocket *wsi_choked[20];
445 static int num_wsi_choked;
448 callback_lws_mirror(struct libwebsocket_context *context,
449 struct libwebsocket *wsi,
450 enum libwebsocket_callback_reasons reason,
451 void *user, void *in, size_t len)
454 struct per_session_data__lws_mirror *pss = (struct per_session_data__lws_mirror *)user;
458 case LWS_CALLBACK_ESTABLISHED:
459 lwsl_info("callback_lws_mirror: "
460 "LWS_CALLBACK_ESTABLISHED\n");
461 pss->ringbuffer_tail = ringbuffer_head;
465 case LWS_CALLBACK_PROTOCOL_DESTROY:
466 lwsl_notice("mirror protocol cleaning up\n");
467 for (n = 0; n < sizeof ringbuffer / sizeof ringbuffer[0]; n++)
468 if (ringbuffer[n].payload)
469 free(ringbuffer[n].payload);
472 case LWS_CALLBACK_SERVER_WRITEABLE:
475 while (pss->ringbuffer_tail != ringbuffer_head) {
477 n = libwebsocket_write(wsi, (unsigned char *)
478 ringbuffer[pss->ringbuffer_tail].payload +
479 LWS_SEND_BUFFER_PRE_PADDING,
480 ringbuffer[pss->ringbuffer_tail].len,
483 lwsl_err("ERROR %d writing to mirror socket\n", n);
486 if (n < ringbuffer[pss->ringbuffer_tail].len) {
487 lwsl_err("mirror partial write %d vs %d\n", n, ringbuffer[pss->ringbuffer_tail].len);
490 if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
491 pss->ringbuffer_tail = 0;
493 pss->ringbuffer_tail++;
495 if (((ringbuffer_head - pss->ringbuffer_tail) &
496 (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 15)) {
497 for (n = 0; n < num_wsi_choked; n++)
498 libwebsocket_rx_flow_control(wsi_choked[n], 1);
501 // lwsl_debug("tx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1));
503 if (lws_send_pipe_choked(wsi)) {
504 libwebsocket_callback_on_writable(context, wsi);
510 case LWS_CALLBACK_RECEIVE:
512 if (((ringbuffer_head - pss->ringbuffer_tail) &
513 (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 1)) {
514 lwsl_err("dropping!\n");
518 if (ringbuffer[ringbuffer_head].payload)
519 free(ringbuffer[ringbuffer_head].payload);
521 ringbuffer[ringbuffer_head].payload =
522 malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
523 LWS_SEND_BUFFER_POST_PADDING);
524 ringbuffer[ringbuffer_head].len = len;
525 memcpy((char *)ringbuffer[ringbuffer_head].payload +
526 LWS_SEND_BUFFER_PRE_PADDING, in, len);
527 if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
532 if (((ringbuffer_head - pss->ringbuffer_tail) &
533 (MAX_MESSAGE_QUEUE - 1)) != (MAX_MESSAGE_QUEUE - 2))
537 if (num_wsi_choked < sizeof wsi_choked / sizeof wsi_choked[0]) {
538 libwebsocket_rx_flow_control(wsi, 0);
539 wsi_choked[num_wsi_choked++] = wsi;
542 // lwsl_debug("rx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1));
544 libwebsocket_callback_on_writable_all_protocol(
545 libwebsockets_get_protocol(wsi));
549 * this just demonstrates how to use the protocol filter. If you won't
550 * study and reject connections based on header content, you don't need
551 * to handle this callback
554 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
555 dump_handshake_info(wsi);
556 /* you could return non-zero here and kill the connection */
567 /* list of supported protocols and callbacks */
569 static struct libwebsocket_protocols protocols[] = {
570 /* first protocol must always be HTTP handler */
573 "http-only", /* name */
574 callback_http, /* callback */
575 sizeof (struct per_session_data__http), /* per_session_data_size */
576 0, /* max frame size / rx buffer */
579 "dumb-increment-protocol",
580 callback_dumb_increment,
581 sizeof(struct per_session_data__dumb_increment),
585 "lws-mirror-protocol",
587 sizeof(struct per_session_data__lws_mirror),
590 { NULL, NULL, 0, 0 } /* terminator */
593 void sighandler(int sig)
598 static struct option options[] = {
599 { "help", no_argument, NULL, 'h' },
600 { "debug", required_argument, NULL, 'd' },
601 { "port", required_argument, NULL, 'p' },
602 { "ssl", no_argument, NULL, 's' },
603 { "interface", required_argument, NULL, 'i' },
604 { "closetest", no_argument, NULL, 'c' },
605 #ifndef LWS_NO_DAEMONIZE
606 { "daemonize", no_argument, NULL, 'D' },
611 int main(int argc, char **argv)
615 struct libwebsocket_context *context;
617 char interface_name[128] = "";
618 const char *iface = NULL;
620 int syslog_options = LOG_PID | LOG_PERROR;
622 unsigned int oldus = 0;
623 struct lws_context_creation_info info;
626 #ifndef LWS_NO_DAEMONIZE
630 memset(&info, 0, sizeof info);
634 n = getopt_long(argc, argv, "ci:hsp:d:D", options, NULL);
638 #ifndef LWS_NO_DAEMONIZE
642 syslog_options &= ~LOG_PERROR;
647 debug_level = atoi(optarg);
653 info.port = atoi(optarg);
656 strncpy(interface_name, optarg, sizeof interface_name);
657 interface_name[(sizeof interface_name) - 1] = '\0';
658 iface = interface_name;
662 fprintf(stderr, " Close testing mode -- closes on "
663 "client after 50 dumb increments"
664 "and suppresses lws_mirror spam\n");
667 fprintf(stderr, "Usage: test-server "
668 "[--port=<p>] [--ssl] "
669 "[-d <log bitfield>]\n");
674 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
676 * normally lock path would be /var/lock/lwsts or similar, to
677 * simplify getting started without having to take care about
678 * permissions or running as root, set to /tmp/.lwsts-lock
680 if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
681 fprintf(stderr, "Failed to daemonize\n");
686 signal(SIGINT, sighandler);
689 /* we will only try to log things according to our debug_level */
690 setlogmask(LOG_UPTO (LOG_DEBUG));
691 openlog("lwsts", syslog_options, LOG_DAEMON);
694 /* tell the library what debug level to emit and to send it to syslog */
695 lws_set_log_level(debug_level, lwsl_emit_syslog);
697 lwsl_notice("libwebsockets test server - "
698 "(C) Copyright 2010-2013 Andy Green <andy@warmcat.com> - "
699 "licensed under LGPL2.1\n");
701 max_poll_elements = getdtablesize();
702 pollfds = malloc(max_poll_elements * sizeof (struct pollfd));
703 fd_lookup = malloc(max_poll_elements * sizeof (int));
704 if (pollfds == NULL || fd_lookup == NULL) {
705 lwsl_err("Out of memory pollfds=%d\n", max_poll_elements);
711 info.protocols = protocols;
712 #ifndef LWS_NO_EXTENSIONS
713 info.extensions = libwebsocket_get_internal_extensions();
716 info.ssl_cert_filepath = NULL;
717 info.ssl_private_key_filepath = NULL;
719 info.ssl_cert_filepath = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
720 info.ssl_private_key_filepath = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
726 context = libwebsocket_create_context(&info);
727 if (context == NULL) {
728 lwsl_err("libwebsocket init failed\n");
733 while (n >= 0 && !force_exit) {
736 gettimeofday(&tv, NULL);
739 * This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every
740 * live websocket connection using the DUMB_INCREMENT protocol,
741 * as soon as it can take more packets (usually immediately)
744 if (((unsigned int)tv.tv_usec - oldus) > 50000) {
745 libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_DUMB_INCREMENT]);
752 * this represents an existing server's single poll action
753 * which also includes libwebsocket sockets
756 n = poll(pollfds, count_pollfds, 50);
762 for (n = 0; n < count_pollfds; n++)
763 if (pollfds[n].revents)
765 * returns immediately if the fd does not
766 * match anything under libwebsockets
769 if (libwebsocket_service_fd(context,
774 * If libwebsockets sockets are all we care about,
775 * you can use this api which takes care of the poll()
776 * and looping through finding who needed service.
778 * If no socket needs service, it'll return anyway after
779 * the number of ms in the second argument.
782 n = libwebsocket_service(context, 50);
790 libwebsocket_context_destroy(context);
792 lwsl_notice("libwebsockets-test-server exited cleanly\n");