SystemAddress TCPInterface::Connect(const char* host, unsigned short remotePort, bool block)
{
	if (block)
	{
		SOCKET sockfd = SocketConnect(host, remotePort);
		if (sockfd==(SOCKET)-1)
			return UNASSIGNED_SYSTEM_ADDRESS;

		RemoteClient *remoteClient;
		remoteClient = new RemoteClient;
		remoteClient->socket=sockfd;
		remoteClient->systemAddress.binaryAddress=inet_addr(host);
		remoteClient->systemAddress.port=remotePort;
		InsertRemoteClient(remoteClient);
		return remoteClient->systemAddress;
	}
	else
	{
		ThisPtrPlusSysAddr *s = new ThisPtrPlusSysAddr;
		s->systemAddress.SetBinaryAddress(host);
		s->systemAddress.port=remotePort;
		s->tcpInterface=this;

		// Start the connection thread
		int errorCode = RakNet::RakThread::Create(ConnectionAttemptLoop, s);
		if (errorCode!=0)
		{
			delete s;
			failedConnectionAttempts.Push(s->systemAddress);
		}
		return UNASSIGNED_SYSTEM_ADDRESS;
	}	
}
static void
tests(void)
{
    int p;
    int fs;
    
    for(p=0; p<NSERVERS;p++) {
    for(int loops=0; loops<NLOOPS; loops++) {
    for(fs=0;fs<2; fs++) {

        ssl_test_handle *client;

        int s;
        OSStatus r;

        s=SocketConnect(servers[p].host, servers[p].port);
        if(s<0) {
            fail("connect failed with err=%d - %s:%d (try %d)", s, servers[p].host, servers[p].port, loops);
            break;
        }

        client = ssl_test_handle_create(s, servers[p].maxprot, fs);

        r=securetransport(client);
        ok(!r, "handshake failed with err=%ld - %s:%d (try %d), false start=%d", (long)r, servers[p].host, servers[p].port, loops, fs);

        close(s);
        free(client);
    } } }
}
示例#3
0
NTSTATUS SocketTest(PVOID Context)
{
    PSOCKET_FACTORY SocketFactory = NULL;
    PSOCKET Socket;
    NTSTATUS Status;
    CHAR HttpResponse[4];
    CHAR HttpRequest[] = "GET / HTTP/1.1\nHost: rbc.ru\nUser-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64)\nAccept: */*\n\n";
    ULONG Sent, Received;
    BOOLEAN Disconnected;

    SocketFactory = NpAlloc(sizeof(*SocketFactory), TESTS_TAG);
    if (!SocketFactory)
        return STATUS_INSUFFICIENT_RESOURCES;

    Status = SocketFactoryInit(SocketFactory);
    if (!NT_SUCCESS(Status)) {
        KLErr("SocketFactoryInit failed Status 0x%x", Status);
        goto socket_factory_free;
    }

    Status = SocketConnect(SocketFactory, L"rbc.ru", L"80", &Socket);
    if (!NT_SUCCESS(Status)) {
        KLErr("SocketConnect failed Status 0x%x", Status);
        goto socket_factory_release;
    }

    Status = SocketSend(Socket, HttpRequest, sizeof(HttpRequest), &Sent);
    if (!NT_SUCCESS(Status)) {
        KLErr("SocketSend failed Status 0x%x", Status);
        goto socket_close;
    }

    if (Sent != sizeof(HttpRequest)) {
        Status = STATUS_UNSUCCESSFUL;
        KLErr("SocketSend failed Sent %d", Sent);
        goto socket_close;
    }

    Status = SocketReceive(Socket, HttpResponse, sizeof(HttpResponse), &Received, &Disconnected);
    if (!NT_SUCCESS(Status)) {
        KLErr("SocketReceive failed Status 0x%x", Status);
        goto socket_close;
    }

    if ((Received != sizeof(HttpResponse)) || Disconnected) {
        KLErr("Received %d Disconnected %d", Received, Disconnected);
        Status = STATUS_UNSUCCESSFUL;
        goto socket_close;
    }

    if (4 != RtlCompareMemory(HttpResponse, "HTTP", 4)) {
        KLErr("Incorrect data received");
        Status = STATUS_UNSUCCESSFUL;
        goto socket_close;
    }

    Status = STATUS_SUCCESS;
socket_close:
    SocketClose(Socket);
socket_factory_release:
    SocketFactoryRelease(SocketFactory);
socket_factory_free:
    NpFree(SocketFactory, TESTS_TAG);
    KLInf("SocketTest Status 0x%x", Status);
    return Status;
}
示例#4
0
SystemAddress TCPInterface::Connect(const char* host, unsigned short remotePort, bool block)
{
    if (threadRunning==false)
        return UNASSIGNED_SYSTEM_ADDRESS;

    int newRemoteClientIndex=-1;
    for (newRemoteClientIndex=0; newRemoteClientIndex < remoteClientsLength; newRemoteClientIndex++)
    {
        remoteClients[newRemoteClientIndex].isActiveMutex.Lock();
        if (remoteClients[newRemoteClientIndex].isActive==false)
        {
            remoteClients[newRemoteClientIndex].SetActive(true);
            remoteClients[newRemoteClientIndex].isActiveMutex.Unlock();
            break;
        }
        remoteClients[newRemoteClientIndex].isActiveMutex.Unlock();
    }
    if (newRemoteClientIndex==-1)
        return UNASSIGNED_SYSTEM_ADDRESS;

    if (block)
    {
        SystemAddress systemAddress;
        systemAddress.binaryAddress=inet_addr(host);
        systemAddress.port=remotePort;
        systemAddress.systemIndex=(SystemIndex) newRemoteClientIndex;

        SOCKET sockfd = SocketConnect(host, remotePort);
        if (sockfd==(SOCKET)-1)
        {
            remoteClients[newRemoteClientIndex].isActiveMutex.Lock();
            remoteClients[newRemoteClientIndex].SetActive(false);
            remoteClients[newRemoteClientIndex].isActiveMutex.Unlock();

            failedConnectionAttemptMutex.Lock();
            failedConnectionAttempts.Push(systemAddress, __FILE__, __LINE__ );
            failedConnectionAttemptMutex.Unlock();

            return UNASSIGNED_SYSTEM_ADDRESS;
        }

        remoteClients[newRemoteClientIndex].socket=sockfd;
        remoteClients[newRemoteClientIndex].systemAddress=systemAddress;

        completedConnectionAttemptMutex.Lock();
        completedConnectionAttempts.Push(remoteClients[newRemoteClientIndex].systemAddress, __FILE__, __LINE__ );
        completedConnectionAttemptMutex.Unlock();

        return remoteClients[newRemoteClientIndex].systemAddress;
    }
    else
    {
        ThisPtrPlusSysAddr *s = RakNet::OP_NEW<ThisPtrPlusSysAddr>( __FILE__, __LINE__ );
        s->systemAddress.SetBinaryAddress(host);
        s->systemAddress.port=remotePort;
        s->systemAddress.systemIndex=(SystemIndex) newRemoteClientIndex;
        s->tcpInterface=this;

        // Start the connection thread
        int errorCode = RakNet::RakThread::Create(ConnectionAttemptLoop, s, threadPriority);
        if (errorCode!=0)
        {
            RakNet::OP_DELETE(s, __FILE__, __LINE__);
            failedConnectionAttempts.Push(s->systemAddress, __FILE__, __LINE__ );
        }
        return UNASSIGNED_SYSTEM_ADDRESS;
    }
}
示例#5
0
static result_t _network_key_get_key( const arguments_t * e )
{
	zuluKey_t key ;
	zuluValue_t * value ;

	socket_t s ;

	result_t result ;

	crypt_buffer_ctx ctx ;
	crypt_buffer_result r ;

	const char * encryption_key      = e->encryption_key ;
	size_t encryption_key_key_length = strlen( encryption_key ) ;

	const char * wallet_name = "zuluCrypt" ;
	const char * wallet_key  = e->wallet_key ;

	size_t n ;

	int k = 0 ;

	char * buffer ;

	memset( &result,'\0',sizeof( result ) ) ;

	memset( &key,'\0',sizeof( zuluKey_t ) ) ;

	key.key_0_length = strlen( e->path ) + 1 ;

	if( key.key_0_length > sizeof( key.key_0 ) ){

		_debug( "error: key length buffer overflow" ) ;
		return result ;
	}else{
		memcpy( key.key_0,e->path,key.key_0_length ) ;
	}

	key.key_1_length = strlen( e->uuid ) + 1 ;

	if( key.key_1_length > sizeof( key.key_1 ) ){

		_debug( "error: key length buffer overflow" ) ;
		return result ;
	}else{
		memcpy( key.key_1,e->uuid,key.key_1_length ) ;
	}

	key.wallet_key_length = strlen( wallet_key ) ;

	if( key.wallet_key_length > sizeof( key.wallet_key ) ){

		_debug( "error: wallet key length buffer overflow" ) ;
		return result ;
	}else{
		memcpy( key.wallet_key,wallet_key,key.wallet_key_length ) ;
	}

	n = strlen( wallet_name ) ;

	if( n > sizeof( key.wallet_name ) ){

		_debug( "error: buffer overflow" ) ;
		return result ;
	}else{
		memcpy( key.wallet_name,wallet_name,n + 1 ) ;
		memcpy( key.application_name,wallet_name,n + 1 ) ;
	}

	while( 1 ){

		_debug( "client connecting ..." ) ;

		s = SocketNet( e->network_address,e->port_number ) ;

		if( SocketConnect( &s ) ){

			_debug( "client connected" ) ;
			break ;
		}else{
			if( k == 10 ){

				_debug( "failed to connect to server" ) ;
				return result ;
			}else{
				sleep( 1 ) ;
				k++ ;
			}
		}
	}

	if( crypt_buffer_init( &ctx,encryption_key,encryption_key_key_length ) ){

		if( crypt_buffer_encrypt( ctx,_cast( &key ),sizeof( zuluKey_t ),&r ) ){

			SocketSendData( s,_cast( r.buffer ),r.length ) ;

			buffer = nullptr ;

			n = SocketGetData( s,&buffer ) ;

			if( buffer ){

				if( crypt_buffer_decrypt( ctx,buffer,n,&r ) ){

					if( r.length == sizeof( zuluValue_t ) ){

						value = ( zuluValue_t * )r.buffer ;

						if( value->key_found ){

							if( value->value_length <= sizeof( result.key ) ){

								result.key_len = value->value_length ;
								memcpy( result.key,value->value,value->value_length ) ;
								result.got_key = 1 ;
							}
						}else{
							_debug( "key not found" ) ;
						}
					}
				}

				free( buffer ) ;
			}
		}

		crypt_buffer_uninit( &ctx ) ;
	}

	SocketClose( &s ) ;

	return result ;
}
示例#6
0
int CommServiceThreadClient( FThread *ptr )
{
	CommService *service = (CommService *)ptr->t_Data;
	
	DEBUG("CommunicationServiceSend Start\n");
	
	struct mq_attr attr;
	char buffer[ MAX_SIZE + 1 ];
/*
	// initialize the queue attributes 
	attr.mq_flags		= 0;
	attr.mq_maxmsg		= MAX_MSG;
	attr.mq_msgsize		= MAX_SIZE;
	attr.mq_curmsgs		= 0;

	DEBUG("QUEUE Before Created SERVER\n");
	// create the message queue 
	mode_t mode  = FLAGS;
	
	
	mode_t omask;
	omask = umask( 0 );
	service->s_inMqfd = mq_open( QUEUE_NAME, (O_CREAT | O_RDONLY), mode, &attr );
	umask( omask );
	
	DEBUG("QUEUE Created SERVER\n");
	*/
	pthread_mutex_lock( &InitMutex ); 
	pthread_cond_signal( &InitCond );    
	pthread_mutex_unlock( &InitMutex );  
	
	//
	// atm we only read FC connections
	//
	
	struct PropertiesLibrary *plib = NULL;
	char *servers = NULL;
	Props *prop = NULL;
	
	if( ( plib = (struct PropertiesLibrary *)LibraryOpen( SLIB, "properties.library", 0 ) ) != NULL )
	{
		char coresPath[ 1024 ];
		sprintf( coresPath, "%s/cfg/cfg.ini", getenv( "FRIEND_HOME" ) );
		
		prop = plib->Open( coresPath  );
		if( prop != NULL)
		{
			DEBUG("[Userlibrary] reading login\n");
			servers = plib->ReadString( prop, "Cores:servers", "" );
			DEBUG("[Userlibrary] servers %s\n", servers );
		}
		//DEBUG("PROPERTIES LIBRARY OPENED, poitner to props %p!   %s  %s  %s  %s  %d\n", prop, login, pass, host, dbname, port );
	}
		
	if( servers != NULL )
	{
		char *token;
		
		DEBUG("Server list found %s\n", servers );
   
		// get the first token 
		token = strtok( servers, SERVER_SPLIT_SIGN );
		// walk through other tokens 
		while( token != NULL ) 
		{
			CommFCConnection *newcon;
			
			char *address = NULL;
			char *name = NULL;
			
			char *pos = strchr( token, SERVER_NAME_SPLIT_SING );
			if( pos != NULL )
			{
				*pos = 0;
				address = token;
				name = ++pos;
				
			}else{
				address = token;
				name = token;
			}
			
			DEBUG("New connection found address : %s name : %s\n", address, name );
				
			//TODO
				
			if( ( newcon = CommFCConnectionNew( address, name ) ) != NULL )
			{
				DEBUG("Outgoing connection mem allocated\n");
				
				newcon->cfcc_Socket = SocketOpen( FRIEND_COMMUNICATION_PORT, SOCKET_TYPE_CLIENT );
				
				DEBUG("Outgoing connection created\n");
				
				if( SocketConnect( newcon->cfcc_Socket, address ) == 0 )
				{
					DEBUG("Connection setup with server : %s\n", token );
					if( service->s_FCConnections == NULL )
					{
						service->s_FCConnections = newcon;
					}
					else
					{	// we already have connections, we must add them to the end of list
						CommFCConnection *lc = service->s_FCConnections;
						while( lc->node.mln_Succ != NULL )
						{
							lc = (CommFCConnection *)lc->node.mln_Succ;
						}
						lc->node.mln_Succ = (MinNode *) newcon;
					}
					
					//
					// sockets connected, we create now special message where we sent ID of our host
					//
					
					DEBUG("Generate Data Form\n");
					DataForm * df = DataFormNew( NULL );
					DEBUG("DataForm Created\n");
					FriendCoreManager *fcm = (FriendCoreManager *) service->s_FCM;
					DataFormAdd( &df, (BYTE *)fcm->fcm_ID, FRIEND_CORE_MANAGER_ID_SIZE );
					//INFO("Message created name byte %c%c%c%c\n", fcm->fcm_ID[32], fcm->fcm_ID[33], fcm->fcm_ID[34], fcm->fcm_ID[35]	);
					
					SocketWrite( newcon->cfcc_Socket, (char *)df, df->df_Size );
					
					DEBUG("Message sent\n");
					DataFormDelete( df );
					
				}
				else
				{
					close( newcon->cfcc_Socket->fd );
					FFree( newcon->cfcc_Socket );
					FFree( newcon );
					ERROR("Cannot setup socket connection!\n");
				}
			}
				
			DEBUG( " %s\n", token );
			
			token = strtok( NULL, "," );
		}
		
		DEBUG("All tokens passed\n");
		
	}
	else
	{	// servers == NULL
	}
	
	if( plib != NULL && prop != NULL )
	{
		plib->Close( prop );
	}
	
	if( plib != NULL )
	{
		LibraryClose( (struct Library *)plib );
	}
	DEBUG("CommunicationServiceClient start\n");
	
	//
	// we should ask for information from connection
	//
	
	// messages get and pass to destination
	
	//int queueFd = mq_ msgqToFd( service->s_inMqfd );
	
	struct timeval tv;
	fd_set writeToServ;
	fd_set readFromServ;
	
	ULONG idMax = 0;
	if( service->s_sendPipe[ 0 ] > idMax ) idMax = service->s_sendPipe[ 0 ];
	if( service->s_sendPipe[ 1 ] > idMax ) idMax = service->s_sendPipe[ 1 ];
	if( service->s_recvPipe[ 0 ] > idMax ) idMax = service->s_recvPipe[ 0 ];
	if( service->s_recvPipe[ 1 ] > idMax ) idMax = service->s_recvPipe[ 1 ];
	
	{
		CommFCConnection *lc = service->s_FCConnections;
		while( lc != NULL )
		{
			if( lc->cfcc_Socket > idMax )
			{
				idMax = lc->cfcc_Socket->fd;
			}
			lc = (CommFCConnection *)lc->node.mln_Succ;
		}
	}
	
	DEBUG("IDMAX SET TO %ld\n", idMax );
	/*
	if( service->s_inMqfd != -1 )
	{*/
		while( service->s_Cam.cam_Quit != 1 )
		{
			FD_ZERO( &writeToServ );
			FD_ZERO( &readFromServ );
			FD_SET( service->s_sendPipe[ 0 ] , &writeToServ );
			//FD_SET( lc->cfcc_Socket , &readFromServ );
			
			tv.tv_sec = 0;
			tv.tv_usec = 10000000;

			//ret = 0;

			int ret = select( idMax+1, &writeToServ, NULL, NULL, &tv );
			
			// handle message
			
			if( ret > 0 )
			{
				int rets = read( service->s_sendPipe[ 0 ], buffer, MAX_SIZE );
				//ERROR("DATAREADED! %d\n", rets );
				
				buffer[ rets ] = '\0';
				//TODO
				// we should read from QUEUE, check destination server and send message
				//
/*
				CommFCConnection *lc = service->s_FCConnections;
				while( lc != NULL )
				{
					//TODO test message , should be removed
					SocketWrite( lc->cfcc_Socket, buffer, rets );//"hello", 5 );
					DEBUG("CommunicationServiceClient Sending message hello\n");
					int sockReadSize = 0;
					
					sockReadSize = SocketRead( lc->cfcc_Socket, buffer, MAX_SIZE, 0 );
					int writeSize = write( service->s_recvPipe[ 1 ], buffer, sockReadSize );
					
					DEBUG("Message received '%s'\n", buffer );
					lc = (CommFCConnection *)lc->node.mln_Succ;
				}*/
				
				}else{
				
				}
			//usleep( 10000000 );
			//DEBUG("CommunicationServiceClient Thread at work %d\n", ret );
		
			ssize_t bytes_read;

			// receive the message 
			//bytes_read = mq_receive( service->s_inMqfd, buffer, MAX_SIZE, NULL );
			//CHECK(bytes_read >= 0);
			/*
			*/
		}
		/*
	}else{
		ERROR("Cannot create QUEUE!\n");
	}*/
	
	DEBUG("CommunicationService close\n");
	
	CommFCConnection *lc = service->s_FCConnections;
	CommFCConnection *rlc = service->s_FCConnections;
	while( lc != NULL )
	{
		rlc = lc;
		lc = (CommFCConnection *) lc->node.mln_Succ;
		
		DEBUG("Closing output connection\n");
		
		SocketClose( rlc->cfcc_Socket );

		CommFCConnectionDelete( rlc );
	}
	
		// closing queue
		
	//mq_close( service->s_inMqfd );
		
	//mq_unlink( QUEUE_NAME );
	
	return 0;
}
示例#7
0
/**
 * @NOTE if #flags.protocol_version is CF_PROTOCOL_UNDEFINED, then classic
 *       protocol is used by default.
 */
AgentConnection *ServerConnection(const char *server, const char *port,
                                  unsigned int connect_timeout,
                                  ConnectionFlags flags, int *err)
{
    AgentConnection *conn = NULL;
    int ret;
    *err = 0;

    conn = NewAgentConn(server, port, flags);

#if !defined(__MINGW32__)
    signal(SIGPIPE, SIG_IGN);

    sigset_t signal_mask;
    sigemptyset(&signal_mask);
    sigaddset(&signal_mask, SIGPIPE);
    pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);

    /* FIXME: username is local */
    GetCurrentUserName(conn->username, sizeof(conn->username));
#else
    /* Always say "root" as username from windows. */
    strlcpy(conn->username, "root", sizeof(conn->username));
#endif

    if (port == NULL || *port == '\0')
    {
        port = CFENGINE_PORT_STR;
    }

    char txtaddr[CF_MAX_IP_LEN] = "";
    conn->conn_info->sd = SocketConnect(server, port, connect_timeout,
                                        flags.force_ipv4,
                                        txtaddr, sizeof(txtaddr));
    if (conn->conn_info->sd == -1)
    {
        Log(LOG_LEVEL_INFO, "No server is responding on port: %s",
            port);
        DisconnectServer(conn);
        *err = -1;
        return NULL;
    }

    assert(sizeof(conn->remoteip) >= sizeof(txtaddr));
    strcpy(conn->remoteip, txtaddr);

    switch (flags.protocol_version)
    {
    case CF_PROTOCOL_UNDEFINED:
    case CF_PROTOCOL_TLS:

        /* Set the version to request during protocol negotiation. After
         * TLSConnect() it will have the version we finally ended up with. */
        conn->conn_info->protocol = CF_PROTOCOL_LATEST;

        ret = TLSConnect(conn->conn_info, flags.trust_server,
                         conn->remoteip, conn->username);

        if (ret == -1)                                      /* Error */
        {
            DisconnectServer(conn);
            *err = -1;
            return NULL;
        }
        else if (ret == 0)                             /* Auth/ID error */
        {
            DisconnectServer(conn);
            errno = EPERM;
            *err = -2;
            return NULL;
        }
        assert(ret == 1);

        conn->conn_info->status = CONNECTIONINFO_STATUS_ESTABLISHED;
        LastSaw1(conn->remoteip, KeyPrintableHash(conn->conn_info->remote_key),
                 LAST_SEEN_ROLE_CONNECT);
        break;

    case CF_PROTOCOL_CLASSIC:

        conn->conn_info->protocol = CF_PROTOCOL_CLASSIC;
        conn->encryption_type = CfEnterpriseOptions();

        if (!IdentifyAgent(conn->conn_info))
        {
            Log(LOG_LEVEL_ERR, "Id-authentication for '%s' failed", VFQNAME);
            errno = EPERM;
            DisconnectServer(conn);
            *err = -2; // auth err
            return NULL;
        }

        if (!AuthenticateAgent(conn, flags.trust_server))
        {
            Log(LOG_LEVEL_ERR, "Authentication dialogue with '%s' failed", server);
            errno = EPERM;
            DisconnectServer(conn);
            *err = -2; // auth err
            return NULL;
        }
        conn->conn_info->status = CONNECTIONINFO_STATUS_ESTABLISHED;
        break;

    default:
        ProgrammingError("ServerConnection: ProtocolVersion %d!",
                         flags.protocol_version);
    }

    conn->authenticated = true;
    return conn;
}