Exemplo n.º 1
0
bool ProtocolRFCOMM::initbase()
{
	struct sockaddr_bt localAddr;

        if (isConnected()) {
                // Nothing to do
                return true;
        }

	if (!openSocket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM, isServer())) {
		HAGGLE_ERR("Could not create RFCOMM socket\n");
                return false;
        }

	memset(&localAddr, 0, sizeof(struct sockaddr_bt));
	localAddr.bt_family = AF_BLUETOOTH;
	localAddr.bt_channel = channel & 0xff;

#ifndef OS_WINDOWS
	if (localIface) {
		BluetoothAddress *addr = localIface->getAddress<BluetoothAddress>();
		if (addr) {
                        // Binding RFCOMM sockets to a hardware address does not
                        // seem to work in Windows
			BDADDR_swap(&localAddr.bt_bdaddr, addr->getRaw());
                }
	}
#endif

	if (isServer()) {
		localAddr.bt_channel = channel & 0xff;
   
             	/* If this is a server we bing to a specific channel to listen on */
                if (!bind((struct sockaddr *)&localAddr, sizeof(localAddr))) {
                        closeSocket();
#ifdef OS_WINDOWS
                        HAGGLE_ERR("Bind failed for local address WSA error=%s\n", StrError(WSAGetLastError()));
#endif
                        
                        HAGGLE_ERR("Could not bind local address for RFCOMM socket\n");
                        
                        return false;
                }

                HAGGLE_DBG("Bound RFCOMM server to channel=%d\n", channel);
   
	} else {
		HAGGLE_DBG("Created RFCOMM client on channel=%d\n", channel);
	}

	return true;
}
Exemplo n.º 2
0
identity_msg::identity_msg():
    msg(sizeof(*this), IDENTITY),
    loc(getLocation()),
    senderIsServer(isServer()),
    sender(me())
{
}
Exemplo n.º 3
0
bool Host::broadcast(ChannelID channel, PacketType type, const PacketData& data)
{
  if (!isServer())
  {
    logError("Only the server is allowed to broadcast");
    return false;
  }

  uint32 flags = 0;

  if (type == RELIABLE)
    flags |= ENET_PACKET_FLAG_RELIABLE;
  else
  {
    if (type == UNSEQUENCED)
      flags |= ENET_PACKET_FLAG_UNSEQUENCED;

    flags |= ENET_PACKET_FLAG_NO_ALLOCATE;
  }

  ENetPacket* packet = enet_packet_create(data.data(), data.size(), flags);
  if (!packet)
  {
    logError("Failed to create ENet packet");
    return false;
  }

  enet_host_broadcast((ENetHost*) m_object, channel, packet);
  return true;
}
Exemplo n.º 4
0
void Purity::NetworkSystem::update(Scene* scene)
{
    if (mCurrentScene != scene)
    {
        mCurrentScene = scene;
    }

    if (mServer && isServer())
    {
        mServer->handleEvents();
        mServer->sendDataToClients(mCurrentScene->getEntityStates());
    }
    else if (mClient)
    {
        mClient->handleEvents();

        while (mClientActionQueue.empty() == false)
        {
            mClient->sendAction(mClientActionQueue.front());

            mClientActionQueue.pop();
        }

        for (auto it = mClientReceievdStates->begin(); it != mClientReceievdStates->end(); ++it)
        {
            mCurrentScene->setEntityState(it->second);
        }
    }
}
Exemplo n.º 5
0
void GadgetDrive::use( dword nWhen, Noun * pTarget, bool shift)
{
	if (! active() )
		NounGadget::use( nWhen, pTarget, shift );

	if ( isServer() )
		setFlags( FLAG_ACTIVE, !active() );
}
Exemplo n.º 6
0
bool JmtNodeParser::isRoutingStation() {

	TiXmlNode *node = getLowerLevelNodeWith(baseNode, "section", "className", "Router");
	if (node != NULL) {
		return !isServer();	// a routing station has a Router section, but no delay section
	}
	return false;
}
Exemplo n.º 7
0
void Artifact::collide(Collisionable* target, float force)
{
    if (!isServer() || !allow_pickup)
        return;
    P<SpaceObject> hit_object = P<Collisionable>(target);
    if (P<PlayerSpaceship>(hit_object))
    {
        destroy();
    }
}
Exemplo n.º 8
0
const std::string Settings::dump() const
{
    std::stringstream ss;
    ss << "Settings: " << std::endl;
    ss << "\tusername: "******"\t address: " << serverAddress() << std::endl;
    ss << "\t server?: " << (isServer() ? "true":"false") << std::endl;
    ss << "\t    port: " << port() << std::endl;

    return ss.str();
}
Exemplo n.º 9
0
void NetworkManager::send(void* data, int size, bool ack)
{
	if (!isActive()) return;
	if (isServer())
	{
		server->broadcastData(data, size, ack);
	}
	else
	{
		client->sendData(data, size, ack);
	}
}
Exemplo n.º 10
0
void GadgetScanner::use( dword when, Noun * pTarget, bool shift)
{
	if ( active() )
		NounGadget::use( when, pTarget, shift );

	if ( isServer() )
	{
		// set the device active
		setFlags( FLAG_ACTIVE, !active() );
		message( CharString().format( "<color;ffffff>Tactical: %s %s.", name(), active() ? "Active" : "Inactive" ), true ); 
	}
}
Exemplo n.º 11
0
void BlackHole::collide(Collisionable* target, float collision_force)
{
    if (update_delta == 0.0)
        return;

    sf::Vector2f diff = getPosition() - target->getPosition();
    float distance = sf::length(diff);
    float force = (getRadius() * getRadius() * 50.0f) / (distance * distance);
    if (force > 10000.0)
    {
        force = 10000.0;
        if (isServer())
            target->destroy();
    }
    DamageInfo info(NULL, DT_Kinetic, getPosition());
    if (force > 100.0 && isServer())
    {
        P<SpaceObject> obj = P<Collisionable>(target);
        if (obj)
            obj->takeDamage(force * update_delta / 10.0f, info);
    }
    target->setPosition(target->getPosition() + diff / distance * update_delta * force);
}
Exemplo n.º 12
0
void NetworkManager::update()
{
	if (!isActive()) return;
	
	if (GameState::instance()->isRunning()) {
		broadcastHeartbeat();
	}

	if (isServer()) {
		server->update();
	} else if (isClient()) {
		client->update();
	}
}
Exemplo n.º 13
0
void NounShip::updateDespawn()
{
	if ( m_bDespawning )
	{		
		if ( m_nDespawnTicks > 0 )
			--m_nDespawnTicks;

		if ( m_nDespawnTicks == 0 )
		{
			if ( isServer() )
				setDetach();
			m_bDespawning = false;
		}
	}
}
Exemplo n.º 14
0
/*!
 * Disconnects a client with \a id using the attached connection manager.
 *
 * If connected to a server, this function is ignored with a warning.
 */
void QxtRPCService::disconnectClient(quint64 id)
{
    if(!isServer()) {
        qWarning() << "QxtRPCService::disconnectClient: not operating as a server";
        return;
    }

    if(!qxt_d().manager->client(id)) {
        qWarning() << "QxtRPCService::disconnectClient: no client with specified ID";
        return;
    }

    // Ask the manager to disconnect the client. QxtAbstractConnectionManager will emit disconnected(), which is chained
    // to QxtRPCService::clientDisconnected(), so that signal is not explicitly emitted here.
    qxt_d().manager->disconnect(id);
}
Exemplo n.º 15
0
void CGameEngine::addScore(boost::shared_ptr<IEntity> playerHero, UInt32 score)
{
	if(isServer())
	{
		UInt8 playerId=-1;
		for(std::map<Int8, CPlayer>::const_iterator i=m_players.begin();i!=m_players.end();i++)
			if(playerHero == i->second.getEntity())
				playerId = i->first;

		if(playerId != 0)
		{
			boost::shared_ptr<CHeroAddScore> addScoreEvent(new CHeroAddScore(playerId,score));
			m_eventEngine->newEvent(addScoreEvent);
		}
	}
}
Exemplo n.º 16
0
bool NounStructure::build()
{
	if (! isBuilding() )
		return true;

	m_nBuildTime += 1;
	if (! isBuilding() )
	{
		// construction complete!
		if ( isServer() && planet() != NULL )
			factionChat( CharString().format( "<color;ffffff>Comms: %s %s constructed", planet()->name(), name() ) );

		return true;
	}
	return false;
}
Exemplo n.º 17
0
void Asteroid::collide(Collisionable* target)
{
    if (!isServer())
        return;
    P<SpaceObject> hit_object = P<Collisionable>(target);
    if (!hit_object || !hit_object->canBeTargeted())
        return;

    DamageInfo info(NULL, DT_Kinetic, getPosition());
    hit_object->takeDamage(35, info);

    P<ExplosionEffect> e = new ExplosionEffect();
    e->setSize(getRadius());
    e->setPosition(getPosition());
    destroy();
}
Exemplo n.º 18
0
////////////////////////////////////////////////////////////////////////
// main
//
int main(int argc, char* argv[])
{
  try
  {
    log_init();
    cxxtools::Arg<bool> isServer(argc, argv, 's');

    if (isServer)
      return server(argc, argv);
    else
      return client(argc, argv);
  }
  catch (const std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }
}
Exemplo n.º 19
0
bool Host::sendPacketTo(TargetID targetID,
                        ChannelID channel,
                        PacketType type,
                        const PacketData& data)
{
  switch (targetID)
  {
    case LOCAL:
    {
      if (m_observer)
      {
        PacketData copy = data;
        m_observer->onPacketReceived(targetID, copy);
      }

      return true;
    }

    case BROADCAST:
      return broadcast(channel, type, data);

    case SERVER:
    {
      if (isServer())
        return sendPacketTo(LOCAL, channel, type, data);

      /* FALLTHROUGH */
    }

    default:
    {
      Peer* peer = findPeer(targetID);
      if (!peer)
      {
        logError("Cannot send event to unknown peer %u", targetID);
        return false;
      }

      return peer->sendPacket(channel, type, data);
    }
  }
}
Exemplo n.º 20
0
/* Perform TLS handshake. */ 
void
SSLSocket::handshake(handshake_callback cb, peer_auth_callback authCb)
{
  assert (_state == State::Open);
  assert (_r.state == Read::State::Off);
  assert (_w.state == Write::State::Off);

  _state = State::Handshaking;
  _h.cb = std::move(cb);
  _h.authCb = std::move(authCb);

  if (!isServer()) {
    /* If this socket was created by the client, the socket has
       not yet been wrapped as an SSL socket */
    sslCtx().initializeSecurity(_fd);
  }
  sslCtx().initializeTLS(*this);
  
  handshakeContinue();
}
Exemplo n.º 21
0
void NounStructure::inflictDamage( dword nWhen, Noun * pFrom, int damage, dword type, const Vector3 & direction )
{
	// don't allow more damage than possible
	int possible = maxDamage() - m_Damage;
	if ( damage > possible )
		damage = possible;

	if ( pFrom != NULL)
	{
		float ratio = float( damage ) / maxDamage();
		if ( isFriend( pFrom ) )
			gameContext()->gameUser()->onFriendlyFire( pFrom, ratio );
		else
			gameContext()->gameUser()->onPlanetsDamaged( pFrom, ratio );
	}

	m_Damage += damage;
	if ( isServer() && m_Damage >= maxDamage() )
		Verb::Ref( new VerbDestroyStructure( this, pFrom ) );
}
Exemplo n.º 22
0
 /** Sets if this server is registered with the stk server. */
 void setRegistered(bool registered)
 {
     assert(isServer());
     m_is_registered = registered; 
 }   // setRegistered
Exemplo n.º 23
0
//loop through command line arguments and extract settings
void Settings::parse(const int argc, const char** argv)
{
    bool hasUserName = false;   //assume user hasn't entered a username

    //loops through arguments, reads in each argument and decides what to do with it
    for(int ii = 0; ii < argc; ++ii)
    {
        std::string arg(argv[ii]);

        if (arg[0] != '-')
        {
            continue;   //not a switch, skip it
        }

        if(arg.find("-username="******"-address=") == 0)    //are we setting a server IP?
        {
            std::string address(getArgValue(arg));
            try
            {
                (void)serverAddress(address);    //set and validate requested server address
            }
            catch (BeeChatException bce)
            {
                throw;    //rethrow the same exception
            }
        }

        else if(arg.find("-server") == 0)
        {
            (void)isServer(true);    //request to bee a server
        }

        else if(arg.find("-port=") == 0)
        {
            std::string portStr(getArgValue(arg));
            try
            {
                (void)port((unsigned short)atoi(portStr.c_str()));    //set and validate requested port
            }
            catch(BeeChatException e)
            {
                std::stringstream ss;
                ss << "Could not set port: " << e.type() << ":" << e.message();
                throw BeeChatException(eET_invalid_port, ss.str());
            }
        }

        else
        {
            std::stringstream ss;
            ss << "Unknown argument: " << arg;
            throw BeeChatException(eET_unknown_arg, ss.str());
        }
    }

    if(!hasUserName)
    {
        throw BeeChatException(eET_empty_username, "No username supplied");
    }

}
Exemplo n.º 24
0
 inline bool isClient()              { return !isServer();       }
Exemplo n.º 25
0
bool ProtocolTCP::initbase()
{
	int optval = 1;
        char buf[SOCKADDR_SIZE];
        struct sockaddr *local_addr = (struct sockaddr *)buf;
        socklen_t addrlen = 0;
        int af = AF_INET;
        unsigned short port = isClient() ? 0 : localport;
	char ip_str[50];
	
        if (!localIface) {
		HAGGLE_ERR("Local interface is NULL\n");
                return false;
        }

	// Check if we are already connected, i.e., we are a client
	// that was created from acceptClient()
	if (isConnected()) {
		// Nothing to initialize
		return true;
	}
        // Figure out the address type based on the local interface
#if defined(ENABLE_IPv6)
	if (localIface->getAddress<IPv6Address>() && peerIface && peerIface->getAddress<IPv6Address>())
                af = AF_INET6;
#endif

        /* Configure a sockaddr for binding to the given port. Do not
         * bind to a specific interface. */
        if (af == AF_INET) {
                struct sockaddr_in *sa = (struct sockaddr_in *)local_addr;
                sa->sin_family = AF_INET;
                sa->sin_addr.s_addr = htonl(INADDR_ANY);
                sa->sin_port = htons(port);
                addrlen = sizeof(struct sockaddr_in);
        }
#if defined(ENABLE_IPv6)
        else if (af == AF_INET6) {
                struct sockaddr_in6 *sa = (struct sockaddr_in6 *)local_addr;
                sa->sin6_family = AF_INET6;
                sa->sin6_len = SOCKADDR_SIZE;
                sa->sin6_addr = in6addr_any;
                sa->sin6_port = htons(port);
                addrlen = sizeof(struct sockaddr_in6);
        }
#endif

	if (!openSocket(local_addr->sa_family, SOCK_STREAM, IPPROTO_TCP, isServer())) {
		HAGGLE_ERR("Could not create TCP socket\n");
                return false;
	}

	if (!setSocketOption(SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))) {
		closeSocket();
		HAGGLE_ERR("setsockopt SO_REUSEADDR failed\n");
                return false;
	}

	if (!setSocketOption(SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval))) {
		closeSocket();
		HAGGLE_ERR("setsockopt SO_KEEPALIVE failed\n");
                return false;
	}

	if (!bind(local_addr, addrlen)) {
		closeSocket();
		HAGGLE_ERR("Could not bind TCP socket\n");
                return false;
        }
	if (inet_ntop(af, &((struct sockaddr_in *)local_addr)->sin_addr, ip_str, sizeof(ip_str))) {
		HAGGLE_DBG("%s Created %s TCP socket - %s:%d\n", 
			   getName(), af == AF_INET ? "AF_INET" : "AF_INET6", ip_str, port);
	}
	return true;
}
Exemplo n.º 26
0
int initSessionNetConnectInfo( const SESSION_INFO *sessionInfoPtr,
							   OUT NET_CONNECT_INFO *connectInfo )
	{
	const ATTRIBUTE_LIST *clientNamePtr, *serverNamePtr, *portInfoPtr;

	assert( isReadPtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) );
	assert( isWritePtr( connectInfo, sizeof( NET_CONNECT_INFO ) ) );

	initNetConnectInfo( connectInfo, sessionInfoPtr->ownerHandle,
				sessionInfoPtr->readTimeout, sessionInfoPtr->connectTimeout,
				( sessionInfoPtr->transportSession != CRYPT_ERROR ) ? \
					NET_OPTION_TRANSPORTSESSION : \
				( sessionInfoPtr->networkSocket != CRYPT_ERROR ) ? \
					NET_OPTION_NETWORKSOCKET : NET_OPTION_HOSTNAME );

	/* If the user has supplied the network transport information, there's
	   nothing further to do */
	if( sessionInfoPtr->transportSession != CRYPT_ERROR )
		{
		connectInfo->iCryptSession = sessionInfoPtr->transportSession;
		return( CRYPT_OK );
		}
	if( sessionInfoPtr->networkSocket != CRYPT_ERROR )
		{
		connectInfo->networkSocket = sessionInfoPtr->networkSocket;
		return( CRYPT_OK );
		}

	/* If there are explicit client and/or server names set, record them.  
	   For a client the server name is the remote system to connect to
	   and the client name is the optional local interface to bind to, for
	   the server the server name is the optional local interface to bind
	   to */
	clientNamePtr = findSessionInfo( sessionInfoPtr->attributeList,
									 CRYPT_SESSINFO_CLIENT_NAME );
	serverNamePtr = findSessionInfo( sessionInfoPtr->attributeList,
									 CRYPT_SESSINFO_SERVER_NAME );
	if( isServer( sessionInfoPtr ) )
		{
		if( serverNamePtr != NULL )
			{
			connectInfo->interface = serverNamePtr->value;
			connectInfo->interfaceLength = serverNamePtr->valueLength;
			}
		}
	else
		{
		REQUIRES( serverNamePtr != NULL );

		connectInfo->name = serverNamePtr->value;
		connectInfo->nameLength = serverNamePtr->valueLength;
		if( clientNamePtr != NULL )
			{
			connectInfo->interface = clientNamePtr->value;
			connectInfo->interfaceLength = clientNamePtr->valueLength;
			}
		}

	/* If there's an explicit port set, connect/bind to it, otherwise use the
	   default port for the protocol */
	if( ( portInfoPtr = \
			findSessionInfo( sessionInfoPtr->attributeList,
							 CRYPT_SESSINFO_SERVER_PORT ) ) != NULL )
		connectInfo->port = portInfoPtr->intValue;
	else
		connectInfo->port = sessionInfoPtr->protocolInfo->port;

	return( CRYPT_OK );
	}
Exemplo n.º 27
0
 /** Returns the server name. */
 const irr::core::stringw& getServerName() const
 {
     assert(isServer());
     return m_server_name;
 }   // getServerName
Exemplo n.º 28
0
 /** Returns if this server is registered with the stk server. */
 bool isRegistered() const
 {
     assert(isServer());
     return m_is_registered;
 }   // isRegistered
Exemplo n.º 29
0
	void World::replicate(int index) {
		if(isServer() && m_replicator)
			m_replicator->replicateEntity(index);
	}
shared_ptr<Server> AccountClient::toServer() {
	if (isServer())
		return shared_ptr<Server>(static_cast<Server*>(this));
	else
		return shared_ptr<Server>();
}