Example #1
0
void BadaMutexManager::unlockMutex(OSystem::MutexRef mutex) {
	Mutex *m = (Mutex*)mutex;
	m->Release();
}
Example #2
0
bool Rehash()
{
#ifdef WIN32
	char * config_file = "ascent-logonserver.conf";
#else
	char * config_file = (char*)CONFDIR "/ascent-logonserver.conf";
#endif
	if(!Config.MainConfig.SetSource(config_file))
	{
		printf("Config file could not be rehashed.\n");
		return false;
	}

	m_encryptedPasswords = Config.MainConfig.GetBoolDefault("LogonServer", "UseEncryptedPasswords", false);

	// re-set the allowed server IP's
	string ips = Config.MainConfig.GetStringDefault("LogonServer", "AllowedIPs", "");
	string ipsmod = Config.MainConfig.GetStringDefault("LogonServer", "AllowedModIPs", "");

	vector<string> vips = StrSplit(ips, " ");
	vector<string> vipsmod = StrSplit(ips, " ");

	m_allowedIpLock.Acquire();
	m_allowedIps.clear();
	m_allowedModIps.clear();
	vector<string>::iterator itr;
	for(itr = vips.begin(); itr != vips.end(); ++itr)
	{
		string::size_type i = itr->find("/");
		if( i == string::npos )
		{
			printf("IP: %s could not be parsed. Ignoring\n", itr->c_str());
			continue;
		}

		string stmp = itr->substr(0, i);
		string smask = itr->substr(i+1);

		unsigned int ipraw = MakeIP(stmp.c_str());
		unsigned int ipmask = atoi(smask.c_str());
		if( ipraw == 0 || ipmask == 0 )
		{
			printf("IP: %s could not be parsed. Ignoring\n", itr->c_str());
			continue;
		}

		AllowedIP tmp;
		tmp.Bytes = ipmask;
		tmp.IP = ipraw;
		m_allowedIps.push_back(tmp);
	}

	for(itr = vipsmod.begin(); itr != vipsmod.end(); ++itr)
	{
		string::size_type i = itr->find("/");
		if( i == string::npos )
		{
			printf("IP: %s could not be parsed. Ignoring\n", itr->c_str());
			continue;
		}

		string stmp = itr->substr(0, i);
		string smask = itr->substr(i+1);

		unsigned int ipraw = MakeIP(stmp.c_str());
		unsigned int ipmask = atoi(smask.c_str());
		if( ipraw == 0 || ipmask == 0 )
		{
			printf("IP: %s could not be parsed. Ignoring\n", itr->c_str());
			continue;
		}

		AllowedIP tmp;
		tmp.Bytes = ipmask;
		tmp.IP = ipraw;
		m_allowedModIps.push_back(tmp);
	}

	if( InformationCore::getSingletonPtr() != NULL )
		sInfoCore.CheckServers();

	m_allowedIpLock.Release();

	return true;
}
Example #3
0
void BadaMutexManager::lockMutex(OSystem::MutexRef mutex) {
	Mutex *m = (Mutex*)mutex;
	m->Acquire();
}
Example #4
0
int main(int argc, char **argv)
{
	std::string LocSocket = "/tmp/ipdupdetect";
	std::unique_ptr<PIDFile> PidFile;
	std::string LocPidFile = "";
	const char *opts = "hdp:";
	int longindex = 0;
	int c = 0;
	int debug = 0;
	struct option loptions[]
	{
		{"help", 0, 0, 'h'},
		{"pid", 1, 0, 'p'},
		{"debug", 0, 0, 'd'},
		{0, 0, 0, 0}
	};
	
	while( (c = getopt_long(argc, argv, opts, loptions, &longindex)) >= 0)
	{
		switch(c)
		{
			case 'd':
				debug = 1;
				break;
			case 'h':
				print_help(stdout, argv[0]);
				exit(EXIT_SUCCESS);
				break;
			case 'p':
				LocPidFile = optarg;
				break;
			default:
				break;
		}
	}
	
	//Add Logging
	if (isatty(fileno(stdout)) == 1)
	{
		std::shared_ptr<ILogger> tmp = std::make_shared<LogStdoutColor>();
		LogManager::Add(tmp);
	} else {
		std::shared_ptr<ILogger> tmp = std::make_shared<LogStdout>();
		LogManager::Add(tmp);
	}

	if (debug)
	{
		LogManager::SetLevel(LOGGER_DEBUG);
	}
	else
	{
		LogManager::SetLevel(LOGGER_INFO);
	}
	
	if (LocPidFile != "")
	{
		PidFile.reset(new PIDFile(LocPidFile));
		if (PidFile->Create() == false)
		{
			LogCritical("Cannot Create PID file '%s'", LocPidFile.c_str());
			exit(EXIT_FAILURE);
		}
		LogInfo("Created PID file '%s'", LocPidFile.c_str());
	}

	SigHandler SHandler;
	SignalHandler Signals = SignalHandler(&SHandler);
	Signals.Block();

	do
	{
		ServerManager *SrvManager = NULL;
		MonitorManager MManager;
		Service *Srv = new Service(&MManager); //Bind instance of MonitorManager to the ServiceProxy
		struct timespec timeout = {60, 0}; //Timeout to reprocess interface list
		ScopedLock lock(&ExitLock);
		SHandler.SetMonitorManager(&MManager); //Bind MonitorManager to signal handler proxy

		
		ServerUnixPolled Unix(LocSocket); //Create a suitable socket
		SrvManager = new ServerManager(Srv); //Create a new server instance
		SrvManager->ServerAdd(&Unix); //Bind our Service proxy to the socket instance

		Signals.UnBlock();
		while(DoExit == false)
		{
			MManager.Scan();
			MManager.Purge();
			ExitLock.Wait(&timeout);
		}
		lock.Unlock(); //Required to prevent hang in signals
		
		SrvManager->ServerRemove(&Unix);
		delete Srv;
		delete SrvManager;
		
		Signals.Block();
		SHandler.SetMonitorManager(NULL);
		Signals.UnBlock();
		
	} while(0);


	return 0;
}
Example #5
0
void ThreadCondition::wait(Mutex& mutex)
{
    m_condition.timedWait(mutex.impl(), INFINITE);
}
Example #6
0
bool
KRT2Device::DataReceived(const void *_data, size_t length,
                         struct NMEAInfo &info)
{
  assert(_data != nullptr);
  assert(length > 0);

  const uint8_t *data = (const uint8_t *)_data;
  const uint8_t *end = data + length;

  do {
    // Append new data to the buffer, as much as fits in there
    auto range = rx_buf.Write();
    if (rx_buf.IsFull()) {
      // Overflow: reset buffer to recover quickly
      rx_buf.Clear();
      expected_msg_length = 0;
      continue;
    }
    size_t nbytes = std::min(range.size, size_t(end - data));
    memcpy(range.data, data, nbytes);
    data += nbytes;
    rx_buf.Append(nbytes);

    for (;;) {
      // Read data from buffer to handle the messages
      range = rx_buf.Read();
      if (range.IsEmpty())
        break;

      if (range.size < expected_msg_length)
        break;

      expected_msg_length = ExpectedMsgLength(range.data, range.size);

      if (range.size >= expected_msg_length) {
        switch (*(const uint8_t *) range.data) {
          case ACK:
          case NAK:
            // Received a response to a normal command (STX)
            response_mutex.Lock();
            response = *(const uint8_t *) range.data;
            // Signal the response to the TX thread
            rx_cond.signal();
            response_mutex.Unlock();
            break;
          default:
            // Received a command from the radio -> ignore it
            break;
        }
        // Message handled -> remove message
        rx_buf.Consume(expected_msg_length);
        expected_msg_length = 0;
        // Received something from the radio -> the connection is alive
        info.alive.Update(info.clock);
      }
    }
  } while (data < end);

  return true;
}
int main(int argc, char* argv[])
{
    Component a, b, c;

    // Force components to use JTCP...

    //a.AddService(new JTCPClient());
    //b.AddService(new JTCPClient());
    //c.AddService(new JTCPClient());

    // Try load settings files.
    // These files determine your UDP network 
    // settings, what Services to turn on/off 
    // or any Service specific settings. See the
    // example file for settings file format.
    if(a.LoadSettings("settings/services.xml") == false ||
       b.LoadSettings("settings/services.xml") == false ||
       c.LoadSettings("settings/services.xml") == false)
    {
        // Working directory probably not set (or not running from output directory), so
        // use default values.
        a.DiscoveryService()->SetSubsystemIdentification(Subsystem::Vehicle,
            "Simulation");
        b.DiscoveryService()->SetSubsystemIdentification(Subsystem::Vehicle,
            "Simulation");
        c.DiscoveryService()->SetSubsystemIdentification(Subsystem::Vehicle,
            "Simulation");
    }

    // Use a callback to know when heartbeat messages were receive
    CallbackTest callback;
    a.TransportService()->RegisterCallback(EVENT, &callback);

    // Initialize a component with any ID.
    std::cout << "Initializing Component A...";
    if(a.Initialize(Address(60001, 1, 1)) == false)
    {
        std::cout << "Failed to Initialize Component A.\n";
        return 0;
    }
    std::cout << "Success!\n";

    std::cout << "Initializing Component B...";
    // Initialize a component with a given ID.
    if(b.Initialize(Address(60002, 1, 1)) == false)
    {
        std::cout << "Failed to Initialize Component B.\n";
        return 0;
    }
    std::cout << "Success!\n";

    std::cout << "Initializing Component C...";
    // Initialize a component with a given ID.
    if(c.Initialize(Address(60003, 1, 1)) == false)
    {
        std::cout << "Failed to Initialize Component C.\n";
        return 0;
    }
    std::cout << "Success!\n";

    // Enable Debug Messages for testing.
    //a.TransportService()->EnableDebugMessages(true);
    //b.TransportService()->EnableDebugMessages(true);
    //a.LivenessService()->EnableDebugMessages(true);
    //a.EventsService()->EnableDebugMessages(true);
    //b.EventsService()->EnableDebugMessages(true);

    //a.TransportService()->EnableLogging(true);
    
    // Allow time for connections to establish before trying
    // to send a query.
    CxUtils::SleepMs(1000);

    // Example inline message query - Get subsystem ID of component B
    QueryIdentification queryIdent(b.GetComponentID(), a.GetComponentID());
    queryIdent.SetQueryType(QueryIdentification::SubsystemIdentification);
    ReportIdentification reportIdent;
    if(a.Send(&queryIdent, &reportIdent, 1000))
    {
        reportIdent.Print();
    }


    Time::Stamp startTimeMs = Time::GetUtcTimeMs();
    while(CxUtils::GetChar() != 27)
    {      
        static bool createdEvent = false;
        if(!createdEvent && !a.EventsService()->HaveSubscription(REPORT_HEARTBEAT_PULSE, b.GetComponentID()))
        {
            // Request Heartbeat Events from component b.
            QueryHeartbeatPulse query;
            createdEvent = a.EventsService()->RequestPeriodicEvent(b.GetComponentID(),
                &query,
                10,
                1); 
        }
        gPrintLock.Lock();
        //a.DiscoveryService()->PrintSystemConfiguration();
        //b.DiscoveryService()->PrintSystemConfiguration();
        c.DiscoveryService()->PrintSystemConfiguration();
        gPrintLock.Unlock();

        // Testing Discovery Service.  This is for testing purposes only. 
        // What should happen is that after a timeout period A will no longer
        // see Component b until it is re-initialized.  Upon re-discovery, a should
        // automatically re-create the Report Heartbeat Pulse event.
        static bool didShutdown = false;
        //if(!didShutdown && b.IsInitialized() && Time::GetUtcTimeMs() - startTimeMs > 5000)
        //{
        //    std::cout << "Testing Loss of Component...\n";
        //    b.Shutdown();
        //    didShutdown = true;
        //}

        //if(!b.IsInitialized() && Time::GetUtcTimeMs() - startTimeMs > 15000)
        //{
        //    std::cout << "Testing Discovery of Component...\n";
        //    b.DiscoveryService()->SetSubsystemIdentification(Subsystem::Vehicle,
        //                                                     "Simulation");
        //    b.Initialize(Address(60000, 1, 2));
        //}

        CxUtils::SleepMs(1000);
    }

    // Shutdown the components.
    a.Shutdown();
    b.Shutdown();

    return 0;
}
Example #8
0
 void Lock() {
   mutex.Lock();
 }
Example #9
0
 void Unlock() {
   mutex.Unlock();
 }
Example #10
0
	bool Condition::wait(Mutex& mutex)
	{
		return SDL_CondWait(p.get(), mutex.raw_ptr()) == 0;
	}
void gSetLogFile(FILE *wFile)
{
	gLogLock.lock();
	gLoggingFile = wFile;
	gLogLock.unlock();
}
Example #12
0
void DroneController::popAllCommands()
{
	m_mutex.lock();
	while(!m_commandStack.empty()) m_commandStack.pop();
	m_mutex.unlock();
}
Example #13
0
void DroneController::popCommand()
{
	m_mutex.lock();
	if(!m_commandStack.empty()) m_commandStack.pop();
	m_mutex.unlock();
}
Example #14
0
void DroneController::clearPosition()
{
	m_mutex.lock();
	m_velIntegrator.clear();
	m_mutex.unlock();
}
Example #15
0
void DroneController::stop()
{
	m_mutex.lock();
	m_stop = true;
	m_mutex.unlock();
}
Example #16
0
void ClientLauncher::speed_tests()
{
	// volatile to avoid some potential compiler optimisations
	volatile static s16 temp16;
	volatile static f32 tempf;
	static v3f tempv3f1;
	static v3f tempv3f2;
	static std::string tempstring;
	static std::string tempstring2;

	tempv3f1 = v3f();
	tempv3f2 = v3f();
	tempstring = std::string();
	tempstring2 = std::string();

	{
		infostream << "The following test should take around 20ms." << std::endl;
		TimeTaker timer("Testing std::string speed");
		const u32 jj = 10000;
		for (u32 j = 0; j < jj; j++) {
			tempstring = "";
			tempstring2 = "";
			const u32 ii = 10;
			for (u32 i = 0; i < ii; i++) {
				tempstring2 += "asd";
			}
			for (u32 i = 0; i < ii+1; i++) {
				tempstring += "asd";
				if (tempstring == tempstring2)
					break;
			}
		}
	}

	infostream << "All of the following tests should take around 100ms each."
	           << std::endl;

	{
		TimeTaker timer("Testing floating-point conversion speed");
		tempf = 0.001;
		for (u32 i = 0; i < 4000000; i++) {
			temp16 += tempf;
			tempf += 0.001;
		}
	}

	{
		TimeTaker timer("Testing floating-point vector speed");

		tempv3f1 = v3f(1, 2, 3);
		tempv3f2 = v3f(4, 5, 6);
		for (u32 i = 0; i < 10000000; i++) {
			tempf += tempv3f1.dotProduct(tempv3f2);
			tempv3f2 += v3f(7, 8, 9);
		}
	}

	{
		TimeTaker timer("Testing std::map speed");

		std::map<v2s16, f32> map1;
		tempf = -324;
		const s16 ii = 300;
		for (s16 y = 0; y < ii; y++) {
			for (s16 x = 0; x < ii; x++) {
				map1[v2s16(x, y)] =  tempf;
				tempf += 1;
			}
		}
		for (s16 y = ii - 1; y >= 0; y--) {
			for (s16 x = 0; x < ii; x++) {
				tempf = map1[v2s16(x, y)];
			}
		}
	}

	{
		infostream << "Around 5000/ms should do well here." << std::endl;
		TimeTaker timer("Testing mutex speed");

		Mutex m;
		u32 n = 0;
		u32 i = 0;
		do {
			n += 10000;
			for (; i < n; i++) {
				m.lock();
				m.unlock();
			}
		}
		// Do at least 10ms
		while(timer.getTimerTime() < 10);

		u32 dtime = timer.stop();
		u32 per_ms = n / dtime;
		infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
	}
}