Пример #1
0
        public void DisposePassThrough()
        {
            var stream = MockRepository.GenerateStrictMock <Stream>();

            stream.Expect(s => s.Dispose()).Repeat.Once();
            var channelStream = new ChannelStream(stream);

            channelStream.Dispose();
            stream.VerifyAllExpectations();
        }
Пример #2
0
        public void DisposeCustomDisposeActionGetsCalledOnDispose()
        {
            var stream        = MockRepository.GenerateStub <Stream>();
            var called        = false;
            var channelStream = new ChannelStream(stream, () => { called = true; });

            Assert.False(called, "Custom dispose action should not have been called yet.");
            channelStream.Dispose();
            Assert.True(called, "Custom dispose action should have been called.");
        }
Пример #3
0
        public void DisposeDoesNotPassThroughIfCustomDisposeAction()
        {
            var stream = MockRepository.GenerateStrictMock <Stream>();

            stream.Expect(s => s.Dispose()).Repeat.Never();
            var channelStream = new ChannelStream(stream, () => { });

            channelStream.Dispose();
            stream.VerifyAllExpectations();
        }
Пример #4
0
        public async Task <string> GetStreamUrlAsync(ChannelStream channelStream)
        {
            StreamInfo streamInfo = new StreamInfo();

            streamInfo.Provider  = channelStream.Provider;
            streamInfo.ChannelId = channelStream.ChannelId;
            streamInfo.Title     = channelStream.Title;
            streamInfo.Url       = channelStream.Url;

            return(await GetStreamUrlAsync(streamInfo));
        }
Пример #5
0
        public void WritePassThrough()
        {
            var stream = MockRepository.GenerateMock <Stream>();

            byte[] buffer = new byte[1];
            stream.Expect(s => s.Write(buffer, 0, 1)).Repeat.Once();
            var channelStream = new ChannelStream(stream);

            channelStream.Write(buffer, 0, 1);
            stream.VerifyAllExpectations();
        }
Пример #6
0
        public void ReadPassThrough()
        {
            var stream = MockRepository.GenerateStrictMock <Stream>();

            byte[] buffer = new byte[1];
            stream.Expect(s => s.Read(buffer, 0, 1)).Repeat.Once().Return(42);
            var channelStream = new ChannelStream(stream);
            var returned      = channelStream.Read(buffer, 0, 1);

            Assert.AreEqual(42, returned);
            stream.VerifyAllExpectations();
        }
Пример #7
0
        public void DisconnectedEventFiresImmediatelyIfDisposed()
        {
            var stream        = MockRepository.GenerateStub <Stream>();
            var channelStream = new ChannelStream(stream);

            channelStream.Dispose();
            bool called       = false;
            var  eventHandler = new DisconnectedEventHandler(() => called = true);

            channelStream.Disconnected += eventHandler;
            Assert.True(called, "Expected event to have been fired");
        }
Пример #8
0
        public void DisconnectedEventHandlerCanBeRemoved()
        {
            var  stream        = MockRepository.GenerateStub <Stream>();
            var  channelStream = new ChannelStream(stream);
            bool called        = false;
            var  eventHandler  = new DisconnectedEventHandler(() => called = true);

            channelStream.Disconnected += eventHandler;
            channelStream.Disconnected -= eventHandler;
            channelStream.Dispose();
            Assert.False(called, "Event handler should not have been called.");
        }
Пример #9
0
        public void DisconnectedEventFiresAfterDispose()
        {
            var  stream        = MockRepository.GenerateStub <Stream>();
            var  channelStream = new ChannelStream(stream);
            bool called        = false;
            var  eventHandler  = new DisconnectedEventHandler(() => called = true);

            channelStream.Disconnected += eventHandler;
            Assert.False(called, "Disconnected should not have fired before Dispose() was called.");
            channelStream.Dispose();
            Assert.True(called, "Expected event to have been fired");
        }
Пример #10
0
        internal static ChannelStream ToServiceModel(this ChannelStreamEntity dataObject)
        {
            ChannelStream serviceModel = new ChannelStream();

            serviceModel.Id          = dataObject.Id;
            serviceModel.ChannelName = dataObject.ChannelName;
            serviceModel.Provider    = (StreamProvider)Enum.Parse(typeof(StreamProvider), dataObject.Provider, true);
            serviceModel.ChannelId   = dataObject.ChannelId;
            serviceModel.Title       = dataObject.Title;
            serviceModel.Url         = dataObject.Url;

            return(serviceModel);
        }
Пример #11
0
        public Stream RequestBitChatNetworkChannel(BinaryID channelName)
        {
            ChannelStream channel = new ChannelStream(this, channelName, ChannelType.BitChatNetwork);

            lock (_bitChatNetworkChannels)
            {
                _bitChatNetworkChannels.Add(channelName, channel);
            }

            //send connect signal
            WriteSignalFrame(channelName, SIGNAL_CONNECT_BIT_CHAT_NETWORK);

            return(channel);
        }
Пример #12
0
        public void WriteFailureThrowsChannelFaultedException(Type exceptionType)
        {
            var stream = MockRepository.GenerateStub <Stream>();

            stream.Stub(s => s.Write(null, 0, 0))
            .IgnoreArguments()
            .Throw(Activator.CreateInstance(exceptionType, string.Empty) as Exception);

            var channelStream = new ChannelStream(stream);
            var buffer        = new byte[1];

            Assert.That(() => { channelStream.Write(buffer, 0, 1); },
                        Throws.Exception.TypeOf <ChannelFaultedException>());
        }
Пример #13
0
        private void RemoveChannel(ChannelStream channel)
        {
            switch (channel.ChannelType)
            {
            case ChannelType.BitChatNetwork:
                lock (_bitChatNetworkChannels)
                {
                    _bitChatNetworkChannels.Remove(channel.ChannelName);
                }

                try
                {
                    //send disconnect signal
                    WriteSignalFrame(channel.ChannelName, SIGNAL_DISCONNECT_BIT_CHAT_NETWORK);
                }
                catch
                { }
                break;

            case ChannelType.ProxyTunnel:
                lock (_proxyTunnelChannels)
                {
                    _proxyTunnelChannels.Remove(channel.ChannelName);
                }

                try
                {
                    //send disconnect signal
                    WriteSignalFrame(channel.ChannelName, SIGNAL_DISCONNECT_PROXY_TUNNEL);
                }
                catch
                { }
                break;

            case ChannelType.VirtualConnection:
                lock (_virtualConnectionChannels)
                {
                    _virtualConnectionChannels.Remove(channel.ChannelName);
                }

                try
                {
                    //send disconnect signal
                    WriteSignalFrame(channel.ChannelName, SIGNAL_DISCONNECT_VIRTUAL_CONNECTION);
                }
                catch
                { }
                break;
            }
        }
Пример #14
0
        public Stream RequestProxyTunnelChannel(IPEndPoint remotePeerEP)
        {
            BinaryID      channelName = new BinaryID(ConvertToBinary(remotePeerEP));
            ChannelStream channel     = new ChannelStream(this, channelName, ChannelType.ProxyTunnel);

            lock (_proxyTunnelChannels)
            {
                _proxyTunnelChannels.Add(channelName, channel);
            }

            //send signal
            WriteSignalFrame(channelName, SIGNAL_CONNECT_PROXY_TUNNEL);

            return(channel);
        }
Пример #15
0
        private Stream RequestVirtualConnectionChannel(IPEndPoint forPeerEP)
        {
            BinaryID      channelName = new BinaryID(ConvertToBinary(forPeerEP));
            ChannelStream channel     = new ChannelStream(this, channelName, ChannelType.VirtualConnection);

            lock (_virtualConnectionChannels)
            {
                _virtualConnectionChannels.Add(channelName, channel);
            }

            //send signal
            WriteSignalFrame(channelName, SIGNAL_CONNECT_VIRTUAL_CONNECTION);

            return(channel);
        }
Пример #16
0
        private void AcceptProxyConnectionAsync(object state)
        {
            ChannelStream channel = state as ChannelStream;

            try
            {
                _connectionManager.AcceptConnectionInitiateProtocol(channel, ConvertChannelNameToEp(channel.ChannelName));
            }
            catch
            {
                try
                {
                    channel.Dispose();
                }
                catch
                { }
            }
        }
Пример #17
0
        public Stream RequestBitChatNetworkChannel(BinaryID channelName)
        {
            ChannelStream channel;

            lock (_bitChatNetworkChannels)
            {
                if (_bitChatNetworkChannels.ContainsKey(channelName))
                {
                    throw new ArgumentException("Channel already exists.");
                }

                channel = new ChannelStream(this, channelName.Clone(), ChannelType.BitChatNetwork);
                _bitChatNetworkChannels.Add(channel.ChannelName, channel);
            }

            //send connect signal
            WriteFrame(SignalType.ConnectChannelBitChatNetwork, channelName, null, 0, 0);

            return(channel);
        }
Пример #18
0
        public Stream ConnectMeshNetwork(BinaryNumber channelId)
        {
            ChannelStream channel;

            lock (_channels)
            {
                if (_channels.ContainsKey(channelId))
                {
                    throw new InvalidOperationException("Channel already exists.");
                }

                channel = new ChannelStream(this, channelId);
                _channels.Add(channel.ChannelId, channel);
            }

            //send connect signal
            WriteFrame(ConnectionSignal.ConnectChannelMeshNetwork, channelId, null, 0, 0);

            return(channel);
        }
Пример #19
0
        private ChannelStream RequestProxyConnection(IPEndPoint forPeerEP)
        {
            BinaryNumber  channelName = ConvertEpToChannelName(forPeerEP);
            ChannelStream channel;

            lock (_channels)
            {
                if (_channels.ContainsKey(channelName))
                {
                    throw new ArgumentException("Channel already exists.");
                }

                channel = new ChannelStream(this, channelName);
                _channels.Add(channelName, channel);
            }

            //send signal
            WriteFrame(SignalType.ConnectChannelProxyConnection, channelName, null, 0, 0);

            return(channel);
        }
Пример #20
0
        public Stream MakeTunnelConnection(EndPoint remotePeerEP)
        {
            BinaryNumber  channelId = ConvertEpToChannelId(remotePeerEP);
            ChannelStream channel;

            lock (_channels)
            {
                if (_channels.ContainsKey(channelId))
                {
                    throw new InvalidOperationException("Channel already exists.");
                }

                channel = new ChannelStream(this, channelId);
                _channels.Add(channelId, channel);
            }

            //send signal
            WriteFrame(ConnectionSignal.ConnectChannelTunnel, channelId, null, 0, 0);

            return(channel);
        }
Пример #21
0
        public Stream RequestProxyTunnel(IPEndPoint remotePeerEP)
        {
            BinaryID      channelName = ConvertEpToChannelName(remotePeerEP);
            ChannelStream channel;

            lock (_proxyChannels)
            {
                if (_proxyChannels.ContainsKey(channelName))
                {
                    throw new ArgumentException("Channel already exists.");
                }

                channel = new ChannelStream(this, channelName, ChannelType.ProxyTunnel);
                _proxyChannels.Add(channelName, channel);
            }

            //send signal
            WriteFrame(SignalType.ConnectChannelProxyTunnel, channelName, null, 0, 0);

            return(channel);
        }
Пример #22
0
 private void Worker()
 {
     m_Listener = new TcpListener(m_LocalAddress, m_Port);
     m_Listener.Start();
     try
     {
         while (!m_Disposed)
         {
             var socket        = m_Listener.AcceptSocket();
             var channelStream = new ChannelStream(new NetworkStream(socket));
             m_ActiveConnections.Add(channelStream);
             channelStream.Disconnected += () => m_ActiveConnections.Remove(channelStream);
             ChannelConnected.Invoke(new ChannelConnectedEventArgs(
                                         Guid.NewGuid().ToString(),
                                         channelStream));
         }
     }
     catch (ObjectDisposedException)
     {
     }
     catch (SocketException)
     {
     }
 }
Пример #23
0
        private void Worker()
        {
            var pipeSecurity = GetPipeSecurity();

            try
            {
                while (!m_Disposed)
                {
                    m_CurrentListener = new NamedPipeServerStream(
                        m_PipeName,
                        PipeDirection.InOut,
                        NamedPipeServerStream.MaxAllowedServerInstances,
                        PipeTransmissionMode.Byte,
                        PipeOptions.Asynchronous,
                        2048,
                        2048,
                        pipeSecurity);

                    m_CurrentListener.WaitForConnection();
                    var channelStream = new ChannelStream(m_CurrentListener);
                    m_ActiveConnections.Add(channelStream);
                    channelStream.Disconnected += () => m_ActiveConnections.Remove(channelStream);
                    ChannelConnected(new ChannelConnectedEventArgs(Guid.NewGuid().ToString(),
                                                                   channelStream));
                }
            }
            catch (IOException)
            {
            }
            catch (ObjectDisposedException)
            {
            }
            catch (SocketException)
            {
            }
        }
Пример #24
0
        private void AcceptVirtualConnectionAsync(object state)
        {
            try
            {
                object[] parameters = state as object[];

                ChannelStream channel             = parameters[0] as ChannelStream;
                IPEndPoint    virtualRemotePeerEP = parameters[1] as IPEndPoint;

                try
                {
                    Connection connection = _connectionManager.AcceptConnectionInitiateProtocol(channel, virtualRemotePeerEP);
                }
                catch
                {
                    if (channel != null)
                    {
                        channel.Dispose();
                    }
                }
            }
            catch
            { }
        }
Пример #25
0
        public Stream RequestProxyTunnelChannel(IPEndPoint remotePeerEP)
        {
            BinaryID channelName = new BinaryID(ConvertToBinary(remotePeerEP));
            ChannelStream channel = new ChannelStream(this, channelName, ChannelType.ProxyTunnel);

            lock (_proxyTunnelChannels)
            {
                _proxyTunnelChannels.Add(channelName, channel);
            }

            //send signal
            WriteSignalFrame(channelName, SIGNAL_CONNECT_PROXY_TUNNEL);

            return channel;
        }
Пример #26
0
        private void ReadFrameAsync()
        {
            try
            {
                //frame parameters
                int          signal;
                BinaryNumber channelId        = new BinaryNumber(new byte[32]);
                byte[]       dataLengthBuffer = new byte[2];
                OffsetStream dataStream       = new OffsetStream(_baseStream, 0, 0, true, false);

                while (true)
                {
                    #region read frame from base stream

                    //read frame signal
                    signal = _baseStream.ReadByte();
                    if (signal == -1)
                    {
                        return; //End of stream
                    }
                    //read channel id
                    _baseStream.ReadBytes(channelId.Value, 0, 32);

                    //read data length
                    _baseStream.ReadBytes(dataLengthBuffer, 0, 2);
                    dataStream.Reset(0, BitConverter.ToUInt16(dataLengthBuffer, 0), 0);

                    #endregion

                    switch ((ConnectionSignal)signal)
                    {
                    case ConnectionSignal.PingRequest:
                        WriteFrame(ConnectionSignal.PingResponse, channelId, null, 0, 0);
                        break;

                    case ConnectionSignal.PingResponse:
                        //do nothing!
                        break;

                    case ConnectionSignal.ConnectChannelMeshNetwork:
                        #region ConnectChannelMeshNetwork

                        lock (_channels)
                        {
                            if (_channels.ContainsKey(channelId))
                            {
                                WriteFrame(ConnectionSignal.DisconnectChannel, channelId, null, 0, 0);
                            }
                            else
                            {
                                ChannelStream channel = new ChannelStream(this, channelId.Clone());
                                _channels.Add(channel.ChannelId, channel);

                                ThreadPool.QueueUserWorkItem(delegate(object state)
                                {
                                    try
                                    {
                                        //done async since the call is blocking and will block the current read thread which can cause DOS
                                        _connectionManager.Node.MeshNetworkRequest(this, channel.ChannelId, channel);
                                    }
                                    catch (Exception ex)
                                    {
                                        Debug.Write(this.GetType().Name, ex);

                                        channel.Dispose();
                                    }
                                });
                            }
                        }

                        //check if tcp relay is hosted for the channel. reply back tcp relay peers list if available
                        Connection[] connections = _connectionManager.GetTcpRelayServerHostedNetworkConnections(channelId);

                        if (connections.Length > 0)
                        {
                            int count = connections.Length;

                            for (int i = 0; i < connections.Length; i++)
                            {
                                if (connections[i].RemotePeerEP.Equals(_remotePeerEP))
                                {
                                    connections[i] = null;
                                    count--;
                                    break;
                                }
                            }

                            using (MemoryStream mS = new MemoryStream(128))
                            {
                                BinaryWriter bW = new BinaryWriter(mS);

                                bW.Write(Convert.ToByte(count));

                                foreach (Connection connection in connections)
                                {
                                    if (connection != null)
                                    {
                                        connection.RemotePeerEP.WriteTo(bW);
                                    }
                                }

                                byte[] data = mS.ToArray();

                                WriteFrame(ConnectionSignal.MeshNetworkPeers, channelId, data, 0, data.Length);
                            }
                        }

                        #endregion
                        break;

                    case ConnectionSignal.ChannelData:
                        #region ChannelData

                        try
                        {
                            ChannelStream channel = null;

                            lock (_channels)
                            {
                                channel = _channels[channelId];
                            }

                            channel.FeedReadBuffer(dataStream, _channelWriteTimeout);
                        }
                        catch
                        { }

                        #endregion
                        break;

                    case ConnectionSignal.DisconnectChannel:
                        #region DisconnectChannel

                        try
                        {
                            ChannelStream channel;

                            lock (_channels)
                            {
                                channel = _channels[channelId];
                                _channels.Remove(channelId);
                            }

                            channel.SetDisconnected();
                            channel.Dispose();
                        }
                        catch
                        { }

                        #endregion
                        break;

                    case ConnectionSignal.ConnectChannelTunnel:
                        #region ConnectChannelTunnel

                        if (IsStreamVirtualConnection(_baseStream))
                        {
                            //nesting virtual connections not allowed
                            WriteFrame(ConnectionSignal.DisconnectChannel, channelId, null, 0, 0);
                        }
                        else
                        {
                            ChannelStream remoteChannel1 = null;

                            lock (_channels)
                            {
                                if (_channels.ContainsKey(channelId))
                                {
                                    WriteFrame(ConnectionSignal.DisconnectChannel, channelId, null, 0, 0);
                                }
                                else
                                {
                                    //add first stream into list
                                    remoteChannel1 = new ChannelStream(this, channelId.Clone());
                                    _channels.Add(remoteChannel1.ChannelId, remoteChannel1);
                                }
                            }

                            if (remoteChannel1 != null)
                            {
                                EndPoint   tunnelToRemotePeerEP = ConvertChannelIdToEp(channelId);                                //get remote peer ep
                                Connection remotePeerConnection = _connectionManager.GetExistingConnection(tunnelToRemotePeerEP); //get remote channel service

                                if (remotePeerConnection == null)
                                {
                                    remoteChannel1.Dispose();
                                }
                                else
                                {
                                    try
                                    {
                                        //get remote proxy connection channel stream
                                        ChannelStream remoteChannel2 = remotePeerConnection.MakeVirtualConnection(_remotePeerEP);

                                        //join current and remote stream
                                        Joint joint = new Joint(remoteChannel1, remoteChannel2);

                                        joint.Disposed += delegate(object sender, EventArgs e)
                                        {
                                            lock (_tunnelJointList)
                                            {
                                                _tunnelJointList.Remove(sender as Joint);
                                            }
                                        };

                                        lock (_tunnelJointList)
                                        {
                                            _tunnelJointList.Add(joint);
                                        }

                                        joint.Start();
                                    }
                                    catch (Exception ex)
                                    {
                                        Debug.Write(this.GetType().Name, ex);

                                        remoteChannel1.Dispose();
                                    }
                                }
                            }
                        }

                        #endregion
                        break;

                    case ConnectionSignal.ConnectChannelVirtualConnection:
                        #region ConnectChannelVirtualConnection

                        if (IsStreamVirtualConnection(_baseStream))
                        {
                            //nesting virtual connections not allowed
                            WriteFrame(ConnectionSignal.DisconnectChannel, channelId, null, 0, 0);
                        }
                        else
                        {
                            lock (_channels)
                            {
                                if (_channels.ContainsKey(channelId))
                                {
                                    WriteFrame(ConnectionSignal.DisconnectChannel, channelId, null, 0, 0);
                                }
                                else
                                {
                                    //add proxy channel stream into list
                                    ChannelStream channel = new ChannelStream(this, channelId.Clone());
                                    _channels.Add(channel.ChannelId, channel);

                                    //pass channel as connection async
                                    ThreadPool.QueueUserWorkItem(delegate(object state)
                                    {
                                        try
                                        {
                                            _connectionManager.AcceptConnectionInitiateProtocol(channel, ConvertChannelIdToEp(channel.ChannelId));
                                        }
                                        catch (Exception ex)
                                        {
                                            Debug.Write(this.GetType().Name, ex);

                                            channel.Dispose();
                                        }
                                    });
                                }
                            }
                        }

                        #endregion
                        break;

                    case ConnectionSignal.TcpRelayServerRegisterHostedNetwork:
                        #region TcpRelayServerRegisterHostedNetwork

                        _connectionManager.TcpRelayServerRegisterHostedNetwork(this, channelId.Clone());

                        _tcpRelayServerModeEnabled = true;

                        #endregion
                        break;

                    case ConnectionSignal.TcpRelayServerUnregisterHostedNetwork:
                        #region TcpRelayServerUnregisterHostedNetwork

                        _connectionManager.TcpRelayServerUnregisterHostedNetwork(this, channelId);

                        #endregion
                        break;

                    case ConnectionSignal.MeshNetworkPeers:
                        #region MeshNetworkPeers
                    {
                        BinaryReader bR = new BinaryReader(dataStream);

                        int             count   = bR.ReadByte();
                        List <EndPoint> peerEPs = new List <EndPoint>(count);

                        for (int i = 0; i < count; i++)
                        {
                            peerEPs.Add(EndPointExtension.Parse(bR));
                        }

                        _connectionManager.Node.ReceivedMeshNetworkPeersViaTcpRelay(this, channelId, peerEPs);
                    }
                        #endregion
                        break;

                    default:
                        throw new IOException("Invalid frame signal.");
                    }

                    //discard any unread data
                    if (dataStream.Length > dataStream.Position)
                    {
                        dataStream.CopyTo(Stream.Null, 1024, Convert.ToInt32(dataStream.Length - dataStream.Position));
                    }
                }
            }
            catch (ThreadAbortException)
            {
                //stopping
            }
            catch (Exception ex)
            {
                Debug.Write(this.GetType().Name, ex);
            }
            finally
            {
                Dispose();
            }
        }
Пример #27
0
        private void ReadDataAsync()
        {
            try
            {
                int channelDataLength;
                int frameSignal;
                byte[] channelNameBuffer = new byte[20];
                BinaryID channelName = new BinaryID(channelNameBuffer);
                ChannelType channelType;
                byte[] buffer = new byte[65536];

                while (true)
                {
                    //read frame signal
                    frameSignal = _baseStream.ReadByte();

                    //read channel name
                    OffsetStream.StreamRead(_baseStream, channelNameBuffer, 0, 20);

                    switch (frameSignal)
                    {
                        case SIGNAL_DATA:
                            {
                                //read channel type
                                channelType = (ChannelType)_baseStream.ReadByte();

                                OffsetStream.StreamRead(_baseStream, buffer, 0, 2);
                                channelDataLength = BitConverter.ToUInt16(buffer, 0) + 1;
                                OffsetStream.StreamRead(_baseStream, buffer, 0, channelDataLength);

                                //switch frame
                                ChannelStream channel = null;

                                try
                                {
                                    switch (channelType)
                                    {
                                        case ChannelType.BitChatNetwork:
                                            lock (_bitChatNetworkChannels)
                                            {
                                                channel = _bitChatNetworkChannels[channelName];
                                            }

                                            channel.WriteBuffer(buffer, 0, channelDataLength, _channelWriteTimeout);
                                            break;

                                        case ChannelType.ProxyTunnel:
                                            lock (_proxyTunnelChannels)
                                            {
                                                channel = _proxyTunnelChannels[channelName];
                                            }

                                            channel.WriteBuffer(buffer, 0, channelDataLength, _channelWriteTimeout);
                                            break;

                                        case ChannelType.VirtualConnection:
                                            lock (_virtualConnectionChannels)
                                            {
                                                channel = _virtualConnectionChannels[channelName];
                                            }

                                            channel.WriteBuffer(buffer, 0, channelDataLength, _channelWriteTimeout);
                                            break;
                                    }
                                }
                                catch
                                {
                                    if (channel != null)
                                        channel.Dispose();
                                }
                            }
                            break;

                        case SIGNAL_CONNECT_BIT_CHAT_NETWORK:
                            {
                                ChannelStream channel = null;

                                try
                                {
                                    channel = new ChannelStream(this, channelName, ChannelType.BitChatNetwork);

                                    lock (_bitChatNetworkChannels)
                                    {
                                        _bitChatNetworkChannels.Add(channelName, channel);
                                    }

                                    Debug.Write("Connection.ReadDataAsync", "SIGNAL_CONNECT_BIT_CHAT_NETWORK; channel: " + channelName.ToString());

                                    _requestHandler.BeginInvoke(this, channelName, ChannelType.BitChatNetwork, channel, null, null);
                                }
                                catch
                                {
                                    if (channel != null)
                                        channel.Dispose();
                                }
                            }
                            break;

                        case SIGNAL_DISCONNECT_BIT_CHAT_NETWORK:
                            try
                            {
                                lock (_bitChatNetworkChannels)
                                {
                                    _bitChatNetworkChannels[channelName].Dispose();
                                }

                                Debug.Write("Connection.ReadDataAsync", "SIGNAL_DISCONNECT_BIT_CHAT_NETWORK; channel: " + channelName.ToString());
                            }
                            catch
                            { }
                            break;

                        case SIGNAL_PEER_STATUS:
                            try
                            {
                                if (_connectionManager.IsPeerConnectionAvailable(ConvertToIP(channelName.ID)))
                                    WriteSignalFrame(channelName, SIGNAL_PEER_STATUS_AVAILABLE);

                                Debug.Write("Connection.ReadDataAsync", "SIGNAL_PEER_STATUS; peerIP: " + ConvertToIP(channelName.ID).ToString());
                            }
                            catch
                            { }
                            break;

                        case SIGNAL_PEER_STATUS_AVAILABLE:
                            try
                            {
                                lock (_peerStatusLockList)
                                {
                                    object lockObject = _peerStatusLockList[channelName];

                                    lock (lockObject)
                                    {
                                        Monitor.Pulse(lockObject);
                                    }
                                }

                                Debug.Write("Connection.ReadDataAsync", "SIGNAL_PEER_STATUS_AVAILABLE; peerIP: " + ConvertToIP(channelName.ID).ToString());
                            }
                            catch
                            { }
                            break;

                        case SIGNAL_CONNECT_PROXY_TUNNEL:
                            {
                                ChannelStream remoteChannel1 = null;
                                Stream remoteChannel2 = null;

                                try
                                {
                                    //get remote peer ep
                                    IPEndPoint tunnelToPeerEP = ConvertToIP(channelName.ID);

                                    //add first stream into list
                                    remoteChannel1 = new ChannelStream(this, channelName, ChannelType.ProxyTunnel);

                                    lock (_proxyTunnelChannels)
                                    {
                                        _proxyTunnelChannels.Add(channelName, remoteChannel1);
                                    }

                                    //get remote channel service
                                    Connection remotePeerConnection = _connectionManager.GetExistingConnection(tunnelToPeerEP);

                                    //get remote stream for virtual connection
                                    remoteChannel2 = remotePeerConnection.RequestVirtualConnectionChannel(_remotePeerEP);

                                    //join current and remote stream
                                    Joint joint = new Joint(remoteChannel1, remoteChannel2);
                                    joint.Disposed += joint_Disposed;

                                    lock (_tunnelJointList)
                                    {
                                        _tunnelJointList.Add(joint);
                                    }

                                    joint.Start();

                                    Debug.Write("Connection.ReadDataAsync", "SIGNAL_CONNECT_PROXY_TUNNEL; tunnel to peerIP: " + tunnelToPeerEP.ToString());
                                }
                                catch
                                {
                                    if (remoteChannel1 != null)
                                        remoteChannel1.Dispose();

                                    if (remoteChannel2 != null)
                                        remoteChannel2.Dispose();
                                }
                            }
                            break;

                        case SIGNAL_DISCONNECT_PROXY_TUNNEL:
                            try
                            {
                                lock (_proxyTunnelChannels)
                                {
                                    _proxyTunnelChannels[channelName].Dispose();
                                }

                                Debug.Write("Connection.ReadDataAsync", "SIGNAL_DISCONNECT_PROXY_TUNNEL; channel: " + channelName.ToString());
                            }
                            catch
                            { }
                            break;

                        case SIGNAL_CONNECT_VIRTUAL_CONNECTION:
                            {
                                ChannelStream channel = null;

                                try
                                {
                                    //add current stream into list
                                    channel = new ChannelStream(this, channelName, ChannelType.VirtualConnection);

                                    lock (_virtualConnectionChannels)
                                    {
                                        _virtualConnectionChannels.Add(channelName, channel);
                                    }

                                    IPEndPoint virtualRemotePeerEP = ConvertToIP(channelName.ID);

                                    Debug.Write("Connection.ReadDataAsync", "SIGNAL_CONNECT_VIRTUAL_CONNECTION; tunnel from peerIP: " + virtualRemotePeerEP.ToString());

                                    //pass channel as virtual connection async
                                    ThreadPool.QueueUserWorkItem(AcceptVirtualConnectionAsync, new object[] { channel, virtualRemotePeerEP });
                                }
                                catch
                                {
                                    if (channel != null)
                                        channel.Dispose();
                                }
                            }
                            break;

                        case SIGNAL_DISCONNECT_VIRTUAL_CONNECTION:
                            try
                            {
                                lock (_virtualConnectionChannels)
                                {
                                    _virtualConnectionChannels[channelName].Dispose();
                                }

                                Debug.Write("Connection.ReadDataAsync", "SIGNAL_DISCONNECT_VIRTUAL_CONNECTION; channel: " + channelName.ToString());
                            }
                            catch
                            { }
                            break;

                        default:
                            throw new IOException("Invalid ChannelManager frame type.");
                    }
                }
            }
            catch
            { }
            finally
            {
                Dispose();
            }
        }
Пример #28
0
        private void RemoveChannel(ChannelStream channel)
        {
            switch (channel.ChannelType)
            {
                case ChannelType.BitChatNetwork:
                    lock (_bitChatNetworkChannels)
                    {
                        _bitChatNetworkChannels.Remove(channel.ChannelName);
                    }

                    try
                    {
                        //send disconnect signal
                        WriteSignalFrame(channel.ChannelName, SIGNAL_DISCONNECT_BIT_CHAT_NETWORK);
                    }
                    catch
                    { }
                    break;

                case ChannelType.ProxyTunnel:
                    lock (_proxyTunnelChannels)
                    {
                        _proxyTunnelChannels.Remove(channel.ChannelName);
                    }

                    try
                    {
                        //send disconnect signal
                        WriteSignalFrame(channel.ChannelName, SIGNAL_DISCONNECT_PROXY_TUNNEL);
                    }
                    catch
                    { }
                    break;

                case ChannelType.VirtualConnection:
                    lock (_virtualConnectionChannels)
                    {
                        _virtualConnectionChannels.Remove(channel.ChannelName);
                    }

                    try
                    {
                        //send disconnect signal
                        WriteSignalFrame(channel.ChannelName, SIGNAL_DISCONNECT_VIRTUAL_CONNECTION);
                    }
                    catch
                    { }
                    break;
            }
        }
Пример #29
0
        private void ReadFrameAsync()
        {
            try
            {
                //frame parameters
                int      signalType;
                BinaryID channelName = new BinaryID(new byte[20]);
                int      dataLength;
                byte[]   dataBuffer = new byte[BUFFER_SIZE];

                while (true)
                {
                    #region Read frame from base stream

                    //read frame signal
                    signalType = _baseStream.ReadByte();
                    if (signalType == -1)
                    {
                        return; //End of stream
                    }
                    //read channel name
                    OffsetStream.StreamRead(_baseStream, channelName.ID, 0, 20);

                    //read data length
                    OffsetStream.StreamRead(_baseStream, dataBuffer, 0, 2);
                    dataLength = BitConverter.ToUInt16(dataBuffer, 0);

                    //read data
                    if (dataLength > 0)
                    {
                        OffsetStream.StreamRead(_baseStream, dataBuffer, 0, dataLength);
                    }

                    #endregion

                    switch ((SignalType)signalType)
                    {
                    case SignalType.NOOP:
                        break;

                    case SignalType.ConnectChannelBitChatNetwork:
                        #region ConnectChannelBitChatNetwork

                        lock (_bitChatNetworkChannels)
                        {
                            if (_bitChatNetworkChannels.ContainsKey(channelName))
                            {
                                WriteFrame(SignalType.DisconnectChannelBitChatNetwork, channelName, null, 0, 0);
                            }
                            else
                            {
                                ChannelStream channel = new ChannelStream(this, channelName.Clone(), ChannelType.BitChatNetwork);
                                _bitChatNetworkChannels.Add(channel.ChannelName, channel);

                                BitChatNetworkChannelRequest.BeginInvoke(this, channel.ChannelName, channel, null, null);
                            }
                        }

                        //check if tcp relay is hosted for the channel. reply back tcp relay peers list if available
                        try
                        {
                            List <IPEndPoint> peerEPs = TcpRelayService.GetPeerEPs(channelName, this);

                            if ((peerEPs != null) && (peerEPs.Count > 0))
                            {
                                using (MemoryStream mS = new MemoryStream(128))
                                {
                                    mS.WriteByte(Convert.ToByte(peerEPs.Count));

                                    foreach (IPEndPoint peerEP in peerEPs)
                                    {
                                        IPEndPointParser.WriteTo(peerEP, mS);
                                    }

                                    byte[] data = mS.ToArray();

                                    WriteFrame(SignalType.TcpRelayResponsePeerList, channelName, data, 0, data.Length);
                                }
                            }
                        }
                        catch
                        { }

                        #endregion
                        break;

                    case SignalType.DataChannelBitChatNetwork:
                        #region DataChannelBitChatNetwork

                        try
                        {
                            ChannelStream channel = null;

                            lock (_bitChatNetworkChannels)
                            {
                                channel = _bitChatNetworkChannels[channelName];
                            }

                            channel.WriteBuffer(dataBuffer, 0, dataLength, _channelWriteTimeout);
                        }
                        catch
                        { }

                        #endregion
                        break;

                    case SignalType.DisconnectChannelBitChatNetwork:
                        #region DisconnectChannelBitChatNetwork

                        try
                        {
                            ChannelStream channel;

                            lock (_bitChatNetworkChannels)
                            {
                                channel = _bitChatNetworkChannels[channelName];
                                _bitChatNetworkChannels.Remove(channelName);
                            }

                            channel.SetDisconnected();
                            channel.Dispose();
                        }
                        catch
                        { }

                        #endregion
                        break;

                    case SignalType.ConnectChannelProxyTunnel:
                        #region ConnectChannelProxyTunnel
                    {
                        ChannelStream remoteChannel1 = null;

                        lock (_proxyChannels)
                        {
                            if (_proxyChannels.ContainsKey(channelName))
                            {
                                WriteFrame(SignalType.DisconnectChannelProxy, channelName, null, 0, 0);
                            }
                            else
                            {
                                //add first stream into list
                                remoteChannel1 = new ChannelStream(this, channelName.Clone(), ChannelType.ProxyTunnel);
                                _proxyChannels.Add(remoteChannel1.ChannelName, remoteChannel1);
                            }
                        }

                        if (remoteChannel1 != null)
                        {
                            IPEndPoint tunnelToRemotePeerEP = ConvertChannelNameToEp(channelName);                            //get remote peer ep
                            Connection remotePeerConnection = _connectionManager.GetExistingConnection(tunnelToRemotePeerEP); //get remote channel service

                            if (remotePeerConnection == null)
                            {
                                remoteChannel1.Dispose();
                            }
                            else
                            {
                                try
                                {
                                    //get remote proxy connection channel stream
                                    ChannelStream remoteChannel2 = remotePeerConnection.RequestProxyConnection(_remotePeerEP);

                                    //join current and remote stream
                                    Joint joint = new Joint(remoteChannel1, remoteChannel2);
                                    joint.Disposed += joint_Disposed;

                                    lock (_proxyTunnelJointList)
                                    {
                                        _proxyTunnelJointList.Add(joint);
                                    }

                                    joint.Start();
                                }
                                catch
                                {
                                    remoteChannel1.Dispose();
                                }
                            }
                        }
                    }
                        #endregion
                        break;

                    case SignalType.ConnectChannelProxyConnection:
                        #region ConnectChannelProxyConnection

                        lock (_proxyChannels)
                        {
                            if (_proxyChannels.ContainsKey(channelName))
                            {
                                WriteFrame(SignalType.DisconnectChannelProxy, channelName, null, 0, 0);
                            }
                            else
                            {
                                //add proxy channel stream into list
                                ChannelStream channel = new ChannelStream(this, channelName.Clone(), ChannelType.ProxyTunnel);
                                _proxyChannels.Add(channel.ChannelName, channel);

                                //pass channel as connection async
                                ThreadPool.QueueUserWorkItem(AcceptProxyConnectionAsync, channel);
                            }
                        }

                        #endregion
                        break;

                    case SignalType.DataChannelProxy:
                        #region DataChannelProxy

                        try
                        {
                            ChannelStream channel = null;

                            lock (_proxyChannels)
                            {
                                channel = _proxyChannels[channelName];
                            }

                            channel.WriteBuffer(dataBuffer, 0, dataLength, _channelWriteTimeout);
                        }
                        catch
                        { }

                        #endregion
                        break;

                    case SignalType.DisconnectChannelProxy:
                        #region DisconnectChannelProxy

                        try
                        {
                            ChannelStream channel;

                            lock (_proxyChannels)
                            {
                                channel = _proxyChannels[channelName];
                                _proxyChannels.Remove(channelName);
                            }

                            channel.SetDisconnected();
                            channel.Dispose();
                        }
                        catch
                        { }

                        #endregion
                        break;

                    case SignalType.PeerStatusQuery:
                        #region PeerStatusQuery

                        try
                        {
                            if (_connectionManager.IsPeerConnectionAvailable(ConvertChannelNameToEp(channelName)))
                            {
                                WriteFrame(SignalType.PeerStatusAvailable, channelName, null, 0, 0);
                            }
                        }
                        catch
                        { }

                        #endregion
                        break;

                    case SignalType.PeerStatusAvailable:
                        #region PeerStatusAvailable

                        try
                        {
                            lock (_peerStatusLockList)
                            {
                                object lockObject = _peerStatusLockList[channelName];

                                lock (lockObject)
                                {
                                    Monitor.Pulse(lockObject);
                                }
                            }
                        }
                        catch
                        { }

                        #endregion
                        break;

                    case SignalType.StartTcpRelay:
                        #region StartTcpRelay
                    {
                        BinaryID[] networkIDs;
                        Uri[]      trackerURIs;

                        using (MemoryStream mS = new MemoryStream(dataBuffer, 0, dataLength, false))
                        {
                            //read network id list
                            networkIDs = new BinaryID[mS.ReadByte()];
                            byte[] XORnetworkID = new byte[20];

                            for (int i = 0; i < networkIDs.Length; i++)
                            {
                                mS.Read(XORnetworkID, 0, 20);

                                byte[] networkID = new byte[20];

                                for (int j = 0; j < 20; j++)
                                {
                                    networkID[j] = (byte)(channelName.ID[j] ^ XORnetworkID[j]);
                                }

                                networkIDs[i] = new BinaryID(networkID);
                            }

                            //read tracker uri list
                            trackerURIs = new Uri[mS.ReadByte()];
                            byte[] data = new byte[255];

                            for (int i = 0; i < trackerURIs.Length; i++)
                            {
                                int length = mS.ReadByte();
                                mS.Read(data, 0, length);

                                trackerURIs[i] = new Uri(Encoding.UTF8.GetString(data, 0, length));
                            }
                        }

                        lock (_tcpRelays)
                        {
                            foreach (BinaryID networkID in networkIDs)
                            {
                                if (!_tcpRelays.ContainsKey(networkID))
                                {
                                    TcpRelayService relay = TcpRelayService.StartTcpRelay(networkID, this, _connectionManager.LocalPort, _connectionManager.DhtClient, trackerURIs);
                                    _tcpRelays.Add(networkID, relay);
                                }
                            }
                        }

                        WriteFrame(SignalType.TcpRelayResponseSuccess, channelName, null, 0, 0);
                    }
                        #endregion
                        break;

                    case SignalType.StopTcpRelay:
                        #region StopTcpRelay
                    {
                        BinaryID[] networkIDs;

                        using (MemoryStream mS = new MemoryStream(dataBuffer, 0, dataLength, false))
                        {
                            //read network id list
                            networkIDs = new BinaryID[mS.ReadByte()];
                            byte[] XORnetworkID = new byte[20];

                            for (int i = 0; i < networkIDs.Length; i++)
                            {
                                mS.Read(XORnetworkID, 0, 20);

                                byte[] networkID = new byte[20];

                                for (int j = 0; j < 20; j++)
                                {
                                    networkID[j] = (byte)(channelName.ID[j] ^ XORnetworkID[j]);
                                }

                                networkIDs[i] = new BinaryID(networkID);
                            }
                        }

                        lock (_tcpRelays)
                        {
                            foreach (BinaryID networkID in networkIDs)
                            {
                                if (_tcpRelays.ContainsKey(networkID))
                                {
                                    _tcpRelays[networkID].StopTcpRelay(this);
                                    _tcpRelays.Remove(networkID);
                                }
                            }
                        }

                        WriteFrame(SignalType.TcpRelayResponseSuccess, channelName, null, 0, 0);
                    }
                        #endregion
                        break;

                    case SignalType.TcpRelayResponseSuccess:
                        #region TcpRelayResponseSuccess

                        try
                        {
                            lock (_tcpRelayRequestLockList)
                            {
                                object lockObject = _tcpRelayRequestLockList[channelName];

                                lock (lockObject)
                                {
                                    Monitor.Pulse(lockObject);
                                }
                            }
                        }
                        catch
                        { }

                        #endregion
                        break;

                    case SignalType.TcpRelayResponsePeerList:
                        #region TcpRelayResponsePeerList

                        using (MemoryStream mS = new MemoryStream(dataBuffer, 0, dataLength, false))
                        {
                            int count = mS.ReadByte();
                            List <IPEndPoint> peerEPs = new List <IPEndPoint>(count);

                            for (int i = 0; i < count; i++)
                            {
                                peerEPs.Add(IPEndPointParser.Parse(mS));
                            }

                            TcpRelayPeersAvailable.BeginInvoke(this, channelName.Clone(), peerEPs, null, null);
                        }

                        #endregion
                        break;

                    case SignalType.DhtPacketData:
                        #region DhtPacketData

                        byte[] response = _connectionManager.DhtClient.ProcessPacket(dataBuffer, 0, dataLength, _remotePeerEP.Address);

                        if (response != null)
                        {
                            WriteFrame(SignalType.DhtPacketData, BinaryID.GenerateRandomID160(), response, 0, response.Length);
                        }

                        #endregion
                        break;

                    case SignalType.BitChatNetworkInvitation:
                        #region ChannelInvitationBitChatNetwork

                        if (_connectionManager.Profile.AllowInboundInvitations)
                        {
                            BitChatNetworkInvitation.BeginInvoke(channelName.Clone(), _remotePeerEP, Encoding.UTF8.GetString(dataBuffer, 0, dataLength), null, null);
                        }

                        #endregion
                        break;

                    default:
                        throw new IOException("Invalid frame signal type.");
                    }
                }
            }
            catch
            { }
            finally
            {
                Dispose();
            }
        }
Пример #30
0
        private Stream RequestVirtualConnectionChannel(IPEndPoint forPeerEP)
        {
            BinaryID channelName = new BinaryID(ConvertToBinary(forPeerEP));
            ChannelStream channel = new ChannelStream(this, channelName, ChannelType.VirtualConnection);

            lock (_virtualConnectionChannels)
            {
                _virtualConnectionChannels.Add(channelName, channel);
            }

            //send signal
            WriteSignalFrame(channelName, SIGNAL_CONNECT_VIRTUAL_CONNECTION);

            return channel;
        }
Пример #31
0
        private void ReadDataAsync()
        {
            try
            {
                int         channelDataLength;
                int         frameSignal;
                byte[]      channelNameBuffer = new byte[20];
                BinaryID    channelName       = new BinaryID(channelNameBuffer);
                ChannelType channelType;
                byte[]      buffer = new byte[65536];

                while (true)
                {
                    //read frame signal
                    frameSignal = _baseStream.ReadByte();

                    //read channel name
                    OffsetStream.StreamRead(_baseStream, channelNameBuffer, 0, 20);

                    switch (frameSignal)
                    {
                    case SIGNAL_DATA:
                    {
                        //read channel type
                        channelType = (ChannelType)_baseStream.ReadByte();

                        OffsetStream.StreamRead(_baseStream, buffer, 0, 2);
                        channelDataLength = BitConverter.ToUInt16(buffer, 0) + 1;
                        OffsetStream.StreamRead(_baseStream, buffer, 0, channelDataLength);

                        //switch frame
                        ChannelStream channel = null;

                        try
                        {
                            switch (channelType)
                            {
                            case ChannelType.BitChatNetwork:
                                lock (_bitChatNetworkChannels)
                                {
                                    channel = _bitChatNetworkChannels[channelName];
                                }

                                channel.WriteBuffer(buffer, 0, channelDataLength, _channelWriteTimeout);
                                break;

                            case ChannelType.ProxyTunnel:
                                lock (_proxyTunnelChannels)
                                {
                                    channel = _proxyTunnelChannels[channelName];
                                }

                                channel.WriteBuffer(buffer, 0, channelDataLength, _channelWriteTimeout);
                                break;

                            case ChannelType.VirtualConnection:
                                lock (_virtualConnectionChannels)
                                {
                                    channel = _virtualConnectionChannels[channelName];
                                }

                                channel.WriteBuffer(buffer, 0, channelDataLength, _channelWriteTimeout);
                                break;
                            }
                        }
                        catch
                        {
                            if (channel != null)
                            {
                                channel.Dispose();
                            }
                        }
                    }
                    break;

                    case SIGNAL_CONNECT_BIT_CHAT_NETWORK:
                    {
                        ChannelStream channel = null;

                        try
                        {
                            channel = new ChannelStream(this, channelName, ChannelType.BitChatNetwork);

                            lock (_bitChatNetworkChannels)
                            {
                                _bitChatNetworkChannels.Add(channelName, channel);
                            }

                            Debug.Write("Connection.ReadDataAsync", "SIGNAL_CONNECT_BIT_CHAT_NETWORK; channel: " + channelName.ToString());

                            _requestHandler.BeginInvoke(this, channelName, ChannelType.BitChatNetwork, channel, null, null);
                        }
                        catch
                        {
                            if (channel != null)
                            {
                                channel.Dispose();
                            }
                        }
                    }
                    break;

                    case SIGNAL_DISCONNECT_BIT_CHAT_NETWORK:
                        try
                        {
                            lock (_bitChatNetworkChannels)
                            {
                                _bitChatNetworkChannels[channelName].Dispose();
                            }

                            Debug.Write("Connection.ReadDataAsync", "SIGNAL_DISCONNECT_BIT_CHAT_NETWORK; channel: " + channelName.ToString());
                        }
                        catch
                        { }
                        break;

                    case SIGNAL_PEER_STATUS:
                        try
                        {
                            if (_connectionManager.IsPeerConnectionAvailable(ConvertToIP(channelName.ID)))
                            {
                                WriteSignalFrame(channelName, SIGNAL_PEER_STATUS_AVAILABLE);
                            }

                            Debug.Write("Connection.ReadDataAsync", "SIGNAL_PEER_STATUS; peerIP: " + ConvertToIP(channelName.ID).ToString());
                        }
                        catch
                        { }
                        break;

                    case SIGNAL_PEER_STATUS_AVAILABLE:
                        try
                        {
                            lock (_peerStatusLockList)
                            {
                                object lockObject = _peerStatusLockList[channelName];

                                lock (lockObject)
                                {
                                    Monitor.Pulse(lockObject);
                                }
                            }

                            Debug.Write("Connection.ReadDataAsync", "SIGNAL_PEER_STATUS_AVAILABLE; peerIP: " + ConvertToIP(channelName.ID).ToString());
                        }
                        catch
                        { }
                        break;

                    case SIGNAL_CONNECT_PROXY_TUNNEL:
                    {
                        ChannelStream remoteChannel1 = null;
                        Stream        remoteChannel2 = null;

                        try
                        {
                            //get remote peer ep
                            IPEndPoint tunnelToPeerEP = ConvertToIP(channelName.ID);

                            //add first stream into list
                            remoteChannel1 = new ChannelStream(this, channelName, ChannelType.ProxyTunnel);

                            lock (_proxyTunnelChannels)
                            {
                                _proxyTunnelChannels.Add(channelName, remoteChannel1);
                            }

                            //get remote channel service
                            Connection remotePeerConnection = _connectionManager.GetExistingConnection(tunnelToPeerEP);

                            //get remote stream for virtual connection
                            remoteChannel2 = remotePeerConnection.RequestVirtualConnectionChannel(_remotePeerEP);

                            //join current and remote stream
                            Joint joint = new Joint(remoteChannel1, remoteChannel2);
                            joint.Disposed += joint_Disposed;

                            lock (_tunnelJointList)
                            {
                                _tunnelJointList.Add(joint);
                            }

                            joint.Start();

                            Debug.Write("Connection.ReadDataAsync", "SIGNAL_CONNECT_PROXY_TUNNEL; tunnel to peerIP: " + tunnelToPeerEP.ToString());
                        }
                        catch
                        {
                            if (remoteChannel1 != null)
                            {
                                remoteChannel1.Dispose();
                            }

                            if (remoteChannel2 != null)
                            {
                                remoteChannel2.Dispose();
                            }
                        }
                    }
                    break;

                    case SIGNAL_DISCONNECT_PROXY_TUNNEL:
                        try
                        {
                            lock (_proxyTunnelChannels)
                            {
                                _proxyTunnelChannels[channelName].Dispose();
                            }

                            Debug.Write("Connection.ReadDataAsync", "SIGNAL_DISCONNECT_PROXY_TUNNEL; channel: " + channelName.ToString());
                        }
                        catch
                        { }
                        break;

                    case SIGNAL_CONNECT_VIRTUAL_CONNECTION:
                    {
                        ChannelStream channel = null;

                        try
                        {
                            //add current stream into list
                            channel = new ChannelStream(this, channelName, ChannelType.VirtualConnection);

                            lock (_virtualConnectionChannels)
                            {
                                _virtualConnectionChannels.Add(channelName, channel);
                            }

                            IPEndPoint virtualRemotePeerEP = ConvertToIP(channelName.ID);

                            Debug.Write("Connection.ReadDataAsync", "SIGNAL_CONNECT_VIRTUAL_CONNECTION; tunnel from peerIP: " + virtualRemotePeerEP.ToString());

                            //pass channel as virtual connection async
                            ThreadPool.QueueUserWorkItem(AcceptVirtualConnectionAsync, new object[] { channel, virtualRemotePeerEP });
                        }
                        catch
                        {
                            if (channel != null)
                            {
                                channel.Dispose();
                            }
                        }
                    }
                    break;

                    case SIGNAL_DISCONNECT_VIRTUAL_CONNECTION:
                        try
                        {
                            lock (_virtualConnectionChannels)
                            {
                                _virtualConnectionChannels[channelName].Dispose();
                            }

                            Debug.Write("Connection.ReadDataAsync", "SIGNAL_DISCONNECT_VIRTUAL_CONNECTION; channel: " + channelName.ToString());
                        }
                        catch
                        { }
                        break;

                    default:
                        throw new IOException("Invalid ChannelManager frame type.");
                    }
                }
            }
            catch
            { }
            finally
            {
                Dispose();
            }
        }
Пример #32
0
        public Stream RequestBitChatNetworkChannel(BinaryID channelName)
        {
            ChannelStream channel = new ChannelStream(this, channelName, ChannelType.BitChatNetwork);

            lock (_bitChatNetworkChannels)
            {
                _bitChatNetworkChannels.Add(channelName, channel);
            }

            //send connect signal
            WriteSignalFrame(channelName, SIGNAL_CONNECT_BIT_CHAT_NETWORK);

            return channel;
        }