int main(int argc, char **argv) { printf("Hello WebSocket World!\n"); signal(SIGINT, sighandler); struct lws_context_creation_info info; memset(&info, 0, sizeof info); lws_set_log_level(0xFFFF, NULL); info.port = CONTEXT_PORT_NO_LISTEN; info.protocols = protocols; info.extensions = libwebsocket_get_internal_extensions(); info.gid = -1; info.uid = -1; context_ = libwebsocket_create_context(&info); if (context_ == NULL) { fprintf(stderr, "Creating libwebsocket context failed\n"); return 1; } return 0; }
int main() { struct lws_context_creation_info info; char *port; signal(SIGINT, sighandler); port = getenv("PORT"); memset(&info, 0, sizeof info); info.port = (port == NULL) ? DEFAULT_PORT : atoi(port); info.protocols = protocols; info.extensions = libwebsocket_get_internal_extensions(); info.gid = -1; info.uid = -1; context = libwebsocket_create_context(&info); if (context == NULL) { lwsl_err("libwebsocket init failed\n"); return -1; } while (!force_exit) { libwebsocket_service(context, 50); } libwebsocket_context_destroy(context); lwsl_notice("exited cleanly\n"); return 0; }
int main () { struct libwebsocket_context *context; struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = 7681; info.iface = NULL; info.protocols = protocols; info.extensions = libwebsocket_get_internal_extensions(); info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; info.gid = -1; info.uid = -1; info.options = 0; context = libwebsocket_create_context(&info); printf ("starting server.\n"); while (1) { libwebsocket_service(context, 50); } libwebsocket_context_destroy(context); return 0; }
int idaapi websocket_thread(void *) { struct libwebsocket_context* context; struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = 3003; info.iface = NULL; info.protocols = protocols; info.extensions = libwebsocket_get_internal_extensions(); info.gid = -1; info.uid = -1; info.options = 0; // i assume this does the bind? context = libwebsocket_create_context(&info); if (context == NULL) { msg("websocket init failed\n"); return -1; } msg("yay websockets\n"); while (websockets_running) { libwebsocket_service(context, 50); } libwebsocket_context_destroy(context); return 0; }
struct lws_context_creation_info * bmx_libwebsockets_contextcreationinfo_new() { struct lws_context_creation_info * info = (struct lws_context_creation_info*) calloc(1, sizeof(struct lws_context_creation_info)); info->extensions = libwebsocket_get_internal_extensions(); info->gid = -1; info->uid = -1; return info; }
int main( void ) { int port = 8080; const char *interface = NULL; struct libwebsocket_context *context; struct lws_context_creation_info context_info; memset( &context_info, 0, sizeof( struct lws_context_creation_info ) ); context_info.port = 8080; context_info.iface = NULL; context_info.protocols = protocols; context_info.extensions = libwebsocket_get_internal_extensions(); context_info.ssl_cert_filepath = NULL; context_info.ssl_private_key_filepath = NULL; context_info.ssl_ca_filepath = NULL; context_info.ssl_cipher_list = NULL; context_info.http_proxy_address = NULL; context_info.http_proxy_port = 0; context_info.gid = -1; context_info.uid = -1; context_info.options = 0; context_info.user = NULL; context_info.ka_time = 0; context_info.ka_probes = 0; context_info.ka_interval = 0; const char *cert_path = NULL; const char *key_path = NULL; int opts = 0; // context = libwebsocket_create_context( port, interface, protocols, // libwebsocket_internal_extensions, // cert_path, key_path, -1, -1, opts ); context = libwebsocket_create_context( &context_info ); if ( context == NULL ) { fprintf( stderr, "libwebsocket init failed\n" ); return -1; } printf( "Starting server ...\n" ); while ( 1 ) { libwebsocket_service( context, 50 ); } libwebsocket_context_destroy( context ); return 0; }
void WebSocket::onSubThreadStarted() { std::lock_guard<std::mutex> lk(_websocketsMutex); struct lws_context_creation_info info; memset(&info, 0, sizeof info); /* * create the websocket 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 = _wsProtocols; #ifndef LWS_NO_EXTENSIONS info.extensions = libwebsocket_get_internal_extensions(); #endif info.gid = -1; info.uid = -1; info.user = (void*)this; _wsContext = libwebsocket_create_context(&info); if(nullptr != _wsContext) { _readyState = State::kStateConnecting; std::string name; for (int i = 0; _wsProtocols[i].callback != nullptr; ++i) { name += (_wsProtocols[i].name); if (_wsProtocols[i+1].callback != nullptr) name += ", "; } _wsInstance = libwebsocket_client_connect(_wsContext, _host.c_str(), _port, _SSLConnection, _path.c_str(), _host.c_str(), _host.c_str(), name.c_str(), -1); if(NULL == _wsInstance) { WsMessage* msg = new WsMessage(); msg->what = WS_MSG_TO_UITHREAD_ERROR; _readyState = State::kStateClosing; _wsHelper->sendMessageToUIThread(msg); } } }
void WebSocketOpcode_initialiseWebSocket(WebSocketOpcode *self, CSOUND *csound) { size_t argumentsCount = self->inputArgumentCount + self->outputArgumentCount; self->webSocket = csound->Calloc(csound, sizeof(WebSocket)); self->webSocket->protocols = csound->Calloc(csound, //Last protocol is null sizeof(struct libwebsocket_protocols) * (argumentsCount + 1)); size_t argumentIndex = 0; int i; for (i = 0; i < self->outputArgumentCount; ++i, ++argumentIndex) { self->webSocket->protocols[argumentIndex].name = self->outputArguments[i].name; self->webSocket->protocols[argumentIndex].callback = Websocket_callback; self->webSocket->protocols[argumentIndex].per_session_data_size = self->outputArguments[i].bytesCount; } for (i = 0; i < self->inputArgumentCount; ++i, ++argumentIndex) { self->webSocket->protocols[argumentIndex].name = self->inputArguments[i].name; self->webSocket->protocols[argumentIndex].callback = Websocket_callback; self->webSocket->protocols[argumentIndex].per_session_data_size = self->inputArguments[i].bytesCount; } self->webSocket->info.port = *self->arguments[self->outputArgumentCount]; self->webSocket->info.protocols = self->webSocket->protocols; self->webSocket->info.extensions = libwebsocket_get_internal_extensions(); self->webSocket->info.gid = -1; self->webSocket->info.uid = -1; self->webSocket->info.user = self; lws_set_log_level(LLL_ERR, NULL); self->webSocket->context = libwebsocket_create_context(&self->webSocket->info); self->webSocket->messageBuffer = csound->Calloc(csound, LWS_SEND_BUFFER_PRE_PADDING + (sizeof(char) * writeBufferBytesCount) + LWS_SEND_BUFFER_POST_PADDING); if (self->webSocket->context == NULL) { csound->Die(csound, Str("websocket: could not initialise websocket, Exiting")); } self->isRunning = true; self->webSocket->processThread = csound->CreateThread(WebSocketOpcode_processThread, self); }
void* HostProcess_WebSocketListener(void* stuff) { HostStuff* phoststuff=(HostStuff*)stuff; struct libwebsocket_context *context; int opts = 0; struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = WEB_PORT; info.iface = 0; info.protocols = protocols; info.extensions = libwebsocket_get_internal_extensions(); info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; info.gid = -1; info.uid = -1; info.options = opts; info.user=phoststuff; context = libwebsocket_create_context(&info); if (context == NULL) { fprintf(stderr, "libwebsocket init failed\n"); return 0; } printf("starting server...\n"); // infinite loop, to end this server send SIGTERM. (CTRL+C) while (1) { libwebsocket_service(context, 50); // libwebsocket_service will process all waiting events with their // callback functions and then wait 50 ms. // (this is a single threaded webserver and this will keep our server // from generating load while there are not requests to process) } libwebsocket_context_destroy(context); return 0; }
int init() { int n = 0; //struct libwebsocket_context *context; int opts = 0; const char *iface = NULL; int syslog_options = LOG_PID | LOG_PERROR; unsigned int oldus = 0; struct lws_context_creation_info info; int debug_level = 7; memset(&info, 0, sizeof info); info.port = 9999; signal(SIGINT, sighandler); /* 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); info.iface = iface; info.protocols = protocols; info.extensions = libwebsocket_get_internal_extensions(); info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; 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; } closelog(); return 0; }//main
int ws_start(short port){ struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = port; lwsl_notice("libwebsockets test server - " "(C) Copyright 2010-2013 Andy Green <*****@*****.**> - " "licensed under LGPL2.1\n"); info.protocols = protocols; info.extensions = libwebsocket_get_internal_extensions(); /*this is critical. otherwise UTF-8 error in client.*/ info.gid = -1; info.uid = -1; info.ka_time=100; context = libwebsocket_create_context(&info); if (!context){ lwsl_err("libwebsocket init failed\n"); return -1; } return 0; }
void WebSocket::onSubThreadStarted() { struct lws_context_creation_info info; memset(&info, 0, sizeof info); /* * create the websocket 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 = _wsProtocols; #ifndef LWS_NO_EXTENSIONS info.extensions = libwebsocket_get_internal_extensions(); #endif info.gid = -1; info.uid = -1; info.user = (void*)this; _wsContext = libwebsocket_create_context(&info); if(NULL != _wsContext){ _readyState = kStateConnecting; std::string name; for (int i = 0; _wsProtocols[i].callback != NULL; ++i) { name += (_wsProtocols[i].name); if (_wsProtocols[i+1].callback != NULL) { name += ", "; } } _wsInstance = libwebsocket_client_connect(_wsContext, _host.c_str(), _port, _SSLConnection, _path.c_str(), _host.c_str(), _host.c_str(), name.c_str(), -1); } }
void WebSocketSinkManager::setConfiguration(map<string, string> config) { // //Config has been passed, let's start stuff up. configuration = config; struct lws_context_creation_info info; memset(&info, 0, sizeof info); //Default values int port = 23000; std::string interface = "lo"; std::string ssl_cert_path; std::string ssl_key_path; int options = 0; bool ssl = false; info.extensions = nullptr; //Try to load config for (map<string,string>::iterator i=configuration.begin();i!=configuration.end();i++) { //printf("Incoming setting: %s:%s\n",(*i).first.c_str(),(*i).second.c_str()); DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Incoming setting:" << (*i).first << ":" << (*i).second << "\n"; if ((*i).first == "interface") { interface = (*i).second; } if ((*i).first == "port") { port = boost::lexical_cast<int>((*i).second); } if ((*i).first == "cert") { ssl_cert_path = (*i).second; } if ((*i).first == "key") { ssl_key_path = (*i).second; } if ((*i).first == "ssl") { if ((*i).second == "true") { ssl = true; } else { ssl = false; } } if ((*i).first == "useExtensions") { { if((*i).second == "true") { info.extensions = libwebsocket_get_internal_extensions(); } else info.extensions = nullptr; } } } info.iface = interface.c_str(); info.protocols = protocollist; info.gid = -1; info.uid = -1; info.options = options; info.port = port; info.user = this; if (ssl) { info.ssl_cert_filepath = ssl_cert_path.c_str(); info.ssl_private_key_filepath = ssl_key_path.c_str(); } context = libwebsocket_create_context(&info); }
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; int syslog_options = LOG_PID | LOG_PERROR; 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; syslog_options &= ~LOG_PERROR; 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 (!client && daemonize && lws_daemonize("/tmp/.lwstecho-lock")) { fprintf(stderr, "Failed to daemonize\n"); return 1; } #endif /* 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); lwsl_notice("libwebsockets echo test - " "(C) Copyright 2010-2013 Andy Green <*****@*****.**> - " "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) > 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"); closelog(); return 0; }
//-------------------------------------------------------------- bool Server::setup( ServerOptions options ){ /* enum lws_log_levels { LLL_ERR = 1 << 0, LLL_WARN = 1 << 1, LLL_NOTICE = 1 << 2, LLL_INFO = 1 << 3, LLL_DEBUG = 1 << 4, LLL_PARSER = 1 << 5, LLL_HEADER = 1 << 6, LLL_EXT = 1 << 7, LLL_CLIENT = 1 << 8, LLL_LATENCY = 1 << 9, LLL_COUNT = 10 }; */ lws_set_log_level(LLL_WARN, NULL); defaultOptions = options; port = defaultOptions.port = options.port; document_root = defaultOptions.documentRoot = options.documentRoot; // NULL protocol is required by LWS struct libwebsocket_protocols null_protocol = { NULL, NULL, 0 }; //setup protocols lws_protocols.clear(); //register main protocol registerProtocol( options.protocol, serverProtocol ); //register any added protocols for (int i=0; i<protocols.size(); ++i){ struct libwebsocket_protocols lws_protocol = { ( protocols[i].first == "NULL" ? NULL : protocols[i].first.c_str() ), lws_callback, protocols[i].second->rx_buffer_size, protocols[i].second->rx_buffer_size }; lws_protocols.push_back(lws_protocol); } lws_protocols.push_back(null_protocol); // make cert paths null if not using ssl const char * sslCert = NULL; const char * sslKey = NULL; if ( defaultOptions.bUseSSL ){ sslCert = defaultOptions.sslCertPath.c_str(); sslKey = defaultOptions.sslKeyPath.c_str(); } int opts = 0; struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = port; info.protocols = &lws_protocols[0]; info.extensions = libwebsocket_get_internal_extensions(); info.ssl_cert_filepath = sslCert; info.ssl_private_key_filepath = sslKey; info.gid = -1; info.uid = -1; if ( options.ka_time != 0 ){ info.ka_time = options.ka_time; info.ka_probes = options.ka_probes; info.ka_interval = options.ka_interval; } info.options = opts; context = libwebsocket_create_context(&info); if (context == NULL){ ofLogError() << "[ofxLibwebsockets] libwebsockets init failed"; return false; } else { startThread(); // blocking, non-verbose return true; } }
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 oldus = 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 <*****@*****.**> - " "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) */ if (((unsigned int)tv.tv_usec - oldus) > 50000) { libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_DUMB_INCREMENT]); oldus = tv.tv_usec; } #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; }
int main(int argc, char **argv) { int n, gid = -1, uid = -1; int option_index = 0; unsigned int oldus = 0; struct libwebsocket_context *context; struct lws_context_creation_info info; const char *cert_filepath = NULL; const char *private_key_filepath = NULL; const char *iface = NULL; atexit(bye); memset(&info, 0, sizeof info); info.port = 8080; strcpy(mpd_host, "127.0.0.1"); mpd_port = 6600; lws_set_log_level(LLL_ERR | LLL_WARN, NULL); static struct option long_options[] = { {"host", required_argument, 0, 'h'}, {"port", required_argument, 0, 'p'}, {"interface", required_argument, 0, 'i'}, {"webport", required_argument, 0, 'w'}, {"resourcepath", required_argument, 0, 'r'}, {"ssl_cert", required_argument, 0, 'c'}, {"ssl_key", required_argument, 0, 'k'}, {"gid", required_argument, 0, 'g'}, {"uid", required_argument, 0, 'u'}, {"verbose", optional_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 0 }, {0, 0, 0, 0 } }; while((n = getopt_long(argc, argv, "h:p:i:w:r:c:k:g:u:v::V", long_options, &option_index)) != -1) { switch (n) { case 'h': strncpy(mpd_host, optarg, sizeof(mpd_host)); break; case 'p': mpd_port = atoi(optarg); case 'i': iface = optarg; break; case 'w': info.port = atoi(optarg); break; case 'r': resource_path = optarg; break; case 'c': cert_filepath = optarg; break; case 'k': private_key_filepath = optarg; break; case 'g': gid = atoi(optarg); break; case 'u': uid = atoi(optarg); break; case 'v': if(optarg) lws_set_log_level(strtol(optarg, NULL, 10), NULL); else lws_set_log_level(LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_INFO, NULL); break; case 'V': fprintf(stdout, "ympd %d.%d.%d\n" "Copyright (C) 2014 Andrew Karpow <*****@*****.**>\n" "Resource Path: "LOCAL_RESOURCE_PATH"\n" "built " __DATE__ " "__TIME__ " ("__VERSION__")\n", YMPD_VERSION_MAJOR, YMPD_VERSION_MINOR, YMPD_VERSION_PATCH); return EXIT_SUCCESS; break; default: fprintf(stderr, "Usage: %s [OPTION]...\n\n" "\t-h, --host <host>\t\tconnect to mpd at host [localhost]\n" "\t-p, --port <port>\t\tconnect to mpd at port [6600]\n" "\t-i, --interface <interface>\tlisten interface for webserver [all]\n" "\t-w, --webport <port>\t\tlisten port for webserver [8080]\n" "\t-r, --resourcepath <path>\tresourcepath for webserver [" LOCAL_RESOURCE_PATH "]\n" "\t-c, --ssl_cert <filepath>\tssl certificate ssl_private_key_filepath\n" "\t-k, --ssl_key <filepath>\tssl private key filepath\n" "\t-u, --uid <id>\t\t\tuser-id after socket bind\n" "\t-g, --gid <id>\t\t\tgroup-id after socket bind\n" "\t-v, --verbose[<level>]\t\tverbosity level\n" "\t-V, --version\t\t\tget version\n" "\t--help\t\t\t\tthis help\n" , argv[0]); return EXIT_FAILURE; } } if(cert_filepath != NULL && private_key_filepath == NULL) { lwsl_err("private key filepath needed\n"); return EXIT_FAILURE; } if(private_key_filepath != NULL && cert_filepath == NULL) { lwsl_err("public cert filepath needed\n"); return EXIT_FAILURE; } info.ssl_cert_filepath = cert_filepath; info.ssl_private_key_filepath = private_key_filepath; info.iface = iface; info.protocols = protocols; info.extensions = libwebsocket_get_internal_extensions(); info.gid = gid; info.uid = uid; info.options = 0; context = libwebsocket_create_context(&info); if (context == NULL) { lwsl_err("libwebsocket init failed\n"); return EXIT_FAILURE; } 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) */ if (((unsigned int)tv.tv_usec - oldus) > 1000 * 500) { mpd_loop(); libwebsocket_callback_on_writable_all_protocol(&protocols[1]); oldus = tv.tv_usec; } n = libwebsocket_service(context, 50); } libwebsocket_context_destroy(context); return 0; }
struct libwebsocket_context * bmx_libwebsockets_create_context(BBObject * handle, struct lws_context_creation_info * info) { info->user = handle; info->extensions = libwebsocket_get_internal_extensions(); return libwebsocket_create_context(info); }
void webui_start() { 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 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 = 5678; const string path = WEBUI_PATH; const char* resource_path = path.c_str(); #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 <*****@*****.**> - " "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 ; } 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; } 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 ; } n = 0; double old_time = 0; while (n >= 0 && !force_exit) { double time = os_GetSeconds(); /* * 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) */ if ((time - old_time ) > 0.050) { libwebsocket_callback_on_writable_all_protocol(&protocols[PROTOCOL_DUMB_INCREMENT]); old_time = time; } #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; }
/* Transport implementation */ int janus_websockets_init(janus_transport_callbacks *callback, const char *config_path) { if(g_atomic_int_get(&stopping)) { /* Still stopping from before */ return -1; } if(callback == NULL || config_path == NULL) { /* Invalid arguments */ return -1; } /* This is the callback we'll need to invoke to contact the gateway */ gateway = callback; /* Read configuration */ char filename[255]; g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_WEBSOCKETS_PACKAGE); JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename); janus_config *config = janus_config_parse(filename); if(config != NULL) { janus_config_print(config); /* Handle configuration */ janus_config_item *item = janus_config_get_item_drilldown(config, "general", "ws_logging"); if(item && item->value) { ws_log_level = atoi(item->value); if(ws_log_level < 0) ws_log_level = 0; } JANUS_LOG(LOG_VERB, "libwebsockets logging: %d\n", ws_log_level); lws_set_log_level(ws_log_level, NULL); old_wss = NULL; janus_mutex_init(&old_wss_mutex); /* Any ACL for either the Janus or Admin API? */ item = janus_config_get_item_drilldown(config, "general", "ws_acl"); if(item && item->value) { gchar **list = g_strsplit(item->value, ",", -1); gchar *index = list[0]; if(index != NULL) { int i=0; while(index != NULL) { if(strlen(index) > 0) { JANUS_LOG(LOG_INFO, "Adding '%s' to the Janus API allowed list...\n", index); janus_websockets_allow_address(g_strdup(index), FALSE); } i++; index = list[i]; } } g_strfreev(list); list = NULL; } item = janus_config_get_item_drilldown(config, "admin", "admin_ws_acl"); if(item && item->value) { gchar **list = g_strsplit(item->value, ",", -1); gchar *index = list[0]; if(index != NULL) { int i=0; while(index != NULL) { if(strlen(index) > 0) { JANUS_LOG(LOG_INFO, "Adding '%s' to the Admin/monitor allowed list...\n", index); janus_websockets_allow_address(g_strdup(index), TRUE); } i++; index = list[i]; } } g_strfreev(list); list = NULL; } /* Setup the Janus API WebSockets server(s) */ item = janus_config_get_item_drilldown(config, "general", "ws"); if(!item || !item->value || !janus_is_true(item->value)) { JANUS_LOG(LOG_WARN, "WebSockets server disabled\n"); } else { int wsport = 8188; item = janus_config_get_item_drilldown(config, "general", "ws_port"); if(item && item->value) wsport = atoi(item->value); /* Prepare context */ struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = wsport; info.iface = NULL; info.protocols = wss_protocols; info.extensions = libwebsocket_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 WebSocket context */ wss = libwebsocket_create_context(&info); if(wss == NULL) { JANUS_LOG(LOG_FATAL, "Error initializing libwebsock...\n"); } else { JANUS_LOG(LOG_INFO, "WebSockets server started (port %d)...\n", wsport); } } item = janus_config_get_item_drilldown(config, "general", "wss"); if(!item || !item->value || !janus_is_true(item->value)) { JANUS_LOG(LOG_WARN, "Secure WebSockets server disabled\n"); } else { int wsport = 8989; item = janus_config_get_item_drilldown(config, "general", "wss_port"); if(item && item->value) wsport = atoi(item->value); item = janus_config_get_item_drilldown(config, "certificates", "cert_pem"); if(!item || !item->value) { JANUS_LOG(LOG_FATAL, "Missing certificate/key path\n"); } else { char *server_pem = (char *)item->value; char *server_key = (char *)item->value; item = janus_config_get_item_drilldown(config, "certificates", "cert_key"); if(item && item->value) server_key = (char *)item->value; JANUS_LOG(LOG_VERB, "Using certificates:\n\t%s\n\t%s\n", server_pem, server_key); /* Prepare secure context */ struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = wsport; info.iface = NULL; info.protocols = swss_protocols; info.extensions = libwebsocket_get_internal_extensions(); info.ssl_cert_filepath = server_pem; info.ssl_private_key_filepath = server_key; info.gid = -1; info.uid = -1; info.options = 0; /* Create the secure WebSocket context */ swss = libwebsocket_create_context(&info); if(swss == NULL) { JANUS_LOG(LOG_FATAL, "Error initializing libwebsock...\n"); } else { JANUS_LOG(LOG_INFO, "Secure WebSockets server started (port %d)...\n", wsport); } } } /* Do the same for the Admin API, if enabled */ item = janus_config_get_item_drilldown(config, "admin", "admin_ws"); if(!item || !item->value || !janus_is_true(item->value)) { JANUS_LOG(LOG_WARN, "Admin WebSockets server disabled\n"); } else { int wsport = 7188; item = janus_config_get_item_drilldown(config, "admin", "admin_ws_port"); if(item && item->value) wsport = atoi(item->value); /* Prepare context */ struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = wsport; info.iface = NULL; info.protocols = admin_wss_protocols; info.extensions = libwebsocket_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 WebSocket context */ admin_wss = libwebsocket_create_context(&info); if(admin_wss == NULL) { JANUS_LOG(LOG_FATAL, "Error initializing libwebsock...\n"); } else { JANUS_LOG(LOG_INFO, "Admin WebSockets server started (port %d)...\n", wsport); } } item = janus_config_get_item_drilldown(config, "admin", "admin_wss"); if(!item || !item->value || !janus_is_true(item->value)) { JANUS_LOG(LOG_WARN, "Secure Admin WebSockets server disabled\n"); } else { int wsport = 7989; item = janus_config_get_item_drilldown(config, "admin", "admin_wss_port"); if(item && item->value) wsport = atoi(item->value); item = janus_config_get_item_drilldown(config, "certificates", "cert_pem"); if(!item || !item->value) { JANUS_LOG(LOG_FATAL, "Missing certificate/key path\n"); } else { char *server_pem = (char *)item->value; char *server_key = (char *)item->value; item = janus_config_get_item_drilldown(config, "certificates", "cert_key"); if(item && item->value) server_key = (char *)item->value; JANUS_LOG(LOG_VERB, "Using certificates:\n\t%s\n\t%s\n", server_pem, server_key); /* Prepare secure context */ struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = wsport; info.iface = NULL; info.protocols = admin_swss_protocols; info.extensions = libwebsocket_get_internal_extensions(); info.ssl_cert_filepath = server_pem; info.ssl_private_key_filepath = server_key; info.gid = -1; info.uid = -1; info.options = 0; /* Create the secure WebSocket context */ admin_swss = libwebsocket_create_context(&info); if(admin_swss == NULL) { JANUS_LOG(LOG_FATAL, "Error initializing libwebsock...\n"); } else { JANUS_LOG(LOG_INFO, "Secure Admin WebSockets server started (port %d)...\n", wsport); } } } } janus_config_destroy(config); config = NULL; if(!wss && !swss && !admin_wss && !admin_swss) { JANUS_LOG(LOG_FATAL, "No WebSockets server started, giving up...\n"); return -1; /* No point in keeping the plugin loaded */ } wss_janus_api_enabled = wss || swss; wss_admin_api_enabled = admin_wss || admin_swss; GError *error = NULL; /* Start the WebSocket service threads */ if(wss != NULL) { wss_thread = g_thread_try_new("websockets thread", &janus_websockets_thread, wss, &error); if(!wss_thread) { g_atomic_int_set(&initialized, 0); JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the WebSockets thread...\n", error->code, error->message ? error->message : "??"); return -1; } } if(swss != NULL) { swss_thread = g_thread_try_new("secure websockets thread", &janus_websockets_thread, swss, &error); if(!swss_thread) { g_atomic_int_set(&initialized, 0); JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Secure WebSockets thread...\n", error->code, error->message ? error->message : "??"); return -1; } } if(admin_wss != NULL) { admin_wss_thread = g_thread_try_new("admin websockets thread", &janus_websockets_thread, admin_wss, &error); if(!admin_wss_thread) { g_atomic_int_set(&initialized, 0); JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Admin WebSockets thread...\n", error->code, error->message ? error->message : "??"); return -1; } } if(admin_swss != NULL) { admin_swss_thread = g_thread_try_new("secure admin websockets thread", &janus_websockets_thread, admin_swss, &error); if(!admin_swss_thread) { g_atomic_int_set(&initialized, 0); JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Secure Admin WebSockets thread...\n", error->code, error->message ? error->message : "??"); return -1; } } /* Done */ g_atomic_int_set(&initialized, 1); JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_WEBSOCKETS_NAME); return 0; }
/* Transport implementation */ int janus_websockets_init(janus_transport_callbacks *callback, const char *config_path) { if(g_atomic_int_get(&stopping)) { /* Still stopping from before */ return -1; } if(callback == NULL || config_path == NULL) { /* Invalid arguments */ return -1; } /* This is the callback we'll need to invoke to contact the gateway */ gateway = callback; #ifdef HAVE_LIBWEBSOCKETS_NEWAPI JANUS_LOG(LOG_INFO, "libwebsockets >= 1.6 available, using new API\n"); #else JANUS_LOG(LOG_INFO, "libwebsockets < 1.6 available, using old API\n"); #endif /* Read configuration */ char filename[255]; g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_WEBSOCKETS_PACKAGE); JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename); janus_config *config = janus_config_parse(filename); if(config != NULL) { janus_config_print(config); /* Handle configuration */ janus_config_item *item = janus_config_get_item_drilldown(config, "general", "json"); if(item && item->value) { /* Check how we need to format/serialize the JSON output */ if(!strcasecmp(item->value, "indented")) { /* Default: indented, we use three spaces for that */ json_format = JSON_INDENT(3) | JSON_PRESERVE_ORDER; } else if(!strcasecmp(item->value, "plain")) { /* Not indented and no new lines, but still readable */ json_format = JSON_INDENT(0) | JSON_PRESERVE_ORDER; } else if(!strcasecmp(item->value, "compact")) { /* Compact, so no spaces between separators */ json_format = JSON_COMPACT | JSON_PRESERVE_ORDER; } else { JANUS_LOG(LOG_WARN, "Unsupported JSON format option '%s', using default (indented)\n", item->value); json_format = JSON_INDENT(3) | JSON_PRESERVE_ORDER; } } /* Check if we need to send events to handlers */ janus_config_item *events = janus_config_get_item_drilldown(config, "general", "events"); if(events != NULL && events->value != NULL) notify_events = janus_is_true(events->value); if(!notify_events && callback->events_is_enabled()) { JANUS_LOG(LOG_WARN, "Notification of events to handlers disabled for %s\n", JANUS_WEBSOCKETS_NAME); } item = janus_config_get_item_drilldown(config, "general", "ws_logging"); if(item && item->value) { ws_log_level = atoi(item->value); if(ws_log_level < 0) ws_log_level = 0; } JANUS_LOG(LOG_VERB, "libwebsockets logging: %d\n", ws_log_level); lws_set_log_level(ws_log_level, NULL); old_wss = NULL; janus_mutex_init(&old_wss_mutex); /* Any ACL for either the Janus or Admin API? */ item = janus_config_get_item_drilldown(config, "general", "ws_acl"); if(item && item->value) { gchar **list = g_strsplit(item->value, ",", -1); gchar *index = list[0]; if(index != NULL) { int i=0; while(index != NULL) { if(strlen(index) > 0) { JANUS_LOG(LOG_INFO, "Adding '%s' to the Janus API allowed list...\n", index); janus_websockets_allow_address(g_strdup(index), FALSE); } i++; index = list[i]; } } g_strfreev(list); list = NULL; } item = janus_config_get_item_drilldown(config, "admin", "admin_ws_acl"); if(item && item->value) { gchar **list = g_strsplit(item->value, ",", -1); gchar *index = list[0]; if(index != NULL) { int i=0; while(index != NULL) { if(strlen(index) > 0) { JANUS_LOG(LOG_INFO, "Adding '%s' to the Admin/monitor allowed list...\n", index); janus_websockets_allow_address(g_strdup(index), TRUE); } i++; index = list[i]; } } g_strfreev(list); list = NULL; } /* Setup the Janus API WebSockets server(s) */ item = janus_config_get_item_drilldown(config, "general", "ws"); if(!item || !item->value || !janus_is_true(item->value)) { JANUS_LOG(LOG_WARN, "WebSockets server disabled\n"); } else { int wsport = 8188; item = janus_config_get_item_drilldown(config, "general", "ws_port"); if(item && item->value) wsport = atoi(item->value); char *interface = NULL; item = janus_config_get_item_drilldown(config, "general", "ws_interface"); if(item && item->value) interface = (char *)item->value; char *ip = NULL; item = janus_config_get_item_drilldown(config, "general", "ws_ip"); if(item && item->value) { ip = (char *)item->value; char *iface = janus_websockets_get_interface_name(ip); if(iface == NULL) { JANUS_LOG(LOG_WARN, "No interface associated with %s? Falling back to no interface...\n", ip); } ip = iface; } /* Prepare context */ struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = wsport; info.iface = ip ? ip : interface; info.protocols = wss_protocols; #ifdef HAVE_LIBWEBSOCKETS_NEWAPI info.extensions = NULL; #else info.extensions = libwebsocket_get_internal_extensions(); #endif info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; info.gid = -1; info.uid = -1; info.options = 0; /* Create the WebSocket context */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI wss = lws_create_context(&info); #else wss = libwebsocket_create_context(&info); #endif if(wss == NULL) { JANUS_LOG(LOG_FATAL, "Error initializing libwebsockets...\n"); } else { JANUS_LOG(LOG_INFO, "WebSockets server started (port %d)...\n", wsport); } g_free(ip); } item = janus_config_get_item_drilldown(config, "general", "wss"); if(!item || !item->value || !janus_is_true(item->value)) { JANUS_LOG(LOG_WARN, "Secure WebSockets server disabled\n"); } else { int wsport = 8989; item = janus_config_get_item_drilldown(config, "general", "wss_port"); if(item && item->value) wsport = atoi(item->value); char *interface = NULL; item = janus_config_get_item_drilldown(config, "general", "wss_interface"); if(item && item->value) interface = (char *)item->value; char *ip = NULL; item = janus_config_get_item_drilldown(config, "general", "wss_ip"); if(item && item->value) { ip = (char *)item->value; char *iface = janus_websockets_get_interface_name(ip); if(iface == NULL) { JANUS_LOG(LOG_WARN, "No interface associated with %s? Falling back to no interface...\n", ip); } ip = iface; } item = janus_config_get_item_drilldown(config, "certificates", "cert_pem"); if(!item || !item->value) { JANUS_LOG(LOG_FATAL, "Missing certificate/key path\n"); } else { char *server_pem = (char *)item->value; char *server_key = (char *)item->value; item = janus_config_get_item_drilldown(config, "certificates", "cert_key"); if(item && item->value) server_key = (char *)item->value; JANUS_LOG(LOG_VERB, "Using certificates:\n\t%s\n\t%s\n", server_pem, server_key); /* Prepare secure context */ struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = wsport; info.iface = ip ? ip : interface; info.protocols = swss_protocols; #ifdef HAVE_LIBWEBSOCKETS_NEWAPI info.extensions = NULL; #else info.extensions = libwebsocket_get_internal_extensions(); #endif info.ssl_cert_filepath = server_pem; info.ssl_private_key_filepath = server_key; info.gid = -1; info.uid = -1; #if LWS_LIBRARY_VERSION_MAJOR >= 2 info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; #else info.options = 0; #endif /* Create the secure WebSocket context */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI swss = lws_create_context(&info); #else swss = libwebsocket_create_context(&info); #endif if(swss == NULL) { JANUS_LOG(LOG_FATAL, "Error initializing libwebsockets...\n"); } else { JANUS_LOG(LOG_INFO, "Secure WebSockets server started (port %d)...\n", wsport); } g_free(ip); } } /* Do the same for the Admin API, if enabled */ item = janus_config_get_item_drilldown(config, "admin", "admin_ws"); if(!item || !item->value || !janus_is_true(item->value)) { JANUS_LOG(LOG_WARN, "Admin WebSockets server disabled\n"); } else { int wsport = 7188; item = janus_config_get_item_drilldown(config, "admin", "admin_ws_port"); if(item && item->value) wsport = atoi(item->value); char *interface = NULL; item = janus_config_get_item_drilldown(config, "admin", "admin_ws_interface"); if(item && item->value) interface = (char *)item->value; char *ip = NULL; item = janus_config_get_item_drilldown(config, "admin", "admin_ws_ip"); if(item && item->value) { ip = (char *)item->value; char *iface = janus_websockets_get_interface_name(ip); if(iface == NULL) { JANUS_LOG(LOG_WARN, "No interface associated with %s? Falling back to no interface...\n", ip); } ip = iface; } /* Prepare context */ struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = wsport; info.iface = ip ? ip : interface; info.protocols = admin_wss_protocols; #ifdef HAVE_LIBWEBSOCKETS_NEWAPI info.extensions = NULL; #else info.extensions = libwebsocket_get_internal_extensions(); #endif info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; info.gid = -1; info.uid = -1; info.options = 0; /* Create the WebSocket context */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI admin_wss = lws_create_context(&info); #else admin_wss = libwebsocket_create_context(&info); #endif if(admin_wss == NULL) { JANUS_LOG(LOG_FATAL, "Error initializing libwebsockets...\n"); } else { JANUS_LOG(LOG_INFO, "Admin WebSockets server started (port %d)...\n", wsport); } g_free(ip); } item = janus_config_get_item_drilldown(config, "admin", "admin_wss"); if(!item || !item->value || !janus_is_true(item->value)) { JANUS_LOG(LOG_WARN, "Secure Admin WebSockets server disabled\n"); } else { int wsport = 7989; item = janus_config_get_item_drilldown(config, "admin", "admin_wss_port"); if(item && item->value) wsport = atoi(item->value); char *interface = NULL; item = janus_config_get_item_drilldown(config, "admin", "admin_wss_interface"); if(item && item->value) interface = (char *)item->value; char *ip = NULL; item = janus_config_get_item_drilldown(config, "admin", "admin_wss_ip"); if(item && item->value) { ip = (char *)item->value; char *iface = janus_websockets_get_interface_name(ip); if(iface == NULL) { JANUS_LOG(LOG_WARN, "No interface associated with %s? Falling back to no interface...\n", ip); } ip = iface; } item = janus_config_get_item_drilldown(config, "certificates", "cert_pem"); if(!item || !item->value) { JANUS_LOG(LOG_FATAL, "Missing certificate/key path\n"); } else { char *server_pem = (char *)item->value; char *server_key = (char *)item->value; item = janus_config_get_item_drilldown(config, "certificates", "cert_key"); if(item && item->value) server_key = (char *)item->value; JANUS_LOG(LOG_VERB, "Using certificates:\n\t%s\n\t%s\n", server_pem, server_key); /* Prepare secure context */ struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = wsport; info.iface = ip ? ip : interface; info.protocols = admin_swss_protocols; #ifdef HAVE_LIBWEBSOCKETS_NEWAPI info.extensions = NULL; #else info.extensions = libwebsocket_get_internal_extensions(); #endif info.ssl_cert_filepath = server_pem; info.ssl_private_key_filepath = server_key; info.gid = -1; info.uid = -1; #if LWS_LIBRARY_VERSION_MAJOR >= 2 info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; #else info.options = 0; #endif /* Create the secure WebSocket context */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI admin_swss = lws_create_context(&info); #else admin_swss = libwebsocket_create_context(&info); #endif if(admin_swss == NULL) { JANUS_LOG(LOG_FATAL, "Error initializing libwebsockets...\n"); } else { JANUS_LOG(LOG_INFO, "Secure Admin WebSockets server started (port %d)...\n", wsport); } g_free(ip); } } } janus_config_destroy(config); config = NULL; if(!wss && !swss && !admin_wss && !admin_swss) { JANUS_LOG(LOG_FATAL, "No WebSockets server started, giving up...\n"); return -1; /* No point in keeping the plugin loaded */ } wss_janus_api_enabled = wss || swss; wss_admin_api_enabled = admin_wss || admin_swss; GError *error = NULL; /* Start the WebSocket service threads */ if(wss != NULL) { wss_thread = g_thread_try_new("ws thread", &janus_websockets_thread, wss, &error); if(!wss_thread) { g_atomic_int_set(&initialized, 0); JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the WebSockets thread...\n", error->code, error->message ? error->message : "??"); return -1; } } if(swss != NULL) { swss_thread = g_thread_try_new("sws thread", &janus_websockets_thread, swss, &error); if(!swss_thread) { g_atomic_int_set(&initialized, 0); JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Secure WebSockets thread...\n", error->code, error->message ? error->message : "??"); return -1; } } if(admin_wss != NULL) { admin_wss_thread = g_thread_try_new("admin ws thread", &janus_websockets_thread, admin_wss, &error); if(!admin_wss_thread) { g_atomic_int_set(&initialized, 0); JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Admin WebSockets thread...\n", error->code, error->message ? error->message : "??"); return -1; } } if(admin_swss != NULL) { admin_swss_thread = g_thread_try_new("admin sws thread", &janus_websockets_thread, admin_swss, &error); if(!admin_swss_thread) { g_atomic_int_set(&initialized, 0); JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Secure Admin WebSockets thread...\n", error->code, error->message ? error->message : "??"); return -1; } } /* Done */ g_atomic_int_set(&initialized, 1); JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_WEBSOCKETS_NAME); return 0; }
int main(int argc, char **argv) { pthread_t rtl_thread; pthread_t fm_thread; char cert_path[1024]; char key_path[1024]; int n = 0; int use_ssl = 0; struct libwebsocket_context *context; int opts = 0; char interface_name[128] = ""; const char *iface = NULL; int syslog_options = LOG_PID | LOG_PERROR; unsigned int oldus = 0; struct lws_context_creation_info info; int debug_level = 7; memset(&info, 0, sizeof info); info.port = PORT; rtl_init(DEV_INDEX); transfer.buf = NULL; transfer.block_id = 0; spectrum = init_spectrum(FFT_POINTS); spectrum_temp_buffer = malloc(FFT_POINTS*2*4); send_buffer = malloc(LWS_SEND_BUFFER_PRE_PADDING + SEND_BUFFER_SIZE + LWS_SEND_BUFFER_POST_PADDING); while (n >= 0) { n = getopt_long(argc, argv, "i:hsp:d:Dr:", options, NULL); if (n < 0) continue; switch (n) { case 'd': debug_level = atoi(optarg); break; case 's': use_ssl = 1; 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 'r': resource_path = optarg; printf("Setting resource path to \"%s\"\n", resource_path); break; case 'h': fprintf(stderr, "Usage: rtl-ws-server " "[--port=<p>] [--ssl] " "[-d <log bitfield>] " "[--resource_path <path>]\n"); exit(1); } } signal(SIGINT, sighandler); /* 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); info.iface = iface; info.protocols = protocols; info.extensions = libwebsocket_get_internal_extensions(); 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; pthread_mutex_init(&data_mutex, NULL); pthread_create(&rtl_thread, NULL, rtl_worker, NULL); pthread_create(&fm_thread, NULL, fm_worker, NULL); while (n >= 0 && !force_exit) { n = libwebsocket_service(context, 50); } force_exit = 1; usleep(100); libwebsocket_context_destroy(context); lwsl_notice("rtl-ws-server exited\n"); closelog(); rtl_close(); pthread_mutex_destroy(&data_mutex); pthread_exit(NULL); if (transfer.buf != NULL) { free(transfer.buf); transfer.buf = NULL; transfer.block_id = 0; } free(send_buffer); free_spectrum(spectrum); free(spectrum_temp_buffer); return 0; }
//-------------------------------------------------------------- bool Client::connect ( ClientOptions options ){ ofLog( OF_LOG_VERBOSE, "[ofxLibwebsockets] connect: "+options.host+":"+ofToString(options.port)+options.channel+":"+ofToString(options.bUseSSL) ); address = options.host; port = options.port; channel = options.channel; defaultOptions = options; bShouldReconnect = defaultOptions.reconnect; /* enum lws_log_levels { LLL_ERR = 1 << 0, LLL_WARN = 1 << 1, LLL_NOTICE = 1 << 2, LLL_INFO = 1 << 3, LLL_DEBUG = 1 << 4, LLL_PARSER = 1 << 5, LLL_HEADER = 1 << 6, LLL_EXT = 1 << 7, LLL_CLIENT = 1 << 8, LLL_LATENCY = 1 << 9, LLL_COUNT = 10 }; */ lws_set_log_level(LLL_ERR, NULL); // set up default protocols struct libwebsocket_protocols null_protocol = { NULL, NULL, 0 }; // setup the default protocol (the one that works when you do addListener()) registerProtocol( options.protocol, clientProtocol ); lws_protocols.clear(); for (int i=0; i<protocols.size(); ++i) { struct libwebsocket_protocols lws_protocol = { ( protocols[i].first == "NULL" ? NULL : protocols[i].first.c_str() ), lws_client_callback, protocols[i].second->rx_buffer_size, protocols[i].second->rx_buffer_size }; lws_protocols.push_back(lws_protocol); } lws_protocols.push_back(null_protocol); struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = CONTEXT_PORT_NO_LISTEN; info.protocols = &lws_protocols[0]; info.extensions = libwebsocket_get_internal_extensions(); info.gid = -1; info.uid = -1; if ( options.ka_time != 0 ){ ofLogVerbose()<<"[ofxLibwebsockets] Setting timeout "<<options.ka_time; info.ka_time = options.ka_time; info.ka_probes = options.ka_probes; info.ka_interval = options.ka_interval; } context = libwebsocket_create_context(&info); //context = libwebsocket_create_context(CONTEXT_PORT_NO_LISTEN, NULL, // &lws_protocols[0], libwebsocket_internal_extensions, // NULL, NULL, /*NULL,*/ -1, -1, 0, NULL); if (context == NULL){ ofLogError() << "[ofxLibwebsockets] libwebsocket init failed"; return false; } else { ofLogVerbose() << "[ofxLibwebsockets] libwebsocket init success"; string host = options.host +":"+ ofToString( options.port ); // register with or without a protocol if ( options.protocol == "NULL"){ lwsconnection = libwebsocket_client_connect( context, options.host.c_str(), options.port, (options.bUseSSL ? 2 : 0 ), options.channel.c_str(), host.c_str(), host.c_str(), NULL, options.version); } else { lwsconnection = libwebsocket_client_connect( context, options.host.c_str(), options.port, (options.bUseSSL ? 2 : 0 ), options.channel.c_str(), host.c_str(), host.c_str(), options.protocol.c_str(), options.version); } if ( lwsconnection == NULL ){ ofLogError() << "[ofxLibwebsockets] client connection failed"; return false; } else { connection = new Connection( (Reactor*) &context, &clientProtocol ); connection->ws = lwsconnection; ofLogVerbose() << "[ofxLibwebsockets] Connection successfully created. Connecting."; startThread(); return true; } } }
int main(int argc, char **argv) { struct libwebsocket_context *context; int opts = 0; char interface_name[128] = ""; const char *interface = NULL; int syslog_options = LOG_PID | LOG_PERROR; int listen_port = 7681; struct lws_context_creation_info info; int debug_level = 7; int daemonize = 0; memset(&info, 0, sizeof info); char c; int opt_index = 0; while ((c = getopt_long(argc, argv, "hd:k:p:i:DK:", long_opts, &opt_index)) != -1) { switch (c) { case 'D': daemonize = 1; syslog_options &= ~LOG_PERROR; break; case 'd': debug_level = atoi(optarg); break; case 'p': listen_port = atoi(optarg); break; case 'k': strncpy(keyfile,optarg,sizeof(keyfile)); keyfile[sizeof(keyfile)-1] = 0; break; case 'K': strncpy(knownhostfile,optarg,sizeof(knownhostfile)); knownhostfile[sizeof(knownhostfile)-1] = 0; 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: %s [OPTIONS]...\n" "Websocket-speaking daemon to acquire authentication tokens\n" "from compatible websites.\n\n" " -p,--port NUM listen on port NUM. (default:%i)\n" " -d,--debug NUM set debug level to NUM.\n" " -k,--keyfile FILE specify IdentityFile for ssh.\n" " -K,--knownhosts FILE specify special ssh known_hosts file\n" " to store host keys acquired by authd\n" " (defaults to %s)\n" " -D,--daemonize run in background.\n" " --help show this message and exit.\n", argv[0],listen_port,knownhostfile); exit(1); } } /* * 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/.lwstecho-lock")) { fprintf(stderr, "Failed to daemonize\n"); return 1; } /* 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); info.port = listen_port; info.iface = interface; info.protocols = protocols; #ifndef LWS_NO_EXTENSIONS info.extensions = libwebsocket_get_internal_extensions(); #endif 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; } signal(SIGINT, sighandler); /* setup temp file: */ int fd = mkstemp(tfname); if (fd == -1) { fprintf(stderr, "Couldn't create temp file %s\n",tfname); return 1; } close(fd); /* file created. we'll use it later. */ int n = 0; while (n >= 0 && !force_exit) { /* The timeout parameter can be used to compromise between * responsiveness and CPU usage. We use 2 tenths of a second: */ n = libwebsocket_service(context, 200); } libwebsocket_context_destroy(context); unlink(tfname); /* remove temp file. */ closelog(); return 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; char ssl_cert[256] = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem"; char ssl_key[256] = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem"; #ifndef _WIN32 int syslog_options = LOG_PID | LOG_PERROR; #endif int client = 0; int listen_port = 80; struct lws_context_creation_info info; char passphrase[256]; char uri[256] = "/"; #ifndef LWS_NO_CLIENT char address[256], ads_port[256 + 30]; int rate_us = 250000; unsigned int oldus = 0; struct libwebsocket *wsi; int disallow_selfsigned = 0; #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:DC:k:P:vu:" #ifndef LWS_NO_CLIENT "c:r:" #endif , options, NULL); if (n < 0) continue; switch (n) { case 'P': strncpy(passphrase, optarg, sizeof(passphrase)); passphrase[sizeof(passphrase) - 1] = '\0'; info.ssl_private_key_password = passphrase; break; case 'C': strncpy(ssl_cert, optarg, sizeof(ssl_cert)); ssl_cert[sizeof(ssl_cert) - 1] = '\0'; disallow_selfsigned = 1; break; case 'k': strncpy(ssl_key, optarg, sizeof(ssl_key)); ssl_key[sizeof(ssl_key) - 1] = '\0'; break; case 'u': strncpy(uri, optarg, sizeof(uri)); uri[sizeof(uri) - 1] = '\0'; break; #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; strncpy(address, optarg, sizeof(address) - 1); address[sizeof(address) - 1] = '\0'; 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 'v': versa = 1; 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\n" " --debug / -d <debug bitfield>\n" " --port / -p <port>\n" " --ssl-cert / -C <cert path>\n" " --ssl-key / -k <key path>\n" #ifndef LWS_NO_CLIENT " --client / -c <server IP>\n" " --ratems / -r <rate in ms>\n" #endif " --ssl / -s\n" " --passphrase / -P <passphrase>\n" " --interface / -i <interface>\n" #ifndef LWS_NO_DAEMONIZE " --daemonize / -D\n" #endif ); 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 #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 echo test - " "(C) Copyright 2010-2015 Andy Green <*****@*****.**> - " "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 && !disallow_selfsigned) { lwsl_info("allowing selfsigned\n"); use_ssl = 2; } else { lwsl_info("requiring server cert validation againts %s\n", ssl_cert); info.ssl_ca_filepath = ssl_cert; } } 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 = ssl_cert; info.ssl_private_key_filepath = ssl_key; } else if (use_ssl && client) { info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; } 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; } signal(SIGINT, sighandler); n = 0; while (n >= 0 && !force_exit) { #ifndef LWS_NO_CLIENT struct timeval tv; if (client && !state) { state = 1; lwsl_notice("Client connecting to %s:%u....\n", address, port); /* we are in client mode */ address[sizeof(address) - 1] = '\0'; sprintf(ads_port, "%s:%u", address, port & 65535); wsi = libwebsocket_client_connect(context, address, port, use_ssl, uri, ads_port, ads_port, NULL, -1); if (!wsi) { lwsl_err("Client failed to connect to %s:%u\n", address, port); goto bail; } } if (client && !versa) { 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"); #ifndef _WIN32 closelog(); #endif return 0; }
//--------------------------------------------------------------------------------- // Purpose: called when the plugin is loaded, load the interface we need from the engine //--------------------------------------------------------------------------------- bool WebSpecPlugin::Load( CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory ) { ConnectTier1Libraries( &interfaceFactory, 1 ); playerInfoManager = (IPlayerInfoManager *)gameServerFactory(INTERFACEVERSION_PLAYERINFOMANAGER,NULL); if ( !playerInfoManager ) { Warning( "[WebSpec] Unable to load PlayerInfoManager!\n" ); return false; } gameEventManager = (IGameEventManager *)interfaceFactory(INTERFACEVERSION_GAMEEVENTSMANAGER,NULL); if( !gameEventManager ) { Warning( "[WebSpec] Unable to load GameEventManager!\n" ); return false; } engine = (IVEngineServer *)interfaceFactory(INTERFACEVERSION_VENGINESERVER, NULL); if (!engine) { Warning("[WebSpec] Unable to load VEngineServer!\n"); return false; } serverGameEnts = (IServerGameEnts *)gameServerFactory(INTERFACEVERSION_SERVERGAMEENTS, NULL); if (!serverGameEnts) { Warning("[WebSpec] Unable to load ServerGameEnts!\n"); return false; } serverGameDLL = (IServerGameDLL *)gameServerFactory("ServerGameDLL008", NULL); // ServerGameDLL008 for TF2, not in hl2sdk-ob-valve if (!serverGameDLL) { return false; } gameEventManager->AddListener(this, true); //Init global variables gpGlobals = playerInfoManager->GetGlobalVars(); ws_teamName[0] = MAKE_STRING("BLU"); ws_teamName[1] = MAKE_STRING("RED"); ws_teamReadyState[0] = false; ws_teamReadyState[1] = false; WSOffsets::PrepareOffsets(); //Init WebSocket server lws_context_creation_info *lwsInfo = new lws_context_creation_info(); lwsInfo->port = wsPort; lwsInfo->iface = NULL; lwsInfo->protocols = wsProtocols; lwsInfo->extensions = libwebsocket_get_internal_extensions(); lwsInfo->ssl_cert_filepath = NULL; lwsInfo->ssl_private_key_filepath = NULL; lwsInfo->ssl_ca_filepath = NULL; lwsInfo->gid = -1; lwsInfo->uid = -1; lwsInfo->options = 0; lwsInfo->user = NULL; lwsInfo->ka_time = 0; wsContext = libwebsocket_create_context(lwsInfo); if (wsContext == NULL) Msg("[WebSpec] failed to init libwebsockets\n"); //Start WebSpec server ws_shouldListen = true; WSServerThreadParams_t *params = new WSServerThreadParams_t; params->ctx = wsContext; CreateSimpleThread( WSServerThread, params ); g_lastUpdateTime = gpGlobals->curtime; //Everything seems ok! Msg("%s loaded!\n", PLUGIN_DESCRIPTION); //Register cvars ConVar_Register( 0 ); return true; }
int main(int argc, char **argv) { int n = 0; int ret = 0; // int port = 8543; int port = 9000; int use_ssl = 0; struct libwebsocket_context *context; // const char *address="192.168.6.176"; const char *address="192.168.6.114"; struct libwebsocket *wsi_dumb; int ietf_version = -1; /* latest */ struct lws_context_creation_info info; memset(&info, 0, sizeof info); fprintf(stderr, "DTS2B websockets client\n" "(C) Copyright 2014-2015 Mleaf_HEXI <*****@*****.**> " "licensed under LGPL2.1\n"); /* * 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 */ /* TITLE: libwebsocket_client_connect - Connect to another websocket server struct libwebsocket * libwebsocket_client_connect (struct libwebsocket_context * context, const char * address, int port, int ssl_connection, const char * path, const char * host, const char * origin, const char * protocol, int ietf_version_or_minus_one) Arguments context Websocket context address Remote server address, eg, "myserver.com" port Port to connect to on the remote server, eg, 80 ssl_connection 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self signed certs path Websocket path on server host Hostname on server origin Socket origin name protocol Comma-separated list of protocols being asked for from the server, or just one. The server will pick the one it likes best. ietf_version_or_minus_one -1 to ask to connect using the default, latest protocol supported, or the specific protocol ordinal Description This function creates a connection to a remote server */ fprintf(stderr, "Connecting to %s:%u\n", address, port); wsi_dumb = libwebsocket_client_connect(context, address, port, use_ssl, "/websocket/uclient/MOCK_DTS2B_ACCESS_CODE_1234567890", address,"origin", protocols[0].name, ietf_version); if (wsi_dumb == NULL) { fprintf(stderr, "libwebsocket connect failed\n"); ret = 1; goto bail; } fprintf(stderr, "Waiting for connect...\n"); sqlite3_test();//sqlite3数据库测试 /* * 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; } bail: fprintf(stderr, "Exiting\n"); libwebsocket_context_destroy(context); return 1; }
int main (int argc, char **argv) { char *address = DEFAULT_ADDRESS; int port = DEFAULT_PORT; char *cert_path = NULL; char *key_path = NULL; int use_ssl = 0; char *host = NULL; char *origin = NULL; int watch = 0; char *arg, *msg = NULL; json_t *json = NULL; int json_flags = JSON_COMPACT|JSON_ENCODE_ANY|JSON_PRESERVE_ORDER|JSON_ENSURE_ASCII; char *web = NULL, *suffix = NULL; char path[PATH_MAX]; char *str = NULL; #ifdef HAVE_WATCH watcher_t *watcher; #endif struct libwebsocket_context *context; struct libwebsocket *wsi; struct lws_context_creation_info info; int opt; const struct option long_options[] = { { "address", 1, NULL, 'a' }, { "port", 1, NULL, 'p' }, #ifdef HAVE_WATCH { "watch", 0, NULL, 'W' }, #endif { "suffix", 1, NULL, 's' }, { "host", 1, NULL, 'H' }, { "certpath", 1, NULL, 'c' }, { "keypath", 1, NULL, 'k' }, { "verbose", 1, NULL, 'v' }, { "quiet", 0, NULL, 'q' }, { "help", 0, NULL, 0 }, { NULL, 0, NULL, 0 } }; while ((opt = getopt_long(argc, argv, "a:p:Ws:H:c:k:vs", long_options, NULL)) != -1) { switch (opt) { case 'a': address = optarg; break; case 'p': port = atoi(optarg); break; case 'W': watch = 1; break; case 's': suffix = optarg; break; case 'H': web = optarg; break; case 'c': cert_path = optarg; break; case 'k': key_path = optarg; break; case 'v': if (optarg) { verbose = atoi(optarg); } else { verbose = 1; } break; case 'q': quiet = 1; break; default: usage(argv[0], NULL); return -1; } } if (argc <= optind) { usage(argv[0], "required args to PATH"); return -1; } arg = argv[optind]; if (!address || strlen(address) <= 0) { usage(argv[0], "invalid server address"); return -1; } if (port < 0) { usage(argv[0], "invalid server port"); return -1; } #ifdef HAVE_SSL if (cert_path || key_path) { use_ssl = 1; } #else use_ssl = 0; cert_path = NULL; key_path = NULL; #endif if (quiet) { lws_set_log_level(-1, NULL); } else if (verbose == 0 || verbose == 1) { lws_set_log_level(LLL_WARN, NULL); } else if (verbose == 2) { lws_set_log_level(LLL_NOTICE, NULL); } #ifdef HAVE_WATCH if (watch) { watcher = watcher_init(); if (!watcher) { _ERR("%s\n", watcher_error()); return -1; } if (watcher_recursively(watcher, arg) != 0) { _ERR("%s\n", watcher_error()); watcher_destroy(watcher); return -1; } signals(); _debug(1, "Starting watching [%s] ...\n", arg); } else { interrupted = 1; } #else interrupted = 1; #endif do { char *filename = NULL; #ifdef HAVE_WATCH if (watch) { if (watcher_next_event(watcher) != 0 || interrupted) { break; } if (watcher_in_event(watcher) != 0) { continue; } filename = watcher_get_filename(watcher); if (!filename) { _ERR("Memory allocate\n"); watcher_destroy(watcher); return -1; } arg = filename; } #endif memset(path, 0, sizeof(path)); str = path; if (web) { if (use_ssl) { str = strcat(str, "https://"); } else { str = strcat(str, "http://"); } str = strcat(str, web); } else { str = strcat(str, "file://"); } #ifdef HAVE_SUFFIX if (suffix) { regex_t preg; regmatch_t pmatch[1]; char *regex = (char *)malloc((strlen(suffix) + 4) * sizeof(char)); if (!regex) { _ERR("Memory allocate\n"); return -1; } sprintf(regex, "(%s)$", suffix); if (regcomp(&preg, suffix, REG_EXTENDED|REG_NEWLINE) == 0) { if (regexec(&preg, arg, 1, pmatch, 0) == 0) { str = strncat(str, arg, (int)pmatch[0].rm_so); } else { str = strcat(str, arg); } regfree(&preg); } else { str = strcat(str, arg); } free(regex); } else { str = strcat(str, arg); } #else str = strcat(str, arg); #endif json = json_object(); if (!json) { _ERR("Creating json object failed\n"); break; } json_object_set_new(json, "command", json_string("reload")); json_object_set_new(json, "path", json_string(path)); msg = json_dumps(json, json_flags); json_delete(json); _debug(1, "Send Message=[%s]\n", msg); memset(&info, 0, sizeof info); info.port = CONTEXT_PORT_NO_LISTEN; info.protocols = protocols; #ifndef LWS_NO_EXTENSIONS info.extensions = libwebsocket_get_internal_extensions(); #endif /* TODO: ssl */ info.ssl_cert_filepath = cert_path; info.ssl_private_key_filepath = key_path; info.gid = -1; info.uid = -1; context = libwebsocket_create_context(&info); if (context == NULL) { _ERR("Creating libwebsocket context failed\n"); } else { host = address; wsi = libwebsocket_client_connect(context, address, port, use_ssl, "/", host, origin, "livereload", -1); if (wsi == NULL) { _ERR("libwebsocket dumb connect failed\n"); } else if (msg) { libwebsocket_service(context, 30); libwebsocket_write(wsi, msg, strlen(msg), LWS_WRITE_TEXT); } libwebsocket_context_destroy(context); } if (msg) { free(msg); } if (filename) { free(filename); filename = NULL; } } while (!interrupted); #ifdef HAVE_WATCH if (watch) { watcher_destroy(watcher); } #endif _debug(1, "\nFinished\n"); return 0; }