Example #1
0
        public override void HandleResponse(Message.Message requestMessage, PeerConnection peerConnection, bool sign, IResponder responder)
        {
            if (!(requestMessage.Type == Message.Message.MessageType.RequestFf1 && requestMessage.Command == Rpc.Commands.Quit.GetNr()))
            {
                throw new ArgumentException("Message content is wrong for this handler.");
            }
            Logger.Debug("Received QUIT message {0}.", requestMessage);

            lock (PeerBean.PeerStatusListeners)
            {
                foreach (var listener in PeerBean.PeerStatusListeners)
                {
                    listener.PeerFailed(requestMessage.Sender,
                        new PeerException(PeerException.AbortCauseEnum.Shutdown, "shutdown"));
                }
            }
            if (requestMessage.IsUdp)
            {
                responder.ResponseFireAndForget();
            }
            else
            {
                responder.Response(CreateResponseMessage(requestMessage, Message.Message.MessageType.Ok));
            }
        }
Example #2
0
        /// <summary>
        /// CLoses the connection.
        /// </summary>
        public void Close()
        {
            if (this.peer != null)
            {
                try
                {
                    this.peer.Dispose();
                }
                catch (Exception)
                {
                    // Ignore.
                }

                this.peer = null;
            }

            if (this.xmppClient != null)
            {
                IDisposable Disposable;

                foreach (ISniffer Sniffer in this.xmppClient.Sniffers)
                {
                    this.xmppClient.Remove(Sniffer);

                    Disposable = Sniffer as IDisposable;
                    if (Disposable != null)
                    {
                        try
                        {
                            Disposable.Dispose();
                        }
                        catch (Exception)
                        {
                            // Ignore
                        }
                    }
                }

                try
                {
                    this.xmppClient.Dispose();
                }
                catch (Exception)
                {
                    // Ignore.
                }

                this.xmppClient = null;
            }
        }
        public void CreatesOneStatsStream()
        {
            var a          = new MemoryStream();
            var b          = new MemoryStream();
            var connection = new PeerConnection();

            Assert.AreEqual(null, connection.Stream);

            connection.Stream = a;
            Assert.AreNotSame(a, connection.Stream);

            connection.Stream = b;
            Assert.AreSame(b, connection.Stream);
        }
 public TcsPeerConnection Done(PeerConnection peerConnection)
 {
     lock (Lock)
     {
         if (!CompletedAndNotify())
         {
             return this;
         }
         _peerConnection = peerConnection;
         // TODO type needed?
     }
     NotifyListeners();
     return this;
 }
Example #5
0
        public void Remove_DoesNotExist()
        {
            var manager = new ConnectionManager();
            var peer    = new Peer {
                Id = aId
            };
            var a = new PeerConnection {
                RemotePeer = peer, Stream = Stream.Null
            };

            Assert.IsFalse(manager.Remove(a));
            Assert.IsFalse(manager.IsConnected(peer));
            Assert.AreEqual(0, manager.Connections.Count());
            Assert.IsNull(a.Stream);
        }
        public async Task SetRemoteDescription_Null()
        {
            using (var pc = new PeerConnection())
            {
                await pc.InitializeAsync();

                // Invalid arguments; SRD not even enqueued, fails immediately while validating arguments
                var message = new SdpMessage {
                    Type = SdpMessageType.Offer, Content = null
                };
                Assert.ThrowsAsync <ArgumentException>(async() => await pc.SetRemoteDescriptionAsync(message));
                message.Content = "";
                Assert.ThrowsAsync <ArgumentException>(async() => await pc.SetRemoteDescriptionAsync(message));
            }
        }
        public void Connect(string host, ServiceFlags serviceFlag)
        {
            if (string.IsNullOrWhiteSpace(host))
            {
                throw new ArgumentNullException(nameof(host));
            }

            var       iid   = Interop.Constants.InterfaceId;
            var       port  = PortsHelper.GetPort(_network);
            IPAddress ipAdr = null;

            if (!IPAddress.TryParse(host, out ipAdr))
            {
                // TODO : Throw an exception.
            }

            var adrBytes = ipAdr.MapToIPv6().GetAddressBytes();

            _serviceFlag      = serviceFlag;
            _currentIpAddress = new IpAddress(serviceFlag, adrBytes, ushort.Parse(port));
            // _client = new RpcClientApi(iid, RpcProtseq.ncacn_ip_tcp, host, port);
            _client = new RpcClientApi(iid, RpcProtseq.ncalrpc, null, host);
            // Connection to peers : https://bitcoin.org/en/developer-guide#connecting-to-peers
            var instance         = PeersStore.Instance();
            var transmittingNode = instance.GetMyIpAddress();
            var nonce            = NonceHelper.GetNonceUInt64();
            var versionMessage   = new VersionMessage(transmittingNode, _currentIpAddress, nonce, string.Empty, 0, false, _network);

            try
            {
                _peerConnection = new PeerConnection(adrBytes);
                var result = _messageCoordinator.Launch(this, versionMessage);
                if (result != null && result is VerackMessage)
                {
                    _peerConnection.Connect();
                    if (ConnectEvent != null)
                    {
                        ConnectEvent(this, new IpAddressEventArgs(_currentIpAddress));
                    }

                    _timer = new Timer(TimerElapsed, _autoEvent, CHECK_INTERVAL, CHECK_INTERVAL); // CHECK PEERS AVAILABILITY EVERY 60 SECONDS.
                }
            }
            catch (Interop.RpcException)
            {
                throw new PeerConnectorException(ErrorCodes.PeerRpcError);
            }
        }
Example #8
0
    private void OnMessage(SocketIOEvent ev)
    {
        string from = GetString(ev.data, "from");

        remotePeerId = from;
        string type = GetString(ev.data, "type");
        //Debug.Log($"socket received {type} from {from}");
        JSONObject payload = null;

        if (type != "init")
        {
            payload = ev.data["payload"];
        }

        Debug.Log(ev.data);
        switch (type)
        {
        case "init":
            _ = PeerConnection.StartConnection();
            break;

        case "offer":
            var sdpOffer = new SdpMessage {
                Type = SdpMessageType.Offer, Content = GetString(payload, "sdp").Replace("\\r\\n", "\r\n")
            };
            PeerConnection.HandleConnectionMessageAsync(sdpOffer).ContinueWith(_ =>
            {
                _nativePeer.CreateAnswer();
            }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.RunContinuationsAsynchronously);
            break;

        case "answer":
            var sdpAnswer = new SdpMessage {
                Type = SdpMessageType.Answer, Content = GetString(payload, "sdp").Replace("\\r\\n", "\r\n")
            };
            _ = PeerConnection.HandleConnectionMessageAsync(sdpAnswer);
            break;

        case "candidate":
            _nativePeer.AddIceCandidate(new IceCandidate()
            {
                SdpMid        = GetString(payload, "id"),
                SdpMlineIndex = GetInt(payload, "label"),
                Content       = GetString(payload, "candidate")
            });
            break;
        }
    }
Example #9
0
        /// <inheritdoc />
        public async Task ProcessMessageAsync(PeerConnection connection, Stream stream, CancellationToken cancel = default(CancellationToken))
        {
            // There is a race condition between getting the remote identity and
            // the remote sending the first wantlist.
            await connection.IdentityEstablished.Task.ConfigureAwait(false);

            while (true)
            {
                var request = await ProtoBufHelper.ReadMessageAsync <Message>(stream, cancel).ConfigureAwait(false);

                // Process want list
                if (request.wantlist != null && request.wantlist.entries != null)
                {
                    foreach (var entry in request.wantlist.entries)
                    {
                        var cid = Cid.Read(entry.block);
                        if (entry.cancel)
                        {
                            // TODO: Unwant specific to remote peer
                            Bitswap.Unwant(cid);
                        }
                        else
                        {
                            // TODO: Should we have a timeout?
                            var _ = GetBlockAsync(cid, connection.RemotePeer, CancellationToken.None);
                        }
                    }
                }

                // Forward sent blocks to the block service.  Eventually
                // bitswap will here about and them and then continue
                // any tasks (GetBlockAsync) waiting for the block.
                if (request.payload != null)
                {
                    log.Debug($"got block(s) from {connection.RemotePeer}");
                    foreach (var sentBlock in request.payload)
                    {
                        using (var ms = new MemoryStream(sentBlock.prefix))
                        {
                            var version     = ms.ReadVarint32();
                            var contentType = ms.ReadMultiCodec().Name;
                            var multiHash   = MultiHash.GetHashAlgorithmName(ms.ReadVarint32());
                            await Bitswap.OnBlockReceivedAsync(connection.RemotePeer, sentBlock.data, contentType, multiHash);
                        }
                    }
                }
            }
        }
Example #10
0
        // When a connection is established
        // (1) Send the local peer's want list to the remote
        async void Swarm_ConnectionEstablished(object sender, PeerConnection connection)
        {
            try
            {
                // There is a race condition between getting the remote identity and
                // the remote sending the first wantlist.
                await connection.IdentityEstablished.Task;

                // Fire and forget.
                var _ = SendWantListAsync(connection.RemotePeer);
            }
            catch (Exception e)
            {
                log.Warn("Sending want list", e);
            }
        }
Example #11
0
        public Server(AuthConfig cfg)
        {
            Config = cfg;

            Prefixes = Config.ListenPrefixes;
            DB       = GetAuthDB();
            DB.Startup(cfg.AuthDBLocation);

            this.MessageProcessor = ProcessAuthMessage;

            foreach (var o in cfg.OutboundUpdatePeers)
            {
                var p = new PeerConnection(o.Name, o.Host, Encryption.BuildCrypto(o.APIKey), DB);
                PeerConnections.Add(o.Name, p);
            }
        }
Example #12
0
        protected override void InitChannel(TcpSocketChannel channel)
        {
            try
            {
                Channel peer = new PeerConnection();
                peer.Init(channel.Pipeline, this.remote_id, this.is_discovery_mode);

                channel.Configuration.RecvByteBufAllocator = new FixedRecvByteBufAllocator(256 * 1024);
                channel.Configuration.SetOption(ChannelOption.SoRcvbuf, 256 * 1024);
                channel.Configuration.SetOption(ChannelOption.SoBacklog, 1024);
            }
            catch (System.Exception e)
            {
                Logger.Error(e.Message);
            }
        }
Example #13
0
        /// <inheritdoc />
        public async Task ProcessMessageAsync(PeerConnection connection, Stream stream, CancellationToken cancel = default(CancellationToken))
        {
            while (true)
            {
                // Read the message.
                var request = new byte[PingSize];
                await stream.ReadExactAsync(request, 0, PingSize, cancel).ConfigureAwait(false);

                log.Debug($"got ping from {connection.RemotePeer}");

                // Echo the message
                await stream.WriteAsync(request, 0, PingSize, cancel).ConfigureAwait(false);

                await stream.FlushAsync(cancel).ConfigureAwait(false);
            }
        }
        //////////////////////////////////////////////////
        // For video streaming
        //////////////////////////////////////////////////

        private void App_Suspending(object sender, SuspendingEventArgs e)
        {
            if (_peerConnection != null)
            {
                _peerConnection.Close();
                _peerConnection.Dispose();
                _peerConnection = null;
            }
            //localVideoPlayerElement.SetMediaPlayer(null);
            if (_signaler != null)
            {
                _signaler.StopPollingAsync();
                _signaler = null;
            }
            remoteVideoPlayerElement.SetMediaPlayer(null);
        }
Example #15
0
        public WebRTCSession(WebRTCHost webrtc)
        {
            this.webrtc        = webrtc;
            this.cancelSession = new CancellationTokenSource();
            this.peer          = new PeerConnection();
            this.source        = new SceneVideoSource()
            {
                PeerConnection = peer
            };

            this.peer.IceStateChanged += OnIceStateChanged;
            this.peer.Connected       += OnConnected;

            this.webrtc.VideoFrameReady += OnFrameReady;
            this.webrtc.Register(this);
        }
Example #16
0
        private bool Check(PeerConnection peer, InventoryMessage message)
        {
            InventoryType type = message.InventoryType;
            int           size = message.GetHashList().Count;

            if (peer.IsNeedSyncFromPeer || peer.IsNeedSyncUs)
            {
                Logger.Warning(
                    string.Format("Drop inv: {0} size: {1} from Peer {2}, syncFromUs: {3}, syncFromPeer: {4}.",
                                  type,
                                  size,
                                  peer.Address.ToString(),
                                  peer.IsNeedSyncUs,
                                  peer.IsNeedSyncFromPeer));

                return(false);
            }

            if (type == InventoryType.Trx)
            {
                int count = peer.NodeStatistics.MessageStatistics.MineralInTrxInventory.GetCount(10);
                if (count > max_count)
                {
                    Logger.Warning(
                        string.Format("Drop inv: {0} size: {1} from Peer {2}, Inv count: {3} is overload.",
                                      type,
                                      size,
                                      peer.Address,
                                      count));

                    return(false);
                }

                if (Manager.Instance.TransactionHandler.IsBusy)
                {
                    Logger.Warning(
                        string.Format("Drop inv: {0} size: {1} from Peer {2}, transactionsMsgHandler is busy.",
                                      type,
                                      size,
                                      peer.Address));

                    return(false);
                }
            }

            return(true);
        }
Example #17
0
        /// <inheritdoc />
        public async Task ProcessMessageAsync(PeerConnection connection, Stream stream, CancellationToken cancel = default(CancellationToken))
        {
            var request = await ProtoBufHelper.ReadMessageAsync <Message>(stream, cancel).ConfigureAwait(false);

            // There is a race condition between getting the remote identity and
            // the remote sending the first wantlist.
            await connection.IdentityEstablished.Task.ConfigureAwait(false);

            log.Debug($"got message from {connection.RemotePeer}");

            // Process want list
            if (request.wantlist != null && request.wantlist.entries != null)
            {
                log.Debug("got want list");
                foreach (var entry in request.wantlist.entries)
                {
                    var s   = Base58.ToBase58(entry.block);
                    Cid cid = s;
                    if (entry.cancel)
                    {
                        // TODO: Unwant specific to remote peer
                        Bitswap.Unwant(cid);
                    }
                    else
                    {
                        // TODO: Should we have a timeout?
                        var _ = GetBlockAsync(cid, connection.RemotePeer, CancellationToken.None);
                    }
                }
            }

            // Forward sent blocks to the block service.  Eventually
            // bitswap will here about and them and then continue
            // any tasks (GetBlockAsync) waiting for the block.
            if (request.blocks != null)
            {
                log.Debug("got some blocks");
                foreach (var sentBlock in request.blocks)
                {
                    ++Bitswap.BlocksReceived;
                    Bitswap.DataReceived += (ulong)sentBlock.Length;
                    await Bitswap.BlockService.PutAsync(sentBlock, pin : false).ConfigureAwait(false);

                    // TODO: Detect if duplicate and update stats
                }
            }
        }
        public async void PeerConnectionLocalConnect()
        {
            using (var pc1 = new PeerConnection())
            {
                await pc1.InitializeAsync();

                using (var pc2 = new PeerConnection())
                {
                    await pc2.InitializeAsync();

                    // Prepare SDP event handlers
                    pc1.LocalSdpReadytoSend += async(string type, string sdp) =>
                    {
                        await pc2.SetRemoteDescriptionAsync(type, sdp);

                        if (type == "offer")
                        {
                            pc2.CreateAnswer();
                        }
                    };
                    pc2.LocalSdpReadytoSend += async(string type, string sdp) =>
                    {
                        await pc1.SetRemoteDescriptionAsync(type, sdp);

                        if (type == "offer")
                        {
                            pc1.CreateAnswer();
                        }
                    };
                    pc1.IceCandidateReadytoSend += (string candidate, int sdpMlineindex, string sdpMid)
                                                   => pc2.AddIceCandidate(sdpMid, sdpMlineindex, candidate);
                    pc2.IceCandidateReadytoSend += (string candidate, int sdpMlineindex, string sdpMid)
                                                   => pc1.AddIceCandidate(sdpMid, sdpMlineindex, candidate);

                    // Connect
                    var conn1 = new ManualResetEventSlim(initialState: false);
                    var conn2 = new ManualResetEventSlim(initialState: false);
                    pc1.Connected += () => conn1.Set();
                    pc2.Connected += () => conn2.Set();
                    pc1.CreateOffer();
                    WaitForSdpExchangeCompleted(conn1, conn2);

                    pc1.Close();
                    pc2.Close();
                }
            }
        }
Example #19
0
            /// <summary>
            /// Destroys the data channel object.
            /// </summary>
            /// <returns>
            /// MLResult.Result will be <c>MLResult.Code.Ok</c> if destroying all handles was successful.
            /// MLResult.Result will be <c>MLResult.Code.WebRTCResultInstanceNotCreated</c> if MLWebRTC instance was not created.
            /// MLResult.Result will be <c>MLResult.Code.WebRTCResultMismatchingHandle</c> if an incorrect handle was sent.
            /// </returns>
            public MLResult Destroy()
            {
                if (this.ParentConnection == null || !MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
                {
                    return(MLResult.Create(MLResult.Code.InvalidParam));
                }

                MLResult.Code resultCode = NativeBindings.MLWebRTCDataChannelDestroy(this.ParentConnection.Handle, this.Handle);
                if (DidNativeCallSucceed(resultCode, "MLWebRTCDataChannelDestroy()"))
                {
                    this.Handle           = MagicLeapNativeBindings.InvalidHandle;
                    this.ParentConnection = null;
                }

                this.gcHandle.Free();
                return(MLResult.Create(resultCode));
            }
        /// <summary>
        /// Is called when game data has been received.
        /// </summary>
        /// <param name="FromPlayer">Data came from this player.</param>
        /// <param name="Connection">Data came over this connection.</param>
        /// <param name="Packet">Data received.</param>
        protected virtual void GameDataReceived(Player FromPlayer, PeerConnection Connection, byte[] Packet)
        {
            GameDataEventHandler h = this.OnGameDataReceived;

            if (!(h is null))
            {
                try
                {
                    h(this, new GameDataEventArgs(FromPlayer, Connection, Packet));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    Debug.WriteLine(ex.StackTrace.ToString());
                }
            }
        }
Example #21
0
        public void TearDownConnectin()
        {
            // Unregister all callbacks
            pc1_.LocalSdpReadytoSend     -= OnLocalSdpReady1;
            pc2_.LocalSdpReadytoSend     -= OnLocalSdpReady2;
            pc1_.IceCandidateReadytoSend -= OnIceCandidateReadytoSend1;
            pc2_.IceCandidateReadytoSend -= OnIceCandidateReadytoSend2;
            pc1_.IceStateChanged         -= OnIceStateChanged1;
            pc2_.IceStateChanged         -= OnIceStateChanged2;
            pc1_.RenegotiationNeeded     -= OnRenegotiationNeeded1;
            pc2_.RenegotiationNeeded     -= OnRenegotiationNeeded2;
            pc1_.TrackAdded   -= OnTrackAdded1;
            pc2_.TrackAdded   -= OnTrackAdded2;
            pc1_.TrackRemoved -= OnTrackRemoved1;
            pc2_.TrackRemoved -= OnTrackRemoved2;

            // Clean-up callback events
            trackAddedEvent1_.Dispose();
            trackAddedEvent1_ = null;
            trackRemovedEvent1_.Dispose();
            trackRemovedEvent1_ = null;
            trackAddedEvent2_.Dispose();
            trackAddedEvent2_ = null;
            trackRemovedEvent2_.Dispose();
            trackRemovedEvent2_ = null;
            renegotiationEvent1_.Dispose();
            renegotiationEvent1_ = null;
            renegotiationEvent2_.Dispose();
            renegotiationEvent2_ = null;
            iceConnectedEvent1_.Dispose();
            iceConnectedEvent1_ = null;
            iceConnectedEvent2_.Dispose();
            iceConnectedEvent2_ = null;
            connectedEvent1_.Dispose();
            connectedEvent1_ = null;
            connectedEvent2_.Dispose();
            connectedEvent2_ = null;

            // Destroy peers
            pc1_.Close();
            pc1_.Dispose();
            pc1_ = null;
            pc2_.Close();
            pc2_.Dispose();
            pc2_ = null;
        }
Example #22
0
        public void ProcessMessage(PeerConnection peer, MineralMessage message)
        {
            InventoryMessage inventory_message = (InventoryMessage)message;
            InventoryType    type = inventory_message.InventoryType;

            if (!Check(peer, inventory_message))
            {
                return;
            }

            foreach (SHA256Hash id in inventory_message.GetHashList())
            {
                Item item = new Item(id, type);
                peer.AddInventoryReceive(item, Helper.CurrentTimeMillis());
                Manager.Instance.AdvanceService.AddInventory(item);
            }
        }
Example #23
0
        /// <summary>
        /// Peer connection state.
        /// </summary>
        /// <param name="Peer">Peer connection.</param>
        /// <param name="Parent">Parent object.</param>
        /// <param name="RemoteFullJID">Remote Full JID</param>
        /// <param name="StreamHeader">Stream header</param>
        /// <param name="StreamFooter">Stream footer</param>
        /// <param name="StreamId">Stream ID</param>
        /// <param name="Version">Protocol version</param>
        /// <param name="Callback">Callback method</param>
        /// <param name="State">State object</param>
        public PeerState(PeerConnection Peer, XmppServerlessMessaging Parent, string RemoteFullJID, string StreamHeader, string StreamFooter,
                         string StreamId, double Version, PeerConnectionEventHandler Callback, object State)
        {
            this.parent        = Parent;
            this.peer          = Peer;
            this.remoteFullJid = RemoteFullJID;
            this.streamHeader  = StreamHeader;
            this.streamFooter  = StreamFooter;
            this.streamId      = StreamId;
            this.version       = Version;
            this.parentFullJid = Parent.FullJid;

            this.callbacks = new LinkedList <KeyValuePair <PeerConnectionEventHandler, object> >();
            this.callbacks.AddLast(new KeyValuePair <PeerConnectionEventHandler, object>(Callback, State));

            this.AddPeerHandlers();
        }
Example #24
0
        public void PeerDisconnectedEvent_ConnectionClose()
        {
            var gotEvent = 0;
            var manager  = new ConnectionManager();

            manager.PeerDisconnected += (s, e) => gotEvent += 1;
            var peerA = new Peer {
                Id = aId
            };
            var a = new PeerConnection {
                RemotePeer = peerA, Stream = Stream.Null
            };

            manager.Add(a);
            a.Dispose();
            Assert.AreEqual(1, gotEvent);
        }
Example #25
0
        public async void PeerConnectionLocalConnect()
        {
            using (var pc1 = new PeerConnection())
            {
                await pc1.InitializeAsync();

                using (var pc2 = new PeerConnection())
                {
                    await pc2.InitializeAsync();

                    // Prepare SDP event handlers
                    pc1.LocalSdpReadytoSend += async(SdpMessage message) =>
                    {
                        await pc2.SetRemoteDescriptionAsync(message);

                        if (message.Type == SdpMessageType.Offer)
                        {
                            pc2.CreateAnswer();
                        }
                    };
                    pc2.LocalSdpReadytoSend += async(SdpMessage message) =>
                    {
                        await pc1.SetRemoteDescriptionAsync(message);

                        if (message.Type == SdpMessageType.Offer)
                        {
                            pc1.CreateAnswer();
                        }
                    };
                    pc1.IceCandidateReadytoSend += (IceCandidate candidate) => pc2.AddIceCandidate(candidate);
                    pc2.IceCandidateReadytoSend += (IceCandidate candidate) => pc1.AddIceCandidate(candidate);

                    // Connect
                    var conn1 = new ManualResetEventSlim(initialState: false);
                    var conn2 = new ManualResetEventSlim(initialState: false);
                    pc1.Connected += () => conn1.Set();
                    pc2.Connected += () => conn2.Set();
                    pc1.CreateOffer();
                    WaitForSdpExchangeCompleted(conn1, conn2);

                    pc1.Close();
                    pc2.Close();
                }
            }
        }
Example #26
0
 public override void HandleResponse(Message.Message requestMessage, PeerConnection peerConnection, bool sign, IResponder responder)
 {
     if (!(requestMessage.Type == Message.Message.MessageType.RequestFf1
         && requestMessage.Command == Rpc.Commands.Broadcast.GetNr()))
     {
         throw new ArgumentException("Message content is wrong for this handler.");   
     }
     Logger.Debug("Received BROADCAST message: {0}.", requestMessage);
     BroadcastHandler.Receive(requestMessage);
     if (requestMessage.IsUdp)
     {
         responder.ResponseFireAndForget();
     }
     else
     {
         responder.Response(CreateResponseMessage(requestMessage, Message.Message.MessageType.Ok));    
     }
 }
Example #27
0
        private static void SendDirectRequest(RequestHandler requestHandler, PeerConnection peerConnection)
        {
            var taskCc = peerConnection.AcquireAsync(requestHandler.TcsResponse);

            taskCc.ContinueWith(tcc =>
            {
                if (!tcc.IsFaulted)
                {
                    var requestMessage = requestHandler.TcsResponse.Task.AsyncState as Message.Message;
                    requestMessage.SetKeepAlive(true);
                    requestHandler.SendTcpAsync(peerConnection.ChannelCreator, peerConnection);
                }
                else
                {
                    requestHandler.TcsResponse.SetException(new TaskFailedException("Could not acquire channel (2).", tcc));
                }
            });
        }
Example #28
0
        /// <summary>
        /// Construct a signaler instance for the given peer connection, with an explicit pipe name.
        /// </summary>
        /// <param name="peerConnection">The peer connection to act as a signaler for. This instance
        /// will subscribe to the <see cref="PeerConnection.LocalSdpReadytoSend"/> and
        /// <see cref="PeerConnection.IceCandidateReadytoSend"/> events to manage outgoing signaling messages.</param>
        /// <param name="pipeName">The unique pipe name shared by the local and remote peers.</param>
        public NamedPipeSignaler(PeerConnection peerConnection, string pipeName)
        {
            PeerConnection = peerConnection;
            _basePipeName  = pipeName;

            // Try to create the server, if not already existing
            IsClient = false;
            try
            {
                _serverPipe = new NamedPipeServerStream(pipeName, PipeDirection.In);
                Console.WriteLine("Created pipe server; acting as server.");
            }
            catch (IOException)
            {
                Console.WriteLine("Pipe server already exists; acting as client.");
                IsClient = true;
            }
        }
Example #29
0
        /// <inheritdoc />
        public async Task ProcessMessageAsync(PeerConnection connection, Stream stream, CancellationToken cancel = default(CancellationToken))
        {
            log.Debug("start processing requests from " + connection.RemoteAddress);
            var muxer = new Muxer
            {
                Channel    = stream,
                Connection = connection,
                Receiver   = true
            };

            muxer.SubstreamCreated += (s, e) => connection.ReadMessages(e, CancellationToken.None);

            // Attach muxer to the connection.  It now becomes the message reader.
            connection.MuxerEstablished.SetResult(muxer);
            await muxer.ProcessRequestsAsync();

            log.Debug("stop processing from " + connection.RemoteAddress);
        }
Example #30
0
        public void PeerDisconnectedEvent_RemovingPeer()
        {
            var gotEvent = false;
            var manager  = new ConnectionManager();

            manager.PeerDisconnected += (s, e) => gotEvent = true;
            var peerA = new Peer {
                Id = aId
            };
            var a = new PeerConnection {
                RemotePeer = peerA, Stream = Stream.Null
            };

            manager.Add(a);

            manager.Remove(peerA.Id);
            Assert.IsTrue(gotEvent);
        }
Example #31
0
 public override void HandleResponse(Message.Message requestMessage, PeerConnection peerConnection, bool sign, IResponder responder)
 {
     if (!(requestMessage.Type == Message.Message.MessageType.RequestFf1 &&
           requestMessage.Command == Rpc.Commands.Broadcast.GetNr()))
     {
         throw new ArgumentException("Message content is wrong for this handler.");
     }
     Logger.Debug("Received BROADCAST message: {0}.", requestMessage);
     BroadcastHandler.Receive(requestMessage);
     if (requestMessage.IsUdp)
     {
         responder.ResponseFireAndForget();
     }
     else
     {
         responder.Response(CreateResponseMessage(requestMessage, Message.Message.MessageType.Ok));
     }
 }
Example #32
0
        public void IfMessageIsNotHandledLocaly_ItIsForwardedAway()
        {
            messageRouter = CreateMessageRouter(externalRoutingTable: externalRoutingTable.Object);
            var message        = Message.Create(new SimpleMessage()).As <Message>();
            var otherNode      = new ReceiverIdentifier(Guid.NewGuid().ToByteArray());
            var peerConnection = new PeerConnection {
                Node = new Node("tcp://127.0.0.1:9009", otherNode.Identity)
            };

            externalRoutingTable.Setup(m => m.FindRoutes(It.IsAny <ExternalRouteLookupRequest>())).Returns(new[] { peerConnection });
            localRouterSocket.SetupMessageReceived(message, ReceiveMessageDelay);
            //
            messageRouter.Start();
            ReceiveMessageCompletionDelay.Sleep();
            messageRouter.Stop();
            //
            scaleOutSocket.Verify(m => m.SendMessage(message));
        }
Example #33
0
        private void Connect_Callback(IAsyncResult ar)
        {
            try
            {
                InitiatorContext context = (InitiatorContext) ar.AsyncState;

                context.Socket.EndConnect(ar);

                PeerConnection connection = new PeerConnection(context.Socket, context.Endpoint, null);

                Connected(connection);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to connect: " + ex.Message);

                ConnectFailed(this);
            }
        }
Example #34
0
        public void Maintains_PeerConnectedAddress()
        {
            var address1 = "/ip4/127.0.0.1/tcp/4007";
            var address2 = "/ip4/127.0.0.2/tcp/4007";

            var manager = new ConnectionManager();
            var peer    = new Peer {
                Id = aId
            };
            var a = new PeerConnection {
                RemotePeer = peer, RemoteAddress = address1, Stream = Stream.Null
            };
            var b = new PeerConnection {
                RemotePeer = peer, RemoteAddress = address2, Stream = Stream.Null
            };

            Assert.AreSame(a, manager.Add(a));
            Assert.IsTrue(manager.IsConnected(peer));
            Assert.AreEqual(1, manager.Connections.Count());
            Assert.IsNotNull(a.Stream);
            Assert.AreEqual(address1, peer.ConnectedAddress);

            Assert.AreSame(b, manager.Add(b));
            Assert.IsTrue(manager.IsConnected(peer));
            Assert.AreEqual(2, manager.Connections.Count());
            Assert.IsNotNull(a.Stream);
            Assert.IsNotNull(b.Stream);
            Assert.AreEqual(address1, peer.ConnectedAddress);

            Assert.IsTrue(manager.Remove(a));
            Assert.IsTrue(manager.IsConnected(peer));
            Assert.AreEqual(1, manager.Connections.Count());
            Assert.IsNull(a.Stream);
            Assert.IsNotNull(b.Stream);
            Assert.AreEqual(address2, peer.ConnectedAddress);

            Assert.IsTrue(manager.Remove(b));
            Assert.IsFalse(manager.IsConnected(peer));
            Assert.AreEqual(0, manager.Connections.Count());
            Assert.IsNull(a.Stream);
            Assert.IsNull(b.Stream);
            Assert.IsNull(peer.ConnectedAddress);
        }
Example #35
0
        /// <summary>
        /// Forwards the request to a handler.
        /// </summary>
        /// <param name="requestMessage">The request requestMessage.</param>
        /// <param name="peerConnection">The peer connection that can be used for communication.</param>
        /// <param name="responder">The responder used to respond the response requestMessage.</param>
        public void ForwardMessage(Message.Message requestMessage, PeerConnection peerConnection, IResponder responder)
        {
            // request requestMessage from Dispatcher (server-side)
            // -> forward to HandleResponse of this DispatchHandler

            // Here, we need a referral since we got contacted and we don't know if
            // we can contact the peer with its address. The peer may be behind a NAT.
            lock (PeerBean.PeerStatusListeners)
            {
                foreach (IPeerStatusListener listener in PeerBean.PeerStatusListeners)
                {
                    listener.PeerFound(requestMessage.Sender, requestMessage.Sender, peerConnection);
                }
            }

            try
            {
                HandleResponse(requestMessage, peerConnection, _sign, responder);
            }
            catch (Exception ex)
            {
                lock (PeerBean.PeerStatusListeners)
                {
                    foreach (IPeerStatusListener listener in PeerBean.PeerStatusListeners)
                    {
                        listener.PeerFailed(requestMessage.Sender, new PeerException(ex));
                    }
                }
                Logger.Error("Exception in custom dispatch handler.", ex);
                responder.Failed(Message.Message.MessageType.Exception);
            }
        }
Example #36
0
 /// <summary>
 /// If the requestMessage is OK, that has been previously checked by the user using CheckMessage,
 /// a response to the requestMessage is generated here.
 /// </summary>
 /// <param name="requestMessage">The request requestMessage.</param>
 /// <param name="peerConnection"></param>
 /// <param name="sign">Flag indicating whether the requestMessage is signed.</param>
 /// <param name="responder"></param>
 public abstract void HandleResponse(Message.Message requestMessage, PeerConnection peerConnection, bool sign,
     IResponder responder);
 public void OnSignalingChange(PeerConnection.SignalingState newState)
 {
 }
 public RunnableAnonymousInnerClassHelper(AppRTCDemoActivity outerInstance, PeerConnection finalPC)
 {
     this.outerInstance = outerInstance;
     this.finalPC = finalPC;
 }
 public void OnIceConnectionChange(PeerConnection.IceConnectionState newState)
 {
 }
 public void OnIceGatheringChange(PeerConnection.IceGatheringState newState)
 {
 }
Example #41
0
        private ITcpClientChannel SendTcpCreateChannel(IPEndPoint recipient, ChannelCreator channelCreator,
            PeerConnection peerConnection, IChannelHandler handler, TimeoutFactory timeoutHandler, int connectTimeoutMillis)
        {
            // create pipeline
            var handlers = new Dictionary<string, IChannelHandler>();
            if (timeoutHandler != null)
            {
                handlers.Add("timeout0", timeoutHandler.CreateIdleStateHandlerTomP2P());
                handlers.Add("timeout1", timeoutHandler.CreateTimeHandler());
            }
            handlers.Add("decoder", new TomP2PCumulationTcp(ChannelClientConfiguration.SignatureFactory));
            handlers.Add("encoder", new TomP2POutbound(false, ChannelClientConfiguration.SignatureFactory));
            if (peerConnection != null)
            {
                // we expect responses on this connection
                handlers.Add("dispatcher", _dispatcher);
            }
            if (timeoutHandler != null)
            {
                handlers.Add("handler", handler);
            }
            HeartBeat heartBeat = null;
            if (peerConnection != null)
            {
                heartBeat = new HeartBeat(peerConnection.HeartBeatMillis, PingBuilderFactory);
                handlers.Add("heartbeat", heartBeat);
            }

            var channel = channelCreator.CreateTcp(recipient, connectTimeoutMillis, handlers);

            if (peerConnection != null && channel != null)
            {
                peerConnection.SetChannel(channel);
                heartBeat.SetPeerConnection(peerConnection);
            }
            return channel;
        }
Example #42
0
        /// <summary>
        /// // TODO document
        /// </summary>
        /// <param name="handler"></param>
        /// <param name="tcsResponse"></param>
        /// <param name="message"></param>
        /// <param name="channelCreator"></param>
        /// <param name="idleTcpSeconds"></param>
        /// <param name="connectTimeoutMillis"></param>
        /// <param name="peerConnection"></param>
        /// <param name="timeoutHandler"></param>
        private async Task HandleRelayAsync(IInboundHandler handler, TaskCompletionSource<Message.Message> tcsResponse,
            Message.Message message, ChannelCreator channelCreator, int idleTcpSeconds, int connectTimeoutMillis,
            PeerConnection peerConnection, TimeoutFactory timeoutHandler)
        {
            var taskPingDone = PingFirst(message.Recipient.PeerSocketAddresses);
            await taskPingDone;
            if (!taskPingDone.IsFaulted)
            {
                var recipient = PeerSocketAddress.CreateSocketTcp(taskPingDone.Result);
                var channel = SendTcpCreateChannel(recipient, channelCreator, peerConnection, handler,
                    timeoutHandler, connectTimeoutMillis);
                await AfterConnectAsync(tcsResponse, message, channel, handler == null);

                // TODO add this before AfterConnect?
                var taskResponse = tcsResponse.Task;
                await taskResponse;
                if (taskResponse.IsFaulted)
                {
                    if (taskResponse.Result != null &&
                        taskResponse.Result.Type != Message.Message.MessageType.User1)
                    {
                        // "clearInactivePeerSocketAddress"
                        var tmp = new List<PeerSocketAddress>();
                        foreach (var psa in message.Recipient.PeerSocketAddresses)
                        {
                            if (psa != null)
                            {
                                if (!psa.Equals(taskPingDone.Result))
                                {
                                    tmp.Add(psa);
                                }
                            }
                        }
                        message.SetPeerSocketAddresses(tmp);

                        await SendTcpAsync(handler, tcsResponse, message, channelCreator, idleTcpSeconds,
                            connectTimeoutMillis, peerConnection);
                    }
                }
            }
            else
            {
                // .NET-specific:
                tcsResponse.SetException(new TaskFailedException("No relay could be contacted. <-> " + taskPingDone.Exception));
            }
        }
Example #43
0
        public override void Read(ChannelHandlerContext ctx, object msg)
        {
            // server-side:
            // message comes (over network) from sender
            // -> correct DispatchHandler handles response

            // Java uses a SimpleChannelInboundHandler that only expects Message objects
            var requestMessage = msg as Message.Message;
            if (requestMessage == null)
            {
                return;
            }
            
            Logger.Debug("Received request message {0} from channel {1}.", requestMessage, ctx.Channel);
            if (requestMessage.Version != _p2PId)
            {
                Logger.Error("Wrong version. We are looking for {0}, but we got {1}. Received: {2}.", _p2PId, requestMessage.Version, requestMessage);
                ctx.Close(); // TODO used?
                lock (_peerBeanMaster.PeerStatusListeners)
                {
                    foreach (IPeerStatusListener listener in _peerBeanMaster.PeerStatusListeners)
                    {
                        listener.PeerFailed(requestMessage.Sender,
                            new PeerException(PeerException.AbortCauseEnum.PeerError, "Wrong P2P version."));
                    }
                }
                return;
            }
            if (!requestMessage.IsRequest())
            {
                Logger.Debug("Handing request message to the next handler. {0}", requestMessage);
                ctx.FireRead(msg);
                return;
            }

            IResponder responder = new DirectResponder(this, _peerBeanMaster, ctx, requestMessage);
            DispatchHandler myHandler = AssociatedHandler(requestMessage);
            if (myHandler != null)
            {
                bool isUdp = ctx.Channel.IsUdp;
                bool isRelay = requestMessage.Sender.IsRelayed;
                if (!isRelay && requestMessage.PeerSocketAddresses.Count != 0)
                {
                    PeerAddress sender =
                        requestMessage.Sender.ChangePeerSocketAddresses(requestMessage.PeerSocketAddresses);
                    requestMessage.SetSender(sender);
                }
                Logger.Debug("About to respond to request message {0}.", requestMessage);

                // handle the request message
                PeerConnection peerConnection = null;
                if (!isUdp)
                {
                    var tcpChannel = ctx.Channel as ITcpChannel;
                    peerConnection = new PeerConnection(requestMessage.Sender, tcpChannel, _heartBeatMillis);
                }
                myHandler.ForwardMessage(requestMessage, peerConnection, responder);
            }
            else
            {
                // do better error handling
                // if a handler is not present at all, print a warning
                if (_ioHandlers.Count == 0)
                {
                    Logger.Debug("No handler found for request message {0}. This peer has probably been shut down.", requestMessage);
                }
                else
                {
                    var knownCommands = KnownCommands();
                    if (knownCommands.Contains(Convert.ToInt32(requestMessage.Command)))
                    {
                        var sb = new StringBuilder();
                        foreach (int cmd in knownCommands)
                        {
                            sb.Append((Rpc.Rpc.Commands) cmd + "; ");
                        }
                        Logger.Warn("No handler found for request message {0}. Is the RPC command {1} registered? Found registered: {2}.", requestMessage, (Rpc.Rpc.Commands) requestMessage.Command, sb);
                    }
                    else
                    {
                        Logger.Debug("No handler found for request message {0}. This peer has probably been partially shut down.", requestMessage);
                    }
                }

                // return response that states that no handler was found
                var responseMessage = DispatchHandler.CreateResponseMessage(requestMessage,
                    Message.Message.MessageType.UnknownId, _peerBeanMaster.ServerPeerAddress);

                Respond(ctx, responseMessage);
            }
        }
Example #44
0
 /// <summary>
 /// Opens a TCP connection and keeps it open. The user can provide the idle timeout, which means 
 /// that the connection gets closed after that time of inactivity. If the other peer goes offline
 /// or closes the connection (due to inactivity), further requests with this connections re-opens 
 /// the connection. This methods blocks until a connection can be reserved.
 /// </summary>
 /// <param name="destination">The endpoint to connect to.</param>
 /// <param name="heartBeatMillis"></param>
 /// <returns></returns>
 public TcsPeerConnection CreatePeerConnection(PeerAddress destination, int heartBeatMillis)
 {
     var tcsPeerConnection = new TcsPeerConnection(destination);
     var taskCc = ConnectionBean.Reservation.CreatePermanentAsync(1);
     taskCc.ContinueWith(tcc =>
     {
         if (!tcc.IsFaulted)
         {
             var cc = tcc.Result;
             var peerConnection = new PeerConnection(destination, cc, heartBeatMillis);
             tcsPeerConnection.Done(peerConnection);
         }
         else
         {
             tcsPeerConnection.SetException(new TaskFailedException(tcc));
         }
     });
     return tcsPeerConnection;
 }
Example #45
0
 public SendDirectBuilder SendDirect(PeerConnection peerConnection)
 {
     return new SendDirectBuilder(this, peerConnection);
 }
Example #46
0
 /// <summary>
 /// Sends a TCP message and expects a response.
 /// </summary>
 /// <param name="channelCreator">The channel creator will create a TCP connection.</param>
 /// <param name="peerConnection"></param>
 /// <returns>The future task that was added in the constructor.</returns>
 public Task<Message.Message> SendTcpAsync(ChannelCreator channelCreator, PeerConnection peerConnection)
 {
     var sendTask = ConnectionBean.Sender.SendTcpAsync(this, _tcsResponse, _message, channelCreator, IdleTcpSeconds,
         ConnectionTimeoutTcpMillis, peerConnection);
     return ExecuteAsync(sendTask);
 }
Example #47
0
        /// <summary>
        /// Sends a message via TCP.
        /// </summary>
        /// <param name="handler">The handler to deal with the response message.</param>
        /// <param name="tcsResponse">The TCS for the response message. (FutureResponse equivalent.)</param>
        /// <param name="message">The message to send.</param>
        /// <param name="channelCreator">The channel creator for the TCP channel.</param>
        /// <param name="idleTcpSeconds">The idle time until message fail.</param>
        /// <param name="connectTimeoutMillis">The idle time for the connection setup.</param>
        /// <param name="peerConnection"></param>
        /// <returns></returns>
        public async Task SendTcpAsync(IInboundHandler handler, TaskCompletionSource<Message.Message> tcsResponse,
            Message.Message message, ChannelCreator channelCreator, int idleTcpSeconds, int connectTimeoutMillis,
            PeerConnection peerConnection)
        {
            // no need to continue if already finished
            if (tcsResponse.Task.IsCompleted)
            {
                return;
            }
            RemovePeerIfFailed(tcsResponse, message);

            bool isFireAndForget = handler == null;

            // we need to set the neighbors if we use relays
            if (message.Sender.IsRelayed && message.Sender.PeerSocketAddresses.Count != 0)
            {
                message.SetPeerSocketAddresses(message.Sender.PeerSocketAddresses);
            }
            if (peerConnection != null && peerConnection.Channel != null && peerConnection.Channel.IsOpen)
            {
                var channel = SendTcpPeerConnection(peerConnection, handler, channelCreator, tcsResponse);
                await AfterConnectAsync(tcsResponse, message, channel, isFireAndForget);
            }
            else if (channelCreator != null)
            {
                var timeoutHandler = CreateTimeoutHandler(tcsResponse, idleTcpSeconds, handler == null);
                // check relay
                if (message.Recipient.IsRelayed)
                {
                    // check if reverse connection is possible
                    if (!message.Sender.IsRelayed)
                    {
                        await HandleRconAsync(handler, tcsResponse, message, channelCreator, connectTimeoutMillis, peerConnection,
                            timeoutHandler);
                    }
                    else
                    {
                        await HandleRelayAsync(handler, tcsResponse, message, channelCreator, idleTcpSeconds, connectTimeoutMillis,
                            peerConnection, timeoutHandler);
                    }
                }
                // normal connection
                else
                {
                    await ConnectAndSendAsync(handler, tcsResponse, channelCreator, connectTimeoutMillis, peerConnection,
                        timeoutHandler, message);
                }
            }
        }
Example #48
0
 public HeartBeat SetPeerConnection(PeerConnection peerConnection)
 {
     _peerConnection = peerConnection;
     return this;
 }
Example #49
0
        /// <summary>
        /// This method initiates the reverse connection setup.
        /// It creates a new message and sends it via relay to the unreachable peer
        /// which then connects to this peer again. After the connect message from the
        /// unreachable peer, this peer will send the original message and its content
        /// directly.
        /// </summary>
        /// <param name="handler"></param>
        /// <param name="tcsResponse"></param>
        /// <param name="message"></param>
        /// <param name="channelCreator"></param>
        /// <param name="connectTimeoutMillis"></param>
        /// <param name="peerConnection"></param>
        /// <param name="timeoutHandler"></param>
        private async Task HandleRconAsync(IInboundHandler handler, TaskCompletionSource<Message.Message> tcsResponse,
            Message.Message message, ChannelCreator channelCreator, int connectTimeoutMillis,
            PeerConnection peerConnection, TimeoutFactory timeoutHandler)
        {
            message.SetKeepAlive(true);

            Logger.Debug("Initiate reverse connection setup to peer with address {0}.", message.Recipient);
            var rconMessage = CreateRconMessage(message);

            // TODO works?
            // cache the original message until the connection is established
            _cachedRequests.AddOrUpdate(message.MessageId, tcsResponse, (i, source) => tcsResponse);

            // wait for response (whether the reverse connection setup was successful)
            var tcsRconResponse = new TaskCompletionSource<Message.Message>(rconMessage);

            // .NET-specific: specify and use a RconInboundHandler class
            var rconInboundHandler = new RconInboundHandler(tcsRconResponse, tcsResponse);

            // send reverse connection request instead of normal message
            await SendTcpAsync(rconInboundHandler, tcsRconResponse, rconMessage, channelCreator, connectTimeoutMillis,
                connectTimeoutMillis, peerConnection);
        }
Example #50
0
        private void Accept_Callback(IAsyncResult ar)
        {
            InitiatorContext context = (InitiatorContext) ar.AsyncState;

            try
            {
                Socket socket = context.Socket.EndAccept(ar);

                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, _connectionTimeout);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _receiveTimeout);

                socket.NoDelay = true;
                socket.LingerState = new LingerOption(false, 0);

                IPEndPoint remoteIp = socket.RemoteEndPoint as IPEndPoint;

                PeerConnection connection = new PeerConnection(socket, remoteIp, null);

                Connected(connection);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to connect: " + ex.Message);

                ConnectFailed(this);
            }
            finally
            {
                PostAccept(context);
            }
        }
Example #51
0
 private async Task ConnectAndSendAsync(IInboundHandler handler, TaskCompletionSource<Message.Message> tcsResponse, ChannelCreator channelCreator, int connectTimeoutMillis, PeerConnection peerConnection, TimeoutFactory timeoutHandler, Message.Message message)
 {
     var recipient = message.Recipient.CreateSocketTcp();
     var channel = SendTcpCreateChannel(recipient, channelCreator, peerConnection, handler, timeoutHandler,
         connectTimeoutMillis);
     await AfterConnectAsync(tcsResponse, message, channel, handler == null);
 }
Example #52
0
        public override void HandleResponse(Message.Message requestMessage, PeerConnection peerConnection, bool sign, IResponder responder)
        {
            if (requestMessage.KeyList.Count < 2)
            {
                throw new ArgumentException("At least location and domain keys are needed.");
            }
            if (!(requestMessage.Type == Message.Message.MessageType.Request1
                || requestMessage.Type == Message.Message.MessageType.Request2
                || requestMessage.Type == Message.Message.MessageType.Request3
                || requestMessage.Type == Message.Message.MessageType.Request4)
                && (requestMessage.Command == Rpc.Commands.Neighbor.GetNr()))
            {
                throw new ArgumentException("Message content is wrong for this handler.");
            }

            Number160 locationKey = requestMessage.Key(0);
            Number160 domainKey = requestMessage.Key(1);

            var neighbors = GetNeighbors(locationKey, NeighborSize);
            if (neighbors == null)
            {
                // return empty neighbor set
                var response = CreateResponseMessage(requestMessage, Message.Message.MessageType.NotFound);
                response.SetNeighborSet(new NeighborSet(-1, new Collection<PeerAddress>()));
                responder.Response(response);
                return;
            }

            // create response message and set neighbors
            var responseMessage = CreateResponseMessage(requestMessage, Message.Message.MessageType.Ok);

            Logger.Debug("Found the following neighbors: {0}.", Convenient.ToString(neighbors));
            var neighborSet = new NeighborSet(NeighborLimit, neighbors);
            responseMessage.SetNeighborSet(neighborSet);

            Number160 contentKey = requestMessage.Key(2);
            var keyBloomFilter = requestMessage.BloomFilter(0);
            var contentBloomFilter = requestMessage.BloomFilter(1);
            var keyCollection = requestMessage.KeyCollection(0);

            // it is important to set an integer if a value is present
            bool isDigest = requestMessage.Type != Message.Message.MessageType.Request1;
            if (isDigest)
            {
                if (requestMessage.Type == Message.Message.MessageType.Request2)
                {
                    DigestInfo digestInfo;
                    if (PeerBean.DigestStorage == null)
                    {
                        // no storage to search
                        digestInfo = new DigestInfo();
                    }
                    else if (contentKey != null && locationKey != null && domainKey != null)
                    {
                        var locationAndDomainKey = new Number320(locationKey, domainKey);
                        var from = new Number640(locationAndDomainKey, contentKey, Number160.Zero);
                        var to = new Number640(locationAndDomainKey, contentKey, Number160.MaxValue);
                        digestInfo = PeerBean.DigestStorage.Digest(from, to, -1, true);
                    }
                    else if ((keyBloomFilter != null || contentBloomFilter != null) && locationKey != null && domainKey != null)
                    {
                        var locationAndDomainKey = new Number320(locationKey, domainKey);
                        digestInfo = PeerBean.DigestStorage.Digest(locationAndDomainKey, keyBloomFilter,
                                contentBloomFilter, -1, true, true);
                    }
                    else if (keyCollection != null && keyCollection.Keys.Count == 2)
                    {
                        var enumerator = keyCollection.Keys.GetEnumerator();
                        var from = enumerator.MoveNext() ? enumerator.Current : null; // TODO works correctly?
                        var to = enumerator.MoveNext() ? enumerator.Current : null;

                        digestInfo = PeerBean.DigestStorage.Digest(from, to, -1, true);
                    }
                    else if (locationKey != null && domainKey != null)
                    {
                        var locationAndDomainKey = new Number320(locationKey, domainKey);
                        var from = new Number640(locationAndDomainKey, Number160.Zero, Number160.Zero);
                        var to = new Number640(locationAndDomainKey, Number160.MaxValue, Number160.MaxValue);
                        digestInfo = PeerBean.DigestStorage.Digest(from, to, -1, true);
                    }
                    else
                    {
                        Logger.Warn("Did not search for anything.");
                        digestInfo = new DigestInfo();
                    }
                    responseMessage.SetIntValue(digestInfo.Size);
                    responseMessage.SetKey(digestInfo.KeyDigest);
                    responseMessage.SetKey(digestInfo.ContentDigest);
                }
                else if (requestMessage.Type == Message.Message.MessageType.Request3)
                {
                    DigestInfo digestInfo;
                    if (PeerBean.DigestTracker == null)
                    {
                        // no tracker to search
                        digestInfo = new DigestInfo();
                    }
                    else
                    {
                        digestInfo = PeerBean.DigestTracker.Digest(locationKey, domainKey, contentKey);
                        if (digestInfo.Size == 0)
                        {
                            Logger.Debug("No entry found on peer {0}.", requestMessage.Recipient);
                        }
                    }
                    responseMessage.SetIntValue(digestInfo.Size);
                }
                else if (requestMessage.Type == Message.Message.MessageType.Request4)
                {
                    lock (PeerBean.PeerStatusListeners)
                    {
                        foreach (var listener in PeerBean.PeerStatusListeners)
                        {
                            listener.PeerFailed(requestMessage.Sender,
                                new PeerException(PeerException.AbortCauseEnum.Shutdown, "shutdown"));
                        }
                    }
                }
            }

            responder.Response(responseMessage);
        }
Example #53
0
 public PingBuilder SetPeerConnection(PeerConnection peerConnection)
 {
     PeerConnection = peerConnection;
     return this;
 }
Example #54
0
        public override void HandleResponse(Message.Message requestMessage, PeerConnection peerConnection, bool sign, IResponder responder)
        {
            if (!(requestMessage.Type == Message.Message.MessageType.Request1
                  || requestMessage.Type == Message.Message.MessageType.Request2)
                && requestMessage.Command == Rpc.Commands.DirectData.GetNr())
            {
                throw new ArgumentException("Message content is wrong for this handler.");
            }
            var responseMessage = CreateResponseMessage(requestMessage, Message.Message.MessageType.Ok);

            if (sign)
            {
                responseMessage.SetPublicKeyAndSign(PeerBean.KeyPair);
            }
            var rawDataReply2 = _rawDataReply;
            var objectDataReply2 = _objectDataReply;

            if (requestMessage.Type == Message.Message.MessageType.Request1 && rawDataReply2 == null)
            {
                responseMessage.SetType(Message.Message.MessageType.NotFound);
            }
            else if (requestMessage.Type == Message.Message.MessageType.Request2 && objectDataReply2 == null)
            {
                responseMessage.SetType(Message.Message.MessageType.NotFound);
            }
            else
            {
                var requestBuffer = requestMessage.Buffer(0);
                // The user can reply with null, indicating not found or returning 
                // the request buffer, which means nothing is returned.
                // Or an exception can be thrown.
                if (requestMessage.Type == Message.Message.MessageType.Request1)
                {
                    Logger.Debug("Handling Request1.");
                    var responseBuffer = rawDataReply2.Reply(requestMessage.Sender, requestBuffer, requestMessage.IsDone);
                    if (responseBuffer == null && requestMessage.IsDone)
                    {
                        Logger.Warn("Raw reply is null, returning not found.");
                        responseMessage.SetType(Message.Message.MessageType.NotFound);
                    }
// ReSharper disable once PossibleUnintendedReferenceComparison
                    else if (responseBuffer != requestBuffer) // reference equality ok
                    {
                        // can be partial as well
                        if (!responseBuffer.IsComplete)
                        {
                            responseMessage.SetStreaming();
                        }
                        responseMessage.SetBuffer(responseBuffer);
                    }
                }
                else
                {
                    // no streaming here when we deal with objects
                    object obj = Utils.Utils.DecodeObject(requestBuffer.BackingBuffer);
                    Logger.Debug("Handling {0}.", obj);

                    object reply = objectDataReply2.Reply(requestMessage.Sender, obj);
                    if (reply == null)
                    {
                        responseMessage.SetType(Message.Message.MessageType.NotFound);
                    }
                    else if (reply == obj)
                    {
                        responseMessage.SetType(Message.Message.MessageType.Ok);
                    }
                    else
                    {
                        sbyte[] me = Utils.Utils.EncodeObject(reply);
                        responseMessage.SetBuffer(new Message.Buffer(Unpooled.WrappedBuffer(me)));
                    }
                }
            }

            responder.Response(responseMessage);
        }
        public void onIceServers(IList<PeerConnection.IceServer> iceServers)
        {
            factory = new PeerConnectionFactory();
            pc = factory.CreatePeerConnection(iceServers, appRtcClient.pcConstraints(), pcObserver);

            // Uncomment to get ALL WebRTC tracing and SENSITIVE libjingle logging.
            // NOTE: this _must_ happen while |factory| is alive!
            // Logging.enableTracing(
            //     "logcat:",
            //     EnumSet.of(Logging.TraceLevel.TRACE_ALL),
            //     Logging.Severity.LS_SENSITIVE);

            {
                PeerConnection finalPC = pc;
                //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
                //ORIGINAL LINE: final Runnable repeatedStatsLogger = new Runnable()
                IRunnable repeatedStatsLogger = new RunnableAnonymousInnerClassHelper(this, finalPC);
                vsv.PostDelayed(repeatedStatsLogger, 10000);
            }

            {
                logAndToast("Creating local video source...");
                MediaStream lMS = factory.CreateLocalMediaStream("ARDAMS");
                if (appRtcClient.videoConstraints() != null)
                {
                    VideoCapturer capturer = VideoCapturer;
                    videoSource = factory.CreateVideoSource(capturer, appRtcClient.videoConstraints());
                    VideoTrack videoTrack = factory.CreateVideoTrack("ARDAMSv0", videoSource);
                    videoTrack.AddRenderer(new VideoRenderer(new VideoCallbacks(this, vsv, VideoStreamsView.Endpoint.LOCAL)));
                    lMS.AddTrack(videoTrack);
                }
                lMS.AddTrack(factory.CreateAudioTrack("ARDAMSa0"));
                pc.AddStream(lMS, new MediaConstraints());
            }
            logAndToast("Waiting for ICE candidates...");
        }
 // Disconnect from remote resources, dispose of local resources, and exit.
 private void disconnectAndExit()
 {
     lock (quit[0])
     {
         if (quit[0] == Boolean.True)
         {
             return;
         }
         quit[0] = Boolean.True;
         if (pc != null)
         {
             pc.Dispose();
             pc = null;
         }
         if (appRtcClient != null)
         {
             appRtcClient.sendMessage("{\"type\": \"bye\"}");
             appRtcClient.disconnect();
             appRtcClient = null;
         }
         if (videoSource != null)
         {
             videoSource.Dispose();
             videoSource = null;
         }
         if (factory != null)
         {
             factory.Dispose();
             factory = null;
         }
         Finish();
     }
 }
Example #57
0
        private ITcpClientChannel SendTcpPeerConnection(PeerConnection peerConnection, IChannelHandler handler, ChannelCreator channelCreator,
            TaskCompletionSource<Message.Message> tcsResponse)
        {
            // if the channel gets closed, the future should get notified
            var channel = peerConnection.Channel;

            // channel creator can be null if we don't need to create any channels
            if (channelCreator != null)
            {
                // TODO this doesn't do anything yet
                channelCreator.SetupCloseListener(channel, tcsResponse);
            }

            // we need to replace the handler if this comes from the peer that created a peer connection,
            // otherwise we need to add a handler
            AddOrReplace(channel.Pipeline, "dispatcher", "handler", handler);
            // TODO uncommented Java stuff needed?
            return channel as ITcpClientChannel; // TODO this will fail if its a server channel!!!
        }
Example #58
0
        static void Main(string[] args)
        {
            // actions, for setLocalDescription/setRemoteDescription
            const ushort SDP_OFFER = 0x100;
            const ushort SDP_PRANSWER = 0x200;
            const ushort SDP_ANSWER = 0x300;

            // PeerConnection state
            const ushort NEW = 0;     // initial state
            const ushort OPENING = 1; // local or remote desc set
            const ushort ACTIVE = 2;  // local and remote desc set
            const ushort CLOSED = 3;  // ended state

            // ICE state
            const ushort ICE_GATHERING = 0x100;
           const ushort ICE_WAITING = 0x200;
           const ushort ICE_CHECKING = 0x300;
           const ushort ICE_CONNECTED = 0x400;
           const ushort ICE_COMPLETED = 0x500;
           const ushort ICE_FAILED = 0x600;
           const ushort ICE_CLOSED = 0x700;


           /*NetTransport transport = new NetTransport();
           transport.OnEvent += (type, data) =>
               {
                   Console.WriteLine("transport.OnEvent({0}, {1})", type, data);
               };

           transport.SetDomain("sip2sip.info");
           Console.WriteLine("Default DstAddr= {0} Dst Port = {1}", transport.defaultDestAddr, transport.defaultDestPort);

           transport.Start(0);
           transport.SendTo("salut", "192.168.0.10", 5060);
           transport.Stop();*/




            PeerConnection peerConnection = new PeerConnection();

            String ro = peerConnection.createAnswer(true, true);
            SessionDescription sdpOffer = new SessionDescription();
            sdpOffer.Init(ro);

            Console.WriteLine("Offer before ICE = {0}", sdpOffer.toSdp());

            peerConnection.IceCallback += (media, candidate, moreToFollow) => 
            {
                sdpOffer.addCandidate(media, candidate);
                if (!moreToFollow)
                {
                    String sdp = sdpOffer.toSdp();
                    Console.WriteLine("Offer after ICE = {0}", sdp);
                    peerConnection.setRemoteDescription(SDP_ANSWER, sdp);
                }
            };



            peerConnection.startIce(0, 0);

            Console.ReadLine();

            peerConnection.close();
        }
Example #59
0
 private Task<PeerAddress> PingPeerConnection(PeerConnection peerConnection)
 {
     var tcsPing = new TaskCompletionSource<PeerAddress>();
     var requestHandler = _peer.PingRpc.Ping(peerConnection.RemotePeer, _connectionConfiguration);
     var taskCc = peerConnection.AcquireAsync(requestHandler.TcsResponse);
     taskCc.ContinueWith(tcc =>
     {
         if (!tcc.IsFaulted)
         {
             requestHandler.TcsResponse.Task.Result.SetKeepAlive(true); // TODO correct?
             var taskResponse = requestHandler.SendTcpAsync(peerConnection);
             AddPingListener(tcsPing, taskResponse);
         }
         else
         {
             tcsPing.SetException(tcc.TryGetException());
         }
     });
     return tcsPing.Task;
 }