Beispiel #1
0
bool 
CServerApp::startServer()
{
	// skip if already started or starting
	if (s_serverState == kStarting || s_serverState == kStarted) {
		return true;
	}

	// initialize if necessary
	if (s_serverState != kInitialized) {
		if (!initServer()) {
			// hard initialization failure
			return false;
		}
		if (s_serverState == kInitializing) {
			// not ready to start
			s_serverState = kInitializingToStart;
			return true;
		}
		assert(s_serverState == kInitialized);
	}

	double retryTime;
	CClientListener* listener = NULL;
	try {
		listener   = openClientListener(args().m_config->getSynergyAddress());
		s_server   = openServer(*args().m_config, s_primaryClient);
		s_listener = listener;
		updateStatus();
		LOG((CLOG_NOTE "started server"));
		s_serverState = kStarted;
		return true;
	}
	catch (XSocketAddressInUse& e) {
		LOG((CLOG_WARN "cannot listen for clients: %s", e.what()));
		closeClientListener(listener);
		updateStatus(CString("cannot listen for clients: ") + e.what());
		retryTime = 10.0;
	}
	catch (XBase& e) {
		LOG((CLOG_CRIT "failed to start server: %s", e.what()));
		closeClientListener(listener);
		return false;
	}

	if (args().m_restartable) {
		// install a timer and handler to retry later
		assert(s_timer == NULL);
		LOG((CLOG_DEBUG "retry in %.0f seconds", retryTime));
		s_timer = EVENTQUEUE->newOneShotTimer(retryTime, NULL);
		EVENTQUEUE->adoptHandler(CEvent::kTimer, s_timer,
			new TMethodEventJob<CServerApp>(this, &CServerApp::retryHandler));
		s_serverState = kStarting;
		return true;
	}
	else {
		// don't try again
		return false;
	}
}
Beispiel #2
0
 int UDPSocket::open(const char * host, int port, bool client)
 {
   if(client)
     return openClient(host, port);
   else
     return openServer(host, port);    
 }
Beispiel #3
0
int main(int argc, char *argv[])
{
	//_CrtSetBreakAlloc(3023);
	QCoreApplication a(argc, argv);
	//获取系统编码,否则移植会出现乱码
	QTextCodec *codec = QTextCodec::codecForName("System"); 
	//设置和对本地文件系统读写时候的默认编码格式
	QTextCodec::setCodecForLocale(codec); 
	//用在字符常量或者QByteArray构造QString对象时使用的一种编码方式
	QTextCodec::setCodecForCStrings(codec); 
	//设置传给tr函数时的默认字符串编码
	QTextCodec::setCodecForTr(codec);
	//SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);//注册异常捕获函数
	//datastore *_datastore = new datastore(NULL);
	datastore _datastore;
	tcpServer = new TcpServer(NULL);
	openServer();
	if(_datastore.dataBaseConnect())
	{
		qDebug()<<"数据库链接成功";
		//_datastore.dataBaseClose();
	}
	else
	{
		qDebug()<<"数据库链接失败";
	}
	return a.exec();
}
Beispiel #4
0
void Bluetooth::init(const char *iname){
	int result;
	this->name = iname;

	if (!EEPROM::instance().read(EEPROM::VAR_LAST_LINK_KEY, 0, &lastLinkKeyIndex, sizeof(lastLinkKeyIndex))){
		lastLinkKeyIndex=0;
	}

	for (int a=0; a<MAX_SUPPORTED_LINK_KEYS; a++){
		//Can't read in one pass because not all link keys are stored. If a non-existing key is tried to read,
		//read will fail and the key will be initialized to 0.
		if (!EEPROM::instance().read(EEPROM::VAR_LINKKEY, a*sizeof(LinkKeyInfo_t), &linkKeyInfo[a], sizeof(LinkKeyInfo_t))){
			memset(&linkKeyInfo[a], 0, sizeof(LinkKeyInfo_t));
		}
	}


	HCI_DRIVER_SET_COMM_INFORMATION(&HCI_DriverInformation, 1, VENDOR_BAUD_RATE, cpHCILL_RTS_CTS);
	HCI_DriverInformation.DriverInformation.COMMDriverInformation.InitializationDelay = 100;

	/* Set up the application callbacks.                                 */
	BTPS_Initialization.MessageOutputCallback = displayCallback;

	/* Initialize the application.                                       */
	if((result = initializeApplication()) > 0){
	//	if (!setClassOfDevice(0x80510)){
			openServer(SPP_PORT_NUMBER_MINIMUM);
	//	}
	}
}
void TelnetAppender::activateOptions()
{
    QMutexLocker locker(&mObjectGuard);

    closeServer();
    openServer();

    AppenderSkeleton::activateOptions();
}
Beispiel #6
0
 MongoShell *App::openShell(ConnectionSettings *connection, const ScriptInfo &scriptInfo)
 {
     MongoServer *server = openServer(connection, false);
     MongoShell *shell = new MongoShell(server,scriptInfo);
     _shells.push_back(shell);
     _bus->publish(new OpeningShellEvent(this, shell));
     shell->execute();
     return shell;
 }
Beispiel #7
0
bool mod_ts::getProcesses(vector<KIWI_WTS_PROCESS_INFO> * mesProcesses, wstring * server)
{
	bool reussite = false;

	PWTS_PROCESS_INFO tabProcess;
	DWORD nbProcess = 0;
	HANDLE hServer = NULL;

	if(openServer(&hServer, server))
	{
		if(reussite = WTSEnumerateProcesses(hServer, 0, 1, &tabProcess, &nbProcess) != 0)
		{
			for(DWORD i = 0; i < nbProcess; i++)
			{
				KIWI_WTS_PROCESS_INFO a = {
					tabProcess[i].SessionId,
					tabProcess[i].ProcessId,
					tabProcess[i].pProcessName
				};

				wstring user;
				wstring domain;
				if(mod_secacl::sidToName(tabProcess[i].pUserSid, &user, &domain, server))
				{
					a.userSid.assign(domain);
					a.userSid.push_back(L'\\');
					a.userSid.append(user);
				}
				else if(!mod_secacl::sidToStrSid(tabProcess[i].pUserSid, &a.userSid))
				{
					if(tabProcess[i].pUserSid)
					{
						a.userSid.assign(L"erreur SID ; ");
						a.userSid.append(mod_system::getWinError());
					}
					else
						a.userSid.assign(L"n.a.");
				}

				mesProcesses->push_back(a);
			}
			WTSFreeMemory(tabProcess);
		}
		closeServer(hServer);
	}
	
	return reussite;
}
int main(int argc, char *argv[])
{

  Aria::init();
  ArVideo::init();


  ArArgumentParser argParser(&argc, argv);

  ArServerBase server;
  ArServerSimpleOpener openServer(&argParser);

  argParser.loadDefaultArguments();
  if(!Aria::parseArgs() || !argParser.checkHelpAndWarnUnparsed()) {
    Aria::logOptions();
    Aria::exit(-1);
  }


  if(!openServer.open(&server))
  {
    std::cout << "error opening ArNetworking server" << std::endl;
    Aria::exit(5);
    return 5;
  }
  server.runAsync();
  std::cout << "ArNetworking server running on port " << server.getTcpPort() << std::endl;

  /* Set up ArNetworking services */

  ArVideoRemoteForwarder forwarder(&server, "localhost", 7070);
  if(!forwarder.connected())
  {
    std::cout << "ERror connecting to server localhost:7070" << std::endl;
    Aria::exit(1);
  }
  std::cout << "ArNetworking server running on port " << server.getTcpPort() << std::endl;
  
  while(true) ArUtil::sleep(10000);

  Aria::exit(0);
  return 0;
}
Beispiel #9
0
bool mod_ts::getSessions(vector<KIWI_WTS_SESSION_INFO> * mesSessions, wstring * server)
{
	bool reussite = false;

	PWTS_SESSION_INFO tabSessions;
	DWORD nbSessions = 0;
	HANDLE hServer = NULL;

	if(openServer(&hServer, server))
	{
		if(reussite = WTSEnumerateSessions(hServer, 0, 1, &tabSessions, &nbSessions) != 0)
		{
			for(DWORD i = 0; i < nbSessions; i++)
			{
				KIWI_WTS_SESSION_INFO a = {tabSessions[i].SessionId, tabSessions[i].State, tabSessions[i].pWinStationName};
				mesSessions->push_back(a);
			}
			WTSFreeMemory(tabSessions);
		}
		closeServer(hServer);
	}
	
	return reussite;
}
Beispiel #10
0
int coInitConnect()
{
    const char *envStr;
    char env[256], *portStr;
    float timeout;
    int32 handshake;
    int port;

    coSimLibData.soc = -1;

#if !(defined(WIN32) || defined(WIN64))
    /* we do our own handling of broken pipes */
    signal(SIGPIPE, SIG_IGN);
#endif

    /* get environment: if variable not set, exit with error-code */
    envStr = getenv("CO_SIMLIB_CONN");
    fprintf(stdout, "SIMLIB: %s\n", envStr);
    if ((!envStr) || (strlen(envStr) > 255))
        return -1;

    /* Client connection */
    strcpy(env, envStr);
    if (*env == 'C')
    {
        size_t retval;
        isServer = 0;
        /* get adress and port */
        portStr = strchr(env, '/');
        if (!portStr)
        {
            fprintf(stderr, "error parsing environment variable [%s]\n", env);
            return -1;
        }
        *portStr = '\0';
        portStr++;
        retval = sscanf(portStr, "%d_%f_%d", &minPort, &timeout, &coSimLibData.verbose);
        if (retval != 3)
        {
            fprintf(stderr, "coInitConnect: sscanf failed\n");
            return -1;
        }
        if (minPort < 1024 || minPort > 32767)
            return -1;

#ifndef WIN32
        if (!inet_aton(env + 2, &ip))
            return -1;
#else
        ip.s_addr = inet_addr(env + 2);
        if (ip.s_addr == -1)
            return -1;
#endif
        if (coSimLibData.verbose > 0)
            fprintf(stderr, " Starting Client to %s Port %d with %f sec timeout\n",
                    inet_ntoa(ip), minPort, timeout);

        /* we try to connect now */
        if ((port = openClient(ip.s_addr, minPort, timeout)) < 0)
            return -1;
    }

    /* Server connection */
    else if (*env == 'S')
    {
        size_t retval;
        isServer = 1;
        /* get adress and port */
        portStr = strchr(env, ':');
        if (!portStr)
        {
            fprintf(stderr, "error parsing environment variable [%s]\n", env);
            return -1;
        }
        *portStr = '\0';
        portStr++;
        retval = sscanf(portStr, "%d-%d_%f_%d", &minPort, &maxPort, &timeout, &coSimLibData.verbose);
        if (retval != 4)
        {
            fprintf(stderr, "coInitConnect: sscanf failed\n");
            return -1;
        }

        if (minPort < 1024 || minPort > 32767 || maxPort < 1024 || maxPort > 32767)
            return -1;

        /* we open and wait for the other side to connect */
        if ((port = openServer(minPort, maxPort)) < 0)
        {
            fprintf(stderr, "could not open server\n");
            return -1;
        }

        if (acceptServer(timeout) < 0)
        {
            fprintf(stderr, "could not accept server\n");
            return -1;
        }
    }
    /* Neither Client nor Server = ERROR */
    else
        return -1;

    /* Handshake: send 12345 to other side, so they might determine byte-swapping */
    handshake = 12345;
    sendData(&handshake, sizeof(int32));

#ifdef HAVE_GLOBUS
    {
        globus_result_t result = GLOBUS_SUCCESS;
        xsd_any *fault;
        int err, fault_type;
        fprintf(stderr, "activate globus modules\n");
        globus_module_activate(GLOBUS_COMMON_MODULE);
        globus_module_activate(GLOBUS_SOAP_MESSAGE_MODULE);
        registerSimulationType regSimulation;
        registerSimulationResponseType *regResponse;
        registerSimulationResponseType_init(&regResponse);
        globus_soap_message_attr_init(&message_attr);
        globus_soap_message_attr_set(message_attr, GLOBUS_SOAP_MESSAGE_AUTHZ_METHOD_KEY,
                                     NULL, NULL,
                                     (void *)GLOBUS_SOAP_MESSAGE_AUTHZ_HOST);
        globus_soap_message_attr_set(message_attr, GLOBUS_SOAP_MESSAGE_AUTH_PROTECTION_KEY,
                                     NULL, NULL,
                                     (void *)GLOBUS_SOAP_MESSAGE_AUTH_PROTECTION_PRIVACY);
        if ((result = SimulationService_client_init(&client_handle, message_attr, NULL)) == GLOBUS_SUCCESS)
        {
            char hostname[128];
            struct passwd *user = getpwuid(getuid());

            gethostname(hostname, 127);
            fprintf(stderr, "globus simulation client initialized\n");

            regSimulation.user = user->pw_name;
            regSimulation.host = hostname;
            regSimulation.port = port;
            regSimulation.name = "Fenfloss";
            fprintf(stderr, "globus regSimulation: [%s] [%s] [%d] [%s]\n", regSimulation.user, regSimulation.host, regSimulation.port, regSimulation.name);
            wsa_EndpointReferenceType_init(&epr);
            wsa_AttributedURI_init_contents(&epr->Address);
            xsd_anyURI_init_contents_cstr(&epr->Address.base_value,
                                          globus_common_create_string(getenv("GLOBUS_SIMULATIONSERVICE")));
            fprintf(stderr, " [%s]\n", getenv("GLOBUS_SIMULATIONSERVICE"));
            if ((err = SimulationPortType_registerSimulation_epr(client_handle,
                                                                 epr,
                                                                 &regSimulation,
                                                                 &regResponse,
                                                                 (SimulationPortType_registerSimulation_fault_t *)&fault_type,
                                                                 &fault)) == GLOBUS_SUCCESS)
            {
                SimulationType r = regResponse->result;

                simulationID = r.id;
            }
            else
            {
                fprintf(stderr, "globus error %d: [%s] \n", err, globus_object_printable_to_string(globus_error_get(err)));
            }
        }
        else
        {
            fprintf(stderr, "globus error %d: [%s] \n", result, globus_object_printable_to_string(globus_error_get(result)));
        }
        registerSimulationResponseType_destroy(regResponse);
    }
#endif
    return 0;
}
Beispiel #11
0
static
bool
startServer()
{
	double retryTime;
	CScreen* serverScreen         = NULL;
	CPrimaryClient* primaryClient = NULL;
	CClientListener* listener     = NULL;
	try {
		CString name    = ARG->m_config->getCanonicalName(ARG->m_name);
		serverScreen    = openServerScreen();
		primaryClient   = openPrimaryClient(name, serverScreen);
		listener        = openClientListener(ARG->m_config->getSynergyAddress());
		s_server        = openServer(*ARG->m_config, primaryClient);
		s_serverScreen  = serverScreen;
		s_primaryClient = primaryClient;
		s_listener      = listener;
		updateStatus();
		LOG((CLOG_NOTE "started server"));
		return true;
	}
	catch (XScreenUnavailable& e) {
		LOG((CLOG_WARN "cannot open primary screen: %s", e.what()));
		closeClientListener(listener);
		closePrimaryClient(primaryClient);
		closeServerScreen(serverScreen);
		updateStatus(CString("cannot open primary screen: ") + e.what());
		retryTime = e.getRetryTime();
	}
	catch (XSocketAddressInUse& e) {
		LOG((CLOG_WARN "cannot listen for clients: %s", e.what()));
		closeClientListener(listener);
		closePrimaryClient(primaryClient);
		closeServerScreen(serverScreen);
		updateStatus(CString("cannot listen for clients: ") + e.what());
		retryTime = 10.0;
	}
	catch (XScreenOpenFailure& e) {
		LOG((CLOG_CRIT "cannot open primary screen: %s", e.what()));
		closeClientListener(listener);
		closePrimaryClient(primaryClient);
		closeServerScreen(serverScreen);
		return false;
	}
	catch (XBase& e) {
		LOG((CLOG_CRIT "failed to start server: %s", e.what()));
		closeClientListener(listener);
		closePrimaryClient(primaryClient);
		closeServerScreen(serverScreen);
		return false;
	}

	if (ARG->m_restartable) {
		// install a timer and handler to retry later
		LOG((CLOG_DEBUG "retry in %.0f seconds", retryTime));
		CEventQueueTimer* timer = EVENTQUEUE->newOneShotTimer(retryTime, NULL);
		EVENTQUEUE->adoptHandler(CEvent::kTimer, timer,
							new CFunctionEventJob(&retryStartHandler, timer));
		return true;
	}
	else {
		// don't try again
		return false;
	}
}
Beispiel #12
0
int main(int argc, char *argv[])
{
    const char *colon;
    int port;
    struct stat st;
    char buffer[BUFSIZ];
    int len;

    // Validate the command-line parameters.
    if ( argc > 1 ) {
        // Use the supplied device name.
        device = argv[1];
    } else {
        // Look for QTOPIA_PHONE_DEVICE and use that if set.
        device = getenv( "QTOPIA_PHONE_DEVICE" );
    }
    if ( argc > 2 ) {
        // Use the supplied port number.
        port = atoi( argv[2] );
    } else {
        // Use the default phonesim port.
        port = 12345;
    }
    if ( !device || port <= 0 ) {
        fprintf( stderr, "Usage: %s device[:baudrate] [port]\n", argv[0] );
        return 1;
    }

    // Split the device specification into name and baud rate.
    colon = strchr( device, ':' );
    if ( colon ) {
        baudRate = atoi( colon + 1 );
        char *dev = strdup( device );
        dev[colon - device] = '\0';
        device = dev;
    } else {
        baudRate = 115200;
    }

    // Check to see if the device seems to exist.  We only open
    // it when the connection arrives from the host.
    if ( stat( device, &st ) < 0 ) {
        perror( "stat" );
        return 1;
    }

    // Bind to the server port to wait for incoming connections.
    listenFd = openServer( port );
    if ( listenFd < 0 ) {
        return 1;
    }

    // Enter the select loop and process events as they arrive.
    for (;;) {
        fd_set readSet;
        int maxFd = listenFd;
        FD_ZERO(&readSet);
        FD_SET(listenFd, &readSet);
        if ( connectionFd != -1 ) {
            FD_SET(connectionFd, &readSet);
            if ( connectionFd > maxFd )
                maxFd = connectionFd;
        }
        if ( deviceFd != -1 ) {
            FD_SET(deviceFd, &readSet);
            if ( deviceFd > maxFd )
                maxFd = deviceFd;
        }
        int result = ::select( maxFd + 1, &readSet, (fd_set *)0,
                               (fd_set *)0, (struct timeval *)0 );
        if ( result < 0 ) {
            // Signal interrupts are ok, but everything else should report.
            if ( errno != EINTR )
                perror( "select" );
        } else {
            if ( FD_ISSET(listenFd, &readSet) ) {
                // Accept a new incoming connection.
                if ( connectionFd != -1 ) {
                    // There is an existing connection - kill it because
                    // the host on the other end has probably crashed.
                    ::close( connectionFd );
                }
                connectionFd = ::accept( listenFd, (struct sockaddr *)0, 0 );
                if ( connectionFd < 0 )
                    perror( "accept" );
                deviceFd = openDevice();
                if ( deviceFd < 0 ) {
                    // Abort the connection if device cannot be opened.
                    ::close( connectionFd );
                    connectionFd = -1;
                }
            }
            if ( connectionFd != -1 && FD_ISSET(connectionFd, &readSet) ) {
                // Read data from the connection and write to the device.
                len = ::read( connectionFd, buffer, sizeof(buffer) );
                if ( len == 0 ) {
                    // The connection has closed.
                    ::close( connectionFd );
                    ::close( deviceFd );
                    connectionFd = -1;
                    deviceFd = -1;
                } else if ( len > 0 ) {
                    writeAll( deviceFd, buffer, len );
                }
            }
            if ( deviceFd != -1 && FD_ISSET(deviceFd, &readSet) ) {
                // Read data from the device and write to the connection.
                len = ::read( deviceFd, buffer, sizeof(buffer) );
                if ( len == 0 ) {
                    // The device has closed.
                    ::close( connectionFd );
                    ::close( deviceFd );
                    connectionFd = -1;
                    deviceFd = -1;
                } else if ( len > 0 ) {
                    writeAll( connectionFd, buffer, len );
                }
            }
        }
    }

    return 0;
}
Beispiel #13
0
int coInitConnect()
{
   const char *envStr;
   char env[256],*portStr;
   int minPort,maxPort;
   struct in_addr ip;
   float timeout;
   
   coSimLibData.soc = -1;
   
   /* we do our own handling of broken pipes */
   signal(SIGPIPE,SIG_IGN);
  
   /* get environment: if variable not set, exit with error-code */
   envStr=getenv("CO_SIMLIB_CONN");
   if ((!envStr)||(strlen(envStr)>255)) 
      return -1;
   
   /* Client connection */
   strcpy(env,envStr);
   if (*env=='C')
   {
      /* get adress and port */
      portStr  = strchr(env,'/');
      *portStr = '\0';
      portStr++;
      sscanf(portStr,"%d,%f,%d",&minPort,&timeout,&coSimLibData.verbose);
      if ( minPort<1024 || minPort>32767 )  return -1;
      if (!inet_aton(env+2,&ip)) return -1;
      
      if (coSimLibData.verbose>0)
         fprintf(stderr," Starting Client to %s Port %d with %f sec timeout\n",
                         inet_ntoa(ip),minPort,timeout);
      
      /* we try to connect now */
      if (openClient(ip.s_addr,minPort,timeout))
         return -1;
   }
   
   /* Server connection */
   else if (*env=='S')
   {
      /* get adress and port */
      portStr  = strchr(env,'/');
      *portStr = '\0';
      portStr++;
      sscanf(portStr,"%d-%d,%f,%d",&minPort,&maxPort,&timeout,&coSimLibData.verbose);
      if (    minPort<1024 || minPort>32767
           || maxPort<1024 || maxPort>32767 )  return -1;
      if (!inet_aton(env+2,&ip)) return -1;

      if (coSimLibData.verbose>0)
         fprintf(stderr," Starting Server to %s Port %d-%d with %f sec timeout\n",
                         inet_ntoa(ip),minPort,maxPort,timeout);
      
      /* we open and wait for the other side to connect */
      if ( openServer(minPort,maxPort) || acceptServer(timeout) )
         return -1;
      
   }
   
   /* Neither Client nor Server = ERROR */
   else
      return -1;
   
   return 0;
}
Beispiel #14
0
void GsServer::run(){
    openServer();
}