Beispiel #1
0
        private void StartDataClient(Guid id, ITransport transport)
        {
            if (this.disposed)
            {
                return;
            }

            var dataClient = transport.Connect(this.host);

            dataClient.WriteSessionId(id);

            var thread = new Thread(new ThreadStart(() =>
            {
                try
                {
                    while (!this.disposed)
                    {
                        var data     = dataClient.ReadMessage();
                        var envelope = data.Item1;
                        var message  = data.Item2;

                        this.replayStart = envelope.OriginatingTime.Ticks + 1; // for restart

                        if (this.allowSequenceRestart)
                        {
                            // patch sequence ID resents (due to exporter process restart)
                            var sourceId   = envelope.SourceId;
                            var sequenceId = envelope.SequenceId;
                            if (!this.lastSequenceIdPerStream.ContainsKey(sourceId))
                            {
                                this.lastSequenceIdPerStream.Add(sourceId, sequenceId - 1); // tracking new source
                            }

                            var lastSequenceId = this.lastSequenceIdPerStream[sourceId];
                            if (lastSequenceId >= sequenceId)
                            {
                                sequenceId = lastSequenceId + 1;
                                envelope   = new Envelope(envelope.OriginatingTime, envelope.Time, sourceId, sequenceId);
                            }

                            this.lastSequenceIdPerStream[sourceId] = sequenceId;
                        }

                        this.storeWriter.Write(new BufferReader(message), envelope);
                        Trace.WriteLine($"RemoteImporter data written (Stream={envelope.SourceId}, ID={id}, SequenceId={envelope.SequenceId}, Size={message.Length})");
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine($"RemoteImporter data connection error (Message={ex.Message}, ID={id})");
                    dataClient.Dispose();
                }
            }))
            {
                IsBackground = true
            };

            thread.Start();
            this.dataClientThread = thread;
        }
        public void Connect(SocketConnectionParameters parameters)
        {
            if (_connection != null)
            {
                _connection.Disconnect();
            }

            _connection = _transport.Connect(parameters.IPAddress, parameters.Port);
        }
Beispiel #3
0
 public void Start()
 {
     if (!_receiverWorker.IsBusy)
     {
         _transport.Connect();
         _receiverWorker.RunWorkerAsync();
         _commandsWorker.RunWorkerAsync();
     }
 }
Beispiel #4
0
        private ITransport CreateTransport(I2PRouterInfo ri)
        {
            ITransport transport = null;

            try
            {
                var pproviders = TransportProtocols
                                 .Select(tp => new
                {
                    Provider   = tp,
                    Capability = tp.ContactCapability(ri)
                })
                                 .Where(tp => tp.Capability != ProtocolCapabilities.None)
                                 .GroupBy(tp => tp.Capability)
                                 .OrderByDescending(cc => (int)cc.Key);

                var pprovider = pproviders.FirstOrDefault()?.Random();

                if (pprovider == null)
                {
                    Logging.LogTransport(
                        $"TransportProvider: CreateTransport: No usable address found for {ri.Identity.IdentHash.Id32Short}!");
                    return(null);
                }

                transport = pprovider.Provider.AddSession(ri);

                Logging.LogTransport($"TransportProvider: Creating new {transport} to {ri.Identity.IdentHash.Id32Short}");

                AddTransport(transport);
                transport.Connect();

                var dstore = new DatabaseStoreMessage(RouterContext.Inst.MyRouterInfo);
                transport.Send(dstore);
            }
            catch (Exception ex)
            {
#if LOG_MUCH_TRANSPORT
                Logging.LogTransport(ex);
                Logging.LogTransport("TransportProvider: CreateTransport stack trace: " + System.Environment.StackTrace);
#else
                Logging.LogTransport($"TransportProvider: Exception [{ex.GetType()}] " +
                                     $"'{ex.Message}' to {ri.Identity.IdentHash.Id32Short}.");
#endif
                if (transport != null)
                {
                    Remove(transport);
                }
                throw;
            }

            return(transport);
        }
Beispiel #5
0
        private async Task <Scene> GetScene(string sceneId, SceneEndpoint ci)
        {
            if (_serverConnection == null)
            {
                if (!_transport.IsRunning)
                {
                    cts = new CancellationTokenSource();
                    _transport.Start("client", new ConnectionHandler(), cts.Token, null, (ushort)(_maxPeers + 1));
                }
                if (!ci.TokenData.Endpoints.ContainsKey(_transport.Name))
                {
                    throw new InvalidOperationException($"No endpoint available on server for transport '{_transport.Name}'");
                }
                _serverConnection = await _transport.Connect(ci.TokenData.Endpoints[_transport.Name]);

                foreach (var kvp in _metadata)
                {
                    _serverConnection.Metadata[kvp.Key] = kvp.Value;
                }
                await UpdateServerMetadata();

                if (ci.TokenData.Version > 0)
                {
                    StartSyncClock();
                }
            }
            var parameter = new Stormancer.Dto.SceneInfosRequestDto {
                Metadata = _serverConnection.Metadata, Token = ci.Token
            };

            var result = await SendSystemRequest <Stormancer.Dto.SceneInfosRequestDto, Stormancer.Dto.SceneInfosDto>((byte)SystemRequestIDTypes.ID_GET_SCENE_INFOS, parameter);

            if (_serverConnection.GetComponent <ISerializer>() == null)
            {
                if (result.SelectedSerializer == null)
                {
                    throw new InvalidOperationException("No seralizer selected.");
                }
                _serverConnection.RegisterComponent(_serializers[result.SelectedSerializer]);
                _serverConnection.Metadata.Add("serializer", result.SelectedSerializer);
            }
            await UpdateServerMetadata();

            var scene = new Scene(this._serverConnection, this, _pluginCtx.BuildingSceneResolver, sceneId, ci.Token, result);

            if (_pluginCtx.SceneCreated != null)
            {
                _pluginCtx.SceneCreated(scene);
            }
            return(scene);
        }
Beispiel #6
0
 private void Connect(object state)
 {
     lock (_result)
     {
         try
         {
             _transport.Connect(_url);
         }
         catch (Exception ex)
         {
             _transportException = ex;
         }
         End();
     }
 }
        /// <summary>
        /// Connects the client to the specified url
        /// </summary>
        public void Connect(string url)
        {
            // check object state
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            if (_transport == null)
            {
                _transport = CreateTransport();
                _transport.Connect(url);
                _url = url;
            }
        }
Beispiel #8
0
        public async Task Connect()
        {
            outputThread              = new Thread(new ThreadStart(ProcessOutput));
            outputThread.Name         = "Microcontroller output";
            outputThread.IsBackground = true;
            outputThread.Start();

            inputThread              = new Thread(new ThreadStart(ProcessInput));
            inputThread.Name         = "Microcontroller input";
            inputThread.IsBackground = true;
            inputThread.Start();

            transport.Connect();

            await RemoteReset();

            LocalReset();
        }
        private void MakeBrokerConnection(IBrokerInfo brokerDetail)
        {
            try
            {
                _stateManager     = new AMQStateManager();
                _protocolListener = new AMQProtocolListener(this, _stateManager);
                _protocolListener.AddFrameListener(_stateManager);

                /*
                 * // Currently there is only one transport option - BlockingSocket.
                 * String assemblyName = "Apache.Qpid.Client.Transport.Socket.Blocking.dll";
                 * String transportType = "Apache.Qpid.Client.Transport.Socket.Blocking.BlockingSocketTransport";
                 *
                 * // Load the transport assembly dynamically.
                 * _transport = LoadTransportFromAssembly(brokerDetail.getHost(), brokerDetail.getPort(), assemblyName, transportType);
                 */

                _transport = new BlockingSocketTransport();

                // Connect.
                _transport.Connect(brokerDetail, this);
                _protocolWriter  = new ProtocolWriter(_transport.ProtocolWriter, _protocolListener);
                _protocolSession = new AMQProtocolSession(_transport.ProtocolWriter, _transport, this);
                _protocolListener.ProtocolSession = _protocolSession;

                // Now start the connection "handshake".
                _transport.ProtocolWriter.Write(new ProtocolInitiation());

                // Blocks until the connection has been opened.
                _stateManager.AttainState(AMQState.CONNECTION_OPEN);

                _failoverPolicy.attainedConnection();

                // XXX: Again this should be changed to a suitable notify.
                _connected = true;
            }
            catch (AMQException e)
            {
                _lastAMQException = e;
                throw; // rethrow
            }
        }
Beispiel #10
0
        public void Connect()
        {
            // 2 requiered headers + 3 optional
            var frame = new Frame(5);

            frame.Type = FrameType.CONNECT;
            frame.Headers.Add(AcceptVersion.ToKeyValue());
            frame.Headers["host"] = Host;
            if (!string.IsNullOrWhiteSpace(Login))
            {
                frame.Headers["login"] = Login;
            }
            if (!string.IsNullOrWhiteSpace(Passcode))
            {
                frame.Headers["passcode"] = Passcode;
            }
            frame.Headers["heart-beat"] = string.Format("{0},{1}", OutgoingHeartbeat, IncomingHeartbeat);
            transport.Connect();
            transport.Send(frame.ToString());
        }
Beispiel #11
0
        public void Connect()
        {
            try
            {
                var state = (StompConnectionState)Interlocked.CompareExchange(
                    ref _state,
                    value: (int)StompConnectionState.Connecting,
                    comparand: (int)StompConnectionState.Disconnected
                    );

                switch (state)
                {
                case StompConnectionState.Disconnected:
                    // Соединение было разорвано, сейчас состояние - Connecting
                    // Текущий поток должен выполнить подключение
                    OnStateChanged(StompConnectionState.Connecting);
                    _transport = _transportFactory.Create(_brokerUri, this);
                    _transport.Connect();
                    break;

                case StompConnectionState.Connecting:
                    // Соединение устанавливается, следует дождаться изменения состояния
                    while (State == StompConnectionState.Connecting)
                    {
                    }
                    break;

                case StompConnectionState.Disconnecting:
                    throw new StompConnectionException("Unable to connect while disconnecting");

                default:
                    return;
                }
            }
            catch (Exception e)
            {
                _logger.Error("Error while connecting", e);
                throw;
            }
        }
Beispiel #12
0
 private void Connect()
 {
     if (_transport.State == TransportState.Closed)
     {
         m_mutex.Wait();
         try
         {
             if (_transport.State == TransportState.Closed)
             {
                 _transport.Connect();
                 if (_optionsAccessor.Password != null)
                 {
                     var response = Execute(new Request(CommandType.Auth, _optionsAccessor.Password));
                     VerifyAuthentication(response);
                 }
             }
         }
         finally
         {
             m_mutex.Release();
         }
     }
 }
Beispiel #13
0
        internal void Add(ITransport transport, TransportCallback connectCallback)
        {
            try {
                // XXX: This should be negotiated as part of the initial handshake.
                transport.Encryptor = new AESTransportEncryptor();

                transports.Add(transport);

                if (NewTransportAdded != null)
                {
                    NewTransportAdded(transport);
                }

                LoggingService.LogInfo($"Transport {transport} added");

                if (transport.Incoming)
                {
                    if (connectCallback != null)
                    {
                        throw new ArgumentException("You can only specify a ConnectCallback for outoging connections!");
                    }

                    if (transport.Encryptor != null)
                    {
                        var dh = new DiffieHellmanManaged();

                        var keyxBytes = new byte[transport.Encryptor.KeyExchangeLength];
                        transport.Receive(keyxBytes, 0, keyxBytes.Length);
                        keyxBytes = dh.DecryptKeyExchange(keyxBytes);

                        var keyBytes = new byte[transport.Encryptor.KeySize];
                        var ivBytes  = new byte[transport.Encryptor.IvSize];
                        Array.Copy(keyxBytes, 0, keyBytes, 0, keyBytes.Length);
                        Array.Copy(keyxBytes, keyBytes.Length, ivBytes, 0, ivBytes.Length);

                        keyxBytes = dh.CreateKeyExchange();
                        transport.Send(keyxBytes, 0, keyxBytes.Length);

                        transport.Encryptor.SetKey(keyBytes, ivBytes);
                    }

                    //Receive connection type, which is a ulong (8 bytes)
                    var responseBuffer = new byte[8];
                    transport.Receive(responseBuffer, 0, 8);
                    var connectionType = EndianBitConverter.ToUInt64(responseBuffer, 0);

                    // Recieve network ID (64 bytes)
                    responseBuffer = new byte[64];
                    transport.Receive(responseBuffer, 0, 64);
                    var networkId = EndianBitConverter.ToString(responseBuffer).Replace("-", "");

                    // Match to one of our known networks!
                    foreach (var network in core.Networks)
                    {
                        if (network.NetworkID == networkId)
                        {
                            transport.Network = network;
                        }
                    }

                    if (transport.Network == null)
                    {
                        throw new Exception($"Unknown network: {networkId}.");
                    }

                    transport.ConnectionType = connectionType;

                    if (connectionType == ConnectionType.NodeConnection)
                    {
                        var connection = new LocalNodeConnection(transport);
                        transport.Operation = connection;
                        transport.Network.AddConnection(connection);
                        connection.Start();
                    }
                    else if (connectionType == ConnectionType.TransferConnection)
                    {
                        core.FileTransferManager.NewIncomingConnection(transport);
                    }
                    else
                    {
                        throw new Exception($"Unknown connection type: {connectionType}.");
                    }
                }
                else
                {
                    if (connectCallback == null)
                    {
                        throw new ArgumentNullException(nameof(connectCallback));
                    }

                    connectCallbacks.Add(transport, connectCallback);

                    LoggingService.LogInfo("Transport {0} connecting...", transport);

                    TransportCallback callback = OnConnected;
                    transport.Connect(callback);
                }
            } catch (Exception ex) {
                transport.Disconnect(ex);
                RaiseTransportError(transport, ex);
            }
        }
Beispiel #14
0
 /// <summary>
 /// Connects to the registry end point
 /// </summary>
 public void Connect(SslProtocols sslProtocols = SslProtocols.Tls)
 {
     transport.Connect(sslProtocols);
     transport.Read();
 }
Beispiel #15
0
        public void Add(ITransport transport, TransportCallback connectCallback)
        {
            try {
                // XXX: This should be negotiated as part of the initial handshake.
                transport.Encryptor = new AESTransportEncryptor();

                transports.Add(transport);

                NewTransportAdded?.Invoke(this, new TransportEventArgs(transport));

                this.loggingService.LogInfo(String.Format("Transport {0} added", transport.ToString()));

                if (transport.Incoming == true)
                {
                    if (connectCallback != null)
                    {
                        throw new ArgumentException("You can only specify a ConnectCallback for outoging connections!");
                    }

                    if (transport.Encryptor != null)
                    {
                        DiffieHellmanManaged dh = new DiffieHellmanManaged();

                        byte[] keyxBytes = new byte[transport.Encryptor.KeyExchangeLength];
                        transport.Receive(keyxBytes, 0, keyxBytes.Length);
                        keyxBytes = dh.DecryptKeyExchange(keyxBytes);

                        byte[] keyBytes = new byte[transport.Encryptor.KeySize];
                        byte[] ivBytes  = new byte[transport.Encryptor.IvSize];
                        Array.Copy(keyxBytes, 0, keyBytes, 0, keyBytes.Length);
                        Array.Copy(keyxBytes, keyBytes.Length, ivBytes, 0, ivBytes.Length);

                        keyxBytes = dh.CreateKeyExchange();
                        transport.Send(keyxBytes, 0, keyxBytes.Length);

                        transport.Encryptor.SetKey(keyBytes, ivBytes);
                    }

                    //Receive connection type, which is a ulong (8 bytes)
                    byte[] responseBuffer = new byte[8];
                    transport.Receive(responseBuffer, 0, 8);
                    ulong connectionType = EndianBitConverter.ToUInt64(responseBuffer, 0);

                    // Recieve network ID (64 bytes)
                    responseBuffer = new byte[64];
                    transport.Receive(responseBuffer, 0, 64);
                    string networkId = EndianBitConverter.ToString(responseBuffer).Replace("-", "");

                    // Match to one of our known networks!
                    foreach (Network network in Core.Networks)
                    {
                        if (network.NetworkID == networkId)
                        {
                            transport.Network = network;
                        }
                    }

                    if (transport.Network == null)
                    {
                        throw new Exception(String.Format("Unknown network: {0}.", networkId));
                    }

                    transport.ConnectionType = connectionType;

                    if (connectionType == ConnectionType.NodeConnection)
                    {
                        LocalNodeConnection connection = new LocalNodeConnection(transport);
                        transport.Operation = connection;
                        transport.Network.AddConnection(connection);
                        connection.Start();
                    }
                    else if (connectionType == ConnectionType.TransferConnection)
                    {
                        this.fileTransferManager.HandleIncomingTransport(transport);
                    }
                    else
                    {
                        throw new Exception(String.Format("Unknown connection type: {0}.",
                                                          connectionType.ToString()));
                    }
                }
                else
                {
                    if (connectCallback == null)
                    {
                        throw new ArgumentNullException("connectCallback");
                    }

                    connectCallbacks.Add(transport, connectCallback);

                    this.loggingService.LogInfo("Transport {0} connecting...", transport);

                    TransportCallback callback = new TransportCallback(OnConnected);
                    transport.Connect(callback);
                }
            } catch (Exception ex) {
                transport.Disconnect(ex);
                RaiseTransportError(transport, ex);
            }
        }
Beispiel #16
0
 /// Make an out going connection to this given host on the given port.
 /// There is no return value on this call because all returns are done via callback.
 public void Connect(string host, int port)
 {
     _transport.Connect(host, port);
 }
Beispiel #17
0
 public void Connect()
 {
     transport.Connect(this);
 }
		/// <summary>
		/// Connects the client to the specified url
		/// </summary>
		public void Connect(string url)
		{
			// check object state
			if (_disposed)
				throw new ObjectDisposedException(GetType().FullName);

			if (_transport == null)
			{
				_transport = CreateTransport();
				_transport.Connect(url);
				_url = url;
			}
		}
Beispiel #19
0
        private void MakeBrokerConnection(IBrokerInfo brokerDetail)
        {
            try
            {
                _stateManager = new AMQStateManager();
                _protocolListener = new AMQProtocolListener(this, _stateManager);
                _protocolListener.AddFrameListener(_stateManager);

                /*
                // Currently there is only one transport option - BlockingSocket.
                String assemblyName = "Apache.Qpid.Client.Transport.Socket.Blocking.dll";
                String transportType = "Apache.Qpid.Client.Transport.Socket.Blocking.BlockingSocketTransport";

                // Load the transport assembly dynamically.
                _transport = LoadTransportFromAssembly(brokerDetail.getHost(), brokerDetail.getPort(), assemblyName, transportType);
                */

                _transport = new BlockingSocketTransport();
                
                // Connect.
                _transport.Connect(brokerDetail, this);                
                _protocolWriter = new ProtocolWriter(_transport.ProtocolWriter, _protocolListener);
                _protocolSession = new AMQProtocolSession(_transport.ProtocolWriter, _transport, this);
                _protocolListener.ProtocolSession = _protocolSession;

                // Now start the connection "handshake".
                _transport.ProtocolWriter.Write(new ProtocolInitiation());

                // Blocks until the connection has been opened.
                _stateManager.AttainState(AMQState.CONNECTION_OPEN);

                _failoverPolicy.attainedConnection();

                // XXX: Again this should be changed to a suitable notify.
                _connected = true;
            }
            catch (AMQException e)
            {
                _lastAMQException = e;
                throw; // rethrow
            }
        }
 public void Connect()
 {
     _wrappedTransport.Connect();
 }
Beispiel #21
0
 public void ConnectUser(string address, string port)
 {
     _transport.Connect(address, port);
 }
Beispiel #22
0
 public void Connect(string url)
 {
     _transport.Connect(url);
 }
Beispiel #23
0
 /// <summary> Connects to a transport layer defined through the current settings. </summary>
 /// <returns> true if it succeeds, false if it fails. </returns>
 public bool Connect()
 {
     return(_transport.Connect());
 }
Beispiel #24
0
 /// <summary> Connects to a transport layer defined through the current settings. </summary>
 /// <returns> true if it succeeds, false if it fails. </returns>
 public bool Connect()
 {
     return(!_transport.IsConnected() && _transport.Connect());
 }
Beispiel #25
0
 public void Connect(SslProtocols sslProtocols = SslProtocols.None)
 {
     transport.Connect(sslProtocols);
 }
Beispiel #26
0
 public void Connect() => _transport.Connect();
Beispiel #27
0
 /// <summary>
 ///   Connects to the server on the specified address.
 /// </summary>
 /// <param name = "address">The address.</param>
 public void Connect()
 {
     _transport.OnOpen    += () => _transport.Send(_serializer.Serialize(new StompMessage("CONNECT")));
     _transport.OnMessage += (msg) => HandleMessage(_serializer.Deserialize(msg));
     _transport.Connect();
 }
Beispiel #28
0
        internal void Add(ITransport transport, TransportCallback connectCallback)
        {
            try {
                // XXX: This should be negotiated as part of the initial handshake.
                transport.Encryptor = new AESTransportEncryptor();

                transports.Add (transport);

                if (NewTransportAdded != null)
                    NewTransportAdded (transport);

                LoggingService.LogInfo(String.Format ("Transport {0} added", transport.ToString()));

                if (transport.Incoming == true) {
                    if (connectCallback != null)
                        throw new ArgumentException ("You can only specify a ConnectCallback for outoging connections!");

                    if (transport.Encryptor != null) {
                        DiffieHellmanManaged dh = new DiffieHellmanManaged ();

                        byte[] keyxBytes = new byte[transport.Encryptor.KeyExchangeLength];
                        transport.Receive (keyxBytes, 0, keyxBytes.Length);
                        keyxBytes = dh.DecryptKeyExchange (keyxBytes);

                        byte[] keyBytes = new byte[transport.Encryptor.KeySize];
                        byte[] ivBytes = new byte[transport.Encryptor.IvSize];
                        Array.Copy (keyxBytes, 0, keyBytes, 0, keyBytes.Length);
                        Array.Copy (keyxBytes, keyBytes.Length, ivBytes, 0, ivBytes.Length);

                        keyxBytes = dh.CreateKeyExchange ();
                        transport.Send (keyxBytes, 0, keyxBytes.Length);

                        transport.Encryptor.SetKey(keyBytes, ivBytes);
                    }

                    //Receive connection type, which is a ulong (8 bytes)
                    byte[] responseBuffer = new byte[8];
                        transport.Receive (responseBuffer, 0, 8);
                    ulong connectionType = EndianBitConverter.ToUInt64 (responseBuffer, 0);

                    // Recieve network ID (64 bytes)
                    responseBuffer = new byte[64];
                    transport.Receive (responseBuffer, 0, 64);
                    string networkId = EndianBitConverter.ToString (responseBuffer).Replace ("-", "");

                    // Match to one of our known networks!
                    foreach (Network network in Core.Networks) {
                        if (network.NetworkID == networkId) {
                            transport.Network = network;
                        }
                    }

                    if (transport.Network == null) {
                        throw new Exception (String.Format ("Unknown network: {0}.", networkId));
                    }

                    transport.ConnectionType = connectionType;

                    if (connectionType == ConnectionType.NodeConnection) {
                        LocalNodeConnection connection = new LocalNodeConnection(transport);
                        transport.Operation = connection;
                        transport.Network.AddConnection(connection);
                        connection.Start();
                    } else if (connectionType == ConnectionType.TransferConnection) {

                        Core.FileTransferManager.NewIncomingConnection(transport);

                    } else {
                        throw new Exception(String.Format("Unknown connection type: {0}.",
                                                          connectionType.ToString()));
                    }

                } else {
                    if (connectCallback == null) {
                        throw new ArgumentNullException("connectCallback");
                    }

                    connectCallbacks.Add (transport, connectCallback);

                    LoggingService.LogInfo("Transport {0} connecting...", transport);

                    TransportCallback callback = new TransportCallback (OnConnected);
                    transport.Connect (callback);
                }
            } catch (Exception ex) {
                transport.Disconnect (ex);
                RaiseTransportError(transport, ex);
            }
        }
Beispiel #29
0
 public void Connect(string hostname, int port)
 {
     clientmode = true;
     transport.Connect(new IPEndPoint(Dns.GetHostAddresses(hostname)[0], port));
     Send("ST_Connect", new byte[1], 0, ControlChannel);
 }