Ejemplo n.º 1
0
int NetHandler::createListenSocket(string socket_name, string port, string address)
{
    int ret = socket(PF_INET, SOCK_STREAM, 0);
    struct addrinfo hints, *res;
    memset(&hints, 0, sizeof (hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    getaddrinfo(address.c_str(), port.c_str(), &hints, &res);
    if (bind(ret, res->ai_addr, res->ai_addrlen) < 0)
    {
        LOG4CXX_FATAL(logger_, "Bind error for " << socket_name);
        return -1;
    }
    if (listen(ret, MAX_QUEUE_LENGTH) < 0)
    {
        LOG4CXX_FATAL(logger_, "Listen error for " << socket_name);
        return -1;
    }
    LOG4CXX_INFO(logger_, "Listening " << socket_name << " on port:" << port);

    if (ret > 0)
    {
        FD_SET(ret, &master);
    }
    return ret;
}
Ejemplo n.º 2
0
int NetHandler::createListenSocket(string socket_name, string port, string address)
{
    int ret = socket(PF_INET, SOCK_STREAM, 0);
    if (ret < 0)
    {
        LOG4CXX_FATAL(logger_, "create socket error for " + socket_name);
        exit(1);
    }
    int yes = 1;
    if (setsockopt(ret, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof (int) ) < 0)
    {
        LOG4CXX_WARN(logger_, "setsockopt failed! for " + socket_name);
    }

    struct addrinfo hints, *res;
    memset(&hints, 0, sizeof (hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    getaddrinfo(address.c_str(), port.c_str(), &hints, &res);

    if (bind(ret, res->ai_addr, res->ai_addrlen) < 0)
    {
        LOG4CXX_FATAL(logger_, "bind error for " + socket_name);
        exit(1);
    }

    freeaddrinfo(res);

    if (listen(ret, MAX_QUEUE_LENGTH) < 0)
    {
        LOG4CXX_FATAL(logger_, "listen error for " + socket_name);
        exit(1);
    }
    LOG4CXX_INFO(logger_, "Listening " + socket_name + " on port:" + port);

    struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = ret;
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, ret, &ev) < 0)
    {
        LOG4CXX_FATAL(logger_, "epoll_ctl error, cannot add " + socket_name);
        exit(1);
    }

    return ret;
}
Ejemplo n.º 3
0
void DebugHelper::critical_msg(const char * str, ...)
{
    if(str == NULL)
        return;

    KBEngine::thread::ThreadGuard tg(&this->logMutex);

#ifdef NO_USE_LOG4CXX
#else
    va_list ap;
    va_start(ap, str);
#if KBE_PLATFORM == PLATFORM_WIN32
    uint32 size = _vsnprintf(_g_buf, DBG_PT_SIZE, str, ap);
#else
    uint32 size = vsnprintf(_g_buf, DBG_PT_SIZE, str, ap);
#endif
    va_end(ap);
    char buf[DBG_PT_SIZE];
    kbe_snprintf(buf, DBG_PT_SIZE, "%s(%d) -> %s\n\t%s\n", _currFile.c_str(), _currLine, _currFuncName.c_str(), _g_buf);
    LOG4CXX_FATAL(g_logger, buf);
#endif

    setFile("", "", 0);

    onMessage(LOG_CRITICAL, _g_buf, size);
}
Ejemplo n.º 4
0
int NetHandler::createConnectSocket(string socket_name, string address, string port, struct addrinfo &sa)
{
    int ret = socket(PF_INET, SOCK_STREAM, 0);
    struct addrinfo hints, *res;
    memset(&hints, 0, sizeof (hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    // Connecting to World Server
    getaddrinfo(address.c_str(), port.c_str(), &hints, &res);
    if (connect(ret, res->ai_addr, res->ai_addrlen) < 0)
    {
        LOG4CXX_FATAL(logger_, "Connect server " << address << "[" << port << "] failed!");
        return -1;
    };
    sa = *res;
    LOG4CXX_INFO(logger_, "connected " + socket_name + " to " + address + ":" + port);

    if (ret > 0)
    {
        FD_SET(ret, &master);
    }

    return ret;
}
Ejemplo n.º 5
0
void
App::setLogLevel(const std::string &logger, const std::string &level)
{
    log4cxx::LoggerPtr loggerptr = ((logger == "") ? (log4cxx::Logger::getRootLogger()) : (log4cxx::Logger::getLogger(logger)));
    std::string lowercaselevel(level);
    for (size_t i = 0; i < lowercaselevel.size(); i++) {
        lowercaselevel[i] = std::tolower(lowercaselevel[i]);
    }

    if (lowercaselevel == "all") {
        loggerptr->setLevel(log4cxx::Level::getAll());
    } else if (lowercaselevel == "trace") {
        loggerptr->setLevel(log4cxx::Level::getTrace());
    } else if (lowercaselevel == "debug") {
        loggerptr->setLevel(log4cxx::Level::getDebug());
    } else if (lowercaselevel == "info") {
        loggerptr->setLevel(log4cxx::Level::getInfo());
    } else if (lowercaselevel == "warn") {
        loggerptr->setLevel(log4cxx::Level::getWarn());
    } else if (lowercaselevel == "error") {
        loggerptr->setLevel(log4cxx::Level::getError());
    } else if (lowercaselevel == "fatal") {
        loggerptr->setLevel(log4cxx::Level::getFatal());
    } else if ((lowercaselevel == "off")  || (lowercaselevel == "none")) {
        loggerptr->setLevel(log4cxx::Level::getOff());
    } else {
        LOG4CXX_FATAL(_logger, "Unrecognized logging level: \"" << level << "\".");
        std::exit(1);
    }
}
Ejemplo n.º 6
0
	void test6()
	{
		log4cxx::PropertyConfigurator::configure("log4cxx.properties");
		log4cxx::LoggerPtr loggerA(log4cxx::Logger::getLogger("aaa"));  
		log4cxx::LoggerPtr loggerB(log4cxx::Logger::getLogger("bbb")); 
		LOG_F("\n");
		LOG4CXX_INFO(loggerA, "this is log4cxx test"); 
		LOG4CXX_INFO(loggerB, "this is log4cxx test"); 


		log4cxx::LoggerPtr logger0(log4cxx::Logger::getLogger("logger0")); 
		LOG4CXX_DEBUG(logger0, "hello");
		LOG4CXX_TRACE(logger0, "hello");
		LOG4CXX_INFO(logger0, "hello");
		LOG4CXX_WARN(logger0, "hello");
		LOG4CXX_ERROR(logger0, "hello");
		LOG4CXX_FATAL(logger0, "hello");

// 		std::set<int> cList;
// 		LOG4CXX_INFO(logger0, cList);

		//log4j.logger.logger0 = INFO, ap0  

// 		INFO 23:02:03 -- hello
// 		WARN 23:02:04 -- hello
// 		ERROR 23:02:04 -- hello
// 		FATAL 23:02:04 -- hello

		LOG_F("\n");
	}
Ejemplo n.º 7
0
 void          Log4::logFatal(int i, std::string *message)
{
  if (logger[i][0]->isFatalEnabled())
    {
      logCall[5] +=1;
      LOG4CXX_FATAL(logger[i][0], *message);
    }
}
Ejemplo n.º 8
0
Yao::Yao(EnvParams &params) : YaoBase(params)
{
	if (Env::s() != 1)
	{
		LOG4CXX_FATAL(logger, "s has to be 1 in the honest-but-curious setting");
		MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
	}

	// Init variables
	m_rnds.resize(Env::node_load());
	m_ccts.resize(Env::node_load());
	m_gen_inp_masks.resize(Env::node_load());
}
Ejemplo n.º 9
0
int ProcwatcherIMV::processFirstMessage(TNC_BufferReference message, TNC_UInt32 length)
{
    LOG4CXX_TRACE(logger, "processFirstMessage()");
    if (loadX509Cert(message, length) < 0) {
        LOG4CXX_FATAL(logger, "Could not create X509"
                " certificate object");
        nothingWrong = false;
        return -1;                      /*  return */
    }

    if (loadPKey() < 0) {
        LOG4CXX_FATAL(logger, "Could not create EVP_PKEY object");
        nothingWrong = false;
        return -1;                  /*  return */
    }

    if (loadRSA() < 0) {
        LOG4CXX_FATAL(logger, "Could not create RSA object");
        nothingWrong = false;
        return -1;                      /*  return */
    }
    return 0;
}
Ejemplo n.º 10
0
int ProcwatcherIMV::loadX509Cert(TNC_BufferReference message, TNC_UInt32 length)
{
    LOG4CXX_TRACE(logger, "loadX509Cert()");

    BIO *bio = BIO_new_mem_buf(message, length);

    if (bio == NULL) {
        LOG4CXX_FATAL(logger, "Could not create BIO object");
        return -1;
    }
    if (isASN1(message, length)) {
        x509Cert = d2i_X509_bio(bio, NULL);
    } else {
        x509Cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
    }
    if (x509Cert == NULL) {
        LOG4CXX_FATAL(logger, "Could not create X509 object");
        BIO_free(bio);
        return -1;
    }
    LOG4CXX_INFO(logger, "X509 certificate successfully received");
    BIO_free(bio);
    return 0;
}
Ejemplo n.º 11
0
//-------------------------------------------------------------------------------------
void DebugHelper::critical_msg(std::string s)
{
	KBEngine::thread::ThreadGuard tg(&this->logMutex); 

	char buf[DBG_PT_SIZE];
	kbe_snprintf(buf, DBG_PT_SIZE, "%s(%d) -> %s\n\t%s\n", _currFile.c_str(), _currLine, _currFuncName.c_str(), s.c_str());

#ifdef NO_USE_LOG4CXX
#else
	LOG4CXX_FATAL(g_logger, buf);
#endif

	onMessage(KBELOG_CRITICAL, buf, strlen(buf));
	backtrace_msg();
}
Ejemplo n.º 12
0
void client_socket_utils::handle_connect(const boost::system::error_code& error, tcp::resolver::iterator endpoint_iterator,
		socket_session_ptr pSession)
{
	LOG4CXX_DEBUG(firebird_log, KDS_CODE_INFO << " enter.");
	std::string sLog;
	try
	{
		if (!error)
		{
			LOG4CXX_FATAL(firebird_log, "服务器:[" << pSession->get_business_type() << "],连接远程地址:[" << pSession->get_remote_addr().c_str() << "]成功!");
			pSession->start();

			//向服务器注册服务类型
			message msg;
			msg.command = regist;
			msg.business_type = pSession->get_business_type();
			msg.app_id = pSession->get_app_id();
			msg.data() = "R";

			pSession->async_write(msg);
		}
		else
			if (endpoint_iterator != tcp::resolver::iterator())
			{
				LOG4CXX_ERROR(firebird_log, "连接远程地址:[" << pSession->get_remote_addr().c_str() << "]失败,试图重连下一个地址。");
				pSession->socket().close(); //此处用socket的close,不应用session的close触发连接,不然会导致一直重连
				tcp::endpoint endpoint = *endpoint_iterator;
				pSession->socket().async_connect(endpoint,
						boost::bind(&client_socket_utils::handle_connect, this, boost::asio::placeholders::error, ++endpoint_iterator, pSession));
			}
			else
			{
				LOG4CXX_ERROR(firebird_log, KDS_CODE_INFO << "连接远程地址:[" << pSession->get_remote_addr().c_str() << "]失败!");
				pSession->socket().close(); //此处用socket的close,不应用session的close触发连接,不然会导致一直重连
			}
	} catch (std::exception& e)
	{
		LOG4CXX_ERROR(firebird_log, KDS_CODE_INFO << "连接远程地址:[" << pSession->get_remote_addr().c_str() << "],socket异常:[" << e.what() << "]");
	} catch (...)
	{
		LOG4CXX_ERROR(firebird_log, KDS_CODE_INFO << "连接远程地址:[" << pSession->get_remote_addr().c_str() << "],socket异常:[未知异常]");
	}
}
Ejemplo n.º 13
0
void client_socket_utils::read_data_callback(const boost::system::error_code& e, socket_session_ptr session, message& msg)
{
	LOG4CXX_DEBUG(firebird_log, "command =[" << msg.command << "],[" << msg.business_type << "],[" << msg.data() << "]");

	if (msg.command == heartbeat)
	{ //心跳
	}
	else
		if (msg.command == regist)
		{ //注册
			LOG4CXX_FATAL(firebird_log, "服务器:[" << session->get_business_type() << "]注册成功。");
		}
		else
			if (msg.command == normal)
			{ //业务数据
				handle_read_data(msg, session);
			}
			else
			{
				LOG4CXX_ERROR(firebird_log, KDS_CODE_INFO << "收到非法消息包!");
			}
}
void BetterYao2::circuit_evaluate()
{
	step_init();

	double start;

	int verify = 1;
	Bytes bufr;

	EVL_BEGIN
		start = MPI_Wtime();
			for (size_t ix = 0; ix < m_ccts.size(); ix++)
			{
				if (m_chks[ix]) // check-circuits
				{
					m_ccts[ix].gen_init(m_ot_keys[ix], m_gen_inp_masks[ix], m_rnds[ix]);
				}
				else // evaluation-circuits
				{
					m_ccts[ix].evl_init(m_ot_keys[ix], m_gen_inp_masks[ix], m_evl_inp);
				}
			}
		m_timer_evl += MPI_Wtime() - start;
	EVL_END

	step_report("pre-cir-evl");
	step_init();

	GEN_BEGIN // start generating circuits gate-by-gate
		start = MPI_Wtime();
			while (Env::circuit().more_gate_binary())
			{
				const Gate &g = Env::circuit().next_gate_binary();

				for (size_t ix = 0; ix < m_ccts.size(); ix++)
				{
						m_ccts[ix].gen_next_gate(g);
						bufr = m_ccts[ix].send();
					m_timer_gen += MPI_Wtime() - start;

					start = MPI_Wtime();
						GEN_SEND(bufr);
					m_timer_com += MPI_Wtime() - start;

					m_comm_sz += bufr.size();

					start = MPI_Wtime(); // start m_timer_gen
				}
			}
		m_timer_gen += MPI_Wtime() - start;
	GEN_END

	EVL_BEGIN
		start = MPI_Wtime();
			int gate_ix = 0;
			while (Env::circuit().more_gate_binary())
			{
				const Gate &g = Env::circuit().next_gate_binary();

				for (size_t ix = 0; ix < m_ccts.size(); ix++)
				{
					m_timer_evl += MPI_Wtime() - start;

					start = MPI_Wtime();
						bufr = EVL_RECV();
					m_timer_com += MPI_Wtime() - start;

					m_comm_sz += bufr.size();

					start = MPI_Wtime();
						if (m_chks[ix]) // check-circuits
						{
							m_ccts[ix].gen_next_gate(g);
							verify &= (m_ccts[ix].send() == bufr);
						}
						else // evaluation-circuits
						{
							m_ccts[ix].recv(bufr);
							m_ccts[ix].evl_next_gate(g);
						}
				}
				gate_ix ++;
			}
		m_timer_evl += MPI_Wtime() - start;
	EVL_END

	EVL_BEGIN // check the hash of all the garbled circuits
		int all_verify = 0;

		start = MPI_Wtime();
			MPI_Reduce(&verify, &all_verify, 1, MPI_INT, MPI_LAND, 0, m_mpi_comm);
		m_timer_mpi += MPI_Wtime() - start;

		start = MPI_Wtime();
			if (Env::is_root() && !all_verify)
			{
				LOG4CXX_FATAL(logger, "Verification failed");
				MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
			}
		m_timer_evl += MPI_Wtime() - start;
	EVL_END

	step_report("circuit-evl");

	if (Env::circuit().evl_out_cnt() != 0)
		proc_evl_out();

    if (Env::circuit().gen_out_cnt() != 0)
        proc_gen_out();
}
Ejemplo n.º 15
0
void NetHandler::start()
{
	m_bRunning = true;
    // first let's increase the limit of open files
	int maxconn = 100000;
	struct rlimit srl;
	srl.rlim_cur = maxconn + 10;
	srl.rlim_max = maxconn + 10;
	if (setrlimit(RLIMIT_NOFILE, &srl) < 0)
	{
		LOG4CXX_FATAL(logger_, "Cannot set RLimit!");
		exit(1);
	}
	epfd = epoll_create(maxconn);

    if (epfd < 0)
    {
        LOG4CXX_FATAL(logger_, "epoll_create error!");
        exit(1);
    }

    // Now let's ignore broken pipes
    struct sigaction sa;
    memset(&sa, 0, sizeof (sa));
    sa.sa_handler = SIG_IGN;
    if (sigaction(SIGPIPE, &sa, NULL) < 0)
    {
        LOG4CXX_WARN(logger_, "Error ignoring SIGPIPE!");
    }

    if (initSockets() < 0)
    {
        exit(1);
    }

    struct epoll_event ev, evs[MAX_EVENTS];
    LOG4CXX_INFO(logger_, "Nethandler started.");
    for (; ; )
    {
		if (!m_bRunning)
		{
			break;
		}
        int count = epoll_wait(epfd, evs, MAX_EVENTS, 1000);
        if (count < 0)
        {
            LOG4CXX_FATAL(logger_, "epoll_wait error!");
        }
        time_t now = Clock::getCurrentSystemTime();
        if (!preNetEvent(now))
        {
            LOG4CXX_ERROR(logger_, "PreNetEvent returned false, terminating...");
            break;
        }
        for (int i = 0; i < count; i++)
        {
            int fd = evs[i].data.fd;
            if (isListenSocket(fd))
            {
                struct sockaddr_in sa;
                socklen_t slen = sizeof (sa);
                int nfd = 0;
                nfd = accept(fd, (struct sockaddr*) &sa, &slen);
                if (nfd > 0)
                {
                    ev.events = EPOLLIN | EPOLLHUP; //| EPOLLRDHUP;
                    ev.data.fd = nfd;
                    if (epoll_ctl(epfd, EPOLL_CTL_ADD, nfd, &ev) < 0)
                    {
                        LOG4CXX_ERROR(logger_, "epoll_ctl error, cannot add client!");
                    }
                    else
                    {
                        size_t rsize = readCacheSize(fd);
                        //size_t rsize = (fd==wsfd ? NetCache::WEBSERVER_READ_SIZE : NetCache::DEFAULT_READ_SIZE);
                        NetCache *cache = addConnection(nfd, sa, rsize);
                        createProtocolHandler(cache, fd);
                    }
                }
            }
            else // data
            {
                NetCache *cache = getCacheFromFd(fd);
                if (cache != NULL)
                {
                    __uint32_t events = evs[i].events;
                    bool readError = false;
                    if ((events & EPOLLIN) > 0)
                    {
                        int64 uid = cache->uid;
                        readError = !cache->read();
                        if (!readError)
                        {
                            string req;
                            while (cache->assemble(req) && !cache->remove)
                            {
                                //LOG4CXX_DEBUG(logger_, "Command Received: \"" << req.c_str() << "\" from uid:" << uid << " fd:" << fd);

                                if (cache->ph != NULL)
                                {
                                    cache->ph->handle(uid, req);
                                }
                                else
                                {
                                    LOG4CXX_ERROR(logger_, "Protocol handler is NULL for fd:" << fd);
                                }
                            }
                        }
                    }
                    if ((events & EPOLLOUT) > 0)
                    {
                        if ( isConnecting( fd ))
                        {
                            connectSuccess( fd );
                        }
                        else if (cache->write())
                        {
                            ev.events = EPOLLIN | EPOLLHUP; // | EPOLLRDHUP;
                            ev.data.fd = fd;
                            epoll_ctl(epfd, EPOLL_CTL_MOD, fd, &ev);
                        }
                    }
                    if ((cache->remove && !cache->waitToWrite()) || readError ||
                            (events & EPOLLHUP) > 0 || //(events&EPOLLRDHUP)>0 ||
                            (events & EPOLLERR) > 0)
                    {
                        int64 uid = cache->uid;
                        if (uid >= 0 && cache->ph != NULL)
                        {
                            cache->ph->leave(uid);
                        }
                        LOG4CXX_DEBUG(logger_, "Client disconnected of fd:" << fd
                                << ", remove: " << cache->remove << ", read error: "
                                << readError << ", hup: " << (events & EPOLLHUP)
                                //<< //", rdhup: " << (events & EPOLLRDHUP) 
                                << ", epoll error: " << (events & EPOLLERR));
                        doCloseConnection(fd);
                        if (isConnectSocket(fd))
                        {
                            connectFailed(fd);
                        }
                    }
                }
                else
                {
                    LOG4CXX_ERROR(logger_, "Cannot find cache for fd:" << fd);
                }
            }
        }
    }

}
Ejemplo n.º 16
0
int main(int argc, char* argv[])
#endif
{
	//log4cxx::BasicConfigurator::configure();
	log4cxx::LoggerPtr logger = log4cxx::Logger::getRootLogger();
	log4cxx::NDC::push("");

	byte exitStatus = EXIT_SUCCESS;
	try {  
		TCLAP::CmdLine cmd( String(
				"\nireon.org player client, version ") + PRODUCT_VERSION_STR + "\n" +
				"Copyright (C) 2005-2006 ireon.org developers council \n\n" +
				"This program is free software; you can redistribute it and/or " +
				"modify it under the terms of the GNU General Public License " +
				"as published by the Free Software Foundation; either version 2 " +
				"of the License, or (at your option) any later version. \n" +

				"This program is distributed in the hope that it will be useful, " +
				"but WITHOUT ANY WARRANTY; without even the implied warranty of " +
				"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the " +
				"GNU General Public License for more details. \n" +

				"You should have received a copy of the GNU General Public License " +
				"along with this program; if not, write to the Free Software " +
				"Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.", ' ', PRODUCT_VERSION_STR);
		TCLAP::ValueArg<String> cfgArg("c","config","Configuration file path. Default: ../config/config.xml",false,"../config/config.xml","path", cmd);
		TCLAP::ValueArg<String> logCfgArg("l","log_config","Log4cxx configuration file path. Default: ../config/log4cxx.xml",false,"../config/log4cxx.xml","path", cmd);
		/*
		cmd.parse( argc, argv );
		*/
		log4cxx::xml::DOMConfigurator::configureAndWatch(logCfgArg.getValue()); 
		LOG4CXX_INFO(logger, "Starting ireon.org player client...");

		CClientApp app(cfgArg.getValue());

		if( !app.init() )
		{
			std::cerr << "Application initialization failed!" << std::endl;
			return 1;
		}
		SET_OS_SIGNAL_HANDLERS;
		app.go();
	}
	catch( Ogre::Exception& e )
	{
		LOG4CXX_ERROR(logger, e.getFullDescription().c_str());

		#ifdef __WIN32__
		MessageBox( NULL, e.getFullDescription().c_str(), "An OGRE exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
		#else
		std::cerr << "An OGRE exception has occured: " <<
		    e.getFullDescription().c_str() << std::endl;
		#endif
	}
	catch (TCLAP::ArgException &e)  // catch command line parser exceptions
	{ 
		LOG4CXX_FATAL(logger, e.error());
		exitStatus = EXIT_FAILURE;
	}
	catch (const xml_schema::exception& e)
	{
		LOG4CXX_FATAL(logger, "XML file parsing error. Details follow:");
		LOG4CXX_FATAL(logger, e.what());
		exitStatus = EXIT_FAILURE;
	}
	/*
	catch (CRootApp::EInitError&)
	{
		LOG4CXX_FATAL(logger, "Player Client initialization error occurred!");
		exitStatus = EXIT_FAILURE;
	}
*/
	LOG4CXX_INFO(logger, "ireon.org player client stopped.");
	return exitStatus;

}
Ejemplo n.º 17
0
App::App(int &argc, char **argv)
    : QApplication(argc, argv)
    , _invocation(argv[0])
    , _gui(false)
    , _interactive(false)
{
    // Enforce singleton property
    if (_instance) {
        throw std::runtime_error("Only one instance of App allowed.");
    }

    // Remember if we are done
    bool done = false;

    // Set the singleton instance to this
    _instance = this;

    // Set the application properties
    setApplicationName(APPLICATION_NAME);
    setApplicationVersion(APPLICATION_VERSION_STRING);
    setOrganizationName(APPLICATION_VENDOR_NAME);
    setOrganizationDomain(APPLICATION_VENDOR_URL);

    // Configure the logging mechanism
    log4cxx::LoggerPtr rootlogger = log4cxx::Logger::getRootLogger();
    rootlogger->addAppender(new log4cxx::ConsoleAppender(new log4cxx::PatternLayout("[%-5p] %m%n")));

    // Parse the commandline
    int idx = 1;
    while (idx < argc) {
        QString arg(argv[idx]);
        if (matches_option(arg, "help", 0) || matches_option(arg, "h") || matches_option(arg, "?", 0)) {
            printHelpMessage();
            std::exit(0);
        } else if (matches_option(arg, "version", 0)) {
            printVersionMessage();
            std::exit(0);
        } else if (matches_option(arg, "version-triplet")) {
            printVersionTripletMessage();
            std::exit(0);
        } else if (matches_option(arg, "prefset")) {
            // Verify that there is another argument
            if ((idx + 1) >= argc) {
                LOG4CXX_FATAL(_logger, "Option \"" << arg << "\" requires a parameter.");
                std::exit(1);
            }

            // Increment the index
            idx++;

            // Get the next parameter
            std::string param(argv[idx]);

            // Determine if there is an equals sign
            // If there is, set the preference;
            // Otherwise, remove the preference
            size_t eqidx = param.find('=');
            if (eqidx != std::string::npos) {
                std::string key = param.substr(0, eqidx);
                std::string val = param.substr(eqidx + 1);
                setPreference(key, val);
            } else {
                unsetPreference(param);
            }
            done = true;
        } else if (matches_option(arg, "prefdel")) {
            // Verify that there is another argument
            if ((idx + 1) >= argc) {
                LOG4CXX_FATAL(_logger, "Option \"" << arg << "\" requires a parameter.");
                std::exit(1);
            }

            // Increment the index
            idx++;

            // Get the next parameter
            std::string param(argv[idx]);

            // Remove the preference
            unsetPreference(param);
            done = true;
        } else if (matches_option(arg, "preflist")) {
            printAllPreferences();
            done = true;
        } else if (matches_option(arg, "prefget")) {
            // Verify that there is another argument
            if ((idx + 1) >= argc) {
                LOG4CXX_FATAL(_logger, "Option \"" << arg << "\" requires a parameter.");
                std::exit(1);
            }

            // Increment the index
            idx++;

            // Get the next parameter
            std::string param(argv[idx]);

            // Print the preference
            printPreference(param);
            done = true;
        } else if (matches_option(arg, "loglevel")) {
            // Verify that there is another argument
            if ((idx + 1) >= argc) {
                LOG4CXX_FATAL(_logger, "Option \"" << arg << "\" requires a parameter.");
                std::exit(1);
            }

            // Increment the index
            idx++;

            // Get the next parameter
            std::string param(argv[idx]);

            // Determine if there is an equals sign and act accordingly
            size_t eqidx = param.find('=');
            if (eqidx != std::string::npos) {
                std::string logger = param.substr(0, eqidx);
                std::string level  = param.substr(eqidx + 1);
                setLogLevel(logger, level);
            } else {
                setLogLevel("", param);
            }
        } else if (matches_option(arg, "appid") || matches_option(arg, "application-identifier")) {
            printApplicationIdentifier();
            std::exit(0);
        } else if (matches_option(arg, "gui")) {
            if (_interactive) {
                LOG4CXX_FATAL(_logger, "Cannot specify both \"--gui\" and \"--interactive\" simultaneously.");
                std::exit(1);
            }
            if (_gui) {
                LOG4CXX_WARN(_logger, "Option \"" << arg << "\" already specified. Ignoring.");
            }
            _gui = true;
        } else if (matches_option(arg, "interactive")) {
            if (_gui) {
                LOG4CXX_FATAL(_logger, "Cannot specify both \"--gui\" and \"--interactive\" simultaneously.");
                std::exit(1);
            }
            if (_interactive) {
                LOG4CXX_WARN(_logger, "Option \"" << arg << "\" already specified. Ignoring.");
            }
            _interactive = true;
        } else {
            LOG4CXX_WARN(_logger, "Unrecognized option: \"" << arg << "\". Ignoring");
        }
        idx++;
    }

    initGUI();
}
Ejemplo n.º 18
0
void MyLog::ErrLog(std::string errinfo)
{
    LOG4CXX_FATAL(DebugInfoLog,errinfo);
}
void BetterYao2::consistency_check()
{
	step_init();

	Bytes send, recv, bufr;
	std::vector<Bytes> recv_chunks, bufr_chunks;

	double start;

	Z m;

	if (Env::is_root())
	{
		GEN_BEGIN // give away the generator's input M_{0,j}
			start = MPI_Wtime();
				bufr.clear();
				for (int jx = 0; jx < Env::circuit().gen_inp_cnt(); jx++)
				{
					bool bit_value = m_gen_inp.get_ith_bit(jx);
					bufr += m_ccts[0].m_M[2*jx+bit_value].to_bytes();
				}
			m_timer_gen += MPI_Wtime() - start;

			start = MPI_Wtime();
				GEN_SEND(bufr);
			m_timer_com += MPI_Wtime() - start;
		GEN_END

		EVL_BEGIN
			start = MPI_Wtime();
				bufr = EVL_RECV();
			m_timer_com += MPI_Wtime() - start;
		EVL_END

		m_comm_sz += bufr.size();
	}

	EVL_BEGIN // forward the generator's input M_{0,j} to slave evaluators
		start = MPI_Wtime();
			bufr.resize(Env::elm_size_in_bytes()*Env::circuit().gen_inp_cnt());
		m_timer_evl += MPI_Wtime() - start;

		start = MPI_Wtime();
			MPI_Bcast(&bufr[0], bufr.size(), MPI_BYTE, 0, m_mpi_comm);
		m_timer_mpi += MPI_Wtime() - start;

		start = MPI_Wtime();
			bufr_chunks = bufr.split(Env::elm_size_in_bytes());
		m_timer_evl += MPI_Wtime() - start;
	EVL_END

	GEN_BEGIN // give away m_{i,j}-m_{0,j} so that M_{i,j} can be reconstructed
		start = MPI_Wtime();
			if (Env::is_root()) // forward m_{0,j} to slave generators
			{
				bufr.clear();
				for (size_t jx = 0; jx < Env::circuit().gen_inp_cnt(); jx++)
				{
					bool bit_value = m_gen_inp.get_ith_bit(jx);
					bufr += m_ccts[0].m_m[2*jx+bit_value].to_bytes();
				}
			}
			bufr.resize(Env::exp_size_in_bytes()*Env::circuit().gen_inp_cnt());
		m_timer_gen += MPI_Wtime() - start;

		start = MPI_Wtime();
			MPI_Bcast(&bufr[0], bufr.size(), MPI_BYTE, 0, m_mpi_comm);
		m_timer_mpi += MPI_Wtime() - start;

		start = MPI_Wtime();
			bufr_chunks = bufr.split(Env::exp_size_in_bytes());

			send.clear();
			send.reserve(Env::exp_size_in_bytes()*Env::circuit().gen_inp_cnt()*m_ccts.size());
			for (size_t jx = 0; jx < Env::circuit().gen_inp_cnt(); jx++)
			{
				m.from_bytes(bufr_chunks[jx]); // retrieve m_{0,j}
				bool bit_value = m_gen_inp.get_ith_bit(jx);

				for (size_t ix = 0; ix < m_ccts.size(); ix++)
				{
					if (m_chks[ix]) // no data for check-circuits
						continue;
					send += (m_ccts[ix].m_m[2*jx+bit_value]-m).to_bytes(); // m_{i,j}-m_{0,j}
				}
			}
		m_timer_gen += MPI_Wtime() - start;

		start = MPI_Wtime();
			GEN_SEND(send);
		m_timer_com += MPI_Wtime() - start;

		m_comm_sz += send.size();
	GEN_END

	int verify = 1;
	G M;

	EVL_BEGIN
		start = MPI_Wtime();
			recv = EVL_RECV();
		m_timer_com += MPI_Wtime() - start;

		m_comm_sz += recv.size();

		start = MPI_Wtime();
			recv_chunks = recv.split(Env::exp_size_in_bytes());
			for (size_t ix = 0, kx = 0; ix < Env::circuit().gen_inp_cnt(); ix++)
			{
				M.from_bytes(bufr_chunks[ix]);

				for (size_t jx = 0; jx < m_ccts.size(); jx++)
				{
					if (m_chks[jx])
						continue;

					// reconstruct M_{i,j}
					m.from_bytes(recv_chunks[kx++]);                // m = m_{i,j}-m_{0,j}
					M *= Env::clawfree().R(m);                      // M_{i,j} = h^m * M_{0,j}
					verify &= (m_ccts[jx].m_M[ix] == M);
				}
			}
		m_timer_evl += MPI_Wtime() - start;

		int all_verify = 0;

		start = MPI_Wtime();
			MPI_Reduce(&verify, &all_verify, 1, MPI_INT, MPI_LAND, 0, m_mpi_comm);
		m_timer_mpi += MPI_Wtime() - start;

		start = MPI_Wtime();
			if (Env::is_root() && !all_verify)
			{
				LOG4CXX_FATAL(logger, "consistency check failed");
				MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
			}
		m_timer_evl += MPI_Wtime() - start;
	EVL_END

	step_report("const-check");
}
Ejemplo n.º 20
0
void NetHandler::start()
{
	m_bRunning = true;
    fd_set readset;
    FD_ZERO(&master);
    int listenFd = initSockets();
    if (listenFd < 0)
    {
        LOG4CXX_FATAL(logger_, "socket create failed!");
        exit(1);
    }
    if (listenFd > fdmax)
    {
        fdmax = listenFd;
    }

    LOG4CXX_INFO(logger_, "NetHandler started.");

    struct timeval timeout;

    for (; ; )
    {
		if (!m_bRunning)
		{
			break;
		}
        readset = master;
        timeout.tv_sec = 1;
        timeout.tv_usec = 0;
        int count = select(fdmax + 1, &readset, NULL, NULL, &timeout);
        if (count < 0)
        {
            LOG4CXX_FATAL(logger_, "Select error!");
            exit(1);
        }
        time_t now = Clock::getCurrentSystemTime();
        if (!preNetEvent(now))
        {
            LOG4CXX_ERROR(logger_, "PreNetEvent returned false, terminating...");
            break;
        }
        if (count > 0)
        {
            for (int i = 0; i <= fdmax; i++)
            {
                if (FD_ISSET(i, &readset))
                {
                    if (isListenSocket(i))
                    {
                        struct sockaddr_in sa;
                        socklen_t slen = sizeof (sa);
                        int nfd = accept(i, (struct sockaddr*) &sa, &slen);
                        if (nfd < 0)
                        {
                            LOG4CXX_ERROR(logger_, "Accept error!");
                        }
                        else
                        {
                            FD_SET(nfd, &master);
                            if (nfd > fdmax)
                            {
                                fdmax = nfd;
                            }
                            size_t rsize = readCacheSize(i);
                            NetCache *cache = addConnection(nfd, sa, rsize);
                            createProtocolHandler(cache, i);
                        }
                    }
                    else
                    {
                        NetCache *cache = getCacheFromFd(i);
                        if (cache != NULL)
                        {
                            int64 uid = cache->uid;
                            bool readSucc = cache->read();
                            if (readSucc)
                            {
                                string req;
                                while (cache->assemble(req) && !cache->remove)
                                {
                                    //LOG4CXX_DEBUG(logger_, "Command Received \"" << req.substr(0, 2) << "\" from uid:" << uid << " fd:" << i);

                                    if (cache->ph != NULL)
                                    {
                                        cache->ph->handle(uid, req);
                                    }
                                    else
                                    {
                                        LOG4CXX_ERROR(logger_, "Protocol handler is NULL for fd:" << i);
                                    }
                                }
                            }
                            if (!readSucc || (cache->remove && !cache->waitToWrite()))
                            {
                                if (uid >= 0 && cache->ph != NULL)
                                {
                                    cache->ph->leave(uid);
                                }
                                doCloseConnection(i);
                                LOG4CXX_DEBUG(logger_, "Client disconnected with fd:" << i);
                                if (isConnectSocket(i))
                                {
                                    int newFd = connectFailed(i);
                                    fdmax = max(fdmax, newFd);
                                }
                            }
                        }
                        else
                        {
                            LOG4CXX_ERROR(logger_, "Cannot find cache for fd:" << i);
                        }
                    }
                }
            }
        }
    }
}
void BetterYao2::cut_and_choose()
{
	step_init();

	double start;

	if (Env::is_root())
	{
		Bytes coins = m_prng.rand(Env::k());          // Step 0: flip coins
		Bytes remote_coins, comm, open;

		EVL_BEGIN
			start = MPI_Wtime();
				comm = EVL_RECV();                    // Step 1: receive bob's commitment
				EVL_SEND(coins);                      // Step 2: send coins to bob
				open = EVL_RECV();
			m_timer_com += MPI_Wtime() - start;

			start = MPI_Wtime();
				if (!(open.hash(Env::s()) == comm))   // Step 3: check bob's decommitment
				{
					LOG4CXX_FATAL(logger, "commitment to coins can't be properly opened");
					MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
				}
				remote_coins = Bytes(open.begin()+Env::k()/8, open.end());
			m_timer_evl += MPI_Wtime() - start;
		EVL_END

		GEN_BEGIN
			start = MPI_Wtime();
				open = m_prng.rand(Env::k()) + coins; // Step 1: commit to coins
				comm = open.hash(Env::s());
			m_timer_gen += MPI_Wtime() - start;

			start = MPI_Wtime();
				GEN_SEND(comm);
				remote_coins = GEN_RECV();            // Step 2: receive alice's coins
				GEN_SEND(open);                       // Step 3: decommit to the coins
			m_timer_com += MPI_Wtime() - start;
		GEN_END

		m_comm_sz = comm.size() + remote_coins.size() + open.size();

		start = MPI_Wtime();
			coins ^= remote_coins;
			Prng prng;
			prng.srand(coins); // use the coins to generate more random bits

			// make 60-40 check-vs-evaluateion circuit ratio
			m_all_chks.assign(Env::s(), 1);

			// FisherÐYates shuffle
			std::vector<uint16_t> indices(m_all_chks.size());
			for (size_t ix = 0; ix < indices.size(); ix++) { indices[ix] = ix; }

			// starting from 1 since the 0-th circuit is always evaluation-circuit
			for (size_t ix = 1; ix < indices.size(); ix++)
			{
				int rand_ix = prng.rand_range(indices.size()-ix);
				std::swap(indices[ix], indices[ix+rand_ix]);
			}

			int num_of_evls;
			switch(m_all_chks.size())
			{
			case 0: case 1:
				LOG4CXX_FATAL(logger, "there isn't enough circuits for cut-and-choose");
				MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
				break;

			case 2: case 3:
				num_of_evls = 1;
				break;

			case 4:
				num_of_evls = 2;
				break;

			default:
				num_of_evls = m_all_chks.size()*2/5;
				break;
			}

			for (size_t ix = 0; ix < num_of_evls; ix++) { m_all_chks[indices[ix]] = 0; }
		m_timer_evl += MPI_Wtime() - start;
		m_timer_gen += MPI_Wtime() - start;
	}

	start = MPI_Wtime();
		m_chks.resize(Env::node_load());
	m_timer_evl += MPI_Wtime() - start;
	m_timer_gen += MPI_Wtime() - start;

	start = MPI_Wtime();
		MPI_Scatter(&m_all_chks[0], m_chks.size(), MPI_BYTE, &m_chks[0], m_chks.size(), MPI_BYTE, 0, m_mpi_comm);
	m_timer_mpi += MPI_Wtime() - start;

	step_report("cut-&-check");
}
Ejemplo n.º 22
0
	static void LuaLogFatal(const std::string &str)
	{
		LOG4CXX_FATAL(gScriptLogger, str);
	}
Ejemplo n.º 23
0
TNC_Result ProcwatcherIMV::receiveMessage(TNC_BufferReference message,
        TNC_UInt32 length,
        TNC_MessageType messageType)
{

            //把FileEntry存好
            //
            //
 
    //this->entry = policyManager->getFileEntries();
  //(this->entry).push_back(FileEntry("/bin/","12345678901234567890")); 
            //
            //


    LOG4CXX_DEBUG(logger, "receiveMessage round " << this->getRound());
    if (firstMessage) {
        LOG4CXX_DEBUG(logger, "Received first message, should be the x509 cert");
        firstMessage = 0;
        if (processFirstMessage(message, length) < 0) {
            return TNC_RESULT_FATAL;
        }
        if (!checkClientKnown()) {
            LOG4CXX_INFO(logger, "Client Certificate unknown. :-(");
            tncs.provideRecommendation(TNC_IMV_ACTION_RECOMMENDATION_NO_ACCESS,
                    TNC_IMV_EVALUATION_RESULT_DONT_KNOW);
        }
        else
        {
            nonceBuf = new unsigned char[50]; 
            //验证完AIK证书后,发一个nonce过去,以防止重放攻击
            LOG4CXX_TRACE(logger, "Generating nonce...");
            if (RAND_bytes(nonceBuf,10) == 0) {
                LOG4CXX_FATAL(logger, "RAND_bytes() failed!!!");
                nothingWrong = false;
                delete[] nonceBuf;
                return -1;
            }
            else
            {
                for(int i=0;i<10;i++)
                {
                    printf("%02hhx",nonceBuf[i]);
                }
                translate2chars((char *)nonceBuf,20);
                //计算hash(n*(hash(file),用于等下收到客户端发过来的该内容时做匹配,类似attestation里的calculate函数
                calculateHash(entry);
                this->tncs.sendMessage(nonceBuf, 20, VENDOR_ID,MESSAGE_SUBTYPE);
                delete[] nonceBuf;   
            }
        }
    }
    else
    {
        char *temp_buf = (char *)malloc(MAX);
        //memcpy(temp_buf,message,20);
        strcpy(temp_buf,(char *)message);
        // print received message dirty out. WARNING: don't ape this,
        // message should end with non-null! Heed: Message can be evil!
        LOG4CXX_INFO(logger, "Received 2nd Message: " << message);

        /* only send one message to ProcwatcherIMC */
        //		/* validation finish, set recommendation & co */
        //        validationFinished = true;
        //
        //		// for no access:
        ////		actionRecommendation = TNC_IMV_ACTION_RECOMMENDATION_NO_ACCESS;
        //		// for isolate:
        ////		actionRecommendation = TNC_IMV_ACTION_RECOMMENDATION_ISOLATE;
        //		// for access allow:
        //        actionRecommendation = TNC_IMV_ACTION_RECOMMENDATION_ALLOW;
        //
        //        // set evaluation (see TNC_IMV_EVALUATION_RESULT_...)
        //        evaluationResult = TNC_IMV_EVALUATION_RESULT_DONT_KNOW;

        //验证签名!标准值来自于:已知进程hash+nonce
        translate2chars(temp_buf,20);
        std::stringstream ss;
        ss.write((const char *)message, length);
        std::vector<prop_type> properties = readAllProperties(ss);

	LOG4CXX_INFO(logger, "good file-hash signature :-)" );
        
	validationFinished = true;
        actionRecommendation = TNC_IMV_ACTION_RECOMMENDATION_ALLOW;
        evaluationResult = TNC_IMV_EVALUATION_RESULT_DONT_KNOW;
        free(temp_buf);

    }

    // return all ok
    return TNC_RESULT_SUCCESS;
}