Пример #1
0
////////////////////////////////////////////////////////////////////////
// main
//
int main(int argc, char* argv[])
{
  try
  {
    log_init();

    cxxtools::Arg<std::string> ip(argc, argv, 'i');
    cxxtools::Arg<unsigned short> port(argc, argv, 'p', 7002);
    cxxtools::Arg<unsigned short> bport(argc, argv, 'b', 7003);
    cxxtools::Arg<unsigned short> jport(argc, argv, 'j', 7004);

    std::cout << "run rpcecho server\n"
              << "http protocol on port "<< port.getValue() << "\n"
              << "binary protocol on port " << bport.getValue() << "\n"
              << "json protocol on port " << jport.getValue() << std::endl;

    // create an event loop
    cxxtools::EventLoop loop;

    // the http server is instantiated with an ip address and a port number
    cxxtools::http::Server httpServer(loop, ip, port);

    // we create an instance of the service class
    cxxtools::xmlrpc::Service service;

    // we register our functions
    service.registerFunction("echo", echo);
    service.registerFunction("add", add);

    // ... and register the service under a url
    httpServer.addService("/xmlrpc", service);

    // for the binary rpc server we define a binary server
    cxxtools::bin::RpcServer binServer(loop, ip, bport);

    // and register the functions in the server
    binServer.registerFunction("echo", echo);
    binServer.registerFunction("add", add);

    // for the json rpc server we define a json server
    cxxtools::json::RpcServer jsonServer(loop, ip, jport);

    // and register the functions in the server
    jsonServer.registerFunction("echo", echo);
    jsonServer.registerFunction("add", add);

    cxxtools::json::HttpService jsonhttpService;
    jsonhttpService.registerFunction("echo", echo);
    jsonhttpService.registerFunction("add", add);
    httpServer.addService("/jsonrpc", jsonhttpService);

    // now start the server and run the event loop
    loop.run();
  }
  catch (const std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }
}
Пример #2
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    // TODO: separate to module based on Server Configurator App
    // with options to turn on/off components/etc
    QCommandLineParser parser;
    parser.setApplicationDescription("SemIoT gateway");
    parser.addHelpOption();
    // TODO: miltiple devices
    QCommandLineOption dbgOption(QStringList() << "d" << "debug", QCoreApplication::translate("main", "Debug output [default: off]."));
    parser.addOption(dbgOption);
    // TODO: get rid of magic default port:
    QCommandLineOption portOption(QStringList() << "p" << "port", QCoreApplication::translate("main", "Port for gateway server [default: 57864]."), QCoreApplication::translate("main", "port"), QLatin1Literal("57864"));
    parser.addOption(portOption);
    parser.process(a);
    bool debug = parser.isSet(dbgOption);
    Q_UNUSED(debug); //TODO
    int port = parser.value(portOption).toInt();
    // Internal part
    //DataServer dataServer;
    //DevicesConfigsLoader devicesConfigsLoader;
    FrontModuleManager fMM(&a);
    // External Part
    WebSocketServer wsServer(port,&a);
    HttpServer httpServer(&a);
    fMM.connectFrontModule((FrontModule*)&wsServer);
    fMM.connectFrontModule((FrontModule*)&httpServer);
    //wsServer.setDataServer(&dataServer);
    //httpServer.setDataServer(&dataServer);
    // FIXME: for all the protocols
    /*
    QObject::connect(&devicesConfigsLoader,SIGNAL(newDataReady(QString,QString)),&wsServer,SLOT(processNewData(QString,QString)));
    QObject::connect(&httpServer,SIGNAL(newRequestReceived(QVariant)),&devicesConfigsLoader,SIGNAL(newRequestReceived(QVariant)));
    QObject::connect(&httpServer,SIGNAL(addDeviceDriverFromUrl(QUrl)),&devicesConfigsLoader,SLOT(addConfig(QUrl)));
    */
    // TODO: linux kernel driver
    // TODO: dbus
    // TODO: systemd?
    /*
    monarch::data::json::JsonLd jsonld();

    monarch::rt::DynamicObject input;
    QFile file("infile");
    file.open(QIODevice::ReadOnly);
    QByteArray ba(file.readAll());

    monarch::rt::DynamicObject options;
    monarch::rt::DynamicObject output;
    jsonld().fromRdf(input,options,output);
    */
    return a.exec();
}
Пример #3
0
int main( int, char** ) 
{
  i2p::util::HTTPServer httpServer (7070);	

  httpServer.Start ();	
  i2p::data::netdb.Start ();
  i2p::transports.Start ();	
  i2p::tunnel::tunnels.Start ();	
 
  sleep (1000);
  i2p::tunnel::tunnels.Stop ();	
  i2p::transports.Stop ();	
  i2p::data::netdb.Stop ();	
  httpServer.Stop ();		
  return 0;
}
Пример #4
0
int FFL_main() {
	char exePath[1024] = {};
	char exeName[1024] = {};
	FFL_getCurrentProcessPath(exePath, 1023, exeName);

	gLastLog = "hi:";
	gLastLog += exePath;

	//if (0) {
	//	TcpHandler handler;
	//	FFL::TcpServer tcpServer("127.0.0.1",5000,&handler);
	//	tcpServer.start(NULL);
	//	int32_t waitMs = 5000;
	//	while (tcpServer.eventLoop(&waitMs)) {
	//	}
	//}
	//else {

	FFL::sp<HttpApiLoginHandelr> handler = new HttpApiLoginHandelr();
	FFL::HttpServer httpServer("127.0.0.1", 5000);
	
	//
	//  上传日志接口
	//
	FFL::HttpServer::HttpApiKey key;
	key.mPath = "/fflog";		
	httpServer.registerApi(key,handler);

	//
	//  下载日志接口
	//		
	FFL::sp<HttGetLogListHandelr> getListHandler = new HttGetLogListHandelr();
	key.mPath = "/FFLv2";
	key.mQuery = "getLogList";
	httpServer.registerApi(key, getListHandler);

	httpServer.start(new FFL::ModuleThread("httpd"));	
	//
	//  启动命令行
	//
	FFL_consoleEvenLoop(myCmdOption, &httpServer, QuitFlag);

	return 0;
}
Пример #5
0
void HttpServerTest::perform(void)
{
	std::cout << "HttpServerTest::perform ..." << std::endl;

	{
		//		HttpConfig cfg;
		//		cfg.maxContentLength_ = 409600;
		//		cfg.cachedLimitSize_ = 40960;
		//		cfg.tempRepository_ = "./";
		//		cfg.username_ = "zhaojiangang";
		//		cfg.subProcessNum_ = 4;
		//		cfg.recvTimeout_ = 5000;
		//		cfg.sendTimeout_ = 100000;
		//		cfg.keepAliveTimeout_ = 100000;
		//		cfg.bufferSize_ = 4096;
		//		cfg.maxConnectionPerProcess_ = 2;
		//
		//		mxcore::SocketAddress listenAddress;
		//		listenAddress.set("192.168.1.99", AF_INET, 10000);
		//
		//		cfg.forceKeepAvlie_ = false;
		//		cfg.listenList_.push_back(listenAddress);
		//
		//		listenAddress.set("192.168.1.99", AF_INET, 20000);
		//		cfg.listenList_.push_back(listenAddress);

		HttpConfigurationXml configuration("mxhttp/conf/mx_httpserv.xml");
		//		HttpServer* httpServer = HttpServer::createInstance(cfg);

		try
		{
			mxcore::ScopePtr<HttpServer> httpServer(
					configuration.buildInstance());
			httpServer->open();
			httpServer->run();
		} catch (mxcore::Exception& e)
		{
			std::cout << e.name() << ", " << e.getMessage() << ", "
					<< e.getErrorCode() << ", " << e.getFilename() << ":"
					<< e.getLineNumber() << std::endl;
			MX_ASSERT(0);
		}
	}
}
Пример #6
0
void QwuiApplicationServer::initialize()
{
    if (!start()) {
        qWarning(qobject_cast<QwuiHttpServer*>(httpServer())->error().toAscii().data());
    }
}
Пример #7
0
void QwuiApplicationServer::setBuiltInServerPort(quint16 port)
{
    qobject_cast<QwuiHttpServer*>(httpServer())->setPort(port);
}
Пример #8
0
void startServer()
{
    //屏蔽PIPE信号
    struct sigaction action;
    action.sa_handler = SIG_IGN;
    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    if (sigaction(SIGPIPE, &action, NULL) < 0)
    {
        LOG_ERROR("sigaction failure");
        return;
    }

    const INT1* pMaxFiles = CServer::getInstance()->getConf()->getConfig("controller", "max_open_files");
    INT4 maxFiles = (NULL == pMaxFiles) ? 20000 : atol(pMaxFiles);
    //设置进程允许打开最大文件数
    struct rlimit rt;
    rt.rlim_max = rt.rlim_cur = maxFiles;
    if (setrlimit(RLIMIT_NOFILE, &rt) < 0) 
    {
        LOG_ERROR("setrlimit error");
        return;
    }

    //初始化消息树
    if (!CServer::getInstance()->getMsgTreeNodeMgr()->init())
    {
        LOG_ERROR("msg tree node mgr init failure");
        return;
    }

    //初始化handler
    if (!CServer::getInstance()->getHandlerMgr()->init())
    {
        LOG_ERROR("handler mgr init failure");
        return;
    }
    CServer::getInstance()->getHandlerMgr()->start();

    //读取of服务端口
    const INT1* pOfport = CServer::getInstance()->getConf()->getConfig("controller", "openflow_server_port");
    UINT4 ofPort = (NULL == pOfport) ? 6633 : atoll(pOfport);

    //读取接收线程个数
    const INT1* pRecvThreadNum = CServer::getInstance()->getConf()->getConfig("controller", "recv_thread_num");
    UINT4 recvThreadNum = (pRecvThreadNum == NULL) ? 10 : atol(pRecvThreadNum);

    //启动of server
    CSmartPtr<CRecvWorker> ptrOfRecvWorker(new COfpRecvWorker());
    CTCPServer tcpServer(0, ofPort, recvThreadNum, maxFiles, ptrOfRecvWorker);
    if (!tcpServer.init())
    {
        LOG_ERROR("ofp server init failure");
        return;  
    }

    //读取http服务端口
    const INT1* pHttpport = CServer::getInstance()->getConf()->getConfig("restful", "http_server_port");
    UINT4 httpPort = (NULL == pHttpport) ? 8081 : atoll(pHttpport);

    //启动http server
    CSmartPtr<CRecvWorker> ptrHttpRecvWorker(new CHttpRecvWorker());
    CTCPServer httpServer(0, httpPort, recvThreadNum, maxFiles, ptrHttpRecvWorker);
    if (!httpServer.init())
    {
        LOG_ERROR("http server init failure");
        return;  
    }

    LOG_INFO("dcfabric server start success");
    while (true)
    {
        sleep(30);
        CServer::getInstance()->getTopoMgr()->printPaths();
    }
}
Пример #9
0
void Nuria::Internal::HttpTcpBackend::newClient (qintptr handle) {
	HttpTcpTransport *transport = new HttpTcpTransport (handle, this, httpServer ());
	Q_UNUSED(transport)
}
Пример #10
0
int main( int argc, char* argv[] )
{
  i2p::util::config::OptionParser(argc,argv);
  volatile int isDaemon = i2p::util::config::GetArg("-daemon", 0);
#ifdef _WIN32
  setlocale(LC_CTYPE, "");
  SetConsoleCP(1251);
  SetConsoleOutputCP(1251);
  setlocale(LC_ALL, "Russian");
#endif


  LogPrint("\n\n\n\ni2pd starting\n");
  LogPrint("data directory: ", i2p::util::filesystem::GetDataDir().string());
  i2p::util::filesystem::ReadConfigFile(i2p::util::config::mapArgs, i2p::util::config::mapMultiArgs);


#ifdef _WIN32
	std::string serviceControl = i2p::util::config::GetArg("-service", "none");
	if (serviceControl == "install")
	{
		InstallService(
			SERVICE_NAME,               // Name of service
			SERVICE_DISPLAY_NAME,       // Name to display
			SERVICE_START_TYPE,         // Service start type
			SERVICE_DEPENDENCIES,       // Dependencies
			SERVICE_ACCOUNT,            // Service running account
			SERVICE_PASSWORD            // Password of the account
			);
		return 0;
	}
	else if (serviceControl == "remove")
	{
		UninstallService(SERVICE_NAME);
		return 0;
	}
	else if (serviceControl != "none")
	{
		printf(" --service=install  to install the service.\n");
		printf(" --service=remove   to remove the service.\n");
		return 0;
	}
	else if (isDaemon)
	{
		std::string logfile = i2p::util::filesystem::GetDataDir().string();
		logfile.append("\\debug.log");
		FILE* openResult = freopen(logfile.c_str(), "a", stdout);
		if (!openResult)
		{
			return -17;
		}
		LogPrint("Service logging enabled.");
		I2PService service(SERVICE_NAME);
		if (!I2PService::Run(service))
		{
			LogPrint("Service failed to run w/err 0x%08lx\n", GetLastError());
		}
		return 0;
	}
#endif


  if (isLogging == 1)
  {
    std::string logfile = i2p::util::filesystem::GetDataDir().string();
#ifndef _WIN32
    logfile.append("/debug.log");
#else
    logfile.append("\\debug.log");
#endif
    FILE* openResult = freopen(logfile.c_str(),"a",stdout);
	// It seems that we need to add FLUSH() for LogPrint and call it in some important places
	if (!openResult)
	{
		LogPrint("Can't do [freopen()].");
		return -17;
	}
    LogPrint("Logging to file enabled.");
  }


#ifndef _WIN32
  if (isDaemon == 1)
  {
    pid_t pid;
    pid = fork();
    if (pid > 0)
    {
      g_Log.Stop();
      return 0;
    }
    if (pid < 0)
    {
      return -1;
    }

    umask(0);
    int sid = setsid();
    if (sid < 0)
    {
      LogPrint("Error, could not create process group.");
      return -1;
    }
    chdir(i2p::util::filesystem::GetDataDir().string().c_str());
  }

  // Pidfile
  std::string pidfile = i2p::util::filesystem::GetDataDir().string();
  pidfile.append("/i2pd.pid");
  int pidFilehandle = open(pidfile.c_str(), O_RDWR|O_CREAT, 0600);
  if (pidFilehandle == -1 )
  {
    LogPrint("Error, could not create pid file (", pidfile, ")\nIs an instance already running?");
    return -1;
  }
  if (lockf(pidFilehandle,F_TLOCK,0) == -1)
  {
    LogPrint("Error, could not lock pid file (", pidfile, ")\nIs an instance already running?");
    return -1;
  }
  char pid[10];
  sprintf(pid,"%d\n",getpid());
  write(pidFilehandle, pid, strlen(pid));

  // Signal handler
  struct sigaction sa;
  sa.sa_handler = handle_signal;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = SA_RESTART;
  sigaction(SIGHUP,&sa,0);
  sigaction(SIGABRT,&sa,0);
  sigaction(SIGTERM,&sa,0);
  sigaction(SIGINT,&sa,0);
#endif

  //TODO: This is an ugly workaround. fix it.
  //TODO: Autodetect public IP.
  i2p::context.OverrideNTCPAddress(i2p::util::config::GetCharArg("-host", "127.0.0.1"),
      i2p::util::config::GetArg("-port", 17070));

  i2p::util::HTTPServer httpServer (i2p::util::config::GetArg("-httpport", 7070));

  httpServer.Start ();
  i2p::data::netdb.Start ();
  i2p::transports.Start ();
  i2p::tunnel::tunnels.Start ();

  while (running)
  {
    //TODO Meeh: Find something better to do here.
    std::this_thread::sleep_for (std::chrono::seconds(1));
  }
  LogPrint("Shutdown started.");

  i2p::tunnel::tunnels.Stop ();
  i2p::transports.Stop ();
  i2p::data::netdb.Stop ();
  httpServer.Stop ();

  if (isLogging == 1)
  {
    fclose (stdout);
  }
#ifndef _WIN32
  close(pidFilehandle);
  unlink(pidfile.c_str());
#endif
  return 0;
}
Пример #11
0
   void testFindHttpService()
      {
         HttpServer      httpServer(NULL);
         
         HttpService* foundService;
         
         CPPUNIT_ASSERT(!httpServer.findHttpService("/", foundService));
         CPPUNIT_ASSERT(NULL == foundService);

         TestHttpService testServiceOne;
         httpServer.addHttpService("/one", &testServiceOne);

         CPPUNIT_ASSERT(!httpServer.findHttpService("/", foundService));
         CPPUNIT_ASSERT(NULL == foundService);

         CPPUNIT_ASSERT(httpServer.findHttpService("/one", foundService));
         CPPUNIT_ASSERT(&testServiceOne == foundService);

         CPPUNIT_ASSERT(httpServer.findHttpService("/one/two", foundService));
         CPPUNIT_ASSERT(&testServiceOne == foundService);

         CPPUNIT_ASSERT(!httpServer.findHttpService("/one_extra", foundService));
         CPPUNIT_ASSERT(NULL == foundService);

         TestHttpService testServiceTwo;
         httpServer.addHttpService("/one/two", &testServiceTwo);

         CPPUNIT_ASSERT(!httpServer.findHttpService("/", foundService));
         CPPUNIT_ASSERT(NULL == foundService);

         CPPUNIT_ASSERT(httpServer.findHttpService("/one", foundService));
         CPPUNIT_ASSERT(&testServiceOne == foundService);

         CPPUNIT_ASSERT(httpServer.findHttpService("/one/two", foundService));
         CPPUNIT_ASSERT(&testServiceTwo == foundService);

         CPPUNIT_ASSERT(httpServer.findHttpService("/one/two/three", foundService));
         CPPUNIT_ASSERT(&testServiceTwo == foundService);

         CPPUNIT_ASSERT(!httpServer.findHttpService("/one_extra", foundService));
         CPPUNIT_ASSERT(NULL == foundService);

         CPPUNIT_ASSERT(!httpServer.findHttpService("/one_extra/two", foundService));
         CPPUNIT_ASSERT(NULL == foundService);

         CPPUNIT_ASSERT(httpServer.findHttpService("/one/two_extra", foundService));
         CPPUNIT_ASSERT(&testServiceOne == foundService);

         TestHttpService testRootService;
         httpServer.addHttpService("/", &testRootService);

         CPPUNIT_ASSERT(httpServer.findHttpService("/", foundService));
         CPPUNIT_ASSERT(&testRootService == foundService);

         CPPUNIT_ASSERT(httpServer.findHttpService("/one", foundService));
         CPPUNIT_ASSERT(&testServiceOne == foundService);

         CPPUNIT_ASSERT(httpServer.findHttpService("/one/two", foundService));
         CPPUNIT_ASSERT(&testServiceTwo == foundService);

         CPPUNIT_ASSERT(httpServer.findHttpService("/one/two/three", foundService));
         CPPUNIT_ASSERT(&testServiceTwo == foundService);

         CPPUNIT_ASSERT(httpServer.findHttpService("/one_extra", foundService));
         CPPUNIT_ASSERT(&testRootService == foundService);

         CPPUNIT_ASSERT(httpServer.findHttpService("/one_extra/two", foundService));
         CPPUNIT_ASSERT(&testRootService == foundService);

         CPPUNIT_ASSERT(httpServer.findHttpService("/one/two_extra", foundService));
         CPPUNIT_ASSERT(&testServiceOne == foundService);
      } 
Пример #12
0
/* ---------------------------------------------------------------------------
**  main
** -------------------------------------------------------------------------*/
int main(int argc, char* argv[])
{
	const char* turnurl       = "";
	const char* defaultlocalstunurl  = "0.0.0.0:3478";
	const char* localstunurl  = NULL;
	const char* stunurl       = "stun.l.google.com:19302";
	int logLevel              = rtc::LERROR;
	const char* webroot       = "./html";
	std::string sslCertificate;
	webrtc::AudioDeviceModule::AudioLayer audioLayer = webrtc::AudioDeviceModule::kPlatformDefaultAudio;
	std::string streamName;
	std::map<std::string,std::string> urlVideoList;
	std::map<std::string,std::string> urlAudioList;
	std::string nbthreads;
	std::string passwdFile;
	std::string publishFilter(".*");

	std::string httpAddress("0.0.0.0:");
	std::string httpPort = "8000";
	const char * port = getenv("PORT");
	if (port)
	{
		httpPort = port;
	}
	httpAddress.append(httpPort);

	int c = 0;
	while ((c = getopt (argc, argv, "hVv::" "c:H:w:T:A:C:" "t:S::s::" "a::q:" "n:u:U:")) != -1)
	{
		switch (c)
		{
			case 'H': httpAddress = optarg; break;
			case 'c': sslCertificate = optarg; break;
			case 'w': webroot = optarg; break;
			case 'T': nbthreads = optarg; break;
			case 'A': passwdFile = optarg; break;

			case 't': turnurl = optarg; break;
			case 'S': localstunurl = optarg ? optarg : defaultlocalstunurl; stunurl = localstunurl; break;
			case 's': localstunurl = NULL; stunurl = optarg ? optarg : defaultlocalstunurl; break;
			
			case 'a': audioLayer = optarg ? (webrtc::AudioDeviceModule::AudioLayer)atoi(optarg) : webrtc::AudioDeviceModule::kDummyAudio; break;
			case 'q': publishFilter = optarg ; break;
				
			case 'C': {
				Json::Value root;  
				std::ifstream stream(optarg);
				stream >> root;
				if (root.isMember("urls")) {
					Json::Value urls = root["urls"];
					for( auto it = urls.begin() ; it != urls.end() ; it++ ) {
						std::string name = it.key().asString();
						Json::Value value = *it;
						if (value.isMember("video")) {
							urlVideoList[name]=value["video"].asString();
						} 
						if (value.isMember("audio")) {
							urlAudioList[name]=value["audio"].asString();
						} 
					}
				}
				break;
			}

			case 'n': streamName = optarg; break;
			case 'u': {
				if (!streamName.empty()) {
					urlVideoList[streamName]=optarg;
				}
			}
			break;
			case 'U': {
				if (!streamName.empty()) {
					urlAudioList[streamName]=optarg;
				}
			}
			break;
			
			case 'v': 
				logLevel--; 
				if (optarg) {
					logLevel-=strlen(optarg); 
				}
			break;			
			case 'V':
				std::cout << VERSION << std::endl;
				exit(0);
			break;
			case 'h':
			default:
				std::cout << argv[0] << " [-H http port] [-S[embeded stun address]] [-t [username:password@]turn_address] -[v[v]]  [url1]...[urln]" << std::endl;
				std::cout << argv[0] << " [-H http port] [-s[externel stun address]] [-t [username:password@]turn_address] -[v[v]] [url1]...[urln]" << std::endl;
				std::cout << argv[0] << " -V" << std::endl;

				std::cout << "\t -v[v[v]]           : verbosity"                                                                  << std::endl;
				std::cout << "\t -V                 : print version"                                                              << std::endl;

				std::cout << "\t -H hostname:port   : HTTP server binding (default "   << httpAddress    << ")"                   << std::endl;
				std::cout << "\t -w webroot         : path to get files"                                                          << std::endl;
				std::cout << "\t -c sslkeycert      : path to private key and certificate for HTTPS"                              << std::endl;
				std::cout << "\t -T nbthreads       : number of threads for HTTP server"                                          << std::endl;
				std::cout << "\t -A passwd          : password file for HTTP server access"                                          << std::endl;
			
				std::cout << "\t -S[stun_address]                   : start embeded STUN server bind to address (default " << defaultlocalstunurl << ")" << std::endl;
				std::cout << "\t -s[stun_address]                   : use an external STUN server (default " << stunurl << ")"                    << std::endl;
				std::cout << "\t -t[username:password@]turn_address : use an external TURN relay server (default disabled)"       << std::endl;

				std::cout << "\t -a[audio layer]                    : spefify audio capture layer to use (default:" << audioLayer << ")"          << std::endl;

				std::cout << "\t -n name -u videourl -U audiourl    : register a stream with name using url"                         << std::endl;			
				std::cout << "\t [url]                              : url to register in the source list"                                         << std::endl;
				std::cout << "\t -C config.json                     : load urls from JSON config file"                                                 << std::endl;
			
				exit(0);
		}
	}

	while (optind<argc)
	{
		std::string url(argv[optind]);
		urlVideoList[url]=url;
		optind++;
	}

	rtc::LogMessage::LogToDebug((rtc::LoggingSeverity)logLevel);
	rtc::LogMessage::LogTimestamps();
	rtc::LogMessage::LogThreads();
	std::cout << "Logger level:" <<  rtc::LogMessage::GetLogToDebug() << std::endl;

	rtc::Thread* thread = rtc::Thread::Current();
	rtc::InitializeSSL();

	// webrtc server
	std::list<std::string> iceServerList;
	iceServerList.push_back(std::string("stun:")+stunurl);
	if (strlen(turnurl)) {
		iceServerList.push_back(std::string("turn:")+turnurl);
	}
	PeerConnectionManager webRtcServer(iceServerList, urlVideoList, urlAudioList, audioLayer, publishFilter);
	if (!webRtcServer.InitializePeerConnection())
	{
		std::cout << "Cannot Initialize WebRTC server" << std::endl;
	}
	else
	{
		// http server
		std::vector<std::string> options;
		options.push_back("document_root");
		options.push_back(webroot);
		options.push_back("access_control_allow_origin");
		options.push_back("*");
		options.push_back("listening_ports");
		options.push_back(httpAddress);
		if (!sslCertificate.empty()) {
			options.push_back("ssl_certificate");
			options.push_back(sslCertificate);
		}
		if (!nbthreads.empty()) {
			options.push_back("num_threads");
			options.push_back(nbthreads);
		}
		if (!passwdFile.empty()) {
			options.push_back("global_auth_file");
			options.push_back(passwdFile);
		}

		try {
			std::cout << "HTTP Listen at " << httpAddress << std::endl;
			HttpServerRequestHandler httpServer(&webRtcServer, options);

			// start STUN server if needed
			std::unique_ptr<cricket::StunServer> stunserver;
			if (localstunurl != NULL)
			{
				rtc::SocketAddress server_addr;
				server_addr.FromString(localstunurl);
				rtc::AsyncUDPSocket* server_socket = rtc::AsyncUDPSocket::Create(thread->socketserver(), server_addr);
				if (server_socket)
				{
					stunserver.reset(new cricket::StunServer(server_socket));
					std::cout << "STUN Listening at " << server_addr.ToString() << std::endl;
				}
			}
			
			// mainloop
			thread->Run();

		} catch (const CivetException & ex) {
			std::cout << "Cannot Initialize start HTTP server exception:" << ex.what() << std::endl;
		}
	}

	rtc::CleanupSSL();
	return 0;
}
Пример #13
0
int supervisorMain(bool bOriginalSupervisor)
{
    // Create forked process which will do nothing unless parent dies.  Parent continues with initialization.
    forkSupervisorInWaiting();

    // Drop privileges down to the specified user & group
    const char * sipxpbxuser = SipXecsService::User();
    const char * sipxpbxgroup = SipXecsService::Group();

    if (NULL == sipxpbxuser || 0 == strlen(sipxpbxuser))
    {
       osPrintf("sipXsupervisor: Failed to setuid(%s), username not defined.\n",
          sipxpbxuser);
       return 2;
    }
    if (NULL == sipxpbxgroup || 0 == strlen(sipxpbxgroup))
    {
       osPrintf("sipXsupervisor: Failed to setgid(%s), groupname not defined.\n",
          sipxpbxgroup);
       return 2;
    }

    struct group * grp = getgrnam(sipxpbxgroup);
    if (NULL == grp)
    {
       if (0 != errno)
       {
          osPrintf("getgrnam(%s) failed, errno = %d.",
             sipxpbxgroup, errno);
       }
       else
       {
          osPrintf(
             "sipXsupervisor: getgrnam(%s) failed, user does not exist.",
                sipxpbxgroup);
       }
       return 3;
    }

    struct passwd * pwd = getpwnam(sipxpbxuser);
    if (NULL == pwd)
    {
       if (0 != errno)
       {
          osPrintf("getpwnam(%s) failed, errno = %d.",
             sipxpbxuser, errno);
       }
       else
       {
          osPrintf(
             "sipXsupervisor: getpwnam(%s) failed, user does not exist.",
                sipxpbxuser);
       }
       return 3;
    }

    // Change group first, cause once user is changed this cannot be done.
    if (0 != setgid(grp->gr_gid))
    {
       osPrintf("sipXsupervisor: setgid(%d) failed, errno = %d.",
          (int)grp->gr_gid, errno);
       return 4;
    }

    if (0 != setuid(pwd->pw_uid))
    {
       osPrintf("sipXsupervisor: setuid(%d) failed, errno = %d.",
          (int)pwd->pw_uid, errno);
       return 4;
    }


# if 0
// Only output problems.  This keeps the startup output clean.
    osPrintf("sipXsupervisor: Dropped privileges with setuid(%s)/setgid(%s).",
       sipxpbxuser, sipxpbxgroup);
#endif

    OsMsgQShared::setQueuePreference(OsMsgQShared::QUEUE_UNLIMITED);

    // Block all signals in this the main thread
    // Any threads created after this will have all signals masked.
    OsTask::blockSignals();

    // Create a new task to wait for signals.  Only that task
    // will ever see a signal from the outside.
    SignalTask* signalTask = new SignalTask();
    signalTask->start() ;

    // All osPrintf output should go to the console until the log file is initialized.
    enableConsoleOutput(true);

    // Initialize the log file.
    Os::LoggerHelper::instance().processName = "Supervisor";
    UtlString logFile = SipXecsService::Path(SipXecsService::LogDirType, "sipxsupervisor.log");
    Os::LoggerHelper::instance().initialize(PRI_DEBUG, logFile.data());

    if (!bOriginalSupervisor)
    {
       Os::Logger::instance().log(FAC_SUPERVISOR, PRI_CRIT,
                     "Restarting sipxsupervisor after unexpected shutdown");
    }
    Os::Logger::instance().log(FAC_SUPERVISOR, PRI_NOTICE,
                  ">>>>> Starting sipxsupervisor version %s",
                  VERSION);

    // Now that the log file is initialized, stop sending osPrintf to the console.
    // All relevant log messages from this point on must use Os::Logger::instance().log().
    enableConsoleOutput(false);
    fflush(NULL); // Flush all output so children don't get a buffer of output

    // Open the supervisor configuration file
    OsConfigDb supervisorConfiguration;
    OsPath supervisorConfigPath = SipXecsService::Path(SipXecsService::ConfigurationDirType,
                                                       CONFIG_SETTINGS_FILE);
    if (OS_SUCCESS != supervisorConfiguration.loadFromFile(supervisorConfigPath.data()))
    {
       Os::Logger::instance().log(FAC_SUPERVISOR,PRI_WARNING,
                     "Failed to open supervisor configuration file at '%s'",
                     supervisorConfigPath.data()
                     );
    }

    // Set logging based on the supervisor configuration - TODO change default to "NOTICE" ?
    OsSysLogPriority logPri = SipXecsService::setLogPriority(supervisorConfiguration, SUPERVISOR_PREFIX, PRI_INFO );
    Os::Logger::instance().setLoggingPriorityForFacility(FAC_ALARM, logPri);

    // Open the domain configuration file
    OsConfigDb domainConfiguration;
    OsPath domainConfigPath = SipXecsService::domainConfigPath();
    if (OS_SUCCESS != domainConfiguration.loadFromFile(domainConfigPath.data()))
    {
       Os::Logger::instance().log(FAC_SUPERVISOR,PRI_ERR,
                     "Failed to open domain configuration '%s'",
                     domainConfigPath.data()
                     );
    }
    // @TODO const char* managementIpBindAddress;
    int managementPortNumber;
    managementPortNumber = domainConfiguration.getPort(SipXecsService::DomainDbKey::SUPERVISOR_PORT);
    if (PORT_NONE == managementPortNumber)
    {
       Os::Logger::instance().log(FAC_SUPERVISOR,PRI_WARNING,
                     "%s not configured in '%s', using default: %d",
                     SipXecsService::DomainDbKey::SUPERVISOR_PORT,
                     domainConfigPath.data(), DEFAULT_SUPERVISOR_PORT
                     );
       managementPortNumber=DEFAULT_SUPERVISOR_PORT;
    }
    else if (PORT_DEFAULT == managementPortNumber)
    {
       Os::Logger::instance().log(FAC_SUPERVISOR,PRI_NOTICE,"%s set to default: %d",
                     SipXecsService::DomainDbKey::SUPERVISOR_PORT, DEFAULT_SUPERVISOR_PORT
                     );
       managementPortNumber=DEFAULT_SUPERVISOR_PORT;
    }

    UtlSList allowedPeers;
    UtlString configHosts;
    domainConfiguration.get(SipXecsService::DomainDbKey::CONFIG_HOSTS, configHosts);
    if (!configHosts.isNull())
    {
       UtlString hostName;
       for (int hostIndex = 0;
            NameValueTokenizer::getSubField(configHosts.data(), hostIndex, ", \t", &hostName);
            hostIndex++)
       {
          // Found at least one config hostname.
          if (!allowedPeers.contains(&hostName))
          {
             Os::Logger::instance().log(FAC_SUPERVISOR,PRI_DEBUG,
                           "%s value '%s'",
                           SipXecsService::DomainDbKey::CONFIG_HOSTS,
                           hostName.data()
                           );
             allowedPeers.insert(new UtlString(hostName));
          }
       }
    }
    else
    {
       Os::Logger::instance().log(FAC_SUPERVISOR,PRI_ERR,
                     "%s not configured in '%s'",
                     SipXecsService::DomainDbKey::CONFIG_HOSTS, domainConfigPath.data()
                     );
    }

    UtlString superHost;
    supervisorConfiguration.get(SUPERVISOR_HOST, superHost);
    if (!superHost.isNull())
    {
       if (!allowedPeers.contains(&superHost))
       {
          allowedPeers.insert(new UtlString(superHost));
       }
    }
    else
    {
       Os::Logger::instance().log(FAC_SUPERVISOR,PRI_ERR,
                     "%s not configured in '%s'",
                     SUPERVISOR_HOST, supervisorConfigPath.data()
                     );
    }

    if (allowedPeers.isEmpty())
    {
       Os::Logger::instance().log(FAC_SUPERVISOR,PRI_ERR,
                     "No configuration peers configured.");
    }

    if (!cAlarmServer::getInstance()->init())
    {
       Os::Logger::instance().log(FAC_SUPERVISOR, PRI_ERR,
             "sipXsupervisor failed to init AlarmServer");
    }

    // Initialize management interfaces on the TLS socket
    OsSSLServerSocket serverSocket(50, managementPortNumber /*@TODO managementIpBindAddress */);
    HttpServer        httpServer(&serverSocket); // set up but don't start https server
    XmlRpcDispatch    xmlRpcDispatcher(&httpServer); // attach xml-rpc service to https
    pSipxRpcImpl = new SipxRpc(&xmlRpcDispatcher, allowedPeers); // register xml-rpc methods
    HttpFileAccess    fileAccessService(&httpServer, pSipxRpcImpl); // attach file xfer to https

    if (serverSocket.isOk())
    {
       Os::Logger::instance().log(FAC_SUPERVISOR, PRI_DEBUG, "Starting Management HTTP Server");
       httpServer.start();
    }
    else
    {
       Os::Logger::instance().log(FAC_SUPERVISOR, PRI_ERR, "Management listening socket failure");
    }

    // Read the process definitions.
    UtlString processDefinitionDirectory =
       SipXecsService::Path(SipXecsService::DataDirType, "process.d");
    SipxProcessManager* processManager = SipxProcessManager::getInstance();
    processManager->instantiateProcesses(processDefinitionDirectory);

    // 3.0 had different process def files.  The only important thing in them is the
    // state of the services.  Transfer this state to the new process def files.
    upgradeFrom3_0();

    doWaitLoop();

    // Successful run.
    return 0;
}