Changed websockets lib, protocol not finalized at all

This commit is contained in:
KimLS
2014-07-15 22:52:18 -07:00
parent 4109b0b88d
commit e0bc0e2e5c
106 changed files with 37317 additions and 93 deletions
@@ -0,0 +1,9 @@
#Ignore build files
libwebsockets-test-*
Makefile
*.o
*.lo
*.la
.libs
.deps
+217
View File
@@ -0,0 +1,217 @@
#!/bin/sh
#
# attack the test server and try to make it fall over
#
SERVER=127.0.0.1
PORT=7681
LOG=/tmp/lwslog
CPID=
LEN=0
function check {
kill -0 $CPID
if [ $? -ne 0 ] ; then
echo "(killed it) *******"
exit 1
fi
dd if=$LOG bs=1 skip=$LEN 2>/dev/null
if [ "$1" = "default" ] ; then
diff /tmp/lwscap /usr/share/libwebsockets-test-server/test.html > /dev/null
if [ $? -ne 0 ] ; then
echo "FAIL: got something other than test.html back"
exit 1
fi
fi
if [ "$1" = "forbidden" ] ; then
if [ -z "`grep '<h1>403 Forbidden</h1>' /tmp/lwscap`" ] ; then
echo "FAIL: should have told forbidden (test server has no dirs)"
exit 1
fi
fi
if [ "$1" == "args" ] ; then
a="`dd if=$LOG bs=1 skip=$LEN 2>/dev/null |grep Uri.Args\: | tr -s ' ' | cut -d' ' -f4-`"
if [ "$a" != "$2" ] ; then
echo "Args '$a' not $2"
exit 1
fi
fi
LEN=`stat $LOG -c %s`
}
rm -rf $LOG
killall libwebsockets-test-server 2>/dev/null
libwebsockets-test-server -d31 2>> $LOG &
CPID=$!
while [ -z "`grep Listening $LOG`" ] ; do
sleep 0.5s
done
check
echo
echo "---- ? processing (%2f%2e%2e%2f%2e./test.html?arg=1)"
rm -f /tmp/lwscap
echo -e "GET %2f%2e%2e%2f%2e./test.html?arg=1 HTTP/1.1\x0d\x0a\x0d\x0a" | nc $SERVER $PORT | sed '1,/^\r$/d'> /tmp/lwscap
check args "arg=1"
echo
echo "---- ? processing (%2f%2e%2e%2f%2e./test.html?arg=/../.)"
rm -f /tmp/lwscap
echo -e "GET %2f%2e%2e%2f%2e./test.html?arg=/../. HTTP/1.1\x0d\x0a\x0d\x0a" | nc $SERVER $PORT | sed '1,/^\r$/d'> /tmp/lwscap
check args "arg=/../."
echo
echo "---- spam enough crap to not be GET"
echo "not GET" | nc $SERVER $PORT
check
echo
echo "---- spam more than the name buffer of crap"
dd if=/dev/urandom bs=1 count=80 2>/dev/null | nc -i1s $SERVER $PORT
check
echo
echo "---- spam 10MB of crap"
dd if=/dev/urandom bs=1 count=655360 | nc -i1s $SERVER $PORT
check
echo
echo "---- malformed URI"
echo "GET nonsense................................................................................................................" \
| nc -i1s $SERVER $PORT
check
echo
echo "---- missing URI"
echo -e "GET HTTP/1.1\x0d\x0a\x0d\x0a" | nc -i1s $SERVER $PORT >/tmp/lwscap
check
echo
echo "---- repeated method"
echo -e "GET blah HTTP/1.1\x0d\x0aGET blah HTTP/1.1\x0d\x0a\x0d\x0a" | nc $SERVER $PORT >/tmp/lwscap
check
echo
echo "---- crazy header name part"
echo -e "GET blah HTTP/1.1\x0d\x0a................................................................................................................" \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
| nc -i1s $SERVER $PORT
check
echo
echo "---- excessive uri content"
echo -e "GET ................................................................................................................" \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
| nc -i1s $SERVER $PORT
check
echo
echo "---- good request but http payload coming too (should be ignored and test.html served)"
echo -e "GET /test.html HTTP/1.1\x0d\x0a\x0d\x0aILLEGAL-PAYLOAD........................................" \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
"......................................................................................................................." \
| nc $SERVER $PORT | sed '1,/^\r$/d'> /tmp/lwscap
check default
echo
echo "---- directory attack 1 (/../../../../etc/passwd should be /etc/passswd)"
rm -f /tmp/lwscap
echo -e "GET /../../../../etc/passwd HTTP/1.1\x0d\x0a\x0d\x0a" | nc $SERVER $PORT | sed '1,/^\r$/d'> /tmp/lwscap
check forbidden
echo
echo "---- directory attack 2 (/../ should be /)"
rm -f /tmp/lwscap
echo -e "GET /../ HTTP/1.1\x0d\x0a\x0d\x0a" | nc $SERVER $PORT | sed '1,/^\r$/d'> /tmp/lwscap
check default
echo
echo "---- directory attack 3 (/./ should be /)"
rm -f /tmp/lwscap
echo -e "GET /./ HTTP/1.1\x0d\x0a\x0d\x0a" | nc $SERVER $PORT | sed '1,/^\r$/d'> /tmp/lwscap
check default
echo
echo "---- directory attack 4 (/blah/.. should be /)"
rm -f /tmp/lwscap
echo -e "GET /blah/.. HTTP/1.1\x0d\x0a\x0d\x0a" | nc $SERVER $PORT | sed '1,/^\r$/d'> /tmp/lwscap
check default
echo
echo "---- directory attack 5 (/blah/../ should be /)"
rm -f /tmp/lwscap
echo -e "GET /blah/../ HTTP/1.1\x0d\x0a\x0d\x0a" | nc $SERVER $PORT | sed '1,/^\r$/d'> /tmp/lwscap
check default
echo
echo "---- directory attack 6 (/blah/../. should be /)"
rm -f /tmp/lwscap
echo -e "GET /blah/../. HTTP/1.1\x0d\x0a\x0d\x0a" | nc $SERVER $PORT | sed '1,/^\r$/d'> /tmp/lwscap
check default
echo
echo "---- directory attack 7 (/%2e%2e%2f../../../etc/passwd should be /etc/passswd)"
rm -f /tmp/lwscap
echo -e "GET /%2e%2e%2f../../../etc/passwd HTTP/1.1\x0d\x0a\x0d\x0a" | nc $SERVER $PORT | sed '1,/^\r$/d'> /tmp/lwscap
check forbidden
echo
echo "---- directory attack 7 (%2f%2e%2e%2f%2e./.%2e/.%2e%2fetc/passwd should be /etc/passswd)"
rm -f /tmp/lwscap
echo -e "GET %2f%2e%2e%2f%2e./.%2e/.%2e%2fetc/passwd HTTP/1.1\x0d\x0a\x0d\x0a" | nc $SERVER $PORT | sed '1,/^\r$/d'> /tmp/lwscap
check forbidden
echo
echo "--- survived OK ---"
kill -2 $CPID
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

+392
View File
@@ -0,0 +1,392 @@
/*
* libwebsockets-test-client - libwebsockets test implementation
*
* Copyright (C) 2011 Andy Green <andy@warmcat.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation:
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <signal.h>
#ifdef _WIN32
#define random rand
#else
#include <unistd.h>
#endif
#ifdef CMAKE_BUILD
#include "lws_config.h"
#endif
#include "../lib/libwebsockets.h"
static unsigned int opts;
static int was_closed;
static int deny_deflate;
static int deny_mux;
static struct libwebsocket *wsi_mirror;
static int mirror_lifetime = 0;
static volatile int force_exit = 0;
static int longlived = 0;
/*
* This demo shows how to connect multiple websockets simultaneously to a
* websocket server (there is no restriction on their having to be the same
* server just it simplifies the demo).
*
* dumb-increment-protocol: we connect to the server and print the number
* we are given
*
* lws-mirror-protocol: draws random circles, which are mirrored on to every
* client (see them being drawn in every browser
* session also using the test server)
*/
enum demo_protocols {
PROTOCOL_DUMB_INCREMENT,
PROTOCOL_LWS_MIRROR,
/* always last */
DEMO_PROTOCOL_COUNT
};
/* dumb_increment protocol */
static int
callback_dumb_increment(struct libwebsocket_context *this,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len)
{
switch (reason) {
case LWS_CALLBACK_CLIENT_ESTABLISHED:
fprintf(stderr, "callback_dumb_increment: LWS_CALLBACK_CLIENT_ESTABLISHED\n");
break;
case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
fprintf(stderr, "LWS_CALLBACK_CLIENT_CONNECTION_ERROR\n");
was_closed = 1;
break;
case LWS_CALLBACK_CLOSED:
fprintf(stderr, "LWS_CALLBACK_CLOSED\n");
was_closed = 1;
break;
case LWS_CALLBACK_CLIENT_RECEIVE:
((char *)in)[len] = '\0';
fprintf(stderr, "rx %d '%s'\n", (int)len, (char *)in);
break;
/* because we are protocols[0] ... */
case LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED:
if ((strcmp(in, "deflate-stream") == 0) && deny_deflate) {
fprintf(stderr, "denied deflate-stream extension\n");
return 1;
}
if ((strcmp(in, "deflate-frame") == 0) && deny_deflate) {
fprintf(stderr, "denied deflate-frame extension\n");
return 1;
}
if ((strcmp(in, "x-google-mux") == 0) && deny_mux) {
fprintf(stderr, "denied x-google-mux extension\n");
return 1;
}
break;
default:
break;
}
return 0;
}
/* lws-mirror_protocol */
static int
callback_lws_mirror(struct libwebsocket_context *context,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len)
{
unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 4096 +
LWS_SEND_BUFFER_POST_PADDING];
int l = 0;
int n;
switch (reason) {
case LWS_CALLBACK_CLIENT_ESTABLISHED:
fprintf(stderr, "callback_lws_mirror: LWS_CALLBACK_CLIENT_ESTABLISHED\n");
mirror_lifetime = 10 + (random() & 1023);
/* useful to test single connection stability */
if (longlived)
mirror_lifetime += 50000;
fprintf(stderr, "opened mirror connection with "
"%d lifetime\n", mirror_lifetime);
/*
* mirror_lifetime is decremented each send, when it reaches
* zero the connection is closed in the send callback.
* When the close callback comes, wsi_mirror is set to NULL
* so a new connection will be opened
*/
/*
* start the ball rolling,
* LWS_CALLBACK_CLIENT_WRITEABLE will come next service
*/
libwebsocket_callback_on_writable(context, wsi);
break;
case LWS_CALLBACK_CLOSED:
fprintf(stderr, "mirror: LWS_CALLBACK_CLOSED mirror_lifetime=%d\n", mirror_lifetime);
wsi_mirror = NULL;
break;
case LWS_CALLBACK_CLIENT_RECEIVE:
/* fprintf(stderr, "rx %d '%s'\n", (int)len, (char *)in); */
break;
case LWS_CALLBACK_CLIENT_WRITEABLE:
for (n = 0; n < 1; n++)
l += sprintf((char *)&buf[LWS_SEND_BUFFER_PRE_PADDING + l],
"c #%06X %d %d %d;",
(int)random() & 0xffffff,
(int)random() % 500,
(int)random() % 250,
(int)random() % 24);
n = libwebsocket_write(wsi,
&buf[LWS_SEND_BUFFER_PRE_PADDING], l, opts | LWS_WRITE_TEXT);
if (n < 0)
return -1;
if (n < l) {
lwsl_err("Partial write LWS_CALLBACK_CLIENT_WRITEABLE\n");
return -1;
}
mirror_lifetime--;
if (!mirror_lifetime) {
fprintf(stderr, "closing mirror session\n");
return -1;
} else
/* get notified as soon as we can write again */
libwebsocket_callback_on_writable(context, wsi);
break;
default:
break;
}
return 0;
}
/* list of supported protocols and callbacks */
static struct libwebsocket_protocols protocols[] = {
{
"dumb-increment-protocol",
callback_dumb_increment,
0,
20,
},
{
"lws-mirror-protocol",
callback_lws_mirror,
0,
128,
},
{ NULL, NULL, 0, 0 } /* end */
};
void sighandler(int sig)
{
force_exit = 1;
}
static struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "debug", required_argument, NULL, 'd' },
{ "port", required_argument, NULL, 'p' },
{ "ssl", no_argument, NULL, 's' },
{ "version", required_argument, NULL, 'v' },
{ "undeflated", no_argument, NULL, 'u' },
{ "nomux", no_argument, NULL, 'n' },
{ "longlived", no_argument, NULL, 'l' },
{ NULL, 0, 0, 0 }
};
int main(int argc, char **argv)
{
int n = 0;
int ret = 0;
int port = 7681;
int use_ssl = 0;
struct libwebsocket_context *context;
const char *address;
struct libwebsocket *wsi_dumb;
int ietf_version = -1; /* latest */
struct lws_context_creation_info info;
memset(&info, 0, sizeof info);
fprintf(stderr, "libwebsockets test client\n"
"(C) Copyright 2010-2013 Andy Green <andy@warmcat.com> "
"licensed under LGPL2.1\n");
if (argc < 2)
goto usage;
while (n >= 0) {
n = getopt_long(argc, argv, "nuv:hsp:d:l", options, NULL);
if (n < 0)
continue;
switch (n) {
case 'd':
lws_set_log_level(atoi(optarg), NULL);
break;
case 's':
use_ssl = 2; /* 2 = allow selfsigned */
break;
case 'p':
port = atoi(optarg);
break;
case 'l':
longlived = 1;
break;
case 'v':
ietf_version = atoi(optarg);
break;
case 'u':
deny_deflate = 1;
break;
case 'n':
deny_mux = 1;
break;
case 'h':
goto usage;
}
}
if (optind >= argc)
goto usage;
signal(SIGINT, sighandler);
address = argv[optind];
/*
* create the websockets context. This tracks open connections and
* knows how to route any traffic and which protocol version to use,
* and if each connection is client or server side.
*
* For this client-only demo, we tell it to not listen on any port.
*/
info.port = CONTEXT_PORT_NO_LISTEN;
info.protocols = protocols;
#ifndef LWS_NO_EXTENSIONS
info.extensions = libwebsocket_get_internal_extensions();
#endif
info.gid = -1;
info.uid = -1;
context = libwebsocket_create_context(&info);
if (context == NULL) {
fprintf(stderr, "Creating libwebsocket context failed\n");
return 1;
}
/* create a client websocket using dumb increment protocol */
wsi_dumb = libwebsocket_client_connect(context, address, port, use_ssl,
"/", argv[optind], argv[optind],
protocols[PROTOCOL_DUMB_INCREMENT].name, ietf_version);
if (wsi_dumb == NULL) {
fprintf(stderr, "libwebsocket connect failed\n");
ret = 1;
goto bail;
}
fprintf(stderr, "Waiting for connect...\n");
/*
* sit there servicing the websocket context to handle incoming
* packets, and drawing random circles on the mirror protocol websocket
* nothing happens until the client websocket connection is
* asynchronously established
*/
n = 0;
while (n >= 0 && !was_closed && !force_exit) {
n = libwebsocket_service(context, 10);
if (n < 0)
continue;
if (wsi_mirror)
continue;
/* create a client websocket using mirror protocol */
wsi_mirror = libwebsocket_client_connect(context,
address, port, use_ssl, "/",
argv[optind], argv[optind],
protocols[PROTOCOL_LWS_MIRROR].name, ietf_version);
if (wsi_mirror == NULL) {
fprintf(stderr, "libwebsocket "
"mirror connect failed\n");
ret = 1;
goto bail;
}
}
bail:
fprintf(stderr, "Exiting\n");
libwebsocket_context_destroy(context);
return ret;
usage:
fprintf(stderr, "Usage: libwebsockets-test-client "
"<server address> [--port=<p>] "
"[--ssl] [-k] [-v <ver>] "
"[-d <log bitfield>] [-l]\n");
return 1;
}
+361
View File
@@ -0,0 +1,361 @@
/*
* libwebsockets-test-echo - libwebsockets echo test implementation
*
* This implements both the client and server sides. It defaults to
* serving, use --client <remote address> to connect as client.
*
* Copyright (C) 2010-2013 Andy Green <andy@warmcat.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation:
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <assert.h>
#include <signal.h>
#ifndef _WIN32
#include <syslog.h>
#include <sys/time.h>
#include <unistd.h>
#endif
#ifdef CMAKE_BUILD
#include "lws_config.h"
#endif
#include "../lib/libwebsockets.h"
static volatile int force_exit = 0;
#define MAX_ECHO_PAYLOAD 1400
#define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
struct per_session_data__echo {
unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_ECHO_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
unsigned int len;
unsigned int index;
};
static int
callback_echo(struct libwebsocket_context *context,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason, void *user,
void *in, size_t len)
{
struct per_session_data__echo *pss = (struct per_session_data__echo *)user;
int n;
switch (reason) {
#ifndef LWS_NO_SERVER
/* when the callback is used for server operations --> */
case LWS_CALLBACK_SERVER_WRITEABLE:
n = libwebsocket_write(wsi, &pss->buf[LWS_SEND_BUFFER_PRE_PADDING], pss->len, LWS_WRITE_TEXT);
if (n < 0) {
lwsl_err("ERROR %d writing to socket, hanging up\n", n);
return 1;
}
if (n < (int)pss->len) {
lwsl_err("Partial write\n");
return -1;
}
break;
case LWS_CALLBACK_RECEIVE:
if (len > MAX_ECHO_PAYLOAD) {
lwsl_err("Server received packet bigger than %u, hanging up\n", MAX_ECHO_PAYLOAD);
return 1;
}
memcpy(&pss->buf[LWS_SEND_BUFFER_PRE_PADDING], in, len);
pss->len = (unsigned int)len;
libwebsocket_callback_on_writable(context, wsi);
break;
#endif
#ifndef LWS_NO_CLIENT
/* when the callback is used for client operations --> */
case LWS_CALLBACK_CLIENT_ESTABLISHED:
lwsl_notice("Client has connected\n");
pss->index = 0;
break;
case LWS_CALLBACK_CLIENT_RECEIVE:
lwsl_notice("Client RX: %s", (char *)in);
break;
case LWS_CALLBACK_CLIENT_WRITEABLE:
/* we will send our packet... */
pss->len = sprintf((char *)&pss->buf[LWS_SEND_BUFFER_PRE_PADDING], "hello from libwebsockets-test-echo client pid %d index %d\n", getpid(), pss->index++);
lwsl_notice("Client TX: %s", &pss->buf[LWS_SEND_BUFFER_PRE_PADDING]);
n = libwebsocket_write(wsi, &pss->buf[LWS_SEND_BUFFER_PRE_PADDING], pss->len, LWS_WRITE_TEXT);
if (n < 0) {
lwsl_err("ERROR %d writing to socket, hanging up\n", n);
return -1;
}
if (n < (int)pss->len) {
lwsl_err("Partial write\n");
return -1;
}
break;
#endif
default:
break;
}
return 0;
}
static struct libwebsocket_protocols protocols[] = {
/* first protocol must always be HTTP handler */
{
"default", /* name */
callback_echo, /* callback */
sizeof(struct per_session_data__echo) /* per_session_data_size */
},
{
NULL, NULL, 0 /* End of list */
}
};
void sighandler(int sig)
{
force_exit = 1;
}
static struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "debug", required_argument, NULL, 'd' },
{ "port", required_argument, NULL, 'p' },
#ifndef LWS_NO_CLIENT
{ "client", required_argument, NULL, 'c' },
{ "ratems", required_argument, NULL, 'r' },
#endif
{ "ssl", no_argument, NULL, 's' },
{ "interface", required_argument, NULL, 'i' },
#ifndef LWS_NO_DAEMONIZE
{ "daemonize", no_argument, NULL, 'D' },
#endif
{ NULL, 0, 0, 0 }
};
int main(int argc, char **argv)
{
int n = 0;
int port = 7681;
int use_ssl = 0;
struct libwebsocket_context *context;
int opts = 0;
char interface_name[128] = "";
const char *interface = NULL;
#ifndef WIN32
int syslog_options = LOG_PID | LOG_PERROR;
#endif
int client = 0;
int listen_port;
struct lws_context_creation_info info;
#ifndef LWS_NO_CLIENT
char address[256];
int rate_us = 250000;
unsigned int oldus = 0;
struct libwebsocket *wsi;
#endif
int debug_level = 7;
#ifndef LWS_NO_DAEMONIZE
int daemonize = 0;
#endif
memset(&info, 0, sizeof info);
#ifndef LWS_NO_CLIENT
lwsl_notice("Built to support client operations\n");
#endif
#ifndef LWS_NO_SERVER
lwsl_notice("Built to support server operations\n");
#endif
while (n >= 0) {
n = getopt_long(argc, argv, "i:hsp:d:D"
#ifndef LWS_NO_CLIENT
"c:r:"
#endif
, options, NULL);
if (n < 0)
continue;
switch (n) {
#ifndef LWS_NO_DAEMONIZE
case 'D':
daemonize = 1;
#ifndef WIN32
syslog_options &= ~LOG_PERROR;
#endif
break;
#endif
#ifndef LWS_NO_CLIENT
case 'c':
client = 1;
strcpy(address, optarg);
port = 80;
break;
case 'r':
rate_us = atoi(optarg) * 1000;
break;
#endif
case 'd':
debug_level = atoi(optarg);
break;
case 's':
use_ssl = 1; /* 1 = take care about cert verification, 2 = allow anything */
break;
case 'p':
port = atoi(optarg);
break;
case 'i':
strncpy(interface_name, optarg, sizeof interface_name);
interface_name[(sizeof interface_name) - 1] = '\0';
interface = interface_name;
break;
case '?':
case 'h':
fprintf(stderr, "Usage: libwebsockets-test-echo "
"[--ssl] "
#ifndef LWS_NO_CLIENT
"[--client <remote ads>] "
"[--ratems <ms>] "
#endif
"[--port=<p>] "
"[-d <log bitfield>]\n");
exit(1);
}
}
#ifndef LWS_NO_DAEMONIZE
/*
* normally lock path would be /var/lock/lwsts or similar, to
* simplify getting started without having to take care about
* permissions or running as root, set to /tmp/.lwsts-lock
*/
#if defined(WIN32) || defined(_WIN32)
#else
if (!client && daemonize && lws_daemonize("/tmp/.lwstecho-lock")) {
fprintf(stderr, "Failed to daemonize\n");
return 1;
}
#endif
#endif
#ifdef WIN32
#else
/* we will only try to log things according to our debug_level */
setlogmask(LOG_UPTO (LOG_DEBUG));
openlog("lwsts", syslog_options, LOG_DAEMON);
/* tell the library what debug level to emit and to send it to syslog */
lws_set_log_level(debug_level, lwsl_emit_syslog);
#endif
lwsl_notice("libwebsockets echo test - "
"(C) Copyright 2010-2013 Andy Green <andy@warmcat.com> - "
"licensed under LGPL2.1\n");
#ifndef LWS_NO_CLIENT
if (client) {
lwsl_notice("Running in client mode\n");
listen_port = CONTEXT_PORT_NO_LISTEN;
if (use_ssl)
use_ssl = 2;
} else {
#endif
#ifndef LWS_NO_SERVER
lwsl_notice("Running in server mode\n");
listen_port = port;
#endif
#ifndef LWS_NO_CLIENT
}
#endif
info.port = listen_port;
info.iface = interface;
info.protocols = protocols;
#ifndef LWS_NO_EXTENSIONS
info.extensions = libwebsocket_get_internal_extensions();
#endif
if (use_ssl && !client) {
info.ssl_cert_filepath = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
info.ssl_private_key_filepath = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
}
info.gid = -1;
info.uid = -1;
info.options = opts;
context = libwebsocket_create_context(&info);
if (context == NULL) {
lwsl_err("libwebsocket init failed\n");
return -1;
}
#ifndef LWS_NO_CLIENT
if (client) {
lwsl_notice("Client connecting to %s:%u....\n", address, port);
/* we are in client mode */
wsi = libwebsocket_client_connect(context, address,
port, use_ssl, "/", address,
"origin", NULL, -1);
if (!wsi) {
lwsl_err("Client failed to connect to %s:%u\n", address, port);
goto bail;
}
lwsl_notice("Client connected to %s:%u\n", address, port);
}
#endif
signal(SIGINT, sighandler);
n = 0;
while (n >= 0 && !force_exit) {
#ifndef LWS_NO_CLIENT
struct timeval tv;
if (client) {
gettimeofday(&tv, NULL);
if (((unsigned int)tv.tv_usec - oldus) > (unsigned int)rate_us) {
libwebsocket_callback_on_writable_all_protocol(&protocols[0]);
oldus = tv.tv_usec;
}
}
#endif
n = libwebsocket_service(context, 10);
}
#ifndef LWS_NO_CLIENT
bail:
#endif
libwebsocket_context_destroy(context);
lwsl_notice("libwebsockets-test-echo exited cleanly\n");
#ifdef WIN32
#else
closelog();
#endif
return 0;
}
+358
View File
@@ -0,0 +1,358 @@
/*
* libwebsockets-test-fraggle - random fragmentation test
*
* Copyright (C) 2010-2011 Andy Green <andy@warmcat.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation:
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include "../lib/libwebsockets.h"
#define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
static int client;
static int terminate;
enum demo_protocols {
PROTOCOL_FRAGGLE,
/* always last */
DEMO_PROTOCOL_COUNT
};
/* fraggle protocol */
enum fraggle_states {
FRAGSTATE_START_MESSAGE,
FRAGSTATE_RANDOM_PAYLOAD,
FRAGSTATE_POST_PAYLOAD_SUM,
};
struct per_session_data__fraggle {
int packets_left;
int total_message;
unsigned long sum;
enum fraggle_states state;
};
static int
callback_fraggle(struct libwebsocket_context *context,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len)
{
int n;
unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 8000 +
LWS_SEND_BUFFER_POST_PADDING];
struct per_session_data__fraggle *psf = user;
int chunk;
int write_mode = LWS_WRITE_CONTINUATION;
unsigned long sum;
unsigned char *p = (unsigned char *)in;
unsigned char *bp = &buf[LWS_SEND_BUFFER_PRE_PADDING];
switch (reason) {
case LWS_CALLBACK_ESTABLISHED:
fprintf(stderr, "server sees client connect\n");
psf->state = FRAGSTATE_START_MESSAGE;
/* start the ball rolling */
libwebsocket_callback_on_writable(context, wsi);
break;
case LWS_CALLBACK_CLIENT_ESTABLISHED:
fprintf(stderr, "client connects to server\n");
psf->state = FRAGSTATE_START_MESSAGE;
break;
case LWS_CALLBACK_CLIENT_RECEIVE:
switch (psf->state) {
case FRAGSTATE_START_MESSAGE:
psf->state = FRAGSTATE_RANDOM_PAYLOAD;
psf->sum = 0;
psf->total_message = 0;
psf->packets_left = 0;
/* fallthru */
case FRAGSTATE_RANDOM_PAYLOAD:
for (n = 0; n < len; n++)
psf->sum += p[n];
psf->total_message += len;
psf->packets_left++;
if (libwebsocket_is_final_fragment(wsi))
psf->state = FRAGSTATE_POST_PAYLOAD_SUM;
break;
case FRAGSTATE_POST_PAYLOAD_SUM:
sum = p[0] << 24;
sum |= p[1] << 16;
sum |= p[2] << 8;
sum |= p[3];
if (sum == psf->sum)
fprintf(stderr, "EOM received %d correctly "
"from %d fragments\n",
psf->total_message, psf->packets_left);
else
fprintf(stderr, "**** ERROR at EOM: "
"length %d, rx sum = 0x%lX, "
"server says it sent 0x%lX\n",
psf->total_message, psf->sum, sum);
psf->state = FRAGSTATE_START_MESSAGE;
break;
}
break;
case LWS_CALLBACK_SERVER_WRITEABLE:
switch (psf->state) {
case FRAGSTATE_START_MESSAGE:
psf->packets_left = (random() % 1024) + 1;
fprintf(stderr, "Spamming %d random fragments\n",
psf->packets_left);
psf->sum = 0;
psf->total_message = 0;
write_mode = LWS_WRITE_BINARY;
psf->state = FRAGSTATE_RANDOM_PAYLOAD;
/* fallthru */
case FRAGSTATE_RANDOM_PAYLOAD:
/*
* note how one chunk can be 8000, but we use the
* default rx buffer size of 4096, so we exercise the
* code for rx spill because the rx buffer is full
*/
chunk = (random() % 8000) + 1;
psf->total_message += chunk;
libwebsockets_get_random(context, bp, chunk);
for (n = 0; n < chunk; n++)
psf->sum += bp[n];
psf->packets_left--;
if (psf->packets_left)
write_mode |= LWS_WRITE_NO_FIN;
else
psf->state = FRAGSTATE_POST_PAYLOAD_SUM;
n = libwebsocket_write(wsi, bp, chunk, write_mode);
if (n < 0)
return -1;
if (n < chunk) {
lwsl_err("Partial write\n");
return -1;
}
libwebsocket_callback_on_writable(context, wsi);
break;
case FRAGSTATE_POST_PAYLOAD_SUM:
fprintf(stderr, "Spamming session over, "
"len = %d. sum = 0x%lX\n",
psf->total_message, psf->sum);
bp[0] = psf->sum >> 24;
bp[1] = psf->sum >> 16;
bp[2] = psf->sum >> 8;
bp[3] = psf->sum;
n = libwebsocket_write(wsi, (unsigned char *)bp,
4, LWS_WRITE_BINARY);
if (n < 0)
return -1;
if (n < 4) {
lwsl_err("Partial write\n");
return -1;
}
psf->state = FRAGSTATE_START_MESSAGE;
libwebsocket_callback_on_writable(context, wsi);
break;
}
break;
case LWS_CALLBACK_CLOSED:
terminate = 1;
break;
/* because we are protocols[0] ... */
case LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED:
if (strcmp(in, "deflate-stream") == 0) {
fprintf(stderr, "denied deflate-stream extension\n");
return 1;
}
break;
default:
break;
}
return 0;
}
/* list of supported protocols and callbacks */
static struct libwebsocket_protocols protocols[] = {
{
"fraggle-protocol",
callback_fraggle,
sizeof(struct per_session_data__fraggle),
},
{
NULL, NULL, 0 /* End of list */
}
};
static struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "debug", required_argument, NULL, 'd' },
{ "port", required_argument, NULL, 'p' },
{ "ssl", no_argument, NULL, 's' },
{ "interface", required_argument, NULL, 'i' },
{ "client", no_argument, NULL, 'c' },
{ NULL, 0, 0, 0 }
};
int main(int argc, char **argv)
{
int n = 0;
int port = 7681;
int use_ssl = 0;
struct libwebsocket_context *context;
int opts = 0;
char interface_name[128] = "";
const char *iface = NULL;
struct libwebsocket *wsi;
const char *address;
int server_port = port;
struct lws_context_creation_info info;
memset(&info, 0, sizeof info);
fprintf(stderr, "libwebsockets test fraggle\n"
"(C) Copyright 2010-2013 Andy Green <andy@warmcat.com> "
"licensed under LGPL2.1\n");
while (n >= 0) {
n = getopt_long(argc, argv, "ci:hsp:d:", options, NULL);
if (n < 0)
continue;
switch (n) {
case 'd':
lws_set_log_level(atoi(optarg), NULL);
break;
case 's':
use_ssl = 1;
break;
case 'p':
port = atoi(optarg);
server_port = port;
break;
case 'i':
strncpy(interface_name, optarg, sizeof interface_name);
interface_name[(sizeof interface_name) - 1] = '\0';
iface = interface_name;
break;
case 'c':
client = 1;
fprintf(stderr, " Client mode\n");
break;
case 'h':
fprintf(stderr, "Usage: libwebsockets-test-fraggle "
"[--port=<p>] [--ssl] "
"[-d <log bitfield>] "
"[--client]\n");
exit(1);
}
}
if (client) {
server_port = CONTEXT_PORT_NO_LISTEN;
if (optind >= argc) {
fprintf(stderr, "Must give address of server\n");
return 1;
}
}
info.port = server_port;
info.iface = iface;
info.protocols = protocols;
#ifndef LWS_NO_EXTENSIONS
info.extensions = libwebsocket_get_internal_extensions();
#endif
if (use_ssl) {
info.ssl_cert_filepath = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
info.ssl_private_key_filepath = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
}
info.gid = -1;
info.uid = -1;
info.options = opts;
context = libwebsocket_create_context(&info);
if (context == NULL) {
fprintf(stderr, "libwebsocket init failed\n");
return -1;
}
if (client) {
address = argv[optind];
fprintf(stderr, "Connecting to %s:%u\n", address, port);
wsi = libwebsocket_client_connect(context, address,
port, use_ssl, "/", address,
"origin", protocols[PROTOCOL_FRAGGLE].name,
-1);
if (wsi == NULL) {
fprintf(stderr, "Client connect to server failed\n");
goto bail;
}
}
n = 0;
while (!n && !terminate)
n = libwebsocket_service(context, 50);
fprintf(stderr, "Terminating...\n");
bail:
libwebsocket_context_destroy(context);
return 0;
}
+543
View File
@@ -0,0 +1,543 @@
/*
* libwebsockets-test-ping - libwebsockets floodping
*
* Copyright (C) 2011 Andy Green <andy@warmcat.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation:
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#ifndef _WIN32
#include <netdb.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <poll.h>
#include <unistd.h>
#endif
#ifdef CMAKE_BUILD
#include "lws_config.h"
#endif
#include "../lib/libwebsockets.h"
/*
* this is specified in the 04 standard, control frames can only have small
* payload length styles
*/
#define MAX_PING_PAYLOAD 125
#define MAX_MIRROR_PAYLOAD 4096
#define MAX_PING_CLIENTS 256
#define PING_RINGBUFFER_SIZE 256
static struct libwebsocket *ping_wsi[MAX_PING_CLIENTS];
static unsigned int interval_us = 1000000;
static unsigned int size = 64;
static int flood;
static const char *address;
static unsigned char pingbuf[LWS_SEND_BUFFER_PRE_PADDING + MAX_MIRROR_PAYLOAD +
LWS_SEND_BUFFER_POST_PADDING];
static char peer_name[128];
static unsigned long started;
static int screen_width = 80;
static int use_mirror;
static unsigned int write_options;
static unsigned long rtt_min = 100000000;
static unsigned long rtt_max;
static unsigned long rtt_avg;
static unsigned long global_rx_count;
static unsigned long global_tx_count;
static int clients = 1;
static unsigned long interrupted_time;
struct ping {
unsigned long issue_timestamp;
unsigned long index;
unsigned int seen;
};
struct per_session_data__ping {
unsigned long ping_index;
struct ping ringbuffer[PING_RINGBUFFER_SIZE];
int ringbuffer_head;
int ringbuffer_tail;
unsigned long rx_count;
};
/*
* uses the ping pong protocol features to provide an equivalent for the
* ping utility for 04+ websockets
*/
enum demo_protocols {
PROTOCOL_LWS_MIRROR,
/* always last */
DEMO_PROTOCOL_COUNT
};
static int
callback_lws_mirror(struct libwebsocket_context * this,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len)
{
struct timeval tv;
unsigned char *p;
int shift;
unsigned long l;
unsigned long iv;
int n;
int match = 0;
struct per_session_data__ping *psd = user;
switch (reason) {
case LWS_CALLBACK_CLOSED:
fprintf(stderr, "LWS_CALLBACK_CLOSED on %p\n", (void *)wsi);
/* remove closed guy */
for (n = 0; n < clients; n++)
if (ping_wsi[n] == wsi) {
clients--;
while (n < clients) {
ping_wsi[n] = ping_wsi[n + 1];
n++;
}
}
break;
case LWS_CALLBACK_CLIENT_ESTABLISHED:
psd->rx_count = 0;
psd->ping_index = 1;
psd->ringbuffer_head = 0;
psd->ringbuffer_tail = 0;
/*
* start the ball rolling,
* LWS_CALLBACK_CLIENT_WRITEABLE will come next service
*/
libwebsocket_callback_on_writable(this, wsi);
break;
case LWS_CALLBACK_CLIENT_RECEIVE:
case LWS_CALLBACK_CLIENT_RECEIVE_PONG:
gettimeofday(&tv, NULL);
iv = (tv.tv_sec * 1000000) + tv.tv_usec;
psd->rx_count++;
shift = 56;
p = in;
l = 0;
while (shift >= 0) {
l |= (*p++) << shift;
shift -= 8;
}
/* find it in the ringbuffer, look backwards from head */
n = psd->ringbuffer_head;
while (!match) {
if (psd->ringbuffer[n].index == l) {
psd->ringbuffer[n].seen++;
match = 1;
continue;
}
if (n == psd->ringbuffer_tail) {
match = -1;
continue;
}
if (n == 0)
n = PING_RINGBUFFER_SIZE - 1;
else
n--;
}
if (match < 1) {
if (!flood)
fprintf(stderr, "%d bytes from %s: req=%ld "
"time=(unknown)\n", (int)len, address, l);
else
fprintf(stderr, "\b \b");
break;
}
if (psd->ringbuffer[n].seen > 1)
fprintf(stderr, "DUP! ");
if ((iv - psd->ringbuffer[n].issue_timestamp) < rtt_min)
rtt_min = iv - psd->ringbuffer[n].issue_timestamp;
if ((iv - psd->ringbuffer[n].issue_timestamp) > rtt_max)
rtt_max = iv - psd->ringbuffer[n].issue_timestamp;
rtt_avg += iv - psd->ringbuffer[n].issue_timestamp;
global_rx_count++;
if (!flood)
fprintf(stderr, "%d bytes from %s: req=%ld "
"time=%lu.%lums\n", (int)len, address, l,
(iv - psd->ringbuffer[n].issue_timestamp) / 1000,
((iv - psd->ringbuffer[n].issue_timestamp) / 100) % 10);
else
fprintf(stderr, "\b \b");
break;
case LWS_CALLBACK_CLIENT_WRITEABLE:
shift = 56;
p = &pingbuf[LWS_SEND_BUFFER_PRE_PADDING];
/* 64-bit ping index in network byte order */
while (shift >= 0) {
*p++ = psd->ping_index >> shift;
shift -= 8;
}
while (p - &pingbuf[LWS_SEND_BUFFER_PRE_PADDING] < size)
*p++ = 0;
gettimeofday(&tv, NULL);
psd->ringbuffer[psd->ringbuffer_head].issue_timestamp =
(tv.tv_sec * 1000000) + tv.tv_usec;
psd->ringbuffer[psd->ringbuffer_head].index = psd->ping_index++;
psd->ringbuffer[psd->ringbuffer_head].seen = 0;
if (psd->ringbuffer_head == PING_RINGBUFFER_SIZE - 1)
psd->ringbuffer_head = 0;
else
psd->ringbuffer_head++;
/* snip any re-used tail so we keep to the ring length */
if (psd->ringbuffer_tail == psd->ringbuffer_head) {
if (psd->ringbuffer_tail == PING_RINGBUFFER_SIZE - 1)
psd->ringbuffer_tail = 0;
else
psd->ringbuffer_tail++;
}
global_tx_count++;
if (use_mirror)
n = libwebsocket_write(wsi,
&pingbuf[LWS_SEND_BUFFER_PRE_PADDING],
size, write_options | LWS_WRITE_BINARY);
else
n = libwebsocket_write(wsi,
&pingbuf[LWS_SEND_BUFFER_PRE_PADDING],
size, write_options | LWS_WRITE_PING);
if (n < 0)
return -1;
if (n < size) {
lwsl_err("Partial write\n");
return -1;
}
if (flood &&
(psd->ping_index - psd->rx_count) < (screen_width - 1))
fprintf(stderr, ".");
break;
default:
break;
}
return 0;
}
/* list of supported protocols and callbacks */
static struct libwebsocket_protocols protocols[] = {
{
"lws-mirror-protocol",
callback_lws_mirror,
sizeof (struct per_session_data__ping),
},
{
NULL, NULL, 0/* end of list */
}
};
static struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "debug", required_argument, NULL, 'd' },
{ "port", required_argument, NULL, 'p' },
{ "ssl", no_argument, NULL, 't' },
{ "interval", required_argument, NULL, 'i' },
{ "size", required_argument, NULL, 's' },
{ "protocol", required_argument, NULL, 'n' },
{ "flood", no_argument, NULL, 'f' },
{ "mirror", no_argument, NULL, 'm' },
{ "replicate", required_argument, NULL, 'r' },
{ "killmask", no_argument, NULL, 'k' },
{ "version", required_argument, NULL, 'v' },
{ NULL, 0, 0, 0 }
};
#ifndef WIN32
static void
signal_handler(int sig, siginfo_t *si, void *v)
{
struct timeval tv;
gettimeofday(&tv, NULL);
interrupted_time = (tv.tv_sec * 1000000) + tv.tv_usec;
}
#endif
int main(int argc, char **argv)
{
int n = 0;
int port = 7681;
int use_ssl = 0;
struct libwebsocket_context *context;
char protocol_name[256];
char ip[30];
#ifndef WIN32
struct sigaction sa;
struct winsize w;
#endif
struct timeval tv;
unsigned long oldus = 0;
unsigned long l;
int ietf_version = -1;
struct lws_context_creation_info info;
memset(&info, 0, sizeof info);
if (argc < 2)
goto usage;
address = argv[1];
optind++;
while (n >= 0) {
n = getopt_long(argc, argv, "v:kr:hmfts:n:i:p:d:", options, NULL);
if (n < 0)
continue;
switch (n) {
case 'd':
lws_set_log_level(atoi(optarg), NULL);
break;
case 'm':
use_mirror = 1;
break;
case 't':
use_ssl = 2; /* 2 = allow selfsigned */
break;
case 'p':
port = atoi(optarg);
break;
case 'n':
strncpy(protocol_name, optarg, sizeof protocol_name);
protocol_name[(sizeof protocol_name) - 1] = '\0';
protocols[PROTOCOL_LWS_MIRROR].name = protocol_name;
break;
case 'i':
interval_us = 1000000.0 * atof(optarg);
break;
case 's':
size = atoi(optarg);
break;
case 'f':
flood = 1;
break;
case 'r':
clients = atoi(optarg);
if (clients > MAX_PING_CLIENTS || clients < 1) {
fprintf(stderr, "Max clients supportd = %d\n",
MAX_PING_CLIENTS);
return 1;
}
break;
case 'k':
write_options = LWS_WRITE_CLIENT_IGNORE_XOR_MASK;
break;
case 'v':
ietf_version = atoi(optarg);
break;
case 'h':
goto usage;
}
}
if (!use_mirror) {
if (size > MAX_PING_PAYLOAD) {
fprintf(stderr, "Max ping opcode payload size %d\n",
MAX_PING_PAYLOAD);
return 1;
}
} else {
if (size > MAX_MIRROR_PAYLOAD) {
fprintf(stderr, "Max mirror payload size %d\n",
MAX_MIRROR_PAYLOAD);
return 1;
}
}
#ifndef WIN32
if (isatty(STDOUT_FILENO))
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1)
if (w.ws_col > 0)
screen_width = w.ws_col;
#endif
info.port = CONTEXT_PORT_NO_LISTEN;
info.protocols = protocols;
#ifndef LWS_NO_EXTENSIONS
info.extensions = libwebsocket_get_internal_extensions();
#endif
info.gid = -1;
info.uid = -1;
context = libwebsocket_create_context(&info);
if (context == NULL) {
fprintf(stderr, "Creating libwebsocket context failed\n");
return 1;
}
/* create client websockets using dumb increment protocol */
for (n = 0; n < clients; n++) {
ping_wsi[n] = libwebsocket_client_connect(context, address,
port, use_ssl, "/", address,
"origin", protocols[PROTOCOL_LWS_MIRROR].name,
ietf_version);
if (ping_wsi[n] == NULL) {
fprintf(stderr, "client connection %d failed to "
"connect\n", n);
return 1;
}
}
libwebsockets_get_peer_addresses(context, ping_wsi[0],
libwebsocket_get_socket_fd(ping_wsi[0]),
peer_name, sizeof peer_name, ip, sizeof ip);
fprintf(stderr, "Websocket PING %s (%s) %d bytes of data.\n",
peer_name, ip, size);
#ifndef WIN32
/* set the ^C handler */
sa.sa_sigaction = signal_handler;
sa.sa_flags = SA_SIGINFO;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
#endif
gettimeofday(&tv, NULL);
started = (tv.tv_sec * 1000000) + tv.tv_usec;
/* service loop */
n = 0;
while (n >= 0) {
gettimeofday(&tv, NULL);
l = (tv.tv_sec * 1000000) + tv.tv_usec;
/* servers can hang up on us */
if (clients == 0) {
n = -1;
continue;
}
if (!interrupted_time) {
if ((l - oldus) > interval_us) {
for (n = 0; n < clients; n++)
libwebsocket_callback_on_writable(
context, ping_wsi[n]);
oldus = l;
}
} else
/* allow time for in-flight pongs to come */
if ((l - interrupted_time) > 250000) {
n = -1;
continue;
}
if (!interval_us)
n = libwebsocket_service(context, 0);
else
n = libwebsocket_service(context, 1);
}
/* stats */
fprintf(stderr, "\n--- %s websocket ping statistics "
"using %d connections ---\n"
"%lu packets transmitted, %lu received, "
"%lu%% packet loss, time %ldms\n"
"rtt min/avg/max = %0.3f/%0.3f/%0.3f ms\n"
"payload bandwidth average %0.3f KiBytes/sec\n",
peer_name, clients, global_tx_count, global_rx_count,
((global_tx_count - global_rx_count) * 100) / global_tx_count,
(l - started) / 1000,
((double)rtt_min) / 1000.0,
((double)rtt_avg / global_rx_count) / 1000.0,
((double)rtt_max) / 1000.0,
((double)global_rx_count * (double)size) /
((double)(l - started) / 1000000.0) / 1024.0);
libwebsocket_context_destroy(context);
return 0;
usage:
fprintf(stderr, "Usage: libwebsockets-test-ping "
"<server address> [--port=<p>] "
"[--ssl] [--interval=<float sec>] "
"[--size=<bytes>] "
"[--protocol=<protocolname>] "
"[--mirror] "
"[--replicate=clients>] "
"[--version <version>] "
"[-d <log bitfield> ]"
"\n");
return 1;
}
+968
View File
@@ -0,0 +1,968 @@
/*
* libwebsockets-test-server - libwebsockets test implementation
*
* Copyright (C) 2010-2011 Andy Green <andy@warmcat.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation:
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
#ifdef CMAKE_BUILD
#include "lws_config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <signal.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#ifdef _WIN32
#include <io.h>
#ifdef EXTERNAL_POLL
#define poll WSAPoll
#endif
#else
#include <syslog.h>
#include <sys/time.h>
#include <unistd.h>
#endif
#include "../lib/libwebsockets.h"
static int close_testing;
int max_poll_elements;
struct pollfd *pollfds;
int *fd_lookup;
int count_pollfds;
static volatile int force_exit = 0;
static struct libwebsocket_context *context;
/*
* This demo server shows how to use libwebsockets for one or more
* websocket protocols in the same server
*
* It defines the following websocket protocols:
*
* dumb-increment-protocol: once the socket is opened, an incrementing
* ascii string is sent down it every 50ms.
* If you send "reset\n" on the websocket, then
* the incrementing number is reset to 0.
*
* lws-mirror-protocol: copies any received packet to every connection also
* using this protocol, including the sender
*/
enum demo_protocols {
/* always first */
PROTOCOL_HTTP = 0,
PROTOCOL_DUMB_INCREMENT,
PROTOCOL_LWS_MIRROR,
/* always last */
DEMO_PROTOCOL_COUNT
};
#define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
char *resource_path = LOCAL_RESOURCE_PATH;
/*
* We take a strict whitelist approach to stop ../ attacks
*/
struct serveable {
const char *urlpath;
const char *mimetype;
};
struct per_session_data__http {
int fd;
};
/*
* this is just an example of parsing handshake headers, you don't need this
* in your code unless you will filter allowing connections by the header
* content
*/
static void
dump_handshake_info(struct libwebsocket *wsi)
{
int n;
static const char *token_names[] = {
/*[WSI_TOKEN_GET_URI] =*/ "GET URI",
/*[WSI_TOKEN_POST_URI] =*/ "POST URI",
/*[WSI_TOKEN_HOST] =*/ "Host",
/*[WSI_TOKEN_CONNECTION] =*/ "Connection",
/*[WSI_TOKEN_KEY1] =*/ "key 1",
/*[WSI_TOKEN_KEY2] =*/ "key 2",
/*[WSI_TOKEN_PROTOCOL] =*/ "Protocol",
/*[WSI_TOKEN_UPGRADE] =*/ "Upgrade",
/*[WSI_TOKEN_ORIGIN] =*/ "Origin",
/*[WSI_TOKEN_DRAFT] =*/ "Draft",
/*[WSI_TOKEN_CHALLENGE] =*/ "Challenge",
/* new for 04 */
/*[WSI_TOKEN_KEY] =*/ "Key",
/*[WSI_TOKEN_VERSION] =*/ "Version",
/*[WSI_TOKEN_SWORIGIN] =*/ "Sworigin",
/* new for 05 */
/*[WSI_TOKEN_EXTENSIONS] =*/ "Extensions",
/* client receives these */
/*[WSI_TOKEN_ACCEPT] =*/ "Accept",
/*[WSI_TOKEN_NONCE] =*/ "Nonce",
/*[WSI_TOKEN_HTTP] =*/ "Http",
"Accept:",
"If-Modified-Since:",
"Accept-Encoding:",
"Accept-Language:",
"Pragma:",
"Cache-Control:",
"Authorization:",
"Cookie:",
"Content-Length:",
"Content-Type:",
"Date:",
"Range:",
"Referer:",
"Uri-Args:",
/*[WSI_TOKEN_MUXURL] =*/ "MuxURL",
};
char buf[256];
for (n = 0; n < sizeof(token_names) / sizeof(token_names[0]); n++) {
if (!lws_hdr_total_length(wsi, n))
continue;
lws_hdr_copy(wsi, buf, sizeof buf, n);
fprintf(stderr, " %s = %s\n", token_names[n], buf);
}
}
const char * get_mimetype(const char *file)
{
int n = strlen(file);
if (n < 5)
return NULL;
if (!strcmp(&file[n - 4], ".ico"))
return "image/x-icon";
if (!strcmp(&file[n - 4], ".png"))
return "image/png";
if (!strcmp(&file[n - 5], ".html"))
return "text/html";
return NULL;
}
/* this protocol server (always the first one) just knows how to do HTTP */
static int callback_http(struct libwebsocket_context *context,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason, void *user,
void *in, size_t len)
{
#if 0
char client_name[128];
char client_ip[128];
#endif
char buf[256];
char leaf_path[1024];
char b64[64];
struct timeval tv;
int n, m;
unsigned char *p;
char *other_headers;
static unsigned char buffer[4096];
struct stat stat_buf;
struct per_session_data__http *pss =
(struct per_session_data__http *)user;
const char *mimetype;
#ifdef EXTERNAL_POLL
struct libwebsocket_pollargs *pa = (struct libwebsocket_pollargs *)in;
#endif
switch (reason) {
case LWS_CALLBACK_HTTP:
dump_handshake_info(wsi);
if (len < 1) {
libwebsockets_return_http_status(context, wsi,
HTTP_STATUS_BAD_REQUEST, NULL);
return -1;
}
/* this server has no concept of directories */
if (strchr((const char *)in + 1, '/')) {
libwebsockets_return_http_status(context, wsi,
HTTP_STATUS_FORBIDDEN, NULL);
return -1;
}
/* if a legal POST URL, let it continue and accept data */
if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
return 0;
/* check for the "send a big file by hand" example case */
if (!strcmp((const char *)in, "/leaf.jpg")) {
if (strlen(resource_path) > sizeof(leaf_path) - 10)
return -1;
sprintf(leaf_path, "%s/leaf.jpg", resource_path);
/* well, let's demonstrate how to send the hard way */
p = buffer;
#ifdef WIN32
pss->fd = open(leaf_path, O_RDONLY | _O_BINARY);
#else
pss->fd = open(leaf_path, O_RDONLY);
#endif
if (pss->fd < 0)
return -1;
fstat(pss->fd, &stat_buf);
/*
* we will send a big jpeg file, but it could be
* anything. Set the Content-Type: appropriately
* so the browser knows what to do with it.
*/
p += sprintf((char *)p,
"HTTP/1.0 200 OK\x0d\x0a"
"Server: libwebsockets\x0d\x0a"
"Content-Type: image/jpeg\x0d\x0a"
"Content-Length: %u\x0d\x0a\x0d\x0a",
(unsigned int)stat_buf.st_size);
/*
* send the http headers...
* this won't block since it's the first payload sent
* on the connection since it was established
* (too small for partial)
*/
n = libwebsocket_write(wsi, buffer,
p - buffer, LWS_WRITE_HTTP);
if (n < 0) {
close(pss->fd);
return -1;
}
/*
* book us a LWS_CALLBACK_HTTP_WRITEABLE callback
*/
libwebsocket_callback_on_writable(context, wsi);
break;
}
/* if not, send a file the easy way */
strcpy(buf, resource_path);
if (strcmp(in, "/")) {
if (*((const char *)in) != '/')
strcat(buf, "/");
strncat(buf, in, sizeof(buf) - strlen(resource_path));
} else /* default file to serve */
strcat(buf, "/test.html");
buf[sizeof(buf) - 1] = '\0';
/* refuse to serve files we don't understand */
mimetype = get_mimetype(buf);
if (!mimetype) {
lwsl_err("Unknown mimetype for %s\n", buf);
libwebsockets_return_http_status(context, wsi,
HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
return -1;
}
/* demostrates how to set a cookie on / */
other_headers = NULL;
if (!strcmp((const char *)in, "/") &&
!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
/* this isn't very unguessable but it'll do for us */
gettimeofday(&tv, NULL);
sprintf(b64, "LWS_%u_%u_COOKIE",
(unsigned int)tv.tv_sec,
(unsigned int)tv.tv_usec);
sprintf(leaf_path,
"Set-Cookie: test=LWS_%u_%u_COOKIE;Max-Age=360000\x0d\x0a",
(unsigned int)tv.tv_sec, (unsigned int)tv.tv_usec);
other_headers = leaf_path;
lwsl_err(other_headers);
}
if (libwebsockets_serve_http_file(context, wsi, buf,
mimetype, other_headers))
return -1; /* through completion or error, close the socket */
/*
* notice that the sending of the file completes asynchronously,
* we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
* it's done
*/
break;
case LWS_CALLBACK_HTTP_BODY:
strncpy(buf, in, 20);
buf[20] = '\0';
if (len < 20)
buf[len] = '\0';
lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
(const char *)buf, (int)len);
break;
case LWS_CALLBACK_HTTP_BODY_COMPLETION:
lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
/* the whole of the sent body arried, close the connection */
libwebsockets_return_http_status(context, wsi,
HTTP_STATUS_OK, NULL);
return -1;
case LWS_CALLBACK_HTTP_FILE_COMPLETION:
// lwsl_info("LWS_CALLBACK_HTTP_FILE_COMPLETION seen\n");
/* kill the connection after we sent one file */
return -1;
case LWS_CALLBACK_HTTP_WRITEABLE:
/*
* we can send more of whatever it is we were sending
*/
do {
n = read(pss->fd, buffer, sizeof buffer);
/* problem reading, close conn */
if (n < 0)
goto bail;
/* sent it all, close conn */
if (n == 0)
goto flush_bail;
/*
* because it's HTTP and not websocket, don't need to take
* care about pre and postamble
*/
m = libwebsocket_write(wsi, buffer, n, LWS_WRITE_HTTP);
if (m < 0)
/* write failed, close conn */
goto bail;
if (m != n)
/* partial write, adjust */
lseek(pss->fd, m - n, SEEK_CUR);
if (m) /* while still active, extend timeout */
libwebsocket_set_timeout(wsi,
PENDING_TIMEOUT_HTTP_CONTENT, 5);
} while (!lws_send_pipe_choked(wsi));
libwebsocket_callback_on_writable(context, wsi);
break;
flush_bail:
/* true if still partial pending */
if (lws_send_pipe_choked(wsi)) {
libwebsocket_callback_on_writable(context, wsi);
break;
}
bail:
close(pss->fd);
return -1;
/*
* callback for confirming to continue with client IP appear in
* protocol 0 callback since no websocket protocol has been agreed
* yet. You can just ignore this if you won't filter on client IP
* since the default uhandled callback return is 0 meaning let the
* connection continue.
*/
case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
#if 0
libwebsockets_get_peer_addresses(context, wsi, (int)(long)in, client_name,
sizeof(client_name), client_ip, sizeof(client_ip));
fprintf(stderr, "Received network connect from %s (%s)\n",
client_name, client_ip);
#endif
/* if we returned non-zero from here, we kill the connection */
break;
#ifdef EXTERNAL_POLL
/*
* callbacks for managing the external poll() array appear in
* protocol 0 callback
*/
case LWS_CALLBACK_LOCK_POLL:
/*
* lock mutex to protect pollfd state
* called before any other POLL related callback
*/
break;
case LWS_CALLBACK_UNLOCK_POLL:
/*
* unlock mutex to protect pollfd state when
* called after any other POLL related callback
*/
break;
case LWS_CALLBACK_ADD_POLL_FD:
if (count_pollfds >= max_poll_elements) {
lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
return 1;
}
fd_lookup[pa->fd] = count_pollfds;
pollfds[count_pollfds].fd = pa->fd;
pollfds[count_pollfds].events = pa->events;
pollfds[count_pollfds++].revents = 0;
break;
case LWS_CALLBACK_DEL_POLL_FD:
if (!--count_pollfds)
break;
m = fd_lookup[pa->fd];
/* have the last guy take up the vacant slot */
pollfds[m] = pollfds[count_pollfds];
fd_lookup[pollfds[count_pollfds].fd] = m;
break;
case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
pollfds[fd_lookup[pa->fd]].events = pa->events;
break;
#endif
case LWS_CALLBACK_GET_THREAD_ID:
/*
* if you will call "libwebsocket_callback_on_writable"
* from a different thread, return the caller thread ID
* here so lws can use this information to work out if it
* should signal the poll() loop to exit and restart early
*/
/* return pthread_getthreadid_np(); */
break;
default:
break;
}
return 0;
}
/* dumb_increment protocol */
/*
* one of these is auto-created for each connection and a pointer to the
* appropriate instance is passed to the callback in the user parameter
*
* for this example protocol we use it to individualize the count for each
* connection.
*/
struct per_session_data__dumb_increment {
int number;
};
static int
callback_dumb_increment(struct libwebsocket_context *context,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len)
{
int n, m;
unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
LWS_SEND_BUFFER_POST_PADDING];
unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
struct per_session_data__dumb_increment *pss = (struct per_session_data__dumb_increment *)user;
switch (reason) {
case LWS_CALLBACK_ESTABLISHED:
lwsl_info("callback_dumb_increment: "
"LWS_CALLBACK_ESTABLISHED\n");
pss->number = 0;
break;
case LWS_CALLBACK_SERVER_WRITEABLE:
n = sprintf((char *)p, "%d", pss->number++);
m = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
if (m < n) {
lwsl_err("ERROR %d writing to di socket\n", n);
return -1;
}
if (close_testing && pss->number == 50) {
lwsl_info("close tesing limit, closing\n");
return -1;
}
break;
case LWS_CALLBACK_RECEIVE:
// fprintf(stderr, "rx %d\n", (int)len);
if (len < 6)
break;
if (strcmp((const char *)in, "reset\n") == 0)
pss->number = 0;
break;
/*
* this just demonstrates how to use the protocol filter. If you won't
* study and reject connections based on header content, you don't need
* to handle this callback
*/
case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
dump_handshake_info(wsi);
/* you could return non-zero here and kill the connection */
break;
default:
break;
}
return 0;
}
/* lws-mirror_protocol */
#define MAX_MESSAGE_QUEUE 32
struct per_session_data__lws_mirror {
struct libwebsocket *wsi;
int ringbuffer_tail;
};
struct a_message {
void *payload;
size_t len;
};
static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
static int ringbuffer_head;
static int
callback_lws_mirror(struct libwebsocket_context *context,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len)
{
int n;
struct per_session_data__lws_mirror *pss = (struct per_session_data__lws_mirror *)user;
switch (reason) {
case LWS_CALLBACK_ESTABLISHED:
lwsl_info("callback_lws_mirror: LWS_CALLBACK_ESTABLISHED\n");
pss->ringbuffer_tail = ringbuffer_head;
pss->wsi = wsi;
break;
case LWS_CALLBACK_PROTOCOL_DESTROY:
lwsl_notice("mirror protocol cleaning up\n");
for (n = 0; n < sizeof ringbuffer / sizeof ringbuffer[0]; n++)
if (ringbuffer[n].payload)
free(ringbuffer[n].payload);
break;
case LWS_CALLBACK_SERVER_WRITEABLE:
if (close_testing)
break;
while (pss->ringbuffer_tail != ringbuffer_head) {
n = libwebsocket_write(wsi, (unsigned char *)
ringbuffer[pss->ringbuffer_tail].payload +
LWS_SEND_BUFFER_PRE_PADDING,
ringbuffer[pss->ringbuffer_tail].len,
LWS_WRITE_TEXT);
if (n < 0) {
lwsl_err("ERROR %d writing to mirror socket\n", n);
return -1;
}
if (n < ringbuffer[pss->ringbuffer_tail].len)
lwsl_err("mirror partial write %d vs %d\n",
n, ringbuffer[pss->ringbuffer_tail].len);
if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
pss->ringbuffer_tail = 0;
else
pss->ringbuffer_tail++;
if (((ringbuffer_head - pss->ringbuffer_tail) &
(MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 15))
libwebsocket_rx_flow_allow_all_protocol(
libwebsockets_get_protocol(wsi));
// lwsl_debug("tx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1));
if (lws_send_pipe_choked(wsi)) {
libwebsocket_callback_on_writable(context, wsi);
break;
}
/*
* for tests with chrome on same machine as client and
* server, this is needed to stop chrome choking
*/
#ifdef _WIN32
Sleep(1);
#else
usleep(1);
#endif
}
break;
case LWS_CALLBACK_RECEIVE:
if (((ringbuffer_head - pss->ringbuffer_tail) &
(MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 1)) {
lwsl_err("dropping!\n");
goto choke;
}
if (ringbuffer[ringbuffer_head].payload)
free(ringbuffer[ringbuffer_head].payload);
ringbuffer[ringbuffer_head].payload =
malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
LWS_SEND_BUFFER_POST_PADDING);
ringbuffer[ringbuffer_head].len = len;
memcpy((char *)ringbuffer[ringbuffer_head].payload +
LWS_SEND_BUFFER_PRE_PADDING, in, len);
if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
ringbuffer_head = 0;
else
ringbuffer_head++;
if (((ringbuffer_head - pss->ringbuffer_tail) &
(MAX_MESSAGE_QUEUE - 1)) != (MAX_MESSAGE_QUEUE - 2))
goto done;
choke:
lwsl_debug("LWS_CALLBACK_RECEIVE: throttling %p\n", wsi);
libwebsocket_rx_flow_control(wsi, 0);
// lwsl_debug("rx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1));
done:
libwebsocket_callback_on_writable_all_protocol(
libwebsockets_get_protocol(wsi));
break;
/*
* this just demonstrates how to use the protocol filter. If you won't
* study and reject connections based on header content, you don't need
* to handle this callback
*/
case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
dump_handshake_info(wsi);
/* you could return non-zero here and kill the connection */
break;
default:
break;
}
return 0;
}
/* list of supported protocols and callbacks */
static struct libwebsocket_protocols protocols[] = {
/* first protocol must always be HTTP handler */
{
"http-only", /* name */
callback_http, /* callback */
sizeof (struct per_session_data__http), /* per_session_data_size */
0, /* max frame size / rx buffer */
},
{
"dumb-increment-protocol",
callback_dumb_increment,
sizeof(struct per_session_data__dumb_increment),
10,
},
{
"lws-mirror-protocol",
callback_lws_mirror,
sizeof(struct per_session_data__lws_mirror),
128,
},
{ NULL, NULL, 0, 0 } /* terminator */
};
void sighandler(int sig)
{
force_exit = 1;
libwebsocket_cancel_service(context);
}
static struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "debug", required_argument, NULL, 'd' },
{ "port", required_argument, NULL, 'p' },
{ "ssl", no_argument, NULL, 's' },
{ "allow-non-ssl", no_argument, NULL, 'a' },
{ "interface", required_argument, NULL, 'i' },
{ "closetest", no_argument, NULL, 'c' },
{ "libev", no_argument, NULL, 'e' },
#ifndef LWS_NO_DAEMONIZE
{ "daemonize", no_argument, NULL, 'D' },
#endif
{ "resource_path", required_argument, NULL, 'r' },
{ NULL, 0, 0, 0 }
};
int main(int argc, char **argv)
{
char cert_path[1024];
char key_path[1024];
int n = 0;
int use_ssl = 0;
int opts = 0;
char interface_name[128] = "";
const char *iface = NULL;
#ifndef WIN32
int syslog_options = LOG_PID | LOG_PERROR;
#endif
unsigned int ms, oldms = 0;
struct lws_context_creation_info info;
int debug_level = 7;
#ifndef LWS_NO_DAEMONIZE
int daemonize = 0;
#endif
memset(&info, 0, sizeof info);
info.port = 7681;
while (n >= 0) {
n = getopt_long(argc, argv, "eci:hsap:d:Dr:", options, NULL);
if (n < 0)
continue;
switch (n) {
case 'e':
opts |= LWS_SERVER_OPTION_LIBEV;
break;
#ifndef LWS_NO_DAEMONIZE
case 'D':
daemonize = 1;
#ifndef WIN32
syslog_options &= ~LOG_PERROR;
#endif
break;
#endif
case 'd':
debug_level = atoi(optarg);
break;
case 's':
use_ssl = 1;
break;
case 'a':
opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
break;
case 'p':
info.port = atoi(optarg);
break;
case 'i':
strncpy(interface_name, optarg, sizeof interface_name);
interface_name[(sizeof interface_name) - 1] = '\0';
iface = interface_name;
break;
case 'c':
close_testing = 1;
fprintf(stderr, " Close testing mode -- closes on "
"client after 50 dumb increments"
"and suppresses lws_mirror spam\n");
break;
case 'r':
resource_path = optarg;
printf("Setting resource path to \"%s\"\n", resource_path);
break;
case 'h':
fprintf(stderr, "Usage: test-server "
"[--port=<p>] [--ssl] "
"[-d <log bitfield>] "
"[--resource_path <path>]\n");
exit(1);
}
}
#if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
/*
* normally lock path would be /var/lock/lwsts or similar, to
* simplify getting started without having to take care about
* permissions or running as root, set to /tmp/.lwsts-lock
*/
if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
fprintf(stderr, "Failed to daemonize\n");
return 1;
}
#endif
signal(SIGINT, sighandler);
#ifndef WIN32
/* we will only try to log things according to our debug_level */
setlogmask(LOG_UPTO (LOG_DEBUG));
openlog("lwsts", syslog_options, LOG_DAEMON);
#endif
/* tell the library what debug level to emit and to send it to syslog */
lws_set_log_level(debug_level, lwsl_emit_syslog);
lwsl_notice("libwebsockets test server - "
"(C) Copyright 2010-2013 Andy Green <andy@warmcat.com> - "
"licensed under LGPL2.1\n");
#ifdef EXTERNAL_POLL
max_poll_elements = getdtablesize();
pollfds = malloc(max_poll_elements * sizeof (struct pollfd));
fd_lookup = malloc(max_poll_elements * sizeof (int));
if (pollfds == NULL || fd_lookup == NULL) {
lwsl_err("Out of memory pollfds=%d\n", max_poll_elements);
return -1;
}
#endif
info.iface = iface;
info.protocols = protocols;
#ifndef LWS_NO_EXTENSIONS
info.extensions = libwebsocket_get_internal_extensions();
#endif
if (!use_ssl) {
info.ssl_cert_filepath = NULL;
info.ssl_private_key_filepath = NULL;
} else {
if (strlen(resource_path) > sizeof(cert_path) - 32) {
lwsl_err("resource path too long\n");
return -1;
}
sprintf(cert_path, "%s/libwebsockets-test-server.pem",
resource_path);
if (strlen(resource_path) > sizeof(key_path) - 32) {
lwsl_err("resource path too long\n");
return -1;
}
sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
resource_path);
info.ssl_cert_filepath = cert_path;
info.ssl_private_key_filepath = key_path;
}
info.gid = -1;
info.uid = -1;
info.options = opts;
context = libwebsocket_create_context(&info);
if (context == NULL) {
lwsl_err("libwebsocket init failed\n");
return -1;
}
n = 0;
while (n >= 0 && !force_exit) {
struct timeval tv;
gettimeofday(&tv, NULL);
/*
* This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every
* live websocket connection using the DUMB_INCREMENT protocol,
* as soon as it can take more packets (usually immediately)
*/
ms = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
if ((ms - oldms) > 50) {
libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_DUMB_INCREMENT]);
oldms = ms;
}
#ifdef EXTERNAL_POLL
/*
* this represents an existing server's single poll action
* which also includes libwebsocket sockets
*/
n = poll(pollfds, count_pollfds, 50);
if (n < 0)
continue;
if (n)
for (n = 0; n < count_pollfds; n++)
if (pollfds[n].revents)
/*
* returns immediately if the fd does not
* match anything under libwebsockets
* control
*/
if (libwebsocket_service_fd(context,
&pollfds[n]) < 0)
goto done;
#else
/*
* If libwebsockets sockets are all we care about,
* you can use this api which takes care of the poll()
* and looping through finding who needed service.
*
* If no socket needs service, it'll return anyway after
* the number of ms in the second argument.
*/
n = libwebsocket_service(context, 50);
#endif
}
#ifdef EXTERNAL_POLL
done:
#endif
libwebsocket_context_destroy(context);
lwsl_notice("libwebsockets-test-server exited cleanly\n");
#ifndef WIN32
closelog();
#endif
return 0;
}
+398
View File
@@ -0,0 +1,398 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8 http-equiv="Content-Language" content="en"/>
<title>Minimal Websocket test app</title>
<style type="text/css">
div.title { font-size:18pt; font: Arial; font-weight:normal; text-align:center; color:#000000; }
.browser { font-size:18pt; font: Arial; font-weight:normal; text-align:center; color:#ffff00; vertical-align:middle; text-align:center; background:#d0b070; padding:12px; -webkit-border-radius:10px; -moz-border-radius:10px; border-radius:10px;}
.group2 { width:600px; vertical-align:middle; text-align:center; background:#f0f0e0; padding:12px; -webkit-border-radius:10px; -moz-border-radius:10px; border-radius:10px; }
.explain { vertical-align:middle; text-align:center; background:#f0f0c0; padding:12px; -webkit-border-radius:10px; -moz-border-radius:10px; border-radius:10px; color:#404000; }
.content { vertical-align:top; text-align:center; background:#fffff0; padding:12px; -webkit-border-radius:10px; -moz-border-radius:10px; border-radius:10px; }
.canvas { vertical-align:top; text-align:center; background:#efefd0; padding:12px; -webkit-border-radius:10px; -moz-border-radius:10px; border-radius:10px; }
</style>
</head>
<body>
<header></header>
<article>
<table><tr><td>
<table width="100%"><tr><td valign=middle align=center><a href="http://libwebsockets.org"><img src="/libwebsockets.org-logo.png"></a></td><td>
<section class="browser">Detected Browser: <div id=brow>...</div></section></td></tr></table>
</td></tr><tr><td>
<section id="increment" class="group2">
<div class="title">libwebsockets "dumb-increment-protocol"</div>
<table><tr><td>
<table class="content" width="200px">
<tr><td align=center><input type=button id=offset value="Reset counter" onclick="reset();" ></td></tr>
<tr><td width=200px align=center><div id=number> </div></td></tr>
<tr><td id=wsdi_statustd align=center class="explain"><div id=wsdi_status>Not initialized</div></td></tr>
</tr>
</table>
</td><td class="explain">
The incrementing number is coming from the server and is individual for
each connection to the server... try opening a second browser window.
<br/><br/>
The button zeros just this connection's number.
<br/><br/>
Click <a href="/leaf.jpg" target="_blank">Here</a> to have the test server send a big picture by http.
</td></tr></table>
</section>
<br>
<section id="mirror" class="group2">
<div class="title">libwebsockets "lws-mirror-protocol"</div>
<div class="explain">
Use the mouse to draw on the canvas below -- all other browser windows open
on this page see your drawing in realtime and you can see any of theirs as
well.
<br/><br/>
The lws-mirror protocol doesn't interpret what is being sent to it, it just
re-sends it to every other websocket it has a connection with using that
protocol, including the guy who sent the packet.
<br/><br/>
<b>libwebsockets-test-client</b> joins in by spamming circles on to this shared canvas when
run.
</div>
<table class="content">
<tr>
<td>Drawing color:
<select id="color" onchange="update_color();">
<option value=#000000>Black</option>
<option value=#0000ff>Blue</option>
<option value=#20ff20>Green</option>
<option value=#802020>Dark Red</option>
</select>
</td>
<td id=wslm_statustd align=center class="explain"><div id=wslm_status>Not initialized</div></td>
</tr>
<tr>
<td colspan=2 width=500 class="content">
<div id="wslm_drawing">
</div></td>
</tr>
</table>
</section>
</td></tr><tr><td>
Looking for support? <a href="http://libwebsockets.org">http://libwebsockets.org</a><br/>
Join the mailing list: <a href="http://ml.libwebsockets.org/mailman/listinfo/libwebsockets">http://ml.libwebsockets.org/mailman/listinfo/libwebsockets</a>
</td></tr></table>
</article>
<script>
/* BrowserDetect came from http://www.quirksmode.org/js/detect.html */
var BrowserDetect = {
init: function () {
this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
this.version = this.searchVersion(navigator.userAgent)
|| this.searchVersion(navigator.appVersion)
|| "an unknown version";
this.OS = this.searchString(this.dataOS) || "an unknown OS";
},
searchString: function (data) {
for (var i=0;i<data.length;i++) {
var dataString = data[i].string;
var dataProp = data[i].prop;
this.versionSearchString = data[i].versionSearch || data[i].identity;
if (dataString) {
if (dataString.indexOf(data[i].subString) != -1)
return data[i].identity;
}
else if (dataProp)
return data[i].identity;
}
},
searchVersion: function (dataString) {
var index = dataString.indexOf(this.versionSearchString);
if (index == -1) return;
return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
},
dataBrowser: [
{
string: navigator.userAgent,
subString: "Chrome",
identity: "Chrome"
},
{ string: navigator.userAgent,
subString: "OmniWeb",
versionSearch: "OmniWeb/",
identity: "OmniWeb"
},
{
string: navigator.vendor,
subString: "Apple",
identity: "Safari",
versionSearch: "Version"
},
{
prop: window.opera,
identity: "Opera",
versionSearch: "Version"
},
{
string: navigator.vendor,
subString: "iCab",
identity: "iCab"
},
{
string: navigator.vendor,
subString: "KDE",
identity: "Konqueror"
},
{
string: navigator.userAgent,
subString: "Firefox",
identity: "Firefox"
},
{
string: navigator.vendor,
subString: "Camino",
identity: "Camino"
},
{ // for newer Netscapes (6+)
string: navigator.userAgent,
subString: "Netscape",
identity: "Netscape"
},
{
string: navigator.userAgent,
subString: "MSIE",
identity: "Explorer",
versionSearch: "MSIE"
},
{
string: navigator.userAgent,
subString: "Gecko",
identity: "Mozilla",
versionSearch: "rv"
},
{ // for older Netscapes (4-)
string: navigator.userAgent,
subString: "Mozilla",
identity: "Netscape",
versionSearch: "Mozilla"
}
],
dataOS : [
{
string: navigator.platform,
subString: "Win",
identity: "Windows"
},
{
string: navigator.platform,
subString: "Mac",
identity: "Mac"
},
{
string: navigator.userAgent,
subString: "iPhone",
identity: "iPhone/iPod"
},
{
string: navigator.platform,
subString: "Linux",
identity: "Linux"
}
]
};
BrowserDetect.init();
document.getElementById("brow").textContent = " " + BrowserDetect.browser + " "
+ BrowserDetect.version +" " + BrowserDetect.OS +" ";
var pos = 0;
function get_appropriate_ws_url()
{
var pcol;
var u = document.URL;
/*
* We open the websocket encrypted if this page came on an
* https:// url itself, otherwise unencrypted
*/
if (u.substring(0, 5) == "https") {
pcol = "wss://";
u = u.substr(8);
} else {
pcol = "ws://";
if (u.substring(0, 4) == "http")
u = u.substr(7);
}
u = u.split('/');
/* + "/xxx" bit is for IE10 workaround */
return pcol + u[0] + "/xxx";
}
document.getElementById("number").textContent = get_appropriate_ws_url();
/* dumb increment protocol */
var socket_di;
if (typeof MozWebSocket != "undefined") {
socket_di = new MozWebSocket(get_appropriate_ws_url(),
"dumb-increment-protocol");
} else {
socket_di = new WebSocket(get_appropriate_ws_url(),
"dumb-increment-protocol");
}
try {
socket_di.onopen = function() {
document.getElementById("wsdi_statustd").style.backgroundColor = "#40ff40";
document.getElementById("wsdi_status").textContent = " websocket connection opened ";
}
socket_di.onmessage =function got_packet(msg) {
document.getElementById("number").textContent = msg.data + "\n";
}
socket_di.onclose = function(){
document.getElementById("wsdi_statustd").style.backgroundColor = "#ff4040";
document.getElementById("wsdi_status").textContent = " websocket connection CLOSED ";
}
} catch(exception) {
alert('<p>Error' + exception);
}
function reset() {
socket_di.send("reset\n");
}
/* lws-mirror protocol */
var down = 0;
var no_last = 1;
var last_x = 0, last_y = 0;
var ctx;
var socket_lm;
var color = "#000000";
if (typeof MozWebSocket != "undefined") {
socket_lm = new MozWebSocket(get_appropriate_ws_url(),
"lws-mirror-protocol");
} else {
socket_lm = new WebSocket(get_appropriate_ws_url(),
"lws-mirror-protocol");
}
try {
socket_lm.onopen = function() {
document.getElementById("wslm_statustd").style.backgroundColor = "#40ff40";
document.getElementById("wslm_status").textContent = " websocket connection opened ";
}
socket_lm.onmessage =function got_packet(msg) {
j = msg.data.split(';');
f = 0;
while (f < j.length - 1) {
i = j[f].split(' ');
if (i[0] == 'd') {
ctx.strokeStyle = i[1];
ctx.beginPath();
ctx.moveTo(+(i[2]), +(i[3]));
ctx.lineTo(+(i[4]), +(i[5]));
ctx.stroke();
}
if (i[0] == 'c') {
ctx.strokeStyle = i[1];
ctx.beginPath();
ctx.arc(+(i[2]), +(i[3]), +(i[4]), 0, Math.PI*2, true);
ctx.stroke();
}
f++;
}
}
socket_lm.onclose = function(){
document.getElementById("wslm_statustd").style.backgroundColor = "#ff4040";
document.getElementById("wslm_status").textContent = " websocket connection CLOSED ";
}
} catch(exception) {
alert('<p>Error' + exception);
}
var canvas = document.createElement('canvas');
canvas.height = 300;
canvas.width = 480;
ctx = canvas.getContext("2d");
document.getElementById('wslm_drawing').appendChild(canvas);
canvas.addEventListener('mousemove', ev_mousemove, false);
canvas.addEventListener('mousedown', ev_mousedown, false);
canvas.addEventListener('mouseup', ev_mouseup, false);
offsetX = offsetY = 0;
element = canvas;
if (element.offsetParent) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
function update_color() {
color = document.getElementById("color").value;
}
function ev_mousedown (ev) {
down = 1;
}
function ev_mouseup(ev) {
down = 0;
no_last = 1;
}
function ev_mousemove (ev) {
var x, y;
if (ev.offsetX) {
x = ev.offsetX;
y = ev.offsetY;
} else {
x = ev.layerX - offsetX;
y = ev.layerY - offsetY;
}
if (!down)
return;
if (no_last) {
no_last = 0;
last_x = x;
last_y = y;
return;
}
socket_lm.send("d " + color + " " + last_x + " " + last_y + " " + x + ' ' + y + ';');
last_x = x;
last_y = y;
}
</script>
</body>
</html>