示例#1
0
int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	struct lws_context *context;
	const char *p;
	int result = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE;

	if ((p = lws_cmdline_option(argc, argv, "-d")))
		logs = atoi(p);

	lws_set_log_level(logs, NULL);
	lwsl_user("LWS gencrypto apis tests\n");

	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
	info.port = CONTEXT_PORT_NO_LISTEN;
	info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;

	context = lws_create_context(&info);
	if (!context) {
		lwsl_err("lws init failed\n");
		return 1;
	}

	result |= test_genaes(context);
	result |= test_genec(context);

	lwsl_user("Completed: %s\n", result ? "FAIL" : "PASS");

	lws_context_destroy(context);

	return result;
}
示例#2
0
int ps_websockets_init (ps_transport_callbacks * callback) {
	
	if (g_atomic_int_get(&stopping)) {
		return -1;
	}
	if (callback == NULL) {
		return -1;
	}
	
	gateway = callback;
	struct lws * wsi;
	
	/* Set Log level */
	lws_set_log_level (0, NULL);
	
	/* Prepare context */
	struct lws_context_creation_info info;
	struct lws_client_connect_info cinfo;
	memset(&info, 0, sizeof info);
	memset(&cinfo, 0, sizeof cinfo);
	
	info.port = CONTEXT_PORT_NO_LISTEN;
	info.iface = NULL;
	info.protocols = wss_protocols;
	info.extensions = NULL; //lws_get_internal_extensions();
	info.ssl_cert_filepath = NULL;
	info.ssl_private_key_filepath = NULL;
	info.gid = -1;
	info.uid = -1;
	info.options = 0;
	
	/* Create the websockets context */
	wss = lws_create_context(&info);
	
	cinfo.context = wss;
	cinfo.ssl_connection = 0;
	cinfo.host = host;
	cinfo.address = host;
	cinfo.port = wsport;
	cinfo.path = path;
	cinfo.protocol = "ps-protocol"; //wss_protocols.name;
	
	GError * error = NULL;
	if (wss != NULL) {
		/* Connect to the server */
		wsi = lws_client_connect_via_info (&cinfo);
		/*TODO: somehow, check if the connection is established?*/
		wss_thread = g_thread_try_new("websockets thread", &ps_websockets_thread, wss, &error);
		if (!wss_thread) {
			g_atomic_int_set(&initialized, 0);
			PS_LOG (LOG_ERR,"Got error %d (%s) trying to launch the wss thread...\n", 
			error->code, error->message ? error->message : "??");
			return -1;
		}
	}
	
	/* done */
	g_atomic_int_set(&initialized, 1);
	return 0;
}
int discord_ws_init(struct im_connection *ic, discord_data *dd)
{
  struct lws_context_creation_info info;

  memset(&info, 0, sizeof(info));

  info.port = CONTEXT_PORT_NO_LISTEN;
  info.protocols = protocols;
#ifndef LWS_NO_EXTENSIONS
  info.extensions = lws_get_internal_extensions();
#else
  info.extensions = NULL;
#endif
  info.gid = -1;
  info.uid = -1;
  info.user = ic;

  lws_set_log_level(0, NULL);

  dd->lwsctx = lws_create_context(&info);
  if (dd->lwsctx == NULL) {
    return -1;
  }

  dd->lws = lws_client_connect(dd->lwsctx, dd->gateway->addr,
                                        dd->gateway->wss ? 443 : 80,
                                        dd->gateway->wss,
                                        dd->gateway->path, dd->gateway->addr,
                                        "discordapp.com",
                                        protocols[0].name, -1);
  return 0;
}
transport_mock_websocket_server_t transport_mock_websocket_server_create(unsigned int port)
{
    transport_mock_websocket_server_t transport_mock_websocket_server = (transport_mock_websocket_server_t)calloc(1, sizeof(struct transport_mock_websocket_server_s));
    if(transport_mock_websocket_server)
    {
        struct lws_context_creation_info ws_info;
        memset(&ws_info, 0, sizeof(ws_info));
    	ws_info.port = port; // listening port
        ws_info.iface = NULL; // bind to all available interfaces
    	ws_info.protocols = protocols;
        ws_info.extensions = NULL;
    	ws_info.gid = -1;
    	ws_info.uid = -1;
    	ws_info.options = 0;
        
        transport_mock_websocket_server->ws_context = lws_create_context(&ws_info);
            
    	if (transport_mock_websocket_server->ws_context == NULL) 
        {
    		lwsl_err("libwebsocket init failed\n");
    		return NULL;
    	}
        
        
    }
    return transport_mock_websocket_server;
}
static void
foreign_timer_service(void *foreign_loop)
{
	void *foreign_loops[1];

	lwsl_user("Foreign 1Hz timer\n");

	if (sequence == TEST_STATE_EXIT && !context && !reported) {
		/*
		 * at this point the lws_context_destroy() we did earlier
		 * has completed and the entire context is wholly destroyed
		 */
		lwsl_user("lws_destroy_context() done, continuing for 5s\n");
		reported = 1;
	}

	if (--lifetime)
		return;

	switch (sequence++) {
	case TEST_STATE_CREATE_LWS_CONTEXT:
		/* this only has to exist for the duration of create context */
		foreign_loops[0] = foreign_loop;
		info.foreign_loops = foreign_loops;

		context = lws_create_context(&info);
		if (!context) {
			lwsl_err("lws init failed\n");
			return;
		}
		lwsl_user("LWS Context created and will be active for 10s\n");
		lifetime = 11;
		break;

	case TEST_STATE_DESTROY_LWS_CONTEXT:
		/* cleanup the lws part */
		lwsl_user("Destroying lws context and continuing loop for 5s\n");
		lws_context_destroy(context);
		lifetime = 6;
		break;

	case TEST_STATE_EXIT:
		lwsl_user("Deciding to exit foreign loop too\n");
#if defined(LWS_WITH_LIBUV)
		if (info.options & LWS_SERVER_OPTION_LIBUV)
			foreign_event_loop_stop_libuv();
#endif
#if defined(LWS_WITH_LIBEVENT)
		if (info.options & LWS_SERVER_OPTION_LIBEVENT)
			foreign_event_loop_stop_libevent();
#endif
#if defined(LWS_WITH_LIBEV)
		if (info.options & LWS_SERVER_OPTION_LIBEV)
			foreign_event_loop_stop_libev();
#endif
		break;
	default:
		break;
	}
}
int main(void)
{
	/*server url will usd port 5000*/
	int port = 5000;
	const char *interface = NULL;
	struct lws_context_creation_info info;
	struct lws_protocols protocol;
	struct lws_context *context;
	/*Not using ssl*/
	const char *cert_path = NULL;
	const char *key_path = NULL;
	/*no special options*/
	int opts = 0;


	/* register the signal SIGINT handler */
	struct sigaction act;
	act.sa_handler = INT_HANDLER;
	act.sa_flags = 0;
	sigemptyset(&act.sa_mask);
	sigaction( SIGINT, &act, 0);

	/* setup websocket protocol */
	protocol.name = "my-echo-protocol";
	protocol.callback = ws_service_callback;
	protocol.per_session_data_size=sizeof(struct per_session_data);
	protocol.rx_buffer_size = 0;

	/* setup websocket context info*/
	memset(&info, 0, sizeof info);
	info.port = port;
	info.iface = interface;
	info.protocols = &protocol;
	info.extensions = lws_get_internal_extensions();
	info.ssl_cert_filepath = cert_path;
	info.ssl_private_key_filepath = key_path;
	info.gid = -1;
	info.uid = -1;
	info.options = opts;

	/* create libwebsocket context. */
	context = lws_create_context(&info);
	if (context == NULL) {
		printf(KRED"[Main] Websocket context create error.\n"RESET);
		return -1;
	}

	printf(KGRN"[Main] Websocket context create success.\n"RESET);

	/* websocket service */
	while ( !destroy_flag ) {
		lws_service(context, 50);
	}
	usleep(10);
	lws_context_destroy(context);

	return 0;
}
int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	const char *p, *plugin_dirs[] = {
		"/usr/local/share/libwebsockets-test-server/plugins",
		NULL };
	int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE
			/* for LLL_ verbosity above NOTICE to be built into lws,
			 * lws must have been configured and built with
			 * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE */
			/* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */
			/* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */
			/* | LLL_DEBUG */;

	if ((p = lws_cmdline_option(argc, argv, "-d")))
		logs = atoi(p);

	lws_set_log_level(logs, NULL);
	lwsl_user("LWS minimal http server TLS | visit https://localhost:7681\n");

	signal(SIGINT, sigint_handler);

	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
	info.port = 7681;
	info.mounts = &mount;
	info.error_document_404 = "/404.html";
	info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT |
		       LWS_SERVER_OPTION_EXPLICIT_VHOSTS;
	info.ssl_cert_filepath = "localhost-100y.cert";
	info.ssl_private_key_filepath = "localhost-100y.key";
	info.plugin_dirs = plugin_dirs;
	info.pvo = &pvo;

	if (lws_cmdline_option(argc, argv, "-h"))
		info.options |= LWS_SERVER_OPTION_VHOST_UPG_STRICT_HOST_CHECK;

	context = lws_create_context(&info);
	if (!context) {
		lwsl_err("lws init failed\n");
		return 1;
	}

	info.headers = &pvo_hsbph[3];

	if (!lws_create_vhost(context, &info)) {
		lwsl_err("lws init failed\n");
		return 1;
	}

	while (n >= 0 && !interrupted)
		n = lws_service(context, 1000);

	lws_context_destroy(context);

	return 0;
}
bool FJavascriptWebSocketServer::Init(uint32 Port, FJavascriptWebSocketClientConnectedCallBack CallBack)
{
	// setup log level.
#if !UE_BUILD_SHIPPING
	lws_set_log_level(LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_DEBUG | LLL_INFO, lws_debugLog_JS);
#endif 

	Protocols = new lws_protocols[3];
	FMemory::Memzero(Protocols, sizeof(lws_protocols) * 3);

	Protocols[0].name = "binary";
	Protocols[0].callback = [](lws *Wsi, lws_callback_reasons Reason, void *User, void *In, size_t Len) {
		auto context = lws_get_context(Wsi);
		return reinterpret_cast<FJavascriptWebSocketServer*>(lws_context_user(context))->unreal_networking_server(Wsi, Reason, User, In, Len);
	};
	Protocols[0].per_session_data_size = sizeof(PerSessionDataServer);
	Protocols[0].rx_buffer_size = 10 * 1024 * 1024;

	Protocols[1].name = nullptr;
	Protocols[1].callback = nullptr;
	Protocols[1].per_session_data_size = 0;

	struct lws_context_creation_info Info;
	memset(&Info, 0, sizeof(lws_context_creation_info));
	// look up libwebsockets.h for details. 
	Info.port = Port;
	ServerPort = Port;
	// we listen on all available interfaces. 
	Info.iface = NULL;
	Info.protocols = &Protocols[0];
	// no extensions
	Info.extensions = NULL;
	Info.gid = -1;
	Info.uid = -1;
	Info.options = 0;
	// tack on this object. 
	Info.user = this;
	Info.port = Port; 
	Context = lws_create_context(&Info);

	if (Context == NULL) 
	{
		ServerPort = 0;
		delete Protocols;
		Protocols = NULL;
		IsAlive = false;
		return false; // couldn't create a server.
	}
	ConnectedCallBack = CallBack; 	
	IsAlive = true;

	return true; 
}
示例#9
0
void Webserver::worker(void *)
{
	// server url will be ws://localhost:9000
	const char *interface = NULL;
	struct lws_context *context = NULL;

	// we're not using ssl
	const char *cert_path = NULL;
	const char *key_path = NULL;

	//lws_set_log_level(7, lwsl_emit_syslog);
	//lws_set_log_level(1, lwsl_emit_syslog);

	// no special options
	int opts = 0;

	// create connection struct
	struct lws_context_creation_info info;
	memset(&info, 0, sizeof info);

	info.port = Webserver::instance()->getPort();
	info.iface = interface;
	info.protocols = protocols;
	info.extensions = NULL;
	info.ssl_cert_filepath = cert_path;
	info.ssl_private_key_filepath = key_path;
	info.options = opts;
	info.gid = -1;
	info.uid = -1;

	// create libwebsocket context representing this server
	context = lws_create_context(&info);

	// make sure it starts
	if (context == NULL)
	{
		Webserver::instance()->mRunning = false;
		fprintf(stderr, "libwebsocket init failed\n");
		return;
	}
	
	printf("starting server...\n");
	// infinite loop, to end this server send SIGTERM. (CTRL+C)
	while (Webserver::instance()->mRunning.load())
	{
		lws_service(context, Webserver::instance()->getTimeout()); //5 ms -> 200 samples / s
		//lws_service(context, 50);
	}
	
	lws_context_destroy(context);
	return;
}
示例#10
0
int main (int argc, char **argv)
{
  int port = 9000;

  struct lws_context_creation_info context_info = {
    .port = port,
    .iface = NULL,
    .protocols = protocols,
    .ssl_cert_filepath = NULL,
    .ssl_private_key_filepath = NULL,
    .ssl_ca_filepath = NULL,

    .gid = -1,
    .uid = -1,

    .max_http_header_pool = 1,
    .options = 0,
  };
  
  // create lws context representing this server
  context = lws_create_context(&context_info);
  
  if (context == NULL) {
    puts("lws init failed\n");
    return -1;
  }

  signal(SIGINT, signal_callback_handler);

  // Setup child reaping handler
  struct sigaction sa;
  sa.sa_handler = &handle_sigchld;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
  if (sigaction(SIGCHLD, &sa, 0) == -1) {
    perror(0);
    exit(1);
  }

  printf("starting server...\n");

  while (true) {
    lws_service(context, 10); // ms
    //lws_callback_on_writable_all_protocol(context, &protocols[1]);
    usleep(1000);
  }

  lws_context_destroy(context);  
  return 0;
}
int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	struct lws_context *context;
	const char *p;
	int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE
			/* for LLL_ verbosity above NOTICE to be built into lws,
			 * lws must have been configured and built with
			 * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE */
			/* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */
			/* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */
			/* | LLL_DEBUG */;

	signal(SIGINT, sigint_handler);

	if ((p = lws_cmdline_option(argc, argv, "-d")))
		logs = atoi(p);

	lws_set_log_level(logs, NULL);
	lwsl_user("LWS minimal ws client + permessage-deflate + multifragment bulk message\n");
	lwsl_user("   needs minimal-ws-server-pmd-bulk running to communicate with\n");
	lwsl_user("   %s [-n (no exts)] [-c (compressible)]\n", argv[0]);

	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
	info.port = CONTEXT_PORT_NO_LISTEN;
	info.protocols = protocols;
	info.pvo = &pvo;
	if (!lws_cmdline_option(argc, argv, "-n"))
		info.extensions = extensions;
	info.pt_serv_buf_size = 32 * 1024;

	if (lws_cmdline_option(argc, argv, "-c"))
		options |= 1;

	context = lws_create_context(&info);
	if (!context) {
		lwsl_err("lws init failed\n");
		return 1;
	}

	while (n >= 0 && !interrupted)
		n = lws_service(context, 1000);

	lws_context_destroy(context);

	lwsl_user("Completed %s\n", interrupted == 2 ? "OK" : "failed");

	return interrupted != 2;
}
示例#12
0
int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	struct lws_context *context;
	const char *p;
	int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE
			/* for LLL_ verbosity above NOTICE to be built into lws,
			 * lws must have been configured and built with
			 * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE */
			/* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */
			/* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */
			/* | LLL_DEBUG */;

	signal(SIGINT, sigint_handler);

	if ((p = lws_cmdline_option(argc, argv, "-d")))
		logs = atoi(p);

	lws_set_log_level(logs, NULL);
	lwsl_user("LWS minimal raw file\n");
	if (argc < 2) {
		lwsl_user("Usage: %s <file to monitor>  "
			  " eg, /dev/ttyUSB0 or /dev/input/event0 or "
			  "/proc/self/fd/0\n", argv[0]);

		return 1;
	}

	signal(SIGINT, sigint_handler);

	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
	info.port = CONTEXT_PORT_NO_LISTEN_SERVER; /* no listen socket for demo */
	info.protocols = protocols;

	lws_strncpy(filepath, argv[1], sizeof(filepath));

	context = lws_create_context(&info);
	if (!context) {
		lwsl_err("lws init failed\n");
		return 1;
	}

	while (n >= 0 && !interrupted)
		n = lws_service(context, 1000);

	lws_context_destroy(context);

	return 0;
}
int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	struct lws_context *context;
	const char *p;
	int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE
			/* for LLL_ verbosity above NOTICE to be built into lws,
			 * lws must have been configured and built with
			 * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE */
			/* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */
			/* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */
			/* | LLL_DEBUG */;

	signal(SIGINT, sigint_handler);

	if ((p = lws_cmdline_option(argc, argv, "-d")))
		logs = atoi(p);

	lws_set_log_level(logs, NULL);
	lwsl_user("LWS minimal http server POST | visit http://localhost:7681\n");

	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
	info.port = 7681;
	info.protocols = protocols;
	info.mounts = &mount;
	info.options =
		LWS_SERVER_OPTION_HTTP_HEADERS_SECURITY_BEST_PRACTICES_ENFORCE;

	if (lws_cmdline_option(argc, argv, "-s")) {
		info.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
		info.ssl_cert_filepath = "localhost-100y.cert";
		info.ssl_private_key_filepath = "localhost-100y.key";
	}

	context = lws_create_context(&info);
	if (!context) {
		lwsl_err("lws init failed\n");
		return 1;
	}

	while (n >= 0 && !interrupted)
		n = lws_service(context, 1000);

	lws_context_destroy(context);

	return 0;
}
示例#14
0
int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	struct lws_context *context;
	const char *p;
	int logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE
			/* for LLL_ verbosity above NOTICE to be built into lws,
			 * lws must have been configured and built with
			 * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE */
			/* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */
			/* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */
			/* | LLL_DEBUG */;

	signal(SIGINT, sigint_handler);

	if ((p = lws_cmdline_option(argc, argv, "-d")))
		logs = atoi(p);

	lws_set_log_level(logs, NULL);
	lwsl_user("LWS minimal ws server + threads | visit http://localhost:7681\n");

	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
	info.port = 7681;
	info.mounts = &mount;
	info.protocols = protocols;
	info.pvo = &pvo; /* per-vhost options */
	info.options =
		LWS_SERVER_OPTION_HTTP_HEADERS_SECURITY_BEST_PRACTICES_ENFORCE;

	context = lws_create_context(&info);
	if (!context) {
		lwsl_err("lws init failed\n");
		return 1;
	}

	/* start the threads that create content */

	while (!interrupted)
		if (lws_service(context, 1000))
			interrupted = 1;

	lws_context_destroy(context);

	return 0;
}
示例#15
0
文件: lws.c 项目: lws-team/esplws
void
init_lws(void)
{
	struct lws_context_creation_info info;
	
	lws_set_log_level(7, lwsl_emit_syslog);	

	os_memset(&info, 0, sizeof(info));

	info.port = 80;
	info.fd_limit_per_thread = 12;
	info.max_http_header_pool = 1;
	info.max_http_header_data = 512;
	info.pt_serv_buf_size = 1500;
	info.keepalive_timeout = 5;	
	//info.ws_ping_pong_interval = 30;
	info.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS;

	context = lws_create_context(&info);
	if (context == NULL)
		return;
	
	lws_get_fops(context)->open = esp8266_lws_fops_open;
	lws_get_fops(context)->close = esp8266_lws_fops_close;
	lws_get_fops(context)->read = esp8266_lws_fops_read;
	lws_get_fops(context)->seek_cur = esp8266_lws_fops_seek_cur;

	if (!lwsesp_is_booting_in_ap_mode()) {
		info.vhost_name = "station";
		info.protocols = protocols_station;
		info.mounts = &mount_station;
		if (!lws_create_vhost(context, &info))
			lwsl_err("Failed to create vhost station\n");
	} else {
		info.vhost_name = "ap";
		info.protocols = protocols_ap;
		info.mounts = &mount_ap;
		if (!lws_create_vhost(context, &info))
			lwsl_err("Failed to create vhost ap\n");
	}

	lws_protocol_init(context);
}
示例#16
0
        bool websocket_server::start()
        {
            struct lws_context_creation_info info;

            memset(&info, 0, sizeof info);
            info.port = world()->websocket_port();
            info.iface = NULL;
            info.protocols = protocols;
            info.extensions = lws_get_internal_extensions();
            info.ssl_cert_filepath = NULL;
            info.ssl_private_key_filepath = NULL;
            info.gid = -1;
            info.uid = -1;
            info.options = 0;
            info.user = this;

            context_ = lws_create_context(&info);

            return context_ != NULL;
        }
示例#17
0
FWebSocket::FWebSocket(
		const FInternetAddr& ServerAddress
)
:IsServerSide(false)
{

#if !PLATFORM_HTML5

#if !UE_BUILD_SHIPPING
	lws_set_log_level(LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_DEBUG | LLL_INFO, lws_debugLogS);
#endif

	Protocols = new lws_protocols[3];
	FMemory::Memzero(Protocols, sizeof(lws_protocols) * 3);

	Protocols[0].name = "binary";
	Protocols[0].callback = unreal_networking_client;
	Protocols[0].per_session_data_size = 0;
	Protocols[0].rx_buffer_size = 10 * 1024 * 1024;

	Protocols[1].name = nullptr;
	Protocols[1].callback = nullptr;
	Protocols[1].per_session_data_size = 0;

	struct lws_context_creation_info Info;
	memset(&Info, 0, sizeof Info);

	Info.port = CONTEXT_PORT_NO_LISTEN;
	Info.protocols = &Protocols[0];
	Info.gid = -1;
	Info.uid = -1;
	Info.user = this;

	Context = lws_create_context(&Info);

	check(Context);

	StrInetAddress = ServerAddress.ToString(false);
	InetPort = ServerAddress.GetPort();
#endif
}
FLwsWebSocket::FLwsWebSocket(const FString& InUrl, const TArray<FString>& InProtocols)
	: LwsContext(nullptr)
	, LwsConnection(nullptr)
	, Url(InUrl)
	, Protocols(InProtocols)
	, ReceiveBuffer()
	, CloseCode(0)
	, CloseReason()
	, bIsConnecting(false)
{
	struct lws_context_creation_info ContextInfo = {};

	InitLwsProtocols();
	ContextInfo.port = CONTEXT_PORT_NO_LISTEN;
	ContextInfo.protocols = LwsProtocols.GetData();
	ContextInfo.uid = -1;
	ContextInfo.gid = -1;
	ContextInfo.options |= LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED | LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS;
	ContextInfo.ssl_cipher_list = nullptr;
	LwsContext = lws_create_context(&ContextInfo);
}
示例#19
0
int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	struct lws_context *context;
	const char *p;
	int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE
			/* for LLL_ verbosity above NOTICE to be built into lws,
			 * lws must have been configured and built with
			 * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE */
			/* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */
			/* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */
			/* | LLL_DEBUG */;

	signal(SIGINT, sigint_handler);

	if ((p = lws_cmdline_option(argc, argv, "-d")))
		logs = atoi(p);

	lws_set_log_level(logs, NULL);
	lwsl_user("LWS minimal ws client tx\n");
	lwsl_user("  Run minimal-ws-broker and browse to that\n");

	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
	info.port = CONTEXT_PORT_NO_LISTEN; /* we do not run any server */
	info.protocols = protocols;

	context = lws_create_context(&info);
	if (!context) {
		lwsl_err("lws init failed\n");
		return 1;
	}

	while (n >= 0 && !interrupted)
		n = lws_service(context, 1000);

	lws_context_destroy(context);
	lwsl_user("Completed\n");

	return 0;
}
示例#20
0
JNIEXPORT jboolean JNICALL jni_initLws(JNIEnv *env, jobject obj)
{
    if(context) return JNI_TRUE;

    // Attach the java virtual machine to this thread
    gJvm->AttachCurrentThread(&gEnv, NULL);

    // Set java global references to the class and object
    jclass cls = env->GetObjectClass(obj);
    gLwsServiceCls = (jclass) env->NewGlobalRef(cls);
    gLwsServiceObj = env->NewGlobalRef(obj);

    // Get the sendMessage method from the LwsService class (inherited from class ThreadService)
    sendMessageId = gEnv->GetMethodID(gLwsServiceCls, "sendMessage", "(ILjava/lang/Object;)V");

    memset(&info, 0, sizeof(info));
    info.port = CONTEXT_PORT_NO_LISTEN;
    info.protocols = protocols;
#if !defined(LWS_WITHOUT_EXTENSIONS)
    info.extensions = exts;
#endif
    info.gid = -1;
    info.uid = -1;

    lws_set_log_level( LLL_NOTICE | LLL_INFO | LLL_ERR | LLL_WARN | LLL_CLIENT, emit_log );

    context = lws_create_context(&info);
    if( context == NULL ){
        emit_log(LLL_ERR, "Creating libwebsocket context failed");
        return JNI_FALSE;
    }

    isExit = 0;

    return JNI_TRUE;
}
bool FNetworkFileServerHttp::Init()
{
	// setup log level.
#if UE_BUILD_DEBUG
	lws_set_log_level( LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_DEBUG , lws_debugLog);
#endif

	struct lws_context_creation_info Info;
	memset(&Info,0,sizeof(lws_context_creation_info));

	// look up libwebsockets.h for details.
	Info.port = Port;
	// we listen on all available interfaces.
	Info.iface = NULL;
	// serve only the http protocols.
	Info.protocols = Protocols;
	// no extensions
	Info.extensions = NULL;
	Info.gid = -1;
	Info.uid = -1;
	Info.options = 0;
	// tack on this object.
	Info.user = this;

	Context = lws_create_context(&Info);

	Port = Info.port;

	if (Context == NULL) {
		UE_LOG(LogFileServer, Fatal, TEXT(" Could not create a libwebsocket content for port : %d"), Port);
		return false;
	}

	Ready.Set(true);
	return true;
}
static int
callback_minimal_broker(struct lws *wsi, enum lws_callback_reasons reason,
			void *user, void *in, size_t len)
{
	struct pss *pss = (struct pss *)user;
	int n;

	switch (reason) {

	case LWS_CALLBACK_PROTOCOL_INIT:
		goto try;

	case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
		lwsl_err("CLIENT_CONNECTION_ERROR: %s\n",
			 in ? (char *)in : "(null)");
		client_wsi = NULL;
		lws_timed_callback_vh_protocol(lws_get_vhost(wsi),
				lws_get_protocol(wsi), LWS_CALLBACK_USER, 1);
		break;

	/* --- client callbacks --- */

	case LWS_CALLBACK_CLIENT_ESTABLISHED:
		lwsl_user("%s: established\n", __func__);
		lws_set_timer_usecs(wsi, 5 * LWS_USEC_PER_SEC);
		break;

	case LWS_CALLBACK_CLIENT_WRITEABLE:
		if (pss->send_a_ping) {
			uint8_t ping[LWS_PRE + 125];
			int m;

			pss->send_a_ping = 0;
			n = 0;
			if (!zero_length_ping)
				n = lws_snprintf((char *)ping + LWS_PRE, 125,
					"ping body!");

			lwsl_user("Sending PING %d...\n", n);

			m = lws_write(wsi, ping + LWS_PRE, n, LWS_WRITE_PING);
			if (m < n) {
				lwsl_err("sending ping failed: %d\n", m);

				return -1;
			}
			
			lws_callback_on_writable(wsi);
		}
		break;

	case LWS_CALLBACK_WS_CLIENT_DROP_PROTOCOL:
		client_wsi = NULL;
		lws_timed_callback_vh_protocol(lws_get_vhost(wsi),
					       lws_get_protocol(wsi),
					       LWS_CALLBACK_USER, 1);
		break;

	case LWS_CALLBACK_CLIENT_RECEIVE_PONG:
		lwsl_user("LWS_CALLBACK_CLIENT_RECEIVE_PONG\n");
		lwsl_hexdump_notice(in, len);
		break;

	case LWS_CALLBACK_TIMER:
		/* we want to send a ws PING every few seconds */
		pss->send_a_ping = 1;
		lws_callback_on_writable(wsi);
		lws_set_timer_usecs(wsi, 5 * LWS_USEC_PER_SEC);
		break;

	/* rate-limited client connect retries */

	case LWS_CALLBACK_USER:
		lwsl_notice("%s: LWS_CALLBACK_USER\n", __func__);
try:
		if (connect_client())
			lws_timed_callback_vh_protocol(lws_get_vhost(wsi),
						       lws_get_protocol(wsi),
						       LWS_CALLBACK_USER, 1);
		break;

	default:
		break;
	}

	return lws_callback_http_dummy(wsi, reason, user, in, len);
}

static const struct lws_protocols protocols[] = {
	{
		"lws-ping-test",
		callback_minimal_broker,
		sizeof(struct pss),
		0,
	},
	{ NULL, NULL, 0, 0 }
};

static void
sigint_handler(int sig)
{
	interrupted = 1;
}

int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	const char *p;
	int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE
			/* for LLL_ verbosity above NOTICE to be built into lws,
			 * lws must have been configured and built with
			 * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE */
			/* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */
			/* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */
			/* | LLL_DEBUG */;

	signal(SIGINT, sigint_handler);

	if ((p = lws_cmdline_option(argc, argv, "-d")))
		logs = atoi(p);

	lws_set_log_level(logs, NULL);
	lwsl_user("LWS minimal ws client PING\n");

	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
	info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
	info.port = CONTEXT_PORT_NO_LISTEN; /* we do not run any server */
	info.protocols = protocols;
#if defined(LWS_WITH_MBEDTLS)
	/*
	 * OpenSSL uses the system trust store.  mbedTLS has to be told which
	 * CA to trust explicitly.
	 */
	info.client_ssl_ca_filepath = "./libwebsockets.org.cer";
#endif

	if (lws_cmdline_option(argc, argv, "-z"))
		zero_length_ping = 1;

	if ((p = lws_cmdline_option(argc, argv, "--protocol")))
		pro = p;

	if ((p = lws_cmdline_option(argc, argv, "--server"))) {
		server_address = p;
		pro = "lws-minimal";
		ssl_connection |= LCCSCF_ALLOW_SELFSIGNED;
	}

	if ((p = lws_cmdline_option(argc, argv, "--port")))
		port = atoi(p);

	/*
	 * since we know this lws context is only ever going to be used with
	 * one client wsis / fds / sockets at a time, let lws know it doesn't
	 * have to use the default allocations for fd tables up to ulimit -n.
	 * It will just allocate for 1 internal and 1 (+ 1 http2 nwsi) that we
	 * will use.
	 */
	info.fd_limit_per_thread = 1 + 1 + 1;

	context = lws_create_context(&info);
	if (!context) {
		lwsl_err("lws init failed\n");
		return 1;
	}

	while (n >= 0 && !interrupted)
		n = lws_service(context, 1000);

	lws_context_destroy(context);
	lwsl_user("Completed\n");

	return 0;
}
示例#23
0
/**
 * Create WebSocket structure
 *
 * @param sb pointer to SystemBase
 * @param port port on which WS will work
 * @param sslOn TRUE when WS must be secured through SSL, otherwise FALSE
 * @return pointer to new WebSocket structure, otherwise NULL
 */
WebSocket *WebSocketNew( void *sb,  int port, FBOOL sslOn )
{
	WebSocket *ws = NULL;
	SystemBase *lsb = (SystemBase *)sb;
	
	DEBUG1("[WS] New websocket\n");
	
	pthread_mutex_init( &WSThreadMutex, NULL );
	
	if( ( ws = FCalloc( 1, sizeof( WebSocket ) ) ) != NULL )
	{
		char *fhome = getenv( "FRIEND_HOME" );
		ws->ws_FCM = lsb->fcm;
		
		ws->ws_Port = port;
		ws->ws_UseSSL = sslOn;
		ws->ws_OldTime = 0;
		ws->ws_InterfaceName[ 0 ] = 0;
		memset( &(ws->ws_Info), 0, sizeof ws->ws_Info );
		ws->ws_Opts = 0;
		ws->ws_Interface = NULL;
		
		if( ws->ws_UseSSL == TRUE )
		{
			INFO("[WS] WebSocket: SSL Enabled\n");
			
			ws->ws_CertPath = lsb->RSA_SERVER_CERT;
			ws->ws_KeyPath = lsb->RSA_SERVER_KEY;
			
			DEBUG1("[WS] server cert %s keycert %s\n", ws->ws_CertPath, ws->ws_KeyPath );
		
			//sprintf( ws->ws_CertPath, "%s%s", fhome, "/libwebsockets-test-server.pem" );
			//sprintf( ws->ws_KeyPath, "%s%s", fhome, "/libwebsockets-test-server.key.pem" );
			//ws->ws_Opts |= LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS;
		}
		
		if( ws->ws_AllowNonSSL == TRUE )
		{
			 //ws->ws_Opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
		}
		
			/*
		case 'k':
			opts = LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK;
			break;
			*/
		ws->ws_Info.port = ws->ws_Port;
		ws->ws_Info.protocols = protocols;
		ws->ws_Info.iface = ws->ws_Interface;
		ws->ws_Info.gid = -1;
		ws->ws_Info.uid = -1;
		ws->ws_Info.extensions = NULL;
		ws->ws_Info.ssl_cert_filepath = ws->ws_CertPath;
		ws->ws_Info.ssl_private_key_filepath = ws->ws_KeyPath;
		ws->ws_Info.options = ws->ws_Opts;// | LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT;
		if( ws->ws_UseSSL == TRUE ) 
		{
			ws->ws_Info.options |= LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS|LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
		}
		
		ws->ws_Info.user = ws;
		
		//ws->ws_Info.extensions = lws_get_internal_extensions();
		//ws->ws_Info.extensions->per_context_private_data = ws;
		ws->ws_Info.ssl_cipher_list = "ECDHE-ECDSA-AES256-GCM-SHA384:"
			       "ECDHE-RSA-AES256-GCM-SHA384:"
			       "DHE-RSA-AES256-GCM-SHA384:"
			       "ECDHE-RSA-AES256-SHA384:"
			       "HIGH:!aNULL:!eNULL:!EXPORT:"
			       "!DES:!MD5:!PSK:!RC4:!HMAC_SHA1:"
			       "!SHA1:!DHE-RSA-AES128-GCM-SHA256:"
			       "!DHE-RSA-AES128-SHA256:"
			       "!AES128-GCM-SHA256:"
			       "!AES128-SHA256:"
			       "!DHE-RSA-AES256-SHA256:"
			       "!AES256-GCM-SHA384:"
			       "!AES256-SHA256";
		
		ws->ws_CountPollfds = 0;
		
		//ws->ws_Info.ka_time = 15;
		//lws_set_log_level( 0, lwsl_emit_syslog);
		
		ws->ws_Context = lws_create_context( &ws->ws_Info );
		if( ws->ws_Context == NULL )
		{
			FERROR( "Libwebsocket init failed, cannot create context\n" );
			FFree( ws );
			return NULL;
		}
		
		INFO("[WS] NEW Websockets ptr %p context %p\n", ws, ws->ws_Context);

		ws->ws_Buf[ LWS_SEND_BUFFER_PRE_PADDING ] = 'x';
			
	}
	else
	{
		FERROR("[WS] Cannot allocate memory for WebSocket\n");
	}
	
	DEBUG1("[WS] Websocket created\n");
	
	return ws;
}
示例#24
0
int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	struct lws_context *context;
	const char *p;
	int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE
			/* for LLL_ verbosity above NOTICE to be built into lws,
			 * lws must have been configured and built with
			 * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE */
			/* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */
			/* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */
			/* | LLL_DEBUG */;

	if ((p = lws_cmdline_option(argc, argv, "-d")))
		logs = atoi(p);

	lws_set_log_level(logs, NULL);
	lwsl_user("LWS minimal http server-multivhost | visit http://localhost:7681 / 7682\n");

	signal(SIGINT, sigint_handler);

	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
	info.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
		LWS_SERVER_OPTION_HTTP_HEADERS_SECURITY_BEST_PRACTICES_ENFORCE;

	/*
	 * Because of LWS_SERVER_OPTION_EXPLICIT_VHOSTS, this only creates
	 * the context and no longer creates a default vhost
	 */
	context = lws_create_context(&info);
	if (!context) {
		lwsl_err("lws init failed\n");
		return 1;
	}

	/* it's our job now to create the vhosts we want:
	 *
	 *   - "localhost1" listen on 7681 and serve ./mount-origin-localhost1/
	 *   - "localhost2" listen on 7682 and serve ./mount-origin-localhost2/
	 *   - "localhost3" share 7682 and serve ./mount-origin-localhost3/
	 *
	 * Note lws supports dynamic vhost creation and destruction at runtime.
	 * When using multi-vhost with your own protocols, you must provide a
	 * pvo for each vhost naming each protocol you want enabled on it.
	 * minimal-ws-server-threads demonstrates how to provide pvos.
	 */

	info.port = 7681;
	info.mounts = &mount_localhost1;
	info.error_document_404 = "/404.html";
	info.vhost_name = "localhost1";

	if (!lws_create_vhost(context, &info)) {
		lwsl_err("Failed to create first vhost\n");
		goto bail;
	}

	info.port = 7682;
	info.mounts = &mount_localhost2;
	info.error_document_404 = "/404.html";
	info.vhost_name = "localhost2";

	if (!lws_create_vhost(context, &info)) {
		lwsl_err("Failed to create second vhost\n");
		goto bail;
	}

	/* a second vhost listens on port 7682 */
	info.mounts = &mount_localhost3;
	info.error_document_404 = "/404.html";
	info.vhost_name = "localhost3";
	info.finalize = vh_destruction_notification;
	info.finalize_arg = NULL;

	if (!lws_create_vhost(context, &info)) {
		lwsl_err("Failed to create third vhost\n");
		goto bail;
	}

	if (lws_cmdline_option(argc, argv, "--die-after-vhost")) {
		lwsl_warn("bailing after creating vhosts\n");
		goto bail;
	}

	while (n >= 0 && !interrupted)
		n = lws_service(context, 1000);

bail:
	lws_context_destroy(context);

	return 0;
}
示例#25
0
文件: server.c 项目: 5ouya/raspC
int main(int argc, char **argv)
{
	daemonize();
	




	//saveData("admin",100,100,"admin");

	config_obj=parseConfigFile();
	ipWhitelist = cJSON_GetObjectItem(config_obj,"ipWhitelist");

	wiringPiSetup();
	pinDirections = cJSON_GetObjectItem(config_obj,"pinDirections");
	handlePinsDirection(pinDirections);

	signal(SIGINT, sighandler);
	


	struct lws_context_creation_info info;
	unsigned int ms, oldms= 0;
	const char *iface = NULL;
	char cert_path[1024];
	char key_path[1024];
	int use_ssl = 0;
	int opts = 0;
	int n = 0;

	/*
	 * take care to zero down the info struct, he contains random garbaage
	 * from the stack otherwise
	 */
	 memset(&info, 0, sizeof info);
	 info.port = 7681;


	 signal(SIGINT, sighandler);



	 info.iface = iface;
	 info.protocols = protocols;
	 info.ssl_cert_filepath = NULL;
	 info.ssl_private_key_filepath = NULL;

	 if (use_ssl) {
	 	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.max_http_header_pool = 1;
	 info.options = opts | LWS_SERVER_OPTION_VALIDATE_UTF8;
	 info.extensions = NULL;
	 context = lws_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)
		 */
		 extern struct ram_usage ram_l;
		 extern struct cpu_live cpu_l;
		 extern struct cpu_freq cpu_freq;




		if(old_client_count!=client_count){
			if(hash){
				free(hash);
			}

			hash=rand_string();
		 	lws_callback_on_writable_all_protocol(context,
		 		&protocols[PROTOCOL_GPIO]);
		 	lws_callback_on_writable_all_protocol(context,
		 		&protocols[PROTOCOL_DETAILS]);		
		 	lws_callback_on_writable_all_protocol(context,
		 		&protocols[PROTOCOL_SERVICES]);	
		 	lws_callback_on_writable_all_protocol(context,
		 		&protocols[PROTOCOL_HOME]);			 				 			 					
			old_client_count=client_count;
		}

		 ms = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
		 if ((ms - oldms) > 200 && get_client_count()>0 && (cpuLive(&cpu_l,5)==0 && ramLive(&ram_l,5)==0  && cpuLiveFreq(&cpu_freq)==0 )) {
		 	lws_callback_on_writable_all_protocol(context,
		 		&protocols[PROTOCOL_DETAILS]);
		 	oldms = ms;
		 }				 


		 n = lws_service(context, 50);
	}

		lws_context_destroy(context);

		lwsl_notice("libwebsockets-test-server exited cleanly\n");


		return 0;
	}
int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	struct lws_context *context;
	const char *p;
	int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE
			/* for LLL_ verbosity above NOTICE to be built into lws,
			 * lws must have been configured and built with
			 * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE */
			/* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */
			/* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */
			/* | LLL_DEBUG */;

	signal(SIGINT, sigint_handler);

	if ((p = lws_cmdline_option(argc, argv, "-d")))
		logs = atoi(p);

	lws_set_log_level(logs, NULL);
	lwsl_user("LWS minimal http server dynamic | visit http://localhost:7681\n");

	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
	info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT |
		       LWS_SERVER_OPTION_EXPLICIT_VHOSTS;

	/* for testing ah queue, not useful in real world */
	if (lws_cmdline_option(argc, argv, "--ah1"))
		info.max_http_header_pool = 1;

	context = lws_create_context(&info);
	if (!context) {
		lwsl_err("lws init failed\n");
		return 1;
	}

	/* http on 7681 */

	info.port = 7681;
	info.protocols = protocols;
	info.mounts = &mount;
	info.vhost_name = "http";

	if (!lws_create_vhost(context, &info)) {
		lwsl_err("Failed to create tls vhost\n");
		goto bail;
	}

	/* https on 7682 */

	info.port = 7682;
	info.error_document_404 = "/404.html";
	info.ssl_cert_filepath = "localhost-100y.cert";
	info.ssl_private_key_filepath = "localhost-100y.key";
	info.vhost_name = "localhost";

	if (!lws_create_vhost(context, &info)) {
		lwsl_err("Failed to create tls vhost\n");
		goto bail;
	}

	while (n >= 0 && !interrupted)
		n = lws_service(context, 1000);

bail:
	lws_context_destroy(context);

	return 0;
}
int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	struct lws_client_connect_info i;
	struct lws_context *context;
	const char *p;
	int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE
		   /*
		    * For LLL_ verbosity above NOTICE to be built into lws,
		    * lws must have been configured and built with
		    * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE
		    *
		    * | LLL_INFO   | LLL_PARSER  | LLL_HEADER | LLL_EXT |
		    *   LLL_CLIENT | LLL_LATENCY | LLL_DEBUG
		    */ ;

	signal(SIGINT, sigint_handler);

	if ((p = lws_cmdline_option(argc, argv, "-d")))
		logs = atoi(p);

	lws_set_log_level(logs, NULL);
	lwsl_user("LWS minimal http client [-d<verbosity>] [-l] [--h1]\n");

	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
	info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
	info.port = CONTEXT_PORT_NO_LISTEN; /* we do not run any server */
	info.protocols = protocols;

#if defined(LWS_WITH_MBEDTLS)
	/*
	 * OpenSSL uses the system trust store.  mbedTLS has to be told which
	 * CA to trust explicitly.
	 */
	info.client_ssl_ca_filepath = "./warmcat.com.cer";
#endif

	context = lws_create_context(&info);
	if (!context) {
		lwsl_err("lws init failed\n");
		return 1;
	}

	memset(&i, 0, sizeof i); /* otherwise uninitialized garbage */
	i.context = context;
	i.ssl_connection = LCCSCF_USE_SSL;

	if (lws_cmdline_option(argc, argv, "-l")) {
		i.port = 7681;
		i.address = "localhost";
		i.ssl_connection |= LCCSCF_ALLOW_SELFSIGNED;
	} else {
		i.port = 443;
		i.address = "warmcat.com";
	}

	if (lws_cmdline_option(argc, argv, "--h1"))
		i.alpn = "http/1.1";

	i.path = "/";
	i.host = i.address;
	i.origin = i.address;
	i.method = "GET";

	i.protocol = protocols[0].name;
	i.pwsi = &client_wsi;
	lws_client_connect_via_info(&i);

	while (n >= 0 && client_wsi && !interrupted)
		n = lws_service(context, 1000);

	lws_context_destroy(context);
	lwsl_user("Completed: %s\n", bad ? "failed" : "OK");

	return bad;
}
示例#28
0
int main(int argc, char **argv)
{
	int n = 0, ret = 0, port = 7681, use_ssl = 0;
	unsigned int rl_dumb = 0, rl_mirror = 0;
	struct lws_context_creation_info info;
	struct lws_context *context;
	int ietf_version = -1; /* latest */
	const char *address;

	memset(&info, 0, sizeof info);

	fprintf(stderr, "libwebsockets test client\n"
			"(C) Copyright 2010-2015 Andy Green <*****@*****.**> "
			"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 = lws_get_internal_extensions();
#endif
	info.gid = -1;
	info.uid = -1;

	context = lws_create_context(&info);
	if (context == NULL) {
		fprintf(stderr, "Creating libwebsocket context failed\n");
		return 1;
	}

	/*
	 * 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... calling lws_client_connect() only
	 * instantiates the connection logically, lws_service() progresses it
	 * asynchronously.
	 */

	while (!force_exit) {

		if (!wsi_dumb && ratelimit_connects(&rl_dumb, 2u)) {
			lwsl_notice("dumb: connecting\n");
			wsi_dumb = lws_client_connect(context, address, port,
				use_ssl, "/", argv[optind], argv[optind],
				protocols[PROTOCOL_DUMB_INCREMENT].name,
				ietf_version);
		}

		if (!wsi_mirror && ratelimit_connects(&rl_mirror, 2u)) {
			lwsl_notice("mirror: connecting\n");
			wsi_mirror = lws_client_connect(context,
				address, port, use_ssl,  "/",
				argv[optind], argv[optind],
				protocols[PROTOCOL_LWS_MIRROR].name,
				ietf_version);
		}

		lws_service(context, 500);
	}

	lwsl_err("Exiting\n");
	lws_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;
}
示例#29
0
int main(int argc, char **argv)
{
	int n = 0, ret = 0, port = 7681, use_ssl = 0, ietf_version = -1;
	unsigned int rl_dumb = 0, rl_mirror = 0, do_ws = 1, pp_secs = 0;
	struct lws_context_creation_info info;
	struct lws_client_connect_info i;
	struct lws_context *context;
	const char *prot, *p;
	char path[300];
	char cert_path[1024] = "";
	char key_path[1024] = "";
	char ca_path[1024] = "";

	memset(&info, 0, sizeof info);

	lwsl_notice("libwebsockets test client - license LGPL2.1+SLE\n");
	lwsl_notice("(C) Copyright 2010-2016 Andy Green <*****@*****.**>\n");

	if (argc < 2)
		goto usage;

	while (n >= 0) {
		n = getopt_long(argc, argv, "Snuv:hsp:d:lC:K:A:P:", options, NULL);
		if (n < 0)
			continue;
		switch (n) {
		case 'd':
			lws_set_log_level(atoi(optarg), NULL);
			break;
		case 's': /* lax SSL, allow selfsigned, skip checking hostname */
			use_ssl = LCCSCF_USE_SSL |
				  LCCSCF_ALLOW_SELFSIGNED |
				  LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;
			break;
		case 'S': /* Strict SSL, no selfsigned, check server hostname */
			use_ssl = LCCSCF_USE_SSL;
			break;
		case 'p':
			port = atoi(optarg);
			break;
		case 'P':
			pp_secs = atoi(optarg);
			lwsl_notice("Setting pingpong interval to %d\n", pp_secs);
			break;
		case 'l':
			longlived = 1;
			break;
		case 'v':
			ietf_version = atoi(optarg);
			break;
		case 'u':
			deny_deflate = 1;
			break;
		case 'n':
			flag_no_mirror_traffic = 1;
			lwsl_notice("Disabled sending mirror data (for pingpong testing)\n");
			break;
		case 'C':
			strncpy(cert_path, optarg, sizeof(cert_path) - 1);
			cert_path[sizeof(cert_path) - 1] = '\0';
			break;
		case 'K':
			strncpy(key_path, optarg, sizeof(key_path) - 1);
			key_path[sizeof(key_path) - 1] = '\0';
			break;
		case 'A':
			strncpy(ca_path, optarg, sizeof(ca_path) - 1);
			ca_path[sizeof(ca_path) - 1] = '\0';
			break;
#if defined(LWS_USE_POLARSSL)
#else
#if defined(LWS_USE_MBEDTLS)
#else
#if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
		case 'R':
			strncpy(crl_path, optarg, sizeof(crl_path) - 1);
			crl_path[sizeof(crl_path) - 1] = '\0';
			break;
#endif
#endif
#endif
		case 'h':
			goto usage;
		}
	}

	if (optind >= argc)
		goto usage;

	signal(SIGINT, sighandler);

	memset(&i, 0, sizeof(i));

	i.port = port;
	if (lws_parse_uri(argv[optind], &prot, &i.address, &i.port, &p))
		goto usage;

	/* add back the leading / on path */
	path[0] = '/';
	strncpy(path + 1, p, sizeof(path) - 2);
	path[sizeof(path) - 1] = '\0';
	i.path = path;

	if (!strcmp(prot, "http") || !strcmp(prot, "ws"))
		use_ssl = 0;
	if (!strcmp(prot, "https") || !strcmp(prot, "wss"))
		if (!use_ssl)
			use_ssl = LCCSCF_USE_SSL;

	/*
	 * 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;
	info.gid = -1;
	info.uid = -1;
	info.ws_ping_pong_interval = pp_secs;

	if (use_ssl) {
		info.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;

		/*
		 * If the server wants us to present a valid SSL client certificate
		 * then we can set it up here.
		 */

		if (cert_path[0])
			info.ssl_cert_filepath = cert_path;
		if (key_path[0])
			info.ssl_private_key_filepath = key_path;

		/*
		 * A CA cert and CRL can be used to validate the cert send by the server
		 */
		if (ca_path[0])
			info.ssl_ca_filepath = ca_path;
#if defined(LWS_USE_POLARSSL)
#else
#if defined(LWS_USE_MBEDTLS)
#else
#if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
		else if (crl_path[0])
			lwsl_notice("WARNING, providing a CRL requires a CA cert!\n");
#endif
#endif
#endif
	}

	if (use_ssl & LCCSCF_USE_SSL)
		lwsl_notice(" Using SSL\n");
	else
		lwsl_notice(" SSL disabled\n");
	if (use_ssl & LCCSCF_ALLOW_SELFSIGNED)
		lwsl_notice(" Selfsigned certs allowed\n");
	else
		lwsl_notice(" Cert must validate correctly (use -s to allow selfsigned)\n");
	if (use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)
		lwsl_notice(" Skipping peer cert hostname check\n");
	else
		lwsl_notice(" Requiring peer cert hostname matches\n");

	context = lws_create_context(&info);
	if (context == NULL) {
		fprintf(stderr, "Creating libwebsocket context failed\n");
		return 1;
	}

	i.context = context;
	i.ssl_connection = use_ssl;
	i.host = i.address;
	i.origin = i.address;
	i.ietf_version_or_minus_one = ietf_version;
	i.client_exts = exts;

	if (!strcmp(prot, "http") || !strcmp(prot, "https")) {
		lwsl_notice("using %s mode (non-ws)\n", prot);
		i.method = "GET";
		do_ws = 0;
	} else
		lwsl_notice("using %s mode (ws)\n", prot);

	/*
	 * 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... calling lws_client_connect() only
	 * instantiates the connection logically, lws_service() progresses it
	 * asynchronously.
	 */

	while (!force_exit) {

		if (do_ws) {
			if (!wsi_dumb && ratelimit_connects(&rl_dumb, 2u)) {
				lwsl_notice("dumb: connecting\n");
				i.protocol = protocols[PROTOCOL_DUMB_INCREMENT].name;
				i.pwsi = &wsi_dumb;
				lws_client_connect_via_info(&i);
			}

			if (!wsi_mirror && ratelimit_connects(&rl_mirror, 2u)) {
				lwsl_notice("mirror: connecting\n");
				i.protocol = protocols[PROTOCOL_LWS_MIRROR].name;
				i.pwsi = &wsi_mirror;
				wsi_mirror = lws_client_connect_via_info(&i);
			}
		} else
			if (!wsi_dumb && ratelimit_connects(&rl_dumb, 2u)) {
				lwsl_notice("http: connecting\n");
				i.pwsi = &wsi_dumb;
				lws_client_connect_via_info(&i);
			}

		lws_service(context, 500);
	}

	lwsl_err("Exiting\n");
	lws_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;
}
示例#30
0
int main(int argc, char **argv)
{
	struct lws_context_creation_info info;
	struct lws_vhost *vhost;
	char interface_name[128] = "";
	unsigned int ms, oldms = 0;
	const char *iface = NULL;
	char cert_path[1024] = "";
	char key_path[1024] = "";
	char ca_path[1024] = "";
	int uid = -1, gid = -1;
	int use_ssl = 0;
	int pp_secs = 0;
	int opts = 0;
	int n = 0;
#ifndef _WIN32
/* LOG_PERROR is not POSIX standard, and may not be portable */
#ifdef __sun
	int syslog_options = LOG_PID;
#else
	int syslog_options = LOG_PID | LOG_PERROR;
#endif
#endif
#ifndef LWS_NO_DAEMONIZE
	int daemonize = 0;
#endif

	/*
	 * take care to zero down the info struct, he contains random garbaage
	 * from the stack otherwise
	 */
	memset(&info, 0, sizeof info);
	info.port = 7681;

	while (n >= 0) {
		n = getopt_long(argc, argv, "eci:hsap:d:Dr:C:K:A:R:vu:g:P:k",
				options, NULL);
		if (n < 0)
			continue;
		switch (n) {
		case 'e':
			opts |= LWS_SERVER_OPTION_LIBEV;
			break;
#ifndef LWS_NO_DAEMONIZE
		case 'D':
			daemonize = 1;
#if !defined(_WIN32) && !defined(__sun)
			syslog_options &= ~LOG_PERROR;
#endif
			break;
#endif
		case 'u':
			uid = atoi(optarg);
			break;
		case 'g':
			gid = atoi(optarg);
			break;
		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 'k':
			info.bind_iface = 1;
#if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
			info.caps[0] = CAP_NET_RAW;
			info.count_caps = 1;
#endif
			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 'C':
			strncpy(cert_path, optarg, sizeof(cert_path) - 1);
			cert_path[sizeof(cert_path) - 1] = '\0';
			break;
		case 'K':
			strncpy(key_path, optarg, sizeof(key_path) - 1);
			key_path[sizeof(key_path) - 1] = '\0';
			break;
		case 'A':
			strncpy(ca_path, optarg, sizeof(ca_path) - 1);
			ca_path[sizeof(ca_path) - 1] = '\0';
			break;
		case 'P':
			pp_secs = atoi(optarg);
			lwsl_notice("Setting pingpong interval to %d\n",
				    pp_secs);
			break;
#if defined(LWS_OPENSSL_SUPPORT)
		case 'v':
			use_ssl = 1;
			opts |=
			    LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT;
			break;

#if defined(LWS_HAVE_SSL_CTX_set1_param)
		case 'R':
			strncpy(crl_path, optarg, sizeof(crl_path) - 1);
			crl_path[sizeof(crl_path) - 1] = '\0';
			break;
#endif
#endif
		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 10;
	}
#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 - license LGPL2.1+SLE\n");
	lwsl_notice("(C) Copyright 2010-2016 Andy Green <*****@*****.**>\n");

	printf("Using resource path \"%s\"\n", resource_path);
#ifdef EXTERNAL_POLL
	max_poll_elements = getdtablesize();
	pollfds = malloc(max_poll_elements * sizeof(struct lws_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;
	info.ssl_cert_filepath = NULL;
	info.ssl_private_key_filepath = NULL;
	info.ws_ping_pong_interval = pp_secs;

	if (use_ssl) {
		if (strlen(resource_path) > sizeof(cert_path) - 32) {
			lwsl_err("resource path too long\n");
			return -1;
		}
		if (!cert_path[0])
			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;
		}
		if (!key_path[0])
			sprintf(key_path,
				"%s/libwebsockets-test-server.key.pem",
				resource_path);

		info.ssl_cert_filepath = cert_path;
		info.ssl_private_key_filepath = key_path;
		if (ca_path[0])
			info.ssl_ca_filepath = ca_path;
	}
	info.gid = gid;
	info.uid = uid;
	info.max_http_header_pool = 16;
	info.options =
	    opts | LWS_SERVER_OPTION_VALIDATE_UTF8 |
	    LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
	    LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
	info.extensions = exts;
	info.timeout_secs = 5;
	info.ssl_cipher_list = "ECDHE-ECDSA-AES256-GCM-SHA384:"
	    "ECDHE-RSA-AES256-GCM-SHA384:"
	    "DHE-RSA-AES256-GCM-SHA384:"
	    "ECDHE-RSA-AES256-SHA384:"
	    "HIGH:!aNULL:!eNULL:!EXPORT:"
	    "!DES:!MD5:!PSK:!RC4:!HMAC_SHA1:"
	    "!SHA1:!DHE-RSA-AES128-GCM-SHA256:"
	    "!DHE-RSA-AES128-SHA256:"
	    "!AES128-GCM-SHA256:"
	    "!AES128-SHA256:"
	    "!DHE-RSA-AES256-SHA256:" "!AES256-GCM-SHA384:" "!AES256-SHA256";

	if (use_ssl)
		/* redirect guys coming on http */
		info.options |= LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS;

	printf("options:%x\r\n", info.options);
	printf("before create\n");
	context = lws_create_context(&info);
	printf("end create\n");
	if (context == NULL) {
		lwsl_err("libwebsocket init failed\n");
		return -1;
	}

	printf("111111\r\n");
	vhost = lws_create_vhost(context, &info);
	if (!vhost) {
		lwsl_err("vhost creation failed\n");
		return -1;
	}
	printf("222222\r\n");
#if !defined(LWS_NO_CLIENT) && defined(LWS_OPENSSL_SUPPORT)
	lws_init_vhost_client_ssl(&info, vhost);
#endif

	/* this shows how to override the lws file operations.  You don't need
	 * to do any of this unless you have a reason (eg, want to serve
	 * compressed files without decompressing the whole archive)
	 */
	/* stash original platform fops */
	fops_plat = *(lws_get_fops(context));
	/* override the active fops */
	lws_get_fops(context)->open = test_server_fops_open;

	n = 0;
#ifdef EXTERNAL_POLL
	int ms_1sec = 0;
#endif
	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) > 1) {
			lws_callback_on_writable_all_protocol(context,
							      &protocols
							      [PROTOCOL_DUMB_INCREMENT]);
			oldms = ms;

		}

		lws_callback_on_writable_all_protocol(context,
						      &protocols
						      [PROTOCOL_FILE_SERVER_SEND]);

#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 (lws_service_fd(context,
							   &pollfds[n]) < 0)
						goto done;

			/* if needed, force-service wsis that may not have read all input */
			while (!lws_service_adjust_timeout(context, 1, 0)) {
				lwsl_notice("extpoll doing forced service!\n");
				lws_service_tsi(context, -1, 0);
			}
		} else {
			/* no revents, but before polling again, make lws check for any timeouts */
			if (ms - ms_1sec > 1000) {
				lwsl_notice("1 per sec\n");
				lws_service_fd(context, NULL);
				ms_1sec = ms;
			}
		}
#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 = lws_service(context, 5);
#endif
	}

#ifdef EXTERNAL_POLL
 done:
#endif

	lws_context_destroy(context);

	lwsl_notice("libwebsockets-test-server exited cleanly\n");

#ifndef _WIN32
	closelog();
#endif

	return 0;
}