예제 #1
0
int SessionParams::openSocket()
{
    qDebug() << "Trying to connect an IGT server:" << getHostname() << ":" << getPort();
    int r = socket->ConnectToServer(getHostname().toStdString().c_str(), getPort());

    if (r != 0)
      qWarning() << "Cannot connect to the server.";

    return r;
}
예제 #2
0
/*
 * This method is the standard setter accessor method for
 * the host name that will be used in all subsequent
 * connections. Because it makes no sense to change the
 * host name while connected to a host, this method will
 * throw a CKException if a connection is already
 * established to a server.
 */
void CKIRCProtocol::setHostname( const CKString & aHost )
{
	// first, see if we're currently connected to some host
	if (isConnected() && (getHostname() != aHost)) {
		std::ostringstream	msg;
		msg << "CKIRCProtocol::setHostname(const CKString &) - there's an "
			"established connection to the server on " << getHostname() << ":" <<
			getPort() << " and that connection needs to be closed before we can "
			"change the host to connect to. Please call disconnect().";
		throw CKException(__FILE__, __LINE__, msg.str());
	}

	// OK... we're clear to save the value
	mHostname = aHost;
}
bool CIRCDDBGatewayConfigIrcDDBSet::Validate()
{
	int n = m_enabled->GetCurrentSelection();
	if (n == wxNOT_FOUND)
		return false;

	bool enabled = getEnabled();
	if (!enabled)
		return true;

	bool res = getHostname().IsEmpty();
	if (res) {
		wxMessageDialog dialog(this, _("The Hostname may not be empty"), m_title + _(" Error"), wxICON_ERROR);
		dialog.ShowModal();
		return false;
	}

	res = getUsername().IsEmpty();
	if (res) {
		wxMessageDialog dialog(this, _("The Username may not be empty"), m_title + _(" Error"), wxICON_ERROR);
		dialog.ShowModal();
		return false;
	}

	return true;
}
예제 #4
0
qChat::qChat(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::qChat)
{
    ui->setupUi(this);

    /* server parameters */
    _host = "achat.lorenzobianconi.net";
    _port = 9999;
    _nick = getHostname() + QString("@") + QHostInfo::localHostName();
    _sock = new QTcpSocket(this);
    _connecTimer = new QTimer(this);

    _ws = CLIENT_NOT_AUTHENTICATED;

    _attempt = 1;

    tableFormat.setBorder(0);

    connect(ui->msgEdit, SIGNAL(returnPressed()), this, SLOT(sndMsg()));
    connect(_sock, SIGNAL(connected()), this, SLOT(clientAuth()));
    connect(_sock, SIGNAL(readyRead()), this, SLOT(getMsg()));
    connect(_sock, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(displayError(QAbstractSocket::SocketError)));
    connect(_connecTimer, SIGNAL(timeout()), this, SLOT(try_connect()));

    _sock->connectToHost(_host, _port);
    _connecTimer->setSingleShot(true);
}
예제 #5
0
int YARPOutputSocketDgram::Prepare (const YARPUniqueNameID& name)
{
	OSDataDgram& d = OSDATA(system_resources);

	/// local_port might not be needed by the socket layer.
	char buf[YARP_STRING_LEN];
	getHostname (buf, YARP_STRING_LEN);
	d._local_addr.set ((u_short)0, buf);
	d._remote_addr = ((YARPUniqueNameSock&)name).getAddressRef();

	int r = d._connector_socket.open (d._local_addr, ACE_PROTOCOL_FAMILY_INET, 0, 1);
	if (r < 0)
	{
		identifier = ACE_INVALID_HANDLE;
		return YARP_FAIL;
	}

	r = YARPNetworkObject::setSocketBufSize (d._connector_socket, MAX_PACKET);
	if (r < 0)
	{
		d._connector_socket.close();
		ACE_DEBUG ((LM_DEBUG, "cannot set buffer size to %d\n", MAX_PACKET));
		return YARP_FAIL;
	}

	identifier = d._connector_socket.get_handle();

	return YARP_OK;
}
/** Initializes all global variables and prepares global log file output.
 * @see TestLogger_t#runnerStarted()}
 */
static void runnerStarted() {
    globalFile = fopen(GLOBAL_FILE_NAME, "w");
    fprintf(globalFile, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
    fprintf(globalFile, "<testsuites>\n");
    fflush(globalFile);
    globalInfo.hostname = getHostname();
    globalInfo.suiteId = 0;
}
예제 #7
0
	json SessionApi::getSystemInfo(const string& aIp) noexcept {
		return {
			{ "path_separator", PATH_SEPARATOR_STR },
			{ "network_type", getNetworkType(aIp) },
			{ "platform", getPlatform() },
			{ "hostname", getHostname() },
		};
	}
예제 #8
0
파일: proxy.c 프로젝트: sam9595/15213_Proxy
/* Send Request from browser to the server*/
int SendRequest(int clientfd, rio_t serverrio_t, char* hostname, char* uriname){
    int i,byte;
    int flag[5] = {0};
    char headerBuff[MAXHEADERSIZE]; 
    char requestLine[MAXHEADERSIZE];

    sprintf(requestLine,"GET %s HTTP/1.0\r\n",uriname);
    rio_writen(clientfd,requestLine,strlen(requestLine));


    byte = rio_readlineb(&serverrio_t,headerBuff,sizeof(headerBuff));
    if( strstr(headerBuff,"Host:") != NULL){
        getHostname(headerBuff,hostname);
    }
    sprintf(requestLine,"Host: %s\r\n",hostname);
    rio_writen(clientfd,requestLine,strlen(requestLine));

    while( (byte = rio_readlineb(&serverrio_t,headerBuff,sizeof(headerBuff))) >0){
        if(strncmp(headerBuff,"GET",3) == 0){
        }
        else if(strncmp(headerBuff,"Host",4) == 0){
        }
        else if(strncmp(headerBuff,"\r",1) == 0){
            break;
        }
        else if(strncmp(headerBuff,"User-Agent:",11) == 0){
            rio_writen(clientfd,headerSet[0],strlen(headerSet[0]));
            flag[0] = 1;
        }
        else if(strncmp(headerBuff,"Accept:",7) == 0){
            rio_writen(clientfd,headerSet[1],strlen(headerSet[1]));
            flag[1] = 1;
        }
        else if(strncmp(headerBuff,"Accept-Encoding:",16) == 0){
            rio_writen(clientfd,headerSet[2],strlen(headerSet[2]));
            flag[2] = 1;
        }
        else if(strncmp(headerBuff,"Connection:",11) == 0){
            rio_writen(clientfd,headerSet[3],strlen(headerSet[3]));
            flag[3] = 1;
        }
        else if(strncmp(headerBuff,"Proxy-Connection:",17) == 0){
            rio_writen(clientfd,headerSet[4],strlen(headerSet[4]));
            flag[4] = 1;
        }
        else{
            rio_writen(clientfd,headerBuff,strlen(headerBuff));
        }
    }
    for(i = 0 ; i < 5 ;i++){
        if(flag[i] == 0){
            rio_writen(clientfd,headerSet[i],strlen(headerSet[i]));
            flag[i] = 1;
        }
    }
    rio_writen(clientfd,"\r\n",strlen("\r\n"));
    return 1;
}
예제 #9
0
void HTAppQt::InitHypothesisManager() {
	//create hypothesis manager (creates server on this host on another port)
	HypothesisManager::create(getHostname(), 4449, mTargets, mObservations, mQtGUI);
	if (!mLaunchClients) {
		for (unsigned int i=0; i < mNumClients; i++) {
			new HypothesisClient(i+100);
		}
	}
}
예제 #10
0
vector<Component *> LoadConfiguration(AutoConfigurator ** outConfigurator, ComponentRegistrar * registrar){
		string hostname = getHostname();

		const char * provider = getenv( "SIOX_CONFIGURATION_PROVIDER_MODULE" );
		const char * path = getenv( "SIOX_CONFIGURATION_PROVIDER_PATH" );
		const char * configuration = getenv( "SIOX_CONFIGURATION_PROVIDER_ENTRY_POINT" );

		provider = ( provider != nullptr ) ? provider : "siox-core-autoconfigurator-FileConfigurationProvider" ;
		path = ( path != nullptr ) ? path : "";
		configuration = ( configuration != nullptr ) ? configuration :  "siox.conf:/usr/local/etc/siox.conf:/etc/siox.conf:monitoring/low-level-c/test/siox.conf:monitoring/low-level-c/test/siox.conf" ;

		AutoConfigurator * configurator = new AutoConfigurator( registrar, provider, path, configuration );
		*outConfigurator = configurator;

		const char * configurationMode = getenv( "SIOX_CONFIGURATION_PROVIDER_MODE" );
		const char * configurationOverride = getenv( "SIOX_CONFIGURATION_SECTION_TO_USE" );

		string configName;
		if( configurationOverride != nullptr ) {
			configName = configurationOverride;
		} else {
			// hostname configurationMode (is optional)

			{
				stringstream configName_s;
				configName_s << hostname;
				if( configurationMode != nullptr ) {
					configName_s << " " << configurationMode;
				}
				configName = configName_s.str();
			}
		}

		cout << provider << " path " << path << " " << configuration << " ConfigName: \"" << configName << "\"" << endl;

		vector<Component *> loadedComponents;
		try {
			loadedComponents = configurator->LoadConfiguration( "Process", configName );
		} catch( InvalidConfiguration & e ) {
			// fallback to global configuration
			loadedComponents = configurator->LoadConfiguration( "Process", "" );
		}


		// if(loadedComponents == nullptr){ // MZ: Error, "==" not defined
		if( loadedComponents.empty() ) {
			cerr << "FATAL Invalid configuration set: " << endl;
			cerr << "SIOX_CONFIGURATION_PROVIDER_MODULE=" << provider << endl;
			cerr << "SIOX_CONFIGURATION_PROVIDER_PATH=" << path << endl;
			cerr << "SIOX_CONFIGURATION_PROVIDER_ENTRY_POINT=" << configuration << endl;
			cerr << "SIOX_CONFIGURATION_PROVIDER_MODE=" << configurationMode << endl;
			// TODO use FATAL function somehow?
			exit( 1 );
		}
		return loadedComponents;
	}
예제 #11
0
파일: client.cpp 프로젝트: studnitz/octopus
QJsonObject Client::getJsonInfo() {
  QJsonObject json;
  json["IP"] = socket.localAddress().toString();
  json["Name"] = getHostname();
  json["CPU"] = getCpuUsage();
  json["Memory"] = getMemoryUsage();
  json["Disk"] = getDiskUsage();
  json["Time"] = currentTime();
  QJsonArray devices = QJsonArray::fromStringList(listAllDevices());
  json["Devices"] = devices;
  return json;
}
예제 #12
0
void setConfigClientName(char *value) {
	if (client_name != NULL) free(client_name); /* free memory */

	if (value == NULL) {
		char *hostname = getHostname();
		client_name = malloc (strlen(hostname)+1);
		strcpy(client_name, hostname);
	} else {
		client_name = malloc (strlen(value)+1);
		strcpy(client_name, value);
	}

	printf ( "CLIENT-NAME: %s\n", client_name );
}
예제 #13
0
파일: socket.cpp 프로젝트: jhmpub/mcs
char * initWinsock() {
    WORD wVersionRequested = MAKEWORD(1,1);
    WSADATA wsaData;
    int nRet;
    static char hostname[256];
    
    // Initialize WinSock and check version
    nRet = WSAStartup(wVersionRequested, &wsaData);
    if (wsaData.wVersion != wVersionRequested) {    
        printf("\ninitWinsock: wrong winsock version\n");
        exit(1);
    }
    
    return getHostname();   
}
예제 #14
0
/*
 * This method is used to copy the parameters for the given connection
 * to the connection that this instance is maintaining for all
 * communications with the IRC Server. It's important to note that
 * this is a copy operation and not an assignment as you might think.
 */
void CKIRCProtocol::setCommPort( const CKTelnetConnection & aConn )
{
	// first, see if we're currently connected to some host
	if (isConnected()) {
		std::ostringstream	msg;
		msg << "CKIRCProtocol::setCommPort(const CKTelnetConnection &) - there's "
			"an established connection to the server on " << getHostname() << ":" <<
			getPort() << " through the existing connection port and that connection "
			"needs to be closed before we can change the port parameters. Please "
			"call disconnect().";
		throw CKException(__FILE__, __LINE__, msg.str());
	}

	// OK... we're clear to copy over the parameters
	mCommPort = aConn;
}
예제 #15
0
size_t getMachineShard(const std::string& hostname = "", bool force = false) {
    static size_t shard = 0;
    if (shard > 0 && !force) {
        return shard;
    }

    // An optional input hostname may override hostname detection for testing.
    auto hn = (hostname.empty()) ? getHostname() : hostname;
    auto hn_hash = hashFromBuffer(HASH_TYPE_MD5, hn.c_str(), hn.size());
    if (hn_hash.size() >= 2) {
        long hn_char;
        if (safeStrtol(hn_hash.substr(0, 2), 16, hn_char)) {
            shard = (hn_char * 100) / 255;
        }
    }
    return shard;
}
bool CStarNetServerIrcDDBSet::Validate()
{
	bool res = getHostname().IsEmpty();
	if (res) {
		wxMessageDialog dialog(this, _("The Hostname may not be empty"), m_title + _(" Error"), wxICON_ERROR);
		dialog.ShowModal();
		return false;
	}

	res = getUsername().IsEmpty();
	if (res) {
		wxMessageDialog dialog(this, _("The Username may not be empty"), m_title + _(" Error"), wxICON_ERROR);
		dialog.ShowModal();
		return false;
	}

	return true;
}
예제 #17
0
void Connect::onLoad(SceneParams& sceneParams)
{
    background->setTexture(background_file);
    background->setPosition(0, 0, 1920, 1080);

    title->setText(font, "Local Multiplayer", 250);
    title->setPosition(1920 / 2, 200, Center);

    player1->setLabel(font, "Player 1", 100);
    player1->setPosition(660, 600, 200, 200);
    player1->onClick(this);

    hostname->setText(font, std::string("Your Hostname : ").append(getHostname()), 60);
    hostname->setPosition(50, 1000, Right);

    player2->setLabel(font, "Player 2", 100);
    player2->setPosition(1060, 600, 200, 200);
    player2->onClick(this);
}
예제 #18
0
int main(int argc, char **argv){
  myDistro->Init(argc,argv);
  char *hostname = NULL;
  if (argc > 1) {
  	hostname = argv[1];
  }
  hostname = getHostname(hostname);
  char* res = getQpidPort(hostname);
  if (!res) {
  	printf("%s\n%s\nDONE \n", hostname, "-1");
  } else {
  	printf("%s\n%s\nDONE \n", hostname, res);  	
  	free(res);
  }
  if (argc <= 1)
  	free(hostname);
  
  return 0;
}
예제 #19
0
/*
 * This method checks to see if the two CKIRCProtocols are equal to
 * one another based on the values they represent and *not* on the
 * actual pointers themselves. If they are equal, then this method
 * returns true, otherwise it returns false.
 */
bool CKIRCProtocol::operator==( const CKIRCProtocol & anOther ) const
{
	bool		equal = true;

	if ((getHostname() != anOther.getHostname()) ||
		(getPort() != anOther.getPort()) ||
		(mCommPort != anOther.mCommPort) ||
		(isLoggedIn() != anOther.isLoggedIn()) ||
		(getPassword() != anOther.getPassword()) ||
		(getNickname() != anOther.getNickname()) ||
		(getUserHost() != anOther.getUserHost()) ||
		(getUserServer() != anOther.getUserServer()) ||
		(getRealName() != anOther.getRealName()) ||
		(mChannelList != anOther.mChannelList) ||
		(mResponders != anOther.mResponders)) {
		equal = false;
	}

	return equal;
}
예제 #20
0
/*
 * Because there are times when it's useful to have a nice
 * human-readable form of the contents of this instance. Most of the
 * time this means that it's used for debugging, but it could be used
 * for just about anything. In these cases, it's nice not to have to
 * worry about the ownership of the representation, so this returns
 * a CKString.
 */
CKString CKIRCProtocol::toString() const
{
	CKString	retval = "< IRC Host=";
	retval += getHostname();
	retval += ", ";
	retval += " IRC Port=";
	retval += getPort();
	retval += ", ";
	retval += " CommPort=";
	retval += mCommPort.toString();
	retval += ", ";
	retval += " isLoggedIn? ";
	retval += (isLoggedIn() ? "Yes" : "No");
	retval += ", ";
	retval += " Password="******" Nickname=";
	retval += getNickname();
	retval += " UserHost=";
	retval += getUserHost();
	retval += " UserServer=";
	retval += getUserServer();
	retval += " RealName=";
	retval += getRealName();
	retval += " ChannelList: [";
	CKStringNode		*i = NULL;
	for (i = mChannelList.getHead(); i != NULL; i = i->getNext()) {
		if (i->getPrev() != NULL) {
			retval += ", ";
		}
		retval += (*i);
	}
	retval += "]>\n";

	return retval;
}
예제 #21
0
파일: sockets.c 프로젝트: fmccabe/l-and-o
retCode connectRemote(char *where, int port,
                      ioEncoding encoding, logical waitForMe,
                      ioPo *inC, ioPo *outC) {
  int sock;
  struct sockaddr_in serv_addr;
  char *host = getHostname(where);
  struct in_addr *addr = host != NULL ? getHostIP(host, 0) : NULL;

  if (addr != NULL) {
    /* Attempt to establish links to the server */
    memset((char *) &serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr = *addr;
    serv_addr.sin_port = htons((u_short) port);

    /* Create the socket ... */
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
      return Error;
    } else {
      ioPo conn = O_IO(newObject(sockClass, host, sock, encoding, ioREAD | ioWRITE));

      configureIo(O_FILE(conn), (waitForMe ? turnOnBlocking : turnOffBlocking));

      while (connect(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) != 0) {
        switch (errno) {    //  Unix version
          case EACCES:
          case EADDRNOTAVAIL:
            outMsg(logFile, "Address %U not available", host);
            markHostUnavail(host);
            closeFile(O_IO(conn));
            return Error;
          case ECONNREFUSED:
            outMsg(logFile, "Connection to %U refused", host);
            markHostUnavail(host);
            closeFile(O_IO(conn));
            return Error;
          case ETIMEDOUT:
            outMsg(logFile, "Connection to %U timed out", host);
            markHostUnavail(host);
            closeFile(O_IO(conn));
            return Error;
          case ENETUNREACH:
            outMsg(logFile, "Network down or %U unreachable", host);
            markHostUnavail(host);
            closeFile(O_IO(conn));
            return Error;
          case EALREADY:
          case EINTR:
          case EWOULDBLOCK:
          case EINPROGRESS:
            closeFile(O_IO(conn));
            return Fail;
          default:
            outMsg(logFile, "Connection to %U refused", host);
            markHostUnavail(host);
            closeFile(O_IO(conn));
            return Error;
        }
      }

      *inC = conn;
      *outC = conn;
      return Ok;
    }
  } else {
    outMsg(logFile, "cant resolve host %U", where);
    return Error;
  }
}
예제 #22
0
파일: nick.cpp 프로젝트: jasuarez/minbif
string Nick::getLongName() const
{
	return getNickname()  + "!" +
	       getIdentname() + "@" +
	       getHostname();
}
예제 #23
0
int main(int argc, char** argv)
{
   // Commandline parameter is the test path to use
   std::string test_path = (argc > 1) ? std::string(argv[1]) : "noninteractive";

   // -------- CONFIGURE METRIC REGISTRY ------- //
   CppUnit::MetricRegistry* metric_reg = CppUnit::MetricRegistry::instance();
   std::string metric_prefix;    // Prefix for all metric labels (mode/hostname)

   std::string host_name = getHostname();
   metric_prefix = host_name + "/";
#ifdef _DEBUG
   metric_prefix += "Debug/";
#endif
#ifdef _OPT
   metric_prefix += "Opt/";
#endif

   std::cout << " host: " << host_name << " prefix: "  << metric_prefix << std::endl;

   metric_reg->setPrefix(metric_prefix);
   metric_reg->setFilename("gmtl_metrics.txt");
   metric_reg->setMetric("Main/MetricTest", 1221.75f);

   // Print out what version of GMTL we're testing.
   std::cout<<std::endl;
   std::cout<<"GMTL Version: "<<gmtl::getVersion()<<std::endl;
   std::cout<<std::endl;

   //------------------------------------
   //  Test suites
   //------------------------------------
   CppUnit::TestFactoryRegistry& global_registry = CppUnit::TestFactoryRegistry::getRegistry();

   // noninteractive
   CppUnit::TestSuite* noninteractive_suite = new CppUnit::TestSuite("noninteractive");
   noninteractive_suite->addTest(global_registry.makeTest());

   // metric
   CppUnit::TestSuite* metric_suite = new CppUnit::TestSuite(gmtlTest::Suites::metric());
   metric_suite->addTest(CppUnit::TestFactoryRegistry::getRegistry(gmtlTest::Suites::metric()).makeTest());

   //------------------------------------
   // Test Runner
   //------------------------------------
   CppUnit::TextUi::TestRunner runner;

   // Make it use a compiler outputter
   CppUnit::Outputter* run_outputter =
      CppUnit::CompilerOutputter::defaultOutputter(&runner.result(), std::cout);
   runner.setOutputter(run_outputter);

   // Add a listener that prints the test names as the tests progress
   CppUnit::TestResult& result_event_manager = runner.eventManager();
   CppUnit::BriefTestProgressListener progress;
   result_event_manager.addListener(&progress);
   
   runner.addTest(noninteractive_suite);
   runner.addTest(metric_suite);


   //------------------------------------
   // Run Tests
   //------------------------------------
   bool success(false);

   try
   {
      std::cout << "Running " << test_path << std::endl;
      success = runner.run(test_path);
   }
   catch (std::invalid_argument& e)
   {
      // Test path was not resolved
      std::cerr   << std::endl
                  << "ERROR: " << e.what()
                  << std::endl;
      success = false;
   }

#ifdef WIN32
   std::cin.get();
#endif

   return (success ? 0 : 1);
}
예제 #24
0
void PreferencesDialog::loadPreferences() {
    
    MyAvatar* myAvatar = DependencyManager::get<AvatarManager>()->getMyAvatar();
    Menu* menuInstance = Menu::getInstance();

    _displayNameString = myAvatar->getDisplayName();
    ui.displayNameEdit->setText(_displayNameString);

    ui.collisionSoundURLEdit->setText(myAvatar->getCollisionSoundURL());

    ui.sendDataCheckBox->setChecked(!menuInstance->isOptionChecked(MenuOption::DisableActivityLogger));

    ui.snapshotLocationEdit->setText(Snapshot::snapshotsLocation.get());

    ui.scriptsLocationEdit->setText(qApp->getScriptsLocation());

    ui.pupilDilationSlider->setValue(myAvatar->getHead()->getPupilDilation() *
                                     ui.pupilDilationSlider->maximum());
    
    auto dde = DependencyManager::get<DdeFaceTracker>();
    ui.ddeEyeClosingThresholdSlider->setValue(dde->getEyeClosingThreshold() * 
                                              ui.ddeEyeClosingThresholdSlider->maximum());

    ui.faceTrackerEyeDeflectionSider->setValue(FaceTracker::getEyeDeflection() *
                                               ui.faceTrackerEyeDeflectionSider->maximum());
    
    auto faceshift = DependencyManager::get<Faceshift>();
    ui.faceshiftHostnameEdit->setText(faceshift->getHostname());

    auto audio = DependencyManager::get<AudioClient>();
    MixedProcessedAudioStream& stream = audio->getReceivedAudioStream();

    ui.dynamicJitterBuffersCheckBox->setChecked(stream.getDynamicJitterBuffers());
    ui.staticDesiredJitterBufferFramesSpin->setValue(stream.getDesiredJitterBufferFrames());
    ui.maxFramesOverDesiredSpin->setValue(stream.getMaxFramesOverDesired());
    ui.useStdevForJitterCalcCheckBox->setChecked(stream.getUseStDevForJitterCalc());
    ui.windowStarveThresholdSpin->setValue(stream.getWindowStarveThreshold());
    ui.windowSecondsForDesiredCalcOnTooManyStarvesSpin->setValue(
            stream.getWindowSecondsForDesiredCalcOnTooManyStarves());
    ui.windowSecondsForDesiredReductionSpin->setValue(stream.getWindowSecondsForDesiredReduction());
    ui.repetitionWithFadeCheckBox->setChecked(stream.getRepetitionWithFade());

    ui.outputBufferSizeSpinner->setValue(audio->getOutputBufferSize());

    ui.outputStarveDetectionCheckBox->setChecked(audio->getOutputStarveDetectionEnabled());
    ui.outputStarveDetectionThresholdSpinner->setValue(audio->getOutputStarveDetectionThreshold());
    ui.outputStarveDetectionPeriodSpinner->setValue(audio->getOutputStarveDetectionPeriod());

    ui.realWorldFieldOfViewSpin->setValue(DependencyManager::get<AvatarManager>()->getMyAvatar()->getRealWorldFieldOfView());

    ui.fieldOfViewSpin->setValue(qApp->getFieldOfView());
    
    ui.leanScaleSpin->setValue(myAvatar->getLeanScale());
    
    ui.avatarScaleSpin->setValue(myAvatar->getScale());
    
    ui.maxOctreePPSSpin->setValue(qApp->getMaxOctreePacketsPerSecond());

    ui.oculusUIAngularSizeSpin->setValue(qApp->getApplicationCompositor().getHmdUIAngularSize());

    SixenseManager& sixense = SixenseManager::getInstance();
    ui.sixenseReticleMoveSpeedSpin->setValue(sixense.getReticleMoveSpeed());
    ui.invertSixenseButtonsCheckBox->setChecked(sixense.getInvertButtons());

    // LOD items
    auto lodManager = DependencyManager::get<LODManager>();
    ui.desktopMinimumFPSSpin->setValue(lodManager->getDesktopLODDecreaseFPS());
    ui.hmdMinimumFPSSpin->setValue(lodManager->getHMDLODDecreaseFPS());
}
예제 #25
0
/*
	bootAgentNotice is used to notice the PM service that the boot Agent starts up. Also,
	the hostname and IP address is deliver to the PM service.
*/
static int bootAgentNotice(int dbg)
{
	int sock;
	char bsip[30];
	char myIP[30];
	char hostname[100];
	char sendbuf[1024];
	char recvbuf[1024];
	int socklen=0;
	fd_set rfds;
	int ret = 0;
	int retry = 0;
	struct timeval tv;
	struct sockaddr_in sendAddr;
	struct sockaddr_in recvaddr;
	if(dbg == 1)
		sprintf(bsip, "127.0.0.1\0");
	else
		bsDiscovery(bsip);
	getInterfaceIP("eth1", myIP, sizeof(myIP));
	if(getHostname(hostname, sizeof(hostname))==-1)
		return -1;
	printf("Hostname-->%s\n",hostname);
	sock=createUdpClient();
	if(sock==-1)
		return -1;
	memset(&sendAddr,0,sizeof(sendAddr));
	sendAddr.sin_family=AF_INET;
	sendAddr.sin_port=htons(POALPORT);
	sendAddr.sin_addr.s_addr=inet_addr(bsip);
	sprintf(sendbuf, "%s,%s\0", hostname, myIP);
	while(1)
	{
		if(sendto(sock, sendbuf, strlen(sendbuf), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr)) ==-1)
		{
			goto errexit;
		}
		socklen=1024;
		memset(recvbuf, 0, sizeof(recvbuf));
		memset(&tv, 0, sizeof(tv));	
		FD_ZERO(&rfds);
		FD_SET(sock, &rfds);
		tv.tv_sec = 1;
		tv.tv_usec = 0;
		ret = select(sock+1, &rfds, NULL, NULL, &tv);
		if(ret ==  -1)
		{
			printf("Select Error\n");
			goto errexit;
		}else if(ret)
		{
			if (recvfrom(sock, recvbuf, sizeof(recvbuf), 0, (struct sockaddr *)&recvaddr, &socklen) > 0)
			{
				printf("%s\n", recvbuf);
				if(!strncmp(recvbuf, "OK", 2))
					break;
			}
		}else
		{
			printf("No Ack retry\n");
			if(retry > 5)
				break;
			retry++;
		}
			
	}
	close(sock);
	return 1;
errexit:
	close(sock);
	return -1;

}
예제 #26
0
파일: server.cpp 프로젝트: joonhwan/Waffle
//-----------------------------------------------------------------------------
QString Server::getConnectionString() const
{
    return makeConnectionString(getHostname(), getPort());
}
예제 #27
0
std::map<std::string, std::string> SIPAccount::getAccountDetails() const
{
    std::map<std::string, std::string> a;

    a[ACCOUNT_ID] = _accountID;
    // The IP profile does not allow to set an alias
    a[CONFIG_ACCOUNT_ALIAS] = (_accountID == IP2IP_PROFILE) ? IP2IP_PROFILE : getAlias();

    a[CONFIG_ACCOUNT_ENABLE] = isEnabled() ? "true" : "false";
    a[CONFIG_ACCOUNT_TYPE] = getType();
    a[HOSTNAME] = getHostname();
    a[USERNAME] = getUsername();

    a[CONFIG_RINGTONE_PATH] = getRingtonePath();
    a[CONFIG_RINGTONE_ENABLED] = getRingtoneEnabled() ? "true" : "false";
    a[CONFIG_ACCOUNT_MAILBOX] = getMailBox();

    RegistrationState state = Unregistered;
    std::string registrationStateCode;
    std::string registrationStateDescription;

    if (_accountID == IP2IP_PROFILE) {
        registrationStateCode = ""; // emtpy field
        registrationStateDescription = "Direct IP call";
    } else {
        state = getRegistrationState();
        int code = getRegistrationStateDetailed().first;
        std::stringstream out;
        out << code;
        registrationStateCode = out.str();
        registrationStateDescription = getRegistrationStateDetailed().second;
    }

    a[REGISTRATION_STATUS] = (_accountID == IP2IP_PROFILE) ? "READY": Manager::instance().mapStateNumberToString (state);
    a[REGISTRATION_STATE_CODE] = registrationStateCode;
    a[REGISTRATION_STATE_DESCRIPTION] = registrationStateDescription;

    // Add sip specific details
    a[ROUTESET] = getServiceRoute();
    a[CONFIG_ACCOUNT_RESOLVE_ONCE] = isResolveOnce() ? "true" : "false";
    a[USERAGENT] = getUseragent();

    a[CONFIG_ACCOUNT_REGISTRATION_EXPIRE] = getRegistrationExpire();
    a[LOCAL_INTERFACE] = getLocalInterface();
    a[PUBLISHED_SAMEAS_LOCAL] = getPublishedSameasLocal() ? "true" : "false";
    a[PUBLISHED_ADDRESS] = getPublishedAddress();

    std::stringstream localport;
    localport << getLocalPort();
    a[LOCAL_PORT] = localport.str();
    std::stringstream publishedport;
    publishedport << getPublishedPort();
    a[PUBLISHED_PORT] = publishedport.str();
    a[STUN_ENABLE] = isStunEnabled() ? "true" : "false";
    a[STUN_SERVER] = getStunServer();
    a[ACCOUNT_DTMF_TYPE] = (getDtmfType() == OVERRTP) ? "overrtp" : "sipinfo";

    a[SRTP_KEY_EXCHANGE] = getSrtpKeyExchange();
    a[SRTP_ENABLE] = getSrtpEnable() ? "true" : "false";
    a[SRTP_RTP_FALLBACK] = getSrtpFallback() ? "true" : "false";

    a[ZRTP_DISPLAY_SAS] = getZrtpDisplaySas() ? "true" : "false";
    a[ZRTP_DISPLAY_SAS_ONCE] = getZrtpDiaplaySasOnce() ? "true" : "false";
    a[ZRTP_HELLO_HASH] = getZrtpHelloHash() ? "true" : "false";
    a[ZRTP_NOT_SUPP_WARNING] = getZrtpNotSuppWarning() ? "true" : "false";

    // TLS listener is unique and parameters are modified through IP2IP_PROFILE
    std::stringstream tlslistenerport;
    tlslistenerport << getTlsListenerPort();
    a[TLS_LISTENER_PORT] = tlslistenerport.str();
    a[TLS_ENABLE] = getTlsEnable();
    a[TLS_CA_LIST_FILE] = getTlsCaListFile();
    a[TLS_CERTIFICATE_FILE] = getTlsCertificateFile();
    a[TLS_PRIVATE_KEY_FILE] = getTlsPrivateKeyFile();
    a[TLS_PASSWORD] = getTlsPassword();
    a[TLS_METHOD] = getTlsMethod();
    a[TLS_CIPHERS] = getTlsCiphers();
    a[TLS_SERVER_NAME] = getTlsServerName();
    a[TLS_VERIFY_SERVER] = getTlsVerifyServer() ? "true" : "false";
    a[TLS_VERIFY_CLIENT] = getTlsVerifyClient() ? "true" : "false";
    a[TLS_REQUIRE_CLIENT_CERTIFICATE] = getTlsRequireClientCertificate() ? "true" : "false";
    a[TLS_NEGOTIATION_TIMEOUT_SEC] = getTlsNegotiationTimeoutSec();
    a[TLS_NEGOTIATION_TIMEOUT_MSEC] = getTlsNegotiationTimeoutMsec();

    return a;
}
예제 #28
0
bool SIPAccount::hostnameMatch (const std::string& hostname) const
{
    return hostname == getHostname();
}
예제 #29
0
void Port::Body()
{
	int tag = 0;
	char *buf = NULL;
	Fragments cmd;
	OutputTarget *target = NULL, *next = NULL;
	BlockReceiver receiver;
	NewFragmentHeader hdr;
	int ok;
	int assume_data;
	int call_on_read = 0;

	YARPUniqueNameID* pid = NULL;
	name_set = 1;

	/// LATER: must actually jump to the end of the thread for proper cleanup instead of returning.
	/// this is the registration section.
	switch (protocol_type)
	{
	case YARP_QNET:
		{
			pid = YARPNameService::RegisterName(name.c_str(), network_name.c_str(), YARP_QNET, YARPNativeEndpointManager::CreateQnetChannel()); 
			if (pid->getServiceType() == YARP_NO_SERVICE_AVAILABLE)
			{
				ACE_DEBUG ((LM_DEBUG, ">>> registration failed, bailing out port thread (qnet)\n"));
				name_set = 0;
				if (asleep)
				{
					asleep = 0;
					okay_to_send.Post();
				}

				_started = false;
				return;
			}
		}
		break;

	case YARP_TCP:
		{
			pid = YARPNameService::RegisterName(name.c_str(), network_name.c_str(), YARP_TCP, YARP_UDP_REGPORTS); 
			if (pid->getServiceType() == YARP_NO_SERVICE_AVAILABLE)
			{
				ACE_DEBUG ((LM_DEBUG, ">>> registration failed, bailing out port thread (tcp)\n"));
				name_set = 0;
				if (asleep)
				{
					asleep = 0;
					okay_to_send.Post();
				}

				_started = false;
				return;
			}
		}
		break;

	case YARP_UDP:
		{
			pid = YARPNameService::RegisterName(name.c_str(), network_name.c_str(), YARP_UDP, YARP_UDP_REGPORTS); 
			if (pid->getServiceType() == YARP_NO_SERVICE_AVAILABLE)
			{
				ACE_DEBUG ((LM_DEBUG, ">>> registration failed, bailing out port thread (udp)\n"));
				name_set = 0;
				if (asleep)
				{
					asleep = 0;
					okay_to_send.Post();
				}

				_started = false;
				return;
			}
		}
		break;

	case YARP_MCAST:
		{
			pid = YARPNameService::RegisterName(name.c_str(), network_name.c_str(), YARP_MCAST, YARP_UDP_REGPORTS);
			if (pid->getServiceType() == YARP_NO_SERVICE_AVAILABLE)
			{
				ACE_DEBUG ((LM_DEBUG, ">>> registration failed, bailing out port thread (mcast)\n"));
				name_set = 0;
				if (asleep)
				{
					asleep = 0;
					okay_to_send.Post();
				}

				_started = false;
				return;
			}
		}
		break;

	default:
		{
			ACE_DEBUG ((LM_DEBUG, "troubles in acquiring ports (?)\n"));
			name_set = 0;
			if (asleep)
			{
				asleep = 0;
				okay_to_send.Post();
			}
			return;
		}
		break;
	}

	YARPEndpointManager::CreateInputEndpoint (*pid);
	
	/// ok, ready to create the sending thread (_strange_select).
	/// all this to avoid sending a message through the port socket.
	tsender.Begin ();

	/// registration completed. now goes the receiver/command thread.
	if (asleep)
	{
		asleep = 0;
		okay_to_send.Post();
	}

	while (!IsTerminated())
    {
		receiver.Begin(pid->getNameID());

		receiver.Get();
		out_mutex.Wait();
		assume_data = !expect_header;
		out_mutex.Post();

		/// WARNING: cmd buffer is not zeroed anywhere, in case buffer is string
		///		it might be better to do it somewhere around here.

		if (!assume_data)
		{
			ok = receiver.Get((char*)(&hdr),sizeof(hdr));
			if (ok || hdr.checker=='/')
			{
				if (hdr.checker == '~')
				{
					tag = hdr.tag;
					cmd.Require(hdr.length);
					if (tag != MSG_ID_DATA)
					{
						ok = receiver.Get(cmd.GetBuffer(),hdr.length);
						YARP_DBG(THIS_DBG) ((LM_DEBUG, "Got some form of command ( %d, %d )\n", ((int)tag), ok));
					}
				}
				else
				{
					if (hdr.checker != '/')
					{
						ACE_DEBUG ((LM_ERROR, "Error - command received in unknown protocol ( %s )\n", name.c_str()));
						ok = 0;
					}
					else
					{
						YARP_DBG(THIS_DBG) ((LM_DEBUG, "%s received unsupported old format request: %s\n", name.c_str()));
					}
				}
			}

			if (!ok)
			{
				tag = MSG_ID_ERROR;
			}

			if (tag == MSG_ID_NULL)
			{
				buf = cmd.GetBuffer();
				tag = buf[0];
			}
			else
			{
				buf = cmd.GetBuffer();
			}
		}
		else
		{
			YARP_DBG(THIS_DBG) ((LM_DEBUG, "Auto assume data\n"));
			tag = MSG_ID_DATA;
		}

		if (tag != MSG_ID_DATA)
		{
			receiver.End();
		}

		list_mutex.Wait ();
		int scanned = 0;
		if (!scanned)
		{
			double now = YARPTime::GetTimeAsSeconds();
			target = targets.GetRoot();
			while (target != NULL)
			{
				next = target->GetMeshNext();
				target->WaitMutex();
				int active = target->active;
				int deactivated = target->deactivated;
				int ticking = target->ticking;
				double started = target->check_tick;
				target->PostMutex();
				int timeout = 0;
				
				if (ticking && now-started > 5)
				{
					active = 0;
					timeout = 1;
				}

				if (!active)
				{
					ACE_DEBUG ((LM_INFO, "*** disconnecting %s and %s %s%s\n",
						name.c_str(), target->GetLabel().c_str(),
						deactivated ? "" : "(target stopped responding)",
						timeout?" (timeout)":""));
					/// remove the port no, from the list of used ports.

					delete target;
				}
				target = next;
			}
			scanned = 1;
		}
		list_mutex.Post ();

		if (pid->isValid())
		{
			switch(tag)
			{
			case MSG_ID_ATTACH:
				{
					list_mutex.Wait ();
					
					/// mcast is handled differently.
					if (protocol_type != YARP_MCAST)
					{
						target = targets.GetByLabel (buf);
						if (target == NULL)
						{
							ACE_DEBUG ((LM_INFO, "*** connecting %s to %s\n", name.c_str(), buf));

							target = targets.NewLink(buf);
							ACE_ASSERT(target != NULL);
							
							target->network_name = network_name;
							target->target_pid = NULL;
							target->protocol_type = protocol_type;
							target->allow_shmem = allow_shmem;
							target->SetRequireAck (GetRequireAck());
							target->SetOwnName (name);

							target->Begin();
						}
						else
						{
							ACE_DEBUG ((LM_DEBUG, "Ignoring %s, already connected\n", buf));
						}
					}
					else
					{
						/// it requires an extra call to the name server.
						YARPUniqueNameID *rem_pid = YARPNameService::LocateName (buf);

						YARPString ifname;
					
						bool same_net = YARPNameService::VerifySame (((YARPUniqueNameSock *)rem_pid)->getAddressRef().get_host_addr(), network_name.c_str(), ifname);

#ifndef DEBUG_DISABLE_SHMEM
						char myhostname[YARP_STRING_LEN];
						getHostname (myhostname, YARP_STRING_LEN);
						ACE_INET_Addr local ((u_short)0, myhostname);
						
						char iplocal[17];
						ACE_OS::memset (iplocal, 0, 17);
						ACE_OS::strcpy (iplocal, local.get_host_addr());

						bool same_machine = YARPNameService::VerifyLocal (((YARPUniqueNameSock *)rem_pid)->getAddressRef().get_host_addr(), iplocal, network_name.c_str());

						if (same_net || same_machine)
						{
#else
						if (same_net)
						{
#endif

							
#ifndef DEBUG_DISABLE_SHMEM
							if (same_machine && allow_shmem)
							{
								/// go into TCP-SHMEM.
								target = targets.GetByLabel (buf);
								if (target == NULL)
								{
									ACE_DEBUG ((LM_INFO, "*** connecting SHMEM between %s and %s\n", name.c_str(), buf));

									target = targets.NewLink(buf);
									ACE_ASSERT(target != NULL);
		
									target->network_name = network_name;
									target->target_pid = NULL;
									target->protocol_type = YARP_UDP;
									target->allow_shmem = allow_shmem;
									target->SetOwnName (name);

									target->Begin();
								}
								else
								{
									ACE_DEBUG ((LM_DEBUG, "Ignoring %s, already connected\n", buf));
								}
							}
							else
#endif
							{
								/// mcast out port thread.
								target = targets.GetByLabel ("mcast-thread");
								if (target == NULL)
								{
									ACE_DEBUG ((LM_INFO, "*** connecting MCAST %s to %s\n", name.c_str(), buf));
									target = targets.NewLink("mcast-thread");

									ACE_ASSERT(target != NULL);
									target->network_name = network_name;
									target->target_pid = NULL;
									target->protocol_type = protocol_type;
									target->allow_shmem = allow_shmem;
									target->SetOwnName (name);

									target->Begin();

									target->ConnectMcast (buf);
								}
								else
								{
									ACE_DEBUG ((LM_INFO, "*** connecting MCAST %s to %s\n", name.c_str(), buf));
									target->ConnectMcast (buf);
								}
							}

						}	/// end if (same_net)
					}	/// if !MCAST 

					list_mutex.Post ();
				}
				break;

			case MSG_ID_DETACH:
				{
					YARP_DBG(THIS_DBG) ((LM_DEBUG, "Received detach request for %s\n", buf+1));

					list_mutex.Wait ();

					if (protocol_type != YARP_MCAST)
					{
						target = targets.GetByLabel(buf+1);
						if (target != NULL)
						{
							ACE_DEBUG ((LM_DEBUG, "Removing connection between %s and %s\n", name.c_str(), target->GetLabel().c_str()));
							target->Deactivate();
						}
					}
					else
					{
#ifndef DEBUG_DISABLE_SHMEM
						target = targets.GetByLabel(buf+1);
						if (target != NULL)
						{
							ACE_DEBUG ((LM_DEBUG, "Removing (SHMEM) connection between %s and %s\n", name.c_str(), target->GetLabel().c_str()));
							target->Deactivate();
						}
						else
#endif
						{
							/// mcast
							target = targets.GetByLabel("mcast-thread");
							if (target != NULL)
							{
								ACE_DEBUG ((LM_DEBUG, "Removing connection between %s and (%s) via %s\n", name.c_str(), buf+1, target->GetLabel().c_str()));
								
								target->DeactivateMcast(buf+1);
							}
						}
					}

					/// scan the list of outputs to delete disconnected ones!

					///
					/// don't I need a wait for completion of the Deactivate procedure here?

					double now = YARPTime::GetTimeAsSeconds();
					target = targets.GetRoot();
					while (target != NULL)
					{
						next = target->GetMeshNext();
						target->WaitMutex();
						int active = target->active;
						int deactivated = target->deactivated;
						int ticking = target->ticking;
						double started = target->check_tick;
						target->PostMutex();
						int timeout = 0;
						
						if (ticking && now-started > 5)
						{
							active = 0;
							timeout = 1;
						}

						if (!active)
						{
							ACE_DEBUG ((LM_INFO, "disconnecting %s and %s %s%s\n",
								name.c_str(), target->GetLabel().c_str(),
								deactivated ? "" : "(target stopped responding)",
								timeout?" (timeout)":""));

							delete target;
						}
						target = next;
					}

					list_mutex.Post ();
				}
				break;

			case MSG_ID_DATA:
				{
					YARP_DBG(THIS_DBG) ((LM_DEBUG, "Gosh, someone sent me data! Me being %s in case you're curious\n", name.c_str()));

					out_mutex.Wait();
					receiving = 1;
					
					if (!ignore_data) 
					{
						while (p_receiver_incoming.Ptr() == NULL)
					    {
							YARP_DBG(THIS_DBG) ((LM_DEBUG, "&&& Waiting for incoming space\n"));
							// HIT - should have way to convey back skip
							// request to sender
							// (can't just ignore, don't know how many)
							// (components message has)

							asleep = 1;
							out_mutex.Post();
							wakeup.Wait();
							out_mutex.Wait();
					    }

						asleep = 0;
						p_receiver_incoming.Ptr()->AddRef();
						out_mutex.Post();

						p_receiver_incoming.Ptr()->Read(receiver);
						p_receiver_incoming.Ptr()->RemoveRef();
					}
					else
					{
						out_mutex.Post();
					}

					receiver.End();

					out_mutex.Wait();
					receiving = 0;
					
					if (!ignore_data) 
					{
						YARP_DBG(THIS_DBG) ((LM_DEBUG, "&&& Received. Switching with latest space\n"));
						p_receiver_latest.Switch(p_receiver_incoming);

						if (!has_input)
						{
							has_input = 1;
							something_to_read.Post();
						}
					}

					out_mutex.Post();

					if (!ignore_data) 
					{
						call_on_read = 1;
					}
				}
				break;

			case MSG_ID_GO:
				{
					ACE_DEBUG ((LM_ERROR, "this shouldn't happen, the new version doesn't accept MSG_ID_GO\n"));
				}
				break;

			case MSG_ID_DETACH_ALL:
				{
					YARP_DBG(THIS_DBG) ((LM_DEBUG, "Received detach_all request (%s)\n", name.c_str()));

					list_mutex.Wait ();

					if (protocol_type != YARP_MCAST)
					{
						target = targets.GetRoot();

						while (target != NULL)
						{
							next = target->GetMeshNext();
							ACE_DEBUG ((LM_INFO, "*** removing connection between %s and %s\n", name.c_str(), target->GetLabel().c_str()));
							target->Deactivate();
							target = next;
						}
					}
					else
					{
						OutputTarget *mtarget = targets.GetByLabel("mcast-thread");
#ifndef DEBUG_DISABLE_SHMEM
						/// takes care of the SHMEM connection
						target = targets.GetRoot();

						while (target != NULL)
						{
							next = target->GetMeshNext();
							ACE_DEBUG ((LM_INFO, "*** removing connection between %s and %s\n", name.c_str(), target->GetLabel().c_str()));
							if (target != mtarget && mtarget != NULL)
								target->Deactivate();
							target = next;
						}
#endif

						/// mcast
						if (mtarget != NULL)
						{
							ACE_DEBUG ((LM_INFO, "*** removing all MCAST connections\n"));
							mtarget->DeactivateMcastAll();
						}
					}

					list_mutex.Post ();

					/// signal the SelfEnd that the msg has been received.

					complete_msg_thread.Signal ();

					/// wait for closure of SelfEnd socket and relative thread.
					complete_terminate.Wait();

					/// only now asks for End.
					AskForEnd ();
				}
				break;

			case MSG_ID_DETACH_IN:
				{
					ACE_DEBUG ((LM_DEBUG, "*** received detach request for %s\n", buf+1));

					YARPUniqueNameID needclose;
					needclose = *pid;
					needclose.setName (buf+1);
					YARPEndpointManager::Close (needclose);
				}
				break;

			case MSG_ID_DUMP_CONNECTIONS:
				{
					ACE_DEBUG ((LM_INFO, "*** dumping connections for %s\n", name.c_str()));
					ACE_DEBUG ((LM_INFO, "*** output connections:\n"));

					list_mutex.Wait ();
					target = targets.GetRoot();
					int i = 0;
					while (target != NULL)
					{
						target->WaitMutex();
						ACE_DEBUG ((LM_INFO, "***   %d: %s %s:%d\n", 
							i, 
							target->GetLabel().c_str(),
							target->GetOwnAddress().get_host_addr(),
							target->GetOwnAddress().get_port_number()));
						target->PostMutex();
						next = target->GetMeshNext();
						target = next;
						i++;
					}

					list_mutex.Post ();

					ACE_DEBUG ((LM_INFO, "*** input connections:\n"));
					YARPEndpointManager::PrintConnections (*pid);
				}	
				break;

			case MSG_ID_ERROR:
				YARP_DBG(THIS_DBG) ((LM_DEBUG, "Error message received by %s!\n", name.c_str()));
				break;

			default:
				{
					YARP_DBG(THIS_DBG) ((LM_DEBUG, "Unknown message received by %s (tag is %d-->'%c', str is %s)!\n", name.c_str(), tag, tag, buf));
				}
				break;
			}
		}	/// end switch/case
      
		if (call_on_read)
		{
			OnRead();
			call_on_read = 0;
		}
	} /// if !terminated

	/// since this is started in this thread close it here.
	tsender.AskForEnd();
	tsender.pulseGo();
	tsender.Join();

	///
	/// tries to shut down the input socket threads.
	/// uses the special request for closing all input threads at once.
	///
	///
	YARPUniqueNameID needcloseall;
	needcloseall = *pid;
	needcloseall.setName ("__All__");
	YARPEndpointManager::Close (needcloseall);

	/// unregister the port name here.
	YARPNameService::UnregisterName (pid);

	/// free memory.
	YARPNameService::DeleteName (pid);
	pid = NULL;

	/// wakes up a potential thread waiting on a blocking Read().
	has_input = 1;
	something_to_read.Post();

	ACE_DEBUG ((LM_DEBUG, "***** main port thread 0x%x returning\n", GetIdentifier()));
}


///
/// this is called from YARPPort::Write to actually send something.
/// Currently it wakes the Port thread up through a socket connection that
///	Paul believes to be responsible for poor performance on Linux/NT.
///
void Port::Share(Sendable *nsendable)
{
	okay_to_send.Wait();
	out_mutex.Wait();
	p_sendable.Set(nsendable);
	out_mutex.Post();

	/// this simply pulses the mutex on the sender thread.
	/// cost an additional thread but hopefully saves a costly message
	/// through the port socket.
	tsender.pulseGo ();
}
예제 #30
0
///
///
/// this is the thread which manages a single output connection.
///
void OutputTarget::Body ()
{
	/// implicit wait mutex for this thread.
	/// see overridden Begin()

#if defined(__QNX6__) || defined(__LINUX__)
	signal (SIGPIPE, SIG_IGN);
#endif
	int success = YARP_OK;
	NewFragmentHeader header;
	BlockSender sender;
	CountedPtr<Sendable> p_local_sendable;

	ACE_OS::memset (cmdname, 0, 2*YARP_STRING_LEN);
	msg_type = 0;

	/// needs to know what is the protocol of the owner.
	switch (protocol_type)
	{
	case YARP_QNET:
		{
			ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : starting a QNET sender thread\n"));

			/// LATER: must do proper bailout if locate fails.
			///
			target_pid = YARPNameService::LocateName (GetLabel().c_str());
			target_pid->setRequireAck(GetRequireAck());
			if (target_pid->getServiceType() != protocol_type)
			{
				/// problems.
				ACE_DEBUG ((LM_DEBUG, "troubles locating %s, the protocol is wrong\n", GetLabel().c_str()));

				YARPNameService::DeleteName(target_pid);
				target_pid = NULL;

				active = 0;
				deactivated = 1;
				PostMutex ();
				return;
			}

			YARPEndpointManager::CreateOutputEndpoint (*target_pid);
			YARPEndpointManager::ConnectEndpoints (*target_pid, own_name);
		}
		break;

	case YARP_TCP:
		{
			ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : starting a TCP sender thread\n"));

			target_pid = YARPNameService::LocateName (GetLabel().c_str(), network_name.c_str());
			target_pid->setRequireAck(GetRequireAck());
			/*
			  There is some kind of hack going on here that
			  prevents a clean use of nameserver (registering
			  ports with the protocol they actually use).
			  Adding a workaround.
			 */
			int use_workaround = 0;
			if (target_pid->isConsistent(YARP_TCP)) {
			  use_workaround = 1;
			}


			if (!(use_workaround||
			      target_pid->isConsistent(YARP_UDP)))
			{
			  if (target_pid->getServiceType()==YARP_NO_SERVICE_AVAILABLE) {
			    ACE_DEBUG ((LM_INFO, "*** FAILED to make connection to %s, port not found\n",GetLabel().c_str()));
			  } else {
			    ACE_DEBUG ((LM_INFO, "***** OutputTarget::Body : can't connect - target on different network, output thread 0x%x bailing out\n", GetIdentifier()));
			  }
				YARPNameService::DeleteName(target_pid);
				target_pid = NULL;

				active = 0;
				deactivated = 1;
				PostMutex ();
				return;	
			}

#ifndef DEBUG_DISABLE_SHMEM
			/// involves a query to dns or to the /etc/hosts file.
			char myhostname[YARP_STRING_LEN];
			getHostname (myhostname, YARP_STRING_LEN);
			ACE_INET_Addr local ((u_short)0, myhostname);

			/// this test is carried out by the nameserver relying on the
			/// subnetwork structure.
			char iplocal[17];
			ACE_OS::memset (iplocal, 0, 17);
			ACE_OS::memcpy (iplocal, local.get_host_addr(), 17);

#ifdef USE_YARP2
			// Test for locality is broken.
			// Is test for same-machine sufficient?
			bool same_machine = YARPNameService::VerifySame (((YARPUniqueNameSock *)target_pid)->getAddressRef().get_host_addr(), iplocal, network_name);
#else
			bool same_machine = YARPNameService::VerifyLocal (((YARPUniqueNameSock *)target_pid)->getAddressRef().get_host_addr(), iplocal, network_name.c_str());
#endif
			///if (((YARPUniqueNameSock *)target_pid)->getAddressRef().get_ip_address() == local.get_ip_address())

			bool accepted = true;

#ifdef USE_YARP2
			// YARP2 extension
			if (same_machine&&allow_shmem) {
			  accepted = (YARPNameService::CheckProperty(GetLabel().c_str(),"accepts", "shmem"))!=0;
			  if (!accepted) {
			    ACE_DEBUG ((LM_DEBUG, "switching to SHMEM mode is prohibited\n"));
			  }
			}
			// YARP2 extension ends			
#endif

			if (same_machine && allow_shmem && accepted)
			{
				/// going into SHMEM mode.
				protocol_type = YARP_SHMEM;
				target_pid->setServiceType (YARP_SHMEM);
				target_pid->setRequireAck(GetRequireAck());

				/// 
				ACE_DEBUG ((LM_DEBUG, "$$$$$ OutputTarget::Body : this goes into SHMEM mode\n"));
			}
			else
#endif
			{
				///
				/// LATER: do proper check. 
				/// 	must always succeed. Any protocol is fine but QNET
				/// 	for creating a socket connection.
				if (target_pid->getServiceType() != protocol_type &&
					target_pid->getServiceType() != YARP_UDP)
				{
					/// problems.
					ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : troubles locating %s, the protocol is wrong\n", GetLabel().c_str()));

					YARPNameService::DeleteName(target_pid);
					target_pid = NULL;

					ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : output thread 0x%x bailing out\n", GetIdentifier()));

					active = 0;
					deactivated = 1;
					PostMutex ();

					return;
					///target_pid->invalidate();
				}

				protocol_type = YARP_TCP;
				target_pid->setServiceType (YARP_TCP);
				target_pid->setRequireAck(GetRequireAck());
			}

			YARPEndpointManager::CreateOutputEndpoint (*target_pid);
			YARPEndpointManager::ConnectEndpoints (*target_pid, own_name);

//#ifdef DEBUG_DISABLE_SHMEM
#	ifdef YARP_TCP_NO_DELAY
			/// disables Nagle's algorithm...
			if (protocol_type == YARP_TCP)
				YARPEndpointManager::SetTCPNoDelay (*target_pid);
#	endif
//#endif
		}
		break;

	case YARP_UDP:
		{
			ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : starting a UDP sender thread\n"));

			target_pid = YARPNameService::LocateName (GetLabel().c_str(), network_name.c_str());
			target_pid->setRequireAck(GetRequireAck());
			if (!target_pid->isConsistent(YARP_UDP))
			{
			  if (target_pid->getServiceType()==YARP_NO_SERVICE_AVAILABLE) {
			    ACE_DEBUG ((LM_INFO, "*** FAILED to make connection to %s, port not found\n",GetLabel().c_str()));
			  } else {
			    ACE_DEBUG ((LM_INFO, "***** OutputTarget::Body : can't connect - target on different network, output thread 0x%x bailing out\n", GetIdentifier()));
			  }
				YARPNameService::DeleteName(target_pid);
				target_pid = NULL;

				active = 0;
				deactivated = 1;
				PostMutex ();

				return;	
			}

#ifndef DEBUG_DISABLE_SHMEM
			char myhostname[YARP_STRING_LEN];
			getHostname (myhostname, YARP_STRING_LEN);
			ACE_INET_Addr local ((u_short)0, myhostname);

			char iplocal[17];
			ACE_OS::memset (iplocal, 0, 17);
			ACE_OS::memcpy (iplocal, local.get_host_addr(), 17);

			/// this test is carried out by the name server.
			bool same_machine = YARPNameService::VerifyLocal (((YARPUniqueNameSock *)target_pid)->getAddressRef().get_host_addr(), iplocal, network_name.c_str());

			///if (((YARPUniqueNameSock *)target_pid)->getAddressRef().get_ip_address() == local.get_ip_address())
			if (same_machine && allow_shmem)
			{
				/// going into SHMEM mode.
				protocol_type = YARP_SHMEM;
				((YARPUniqueNameSock *)target_pid)->setServiceType (YARP_SHMEM);
				target_pid->setRequireAck(GetRequireAck());

				/// 
				ACE_DEBUG ((LM_DEBUG, "$$$$$ OutputTarget::Body : this goes into SHMEM mode\n"));
			}
			else
			{
				/// needed because the port changes from that of the incoming call
				/// it is used to accept data (pretend a connection to the remote).
				if (target_pid->getServiceType() != YARP_UDP)
				{
					/// problems.
					ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : troubles locating %s, the protocol is wrong\n", GetLabel().c_str()));
					YARPNameService::DeleteName(target_pid);
					target_pid = NULL;
	
					ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : output thread 0x%x bailing out\n", GetIdentifier()));

					active = 0;
					deactivated = 1;
					PostMutex ();

					return;	
					///target_pid->invalidate();
				}
			}
#else
			if (target_pid->getServiceType() != YARP_UDP)
			{
				/// problems.
				ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : troubles locating %s, the protocol is wrong\n", GetLabel().c_str()));
				///target_pid->invalidate();
				YARPNameService::DeleteName(target_pid);
				target_pid = NULL;

				ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : output thread 0x%x bailing out\n", GetIdentifier()));

				active = 0;
				deactivated = 1;
				PostMutex ();

				return;	
			}
#endif

			YARPEndpointManager::CreateOutputEndpoint (*target_pid);
			YARPEndpointManager::ConnectEndpoints (*target_pid, own_name);
		}
		break;

	case YARP_MCAST:
		{
			ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : starting a MCAST sender thread\n"));

			/// MCAST is different! Locate prepares the MCAST group and registers it.
			/// additional commands are sent to "clients" to ask to join the specific group.
			/// ALSO: VerifySame had been called before actually running the thread.

			target_pid = YARPNameService::LocateName(GetLabel().c_str(), network_name.c_str(), YARP_MCAST);
			target_pid->setRequireAck(GetRequireAck());
			YARPEndpointManager::CreateOutputEndpoint (*target_pid);

			if (target_pid->getServiceType() != YARP_MCAST)
			{
				/// problems.
				ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : troubles locating %s, the protocol is wrong\n", GetLabel().c_str()));
				///target_pid->invalidate();
				YARPNameService::DeleteName(target_pid);
				target_pid = NULL;
			
				ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : output thread 0x%x bailing out\n", GetIdentifier()));

				active = 0;
				deactivated = 1;
				PostMutex ();

				return;	
			}
		}
		break;
	}

	/// this wait for initialization.
	PostMutex ();
	YARP_DBG(THIS_DBG) ((LM_DEBUG, "Output target after initialization section\n"));

	/// if the address is not valid, terminates the thread.
	if (!target_pid->isValid())
	{
		/// 
		ACE_DEBUG ((LM_DEBUG, "***** OutputTarget, troubles, perhaps a process died without unregistering\n"));
		ACE_DEBUG ((LM_DEBUG, "***** OutputTarget, can't connect to the remote endpoint\n"));

		YARPNameService::DeleteName(target_pid);
		target_pid = NULL;
	
		ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : output thread 0x%x bailing out\n", GetIdentifier()));

		active = 0;
		deactivated = 1;
		PostMutex ();

		return;	
	}

	while (!deactivated)
	{
		YARP_DBG(THIS_DBG) ((LM_DEBUG, "Waiting for sema to send\n"));
		something_to_send.Wait();

		YARP_DBG(THIS_DBG) ((LM_DEBUG, "Done waiting for sema to send\n"));

		WaitMutex();

		if (deactivate)
		{
			active = 0;
			deactivated = 1;
			PostMutex ();
			continue;
		}

		///
		/// MCAST commands follow: 
		///		- these are sent and processed by contacting the TCP channel of the port.
		if (protocol_type == YARP_MCAST)
		{
			/// LATER: need to figure out whether this is always ok.
			/// multiple connection requests might overlap?

			YARP_DBG(THIS_DBG) ((LM_DEBUG, "-------- msg_type is %d\n", msg_type));

			/// process connect/disconnect messages.
			switch (msg_type)
			{
			case 1:
				{
					/// connect
					YARPUniqueNameID* udp_channel = YARPNameService::LocateName(cmdname, network_name.c_str(), YARP_UDP);
					YARPEndpointManager::ConnectEndpoints (*udp_channel, own_name);
					YARPNameService::DeleteName (udp_channel);
				}
				break;

			case 2:
				{
					/// disconnect
					YARPUniqueNameID* udp_channel = YARPNameService::LocateName(cmdname, network_name.c_str(), YARP_UDP);
					if (udp_channel->getServiceType() == YARP_NO_SERVICE_AVAILABLE)
						udp_channel->setName(cmdname);

					/// first tries a Close of the endpoint.
					YARPEndpointManager::Close (*udp_channel);

					/// tests whether a thread termination is required.
					if (YARPEndpointManager::GetNumberOfClients () < 1)
					{
						active = 0;
						deactivated = 1;
					}

					YARPNameService::DeleteName (udp_channel);
				}
				break;

			case 3:
				{
					/// disconnect all
					YARPEndpointManager::CloseMcastAll ();
					active = 0;
					deactivated = 1;	/// perhaps deactivate = 1;
				}
				break;
			}

			/// if a message has been processed jump to the end of thread cycle.
			if (msg_type != 0)
			{
				msg_type = 0;
				PostMutex();
				continue;
			}

		}	/// end of if (protocol_type).


		///
		///
		check_tick = YARPTime::GetTimeAsSeconds();
		ticking = 1;
		p_local_sendable.Set(p_sendable.Ptr());
		p_sendable.Reset();
		
		PostMutex();
		YARP_DBG(THIS_DBG) ((LM_DEBUG, "Waiting for sema to send <<< sema okay!\n"));

		target_pid->getNameID().setRequireAck(GetRequireAck());
		sender.Begin(target_pid->getNameID());
		header.tag = MSG_ID_DATA;
		header.length = 0;
		header.first = 1;
		header.more = 0;
		
		if (add_header)
		{
			sender.Add ((char*)(&header), sizeof(header));
		}

		success = p_local_sendable.Ptr()->Write(sender);
		if (!success)
			YARP_DBG(THIS_DBG) ((LM_DEBUG, "*** Fire failed\n"));
		success = success && sender.End();

		WaitMutex();

		if (deactivate)
		{
			active = 0;
			deactivated = 1;
		}

		if (!success)
		{
			YARP_DBG(THIS_DBG) ((LM_DEBUG, "*** Send failed\n"));
			active = 0;
		}
		
		sending = 0;
		ticking = 0;
		PostMutex();
		p_local_sendable.Reset();
		space_available.Post();

		OnSend();
	} /// while (!deactivated)

	if (protocol_type == YARP_MCAST)
	{
		YARPEndpointManager::CloseMcastAll ();
		/// unregister the mcast group.
		YARPNameService::UnregisterName (target_pid);
	}
	else
	{
		YARPEndpointManager::Close (*target_pid);
	}

	/// but see also what I said on closing the Port thread.
	YARPNameService::DeleteName(target_pid);

	ACE_DEBUG ((LM_DEBUG, "***** OutputTarget::Body : output thread 0x%x bailing out\n", GetIdentifier()));
}