コード例 #1
0
ファイル: I2NPMessagesTest.cs プロジェクト: itfenom/i2p-cs
        public void TestSimpleDatabaseHeader5StoreCreation()
        {
            var mapping = new I2PMapping();

            mapping["One"] = "1";
            mapping["2"]   = "Two";

            var ri = new I2PRouterInfo(
                new I2PRouterIdentity(Public, PublicSigning),
                I2PDate.Now,
                new I2PRouterAddress[] { new I2PRouterAddress(new IPAddress(424242L), 773, 42, "SSU") },
                mapping,
                PrivateSigning);

            var dbsm = new DatabaseStoreMessage(ri);

            var data = dbsm.CreateHeader16.HeaderAndPayload;

            var recreated = I2NPMessage.ReadHeader16(new BufRefLen(data));

            Assert.IsTrue(recreated.MessageType == I2NPMessage.MessageTypes.DatabaseStore);
            var rdsm = (DatabaseStoreMessage)recreated.Message;

            Assert.IsTrue(rdsm.RouterInfo.Options["One"] == "1");
            Assert.IsTrue(rdsm.RouterInfo.Options["2"] == "Two");
            Assert.IsTrue(rdsm.RouterInfo.VerifySignature());
        }
コード例 #2
0
        public void TestSimpleTunnelDataCreation()
        {
            var smalldata = BufUtils.RandomBytes(38);

            var srcmsgs = new List <TunnelMessage>();

            srcmsgs.Add(new TunnelMessageLocal(new DeliveryStatusMessage(1234)));
            var msgfrags = TunnelDataMessage.MakeFragments(srcmsgs, 0x3e5c);

            Assert.IsTrue(msgfrags.Count() == 1);

            var firstmsg   = msgfrags.First();
            var serialized = firstmsg.CreateHeader16.HeaderAndPayload;

            var recovered = I2NPMessage.ReadHeader16(new BufRefLen(serialized));

            var reassembler     = new TunnelDataFragmentReassembly();
            var reassembledmsgs = reassembler.Process(
                new TunnelDataMessage[]
            {
                (TunnelDataMessage)recovered.Message
            }, out var _);

            Assert.IsTrue(reassembledmsgs.Count() == 1);

            var firstrecinstr = reassembledmsgs.First();

            Assert.IsTrue(firstrecinstr.Delivery == TunnelMessage.DeliveryTypes.Local);
            Assert.IsTrue(firstrecinstr.Message.MessageType == I2NPMessage.MessageTypes.DeliveryStatus);
            Assert.IsTrue(((DeliveryStatusMessage)firstrecinstr.Message).StatusMessageId == 1234);
        }
コード例 #3
0
        public void TestSimpleDatabaseStoreLeaseSetEd25519Creation()
        {
            var linfo  = new I2PLeaseInfo(Public, PublicSigningEd25519, Private, PrivateSigningEd25519);
            var leases = new List <I2PLease>();

            for (int i = 0; i < 5; ++i)
            {
                leases.Add(new I2PLease(new I2PIdentHash(true), (uint)((i * 72 + 6) * i * 1314 + 5) % 40000, I2PDate.Now));
            }
            var ls = new I2PLeaseSet(new I2PDestination(Public, PublicSigningEd25519), leases, linfo);

            var dbsm = new DatabaseStoreMessage(ls);

            var data = dbsm.Header16.HeaderAndPayload;

            var recreated = I2NPMessage.ReadHeader16(new BufRefLen(data));

            Assert.IsTrue(recreated.MessageType == I2NPMessage.MessageTypes.DatabaseStore);
            var rdsm = (DatabaseStoreMessage)recreated.Message;

            Assert.IsTrue(rdsm.LeaseSet.Leases.Count == 5);

            Assert.IsTrue(BufUtils.Equal(ls.Destination.ToByteArray(), rdsm.LeaseSet.Destination.ToByteArray()));
            Assert.IsTrue(BufUtils.Equal(ls.PublicKey.ToByteArray(), rdsm.LeaseSet.PublicKey.ToByteArray()));
            Assert.IsTrue(BufUtils.Equal(ls.PublicSigningKey.ToByteArray(), rdsm.LeaseSet.PublicSigningKey.ToByteArray()));
            for (int i = 0; i < 5; ++i)
            {
                Assert.IsTrue(BufUtils.Equal(ls.Leases[i].ToByteArray(), rdsm.LeaseSet.Leases[i].ToByteArray()));
            }

            Assert.IsTrue(rdsm.LeaseSet.VerifySignature());
        }
コード例 #4
0
        public void MakeAndReadFragmentsWithSerialize()
        {
            var origmsgs = new List <TunnelMessage>();

            for (int i = 0; i < 200; ++i)
            {
                switch (BufUtils.RandomInt(3))
                {
                case 0:
                    var adatarec = new DataMessage(
                        new BufLen(
                            BufUtils.RandomBytes(2048 + BufUtils.RandomInt(1024))));

                    origmsgs.Add(new TunnelMessageLocal(adatarec));
                    break;

                case 1:
                    var arec = new DatabaseLookupMessage(
                        new I2PIdentHash(true),
                        new I2PIdentHash(true),
                        DatabaseLookupMessage.LookupTypes.RouterInfo);

                    origmsgs.Add(new TunnelMessageRouter(
                                     arec,
                                     new I2PIdentHash(true)));
                    break;

                case 2:
                    var adatarec2 = new DataMessage(
                        new BufLen(
                            BufUtils.RandomBytes(2048 + BufUtils.RandomInt(1024))));

                    origmsgs.Add(new TunnelMessageTunnel(adatarec2,
                                                         new I2PIdentHash(true),
                                                         BufUtils.RandomUint()));
                    break;
                }
            }

            var msgs     = TunnelDataMessage.MakeFragments(origmsgs, BufUtils.RandomUint());
            var recvlist = new List <TunnelDataMessage>();

            foreach (var msg in msgs)
            {
                recvlist.Add((TunnelDataMessage)I2NPMessage.ReadHeader16(
                                 new BufRefLen(msg.CreateHeader16.HeaderAndPayload)).Message);
            }

            var mkmsg     = new TunnelDataFragmentReassembly();
            var recvtmsgs = mkmsg.Process(recvlist, out var _);

            foreach (var rmsg in recvtmsgs)
            {
                Assert.IsTrue(origmsgs.SingleOrDefault(m =>
                                                       m.Delivery == rmsg.Delivery &&
                                                       m.Message.CreateHeader16.HeaderAndPayload == rmsg.Message.CreateHeader16.HeaderAndPayload
                                                       ) != null);
            }
        }
コード例 #5
0
 public GarlicClove(BufRef reader)
 {
     Delivery   = GarlicCloveDelivery.CreateGarlicCloveDelivery(reader);
     Message    = I2NPMessage.ReadHeader16(reader).Message;
     CloveId    = reader.Read32();
     Expiration = new I2PDate(reader);
     reader.Seek(3);   // Cert
 }
コード例 #6
0
ファイル: I2NPMessagesTest.cs プロジェクト: itfenom/i2p-cs
        public void TestSimpleDatabaseStoreLeaseSetCreation()
        {
            var linfo = new I2PLeaseInfo(Public, PublicSigning, Private, PrivateSigning);

            var leases = new List <I2PLease>();

            for (int i = 0; i < 5; ++i)
            {
                leases.Add(new I2PLease(
                               new I2PIdentHash(true),
                               new I2PTunnelId()));
            }

            var ls = new I2PLeaseSet(new I2PDestination(Public, PublicSigning), leases, linfo);

            var dbsm = new DatabaseStoreMessage(ls);

            var data = dbsm.CreateHeader16.HeaderAndPayload.Clone();

            var recreated = I2NPMessage.ReadHeader16(new BufRefLen(data));

            Assert.IsTrue(recreated.MessageType == I2NPMessage.MessageTypes.DatabaseStore);
            var rdsm = (DatabaseStoreMessage)recreated.Message;

            Assert.IsTrue(rdsm.LeaseSet.Leases.Count() == 5);

            Assert.IsTrue(BufUtils.Equal(ls.Destination.ToByteArray(), rdsm.LeaseSet.Destination.ToByteArray()));
            Assert.IsTrue(BufUtils.Equal(ls.PublicKey.ToByteArray(), rdsm.LeaseSet.PublicKey.ToByteArray()));
            Assert.IsTrue(BufUtils.Equal(ls.PublicSigningKey.ToByteArray(), rdsm.LeaseSet.PublicSigningKey.ToByteArray()));

            var rdsmlsar = rdsm.LeaseSet.Leases.ToArray();
            var lsar     = ls.Leases.ToArray();

            // Order should be maintained
            for (int i = 0; i < 5; ++i)
            {
                Assert.IsTrue(
                    BufUtils.Equal(
                        lsar[i].ToByteArray(),
                        rdsmlsar[i].ToByteArray()));
            }

            Assert.IsTrue(rdsm.LeaseSet.VerifySignature(PublicSigning));
        }
コード例 #7
0
        public void TestSingleLargeTunnelDataCreation()
        {
            var sourcedata = new BufLen(BufUtils.RandomBytes(9000));

            var srcmsgs = new List <TunnelMessage>();

            srcmsgs.Add(new TunnelMessageTunnel(new DataMessage(sourcedata), new I2PIdentHash(true), 4242));
            var msgfrags = TunnelDataMessage.MakeFragments(srcmsgs, 0x3e5c);

            Assert.IsTrue(msgfrags.Count() == 10);

            var serbuf = new List <byte>();

            foreach (var frag in msgfrags)
            {
                serbuf.AddRange(frag.CreateHeader16.HeaderAndPayload);
            }
            var serbufarray = serbuf.ToArray();

            var reassembler = new TunnelDataFragmentReassembly();
            var reader      = new BufRefLen(serbufarray);
            var readmsgs    = new List <TunnelDataMessage>();

            while (reader.Length > 0)
            {
                readmsgs.Add((TunnelDataMessage)(I2NPMessage.ReadHeader16(reader)).Message);
            }

            var reassembledmsgs = reassembler.Process(readmsgs, out var _);

            Assert.IsTrue(reassembledmsgs.Count() == 1);
            Assert.IsTrue(reassembler.BufferedFragmentCount == 0);

            var firstrecinstr = reassembledmsgs.First();

            Assert.IsTrue(firstrecinstr.Delivery == TunnelMessage.DeliveryTypes.Tunnel);
            Assert.IsTrue(((TunnelMessageTunnel)firstrecinstr).Tunnel == 4242);
            Assert.IsTrue(firstrecinstr.Message.MessageType == I2NPMessage.MessageTypes.Data);

            var datamsg = (DataMessage)firstrecinstr.Message;

            Assert.IsTrue(datamsg.DataMessagePayloadLength == sourcedata.Length);
            Assert.IsTrue(datamsg.DataMessagePayload == sourcedata);
        }
コード例 #8
0
        private static void AddTunnelMessage(List <TunnelMessage> result, TunnelDataFragment initialfragment, byte[] buf)
        {
            switch (initialfragment.Delivery)
            {
            case TunnelMessage.DeliveryTypes.Local:
                result.Add(new TunnelMessageLocal(I2NPMessage.ReadHeader16(new BufRef(buf))));
                break;

            case TunnelMessage.DeliveryTypes.Router:
                result.Add(new TunnelMessageRouter(I2NPMessage.ReadHeader16(new BufRef(buf)),
                                                   new I2PIdentHash((BufRefLen)initialfragment.ToHash)));
                break;

            case TunnelMessage.DeliveryTypes.Tunnel:
                result.Add(new TunnelMessageTunnel(I2NPMessage.ReadHeader16(new BufRef(buf)),
                                                   new I2PIdentHash((BufRefLen)initialfragment.ToHash), initialfragment.Tunnel));
                break;
            }
        }
コード例 #9
0
        void Run()
        {
            try
            {
                try
                {
                    NTCPContext.TransportInstance = TransportInstance;

                    Watchdog.Inst.StartMonitor(Thread.CurrentThread, 20000);

                    try
                    {
                        MySocket = CreateSocket();

                        RemoteDescription = MySocket.RemoteEndPoint.ToString();

#if LOG_ALL_TRANSPORT
                        DebugUtils.LogDebug("My local endpoint IP#   : " + ((IPEndPoint)MySocket.LocalEndPoint).Address.ToString());
                        DebugUtils.LogDebug("My local endpoint Port  : " + ((IPEndPoint)MySocket.LocalEndPoint).Port.ToString());
#endif

                        DHNegotiate();
                    }
                    catch (SocketException ex)
                    {
                        if (NTCPContext.RemoteRouterIdentity != null)
                        {
                            NetDb.Inst.Statistics.FailedToConnect(NTCPContext.RemoteRouterIdentity.IdentHash);
                        }
                        throw new FailedToConnectException(ex.ToString());
                    }
                    catch (FormatException)
                    {
                        if (NTCPContext.RemoteRouterIdentity != null)
                        {
                            NetDb.Inst.Statistics.DestinationInformationFaulty(NTCPContext.RemoteRouterIdentity.IdentHash);
                        }
                        throw;
                    }
                    catch (NotSupportedException)
                    {
                        if (NTCPContext.RemoteRouterIdentity != null)
                        {
                            NetDb.Inst.Statistics.DestinationInformationFaulty(NTCPContext.RemoteRouterIdentity.IdentHash);
                        }
                        throw;
                    }
                    catch (ThreadInterruptedException)
                    {
                        if (NTCPContext.RemoteRouterIdentity != null)
                        {
                            NetDb.Inst.Statistics.SlowHandshakeConnect(NTCPContext.RemoteRouterIdentity.IdentHash);
                        }
                        throw;
                    }
                    catch (ThreadAbortException)
                    {
                        if (NTCPContext.RemoteRouterIdentity != null)
                        {
                            NetDb.Inst.Statistics.SlowHandshakeConnect(NTCPContext.RemoteRouterIdentity.IdentHash);
                        }
                        throw;
                    }

                    DHSucceeded = true;

                    Watchdog.Inst.UpdateTimeout(Thread.CurrentThread, InactivityTimeoutSeconds * 1000);

                    TryInitiateSend();

#if DEBUG
                    if (ConnectionEstablished == null)
                    {
                        DebugUtils.LogWarning("NTCPClient: No observers for ConnectionEstablished!");
                    }
#endif
                    if (ConnectionEstablished != null)
                    {
                        ConnectionEstablished(this);
                    }
                    NetDb.Inst.Statistics.SuccessfulConnect(NTCPContext.RemoteRouterIdentity.IdentHash);

                    var reader = new NTCPReader(MySocket, NTCPContext);

                    while (!Terminated)
                    {
                        var data = reader.Read();
                        //DebugUtils.LogDebug( "Read: " + data.Length );

                        Watchdog.Inst.Ping(Thread.CurrentThread);

                        if (reader.NTCPDataSize == 0)
                        {
                            //if ( TimeSyncReceived != null ) TimeSyncReceived( this, data );
                        }
                        else
                        {
#if DEBUG
                            if (DataBlockReceived == null)
                            {
                                DebugUtils.LogWarning("NTCPClient: No observers for DataBlockReceived !");
                            }
#endif
                            if (DataBlockReceived != null)
                            {
                                DataBlockReceived(this, I2NPMessage.ReadHeader16(new BufRefLen(data)));
                            }
                        }
                    }
                }
                catch (ThreadAbortException)
                {
                    DebugUtils.LogDebug(string.Format("NTCP {0} Aborted", DebugId));
                }
                catch (ThreadInterruptedException)
                {
                    DebugUtils.LogDebug(string.Format("NTCP {0} Interrupted", DebugId));
                }
                catch (FailedToConnectException)
                {
                    DebugUtils.LogDebug(string.Format("NTCP {0} Failed to connect", DebugId));
                }
                catch (EndOfStreamEncounteredException)
                {
                    DebugUtils.LogDebug(string.Format("NTCP {0} Disconnected", DebugId));
                }
                catch (IOException ex)
                {
                    DebugUtils.LogDebug(string.Format("NTCP {1} Exception: {0}", ex, DebugId));
                }
                catch (SocketException ex)
                {
                    DebugUtils.LogDebug(string.Format("NTCP {1} Exception: {0}", ex, DebugId));
                }
                catch (Exception ex)
                {
#if DEBUG
                    if (ConnectionException == null)
                    {
                        DebugUtils.LogWarning("NTCPClient: No observers for ConnectionException!");
                    }
#endif
                    if (ConnectionException != null)
                    {
                        ConnectionException(this, ex);
                    }
                    DebugUtils.LogDebug(string.Format("NTCP {1} Exception: {0}", ex, DebugId));
                }
            }

            finally
            {
                Terminated = true;
                Watchdog.Inst.StopMonitor(Thread.CurrentThread);

                try
                {
                    if (!DHSucceeded && NTCPContext.RemoteRouterIdentity != null)
                    {
                        NetDb.Inst.Statistics.FailedToConnect(NTCPContext.RemoteRouterIdentity.IdentHash);
                    }
                }
                catch (Exception ex)
                {
                    DebugUtils.Log(DebugId, ex);
                }

                DebugUtils.LogDebug(string.Format("NTCP {0} Shut down. {1}", DebugId, RemoteDescription));

                try
                {
#if DEBUG
                    if (ConnectionShutDown == null)
                    {
                        DebugUtils.LogWarning("NTCPClient: No observers for ConnectionShutDown!");
                    }
#endif
                    if (ConnectionShutDown != null)
                    {
                        ConnectionShutDown(this);
                    }
                }
                catch (Exception ex)
                {
                    DebugUtils.Log(DebugId, ex);
                }

                if (MySocket != null)
                {
                    try
                    {
                        MySocket.Shutdown(SocketShutdown.Both);
                        MySocket.Close();
                    }
                    catch (Exception ex)
                    {
                        DebugUtils.Log(DebugId, ex);
                    }
                    finally
                    {
                        MySocket = null;
                    }
                }
            }
        }
コード例 #10
0
        public override SSUState HandleMessage(SSUHeader header, BufRefLen reader)
        {
            switch (header.MessageType)
            {
            case SSUHeader.MessageTypes.Data:
                try
                {
                    var datamsg = new SSUDataMessage(reader, Session.Defragmenter);
                    if (datamsg.ExplicitAcks != null)
                    {
                        Session.Fragmenter.GotAck(datamsg.ExplicitAcks);
                    }
                    if (datamsg.AckBitfields != null)
                    {
                        Session.Fragmenter.GotAck(datamsg.AckBitfields);
                    }
                    if (datamsg.NewMessages != null)
                    {
                        foreach (var msg in datamsg.NewMessages)
                        {
                            var i2npmsg = I2NPMessage.ReadHeader16((BufRefLen)msg.GetPayload());

#if LOG_MUCH_TRANSPORT
                            Logging.LogDebugData($"SSU {this} complete message " +
                                                 $"{msg.MessageId}: {i2npmsg.Expiration}");
#endif

                            if (i2npmsg.MessageType == I2NPMessage.MessageTypes.DeliveryStatus)
                            {
                                if (((DeliveryStatusMessage)i2npmsg.Message).IsNetworkId((ulong)I2PConstants.I2P_NETWORK_ID))
                                {
                                    continue;
                                }
                            }

                            Session.MessageReceived(i2npmsg);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging.Log("EstablishedState: SSUHost.SSUMessageTypes.Data", ex);
                }
                break;

            case SSUHeader.MessageTypes.PeerTest:
                HandleIncomingPeerTestPackage(reader);
                break;

            case SSUHeader.MessageTypes.RelayResponse:
                Logging.LogTransport($"SSU EstablishedState {Session.DebugId}: RelayResponse received from {Session.RemoteEP}.");
                var response = new RelayResponse(reader);
                Session.Host.ReportRelayResponse(header, response, Session.RemoteEP);
                break;

            case SSUHeader.MessageTypes.RelayIntro:
                var intro = new RelayIntro(reader);
                Logging.LogTransport($"SSU EstablishedState {Session.DebugId}: RelayIntro received from {Session.RemoteEP} for {intro.AliceEndpoint}.");

                var data = new BufLen(new byte[12]);
                data.Randomize();
                Send(intro.AliceEndpoint, data);

                ++Session.Host.EPStatisitcs[Session.RemoteEP].RelayIntrosReceived;
                ++Session.RelayIntroductionsReceived;
                break;

            case SSUHeader.MessageTypes.RelayRequest:
                // TODO: Implement
                // if ( !SSUHost.IntroductionSupported ) throw new Exception( "SSU relay introduction not supported" );
                Logging.LogTransport(string.Format("SSU EstablishedState {0}: Relay introduction not supported.", Session.DebugId));
                break;

            case SSUHeader.MessageTypes.SessionRequest:
                Logging.LogTransport(string.Format("SSU EstablishedState {0}: SessionRequest received. Ending session.", Session.DebugId));
                SendSessionDestroyed();
                return(null);

            default:
                Logging.LogTransport(string.Format("SSU EstablishedState {0}: Unexpected message received: {1}.",
                                                   Session.DebugId, header.MessageType));
                break;
            }

            return(this);
        }
コード例 #11
0
ファイル: TransportTest.cs プロジェクト: githubassets/i2p-cs
        public void TestSSUOutOfOrderFragmentation()
        {
            var fragmenter = new DataFragmenter();

            var smalldata        = new BufLen(BufUtils.RandomBytes(4 + BufUtils.RandomInt(4)));
            var smalldatamessage = new DataMessage(smalldata);

            var smalldata1        = new BufLen(BufUtils.RandomBytes(40 + BufUtils.RandomInt(14)));
            var smalldatamessage1 = new DataMessage(smalldata1);

            var smalldata2        = new BufLen(BufUtils.RandomBytes(130 + BufUtils.RandomInt(39)));
            var smalldatamessage2 = new DataMessage(smalldata2);

            var smalldata3        = new BufLen(BufUtils.RandomBytes(770 + BufUtils.RandomInt(220)));
            var smalldatamessage3 = new DataMessage(smalldata3);

            var data        = new BufLen(BufUtils.RandomBytes(30000 + BufUtils.RandomInt(30)));
            var datamessage = new DataMessage(data);

            var data2        = new BufLen(BufUtils.RandomBytes(20000 + BufUtils.RandomInt(1040)));
            var datamessage2 = new DataMessage(data2);

            var dest   = new byte[MTUConfig.BufferSize];
            var start  = new BufLen(dest);
            var writer = new BufRefLen(dest);

            var tosend = new LinkedList <II2NPHeader16>();

            tosend.AddLast(smalldatamessage.CreateHeader16);
            tosend.AddLast(datamessage.CreateHeader16);
            tosend.AddLast(smalldatamessage1.CreateHeader16);
            tosend.AddLast(smalldatamessage2.CreateHeader16);
            tosend.AddLast(smalldatamessage3.CreateHeader16);
            tosend.AddLast(datamessage2.CreateHeader16);

            var tosendshuffle  = tosend.Shuffle();
            var tosendshuffled = new ConcurrentQueue <II2NPHeader16>(tosendshuffle);

            var sent = new LinkedList <II2NPHeader16>();

            foreach (var one in tosend)
            {
                sent.AddLast(one);
            }

            var sentdata = new LinkedList <BufLen>();

            while (true)
            {
                var flagbuf      = writer.ReadBufLen(1);
                var fragcountbuf = writer.ReadBufLen(1);

                var fragments = fragmenter.Send(writer, tosendshuffled);
                if (fragments == 0)
                {
                    break;
                }

                flagbuf[0] |= (byte)SSUDataMessage.DataMessageFlags.WantReply;
                // no ACKs
                fragcountbuf[0] = (byte)fragments;

                sentdata.AddLast(new BufLen(start, 0, writer - start));
                dest   = new byte[MTUConfig.BufferSize];
                start  = new BufLen(dest);
                writer = new BufRefLen(dest);
            }

            var shuffled = sentdata.Shuffle();

            var receivedmessages = new LinkedList <II2NPHeader16>();

            var defragmenter = new DataDefragmenter();

            foreach (var frag in shuffled)
            {
                var datamsg = new SSUDataMessage(new BufRefLen(frag), defragmenter);
                if (datamsg.NewMessages != null)
                {
                    foreach (var msg in datamsg.NewMessages)
                    {
                        var i2npmsg = I2NPMessage.ReadHeader16((BufRefLen)msg.GetPayload());
                        receivedmessages.AddLast(i2npmsg);
                    }
                }
            }

            Assert.IsTrue(receivedmessages.Count == sent.Count);

            foreach (var sentmsg in sent)
            {
                Assert.IsTrue(receivedmessages.SingleOrDefault(m => ((DataMessage)m.Message).Payload ==
                                                               ((DataMessage)sentmsg.Message).Payload) != null);
            }
        }
コード例 #12
0
ファイル: TransportTest.cs プロジェクト: githubassets/i2p-cs
        public void TestSSUFragmentation()
        {
            var fragmenter = new DataFragmenter();

            var smalldata        = new BufLen(BufUtils.RandomBytes(30));
            var smalldatamessage = new DataMessage(smalldata);

            var data        = new BufLen(BufUtils.RandomBytes(30000));
            var datamessage = new DataMessage(data);

            var data2        = new BufLen(BufUtils.RandomBytes(30000));
            var datamessage2 = new DataMessage(data2);

            var dest   = new byte[MTUConfig.BufferSize];
            var start  = new BufLen(dest);
            var writer = new BufRefLen(dest);

            var tosend = new ConcurrentQueue <II2NPHeader16>();

            tosend.Enqueue(smalldatamessage.CreateHeader16);
            tosend.Enqueue(datamessage.CreateHeader16);
            tosend.Enqueue(datamessage2.CreateHeader16);

            var sent = new LinkedList <II2NPHeader16>();

            foreach (var one in tosend)
            {
                sent.AddLast(one);
            }

            var sentdata = new LinkedList <BufLen>();

            while (true)
            {
                var flagbuf      = writer.ReadBufLen(1);
                var fragcountbuf = writer.ReadBufLen(1);

                var fragments = fragmenter.Send(writer, tosend);
                if (fragments == 0)
                {
                    break;
                }

                flagbuf[0] |= (byte)SSUDataMessage.DataMessageFlags.WantReply;
                // no ACKs
                fragcountbuf[0] = (byte)fragments;

                sentdata.AddLast(new BufLen(start, 0, writer - start));
                dest   = new byte[MTUConfig.BufferSize];
                start  = new BufLen(dest);
                writer = new BufRefLen(dest);
            }

            var receivedmessages = new LinkedList <II2NPHeader16>();

            var defragmenter = new DataDefragmenter();

            foreach (var frag in sentdata)
            {
                var datamsg = new SSUDataMessage(new BufRefLen(frag), defragmenter);
                if (datamsg.NewMessages != null)
                {
                    foreach (var msg in datamsg.NewMessages)
                    {
                        var i2npmsg = I2NPMessage.ReadHeader16((BufRefLen)msg.GetPayload());
                        receivedmessages.AddLast(i2npmsg);
                    }
                }
            }

            Assert.IsTrue(receivedmessages.Count == sent.Count);

            foreach (var sentmsg in sent)
            {
                Assert.IsTrue(receivedmessages.Any(m => m.Message.Payload ==
                                                   sentmsg.Message.Payload));
            }
        }
コード例 #13
0
ファイル: TransportTest.cs プロジェクト: githubassets/i2p-cs
        public void TestSSUFragmentation1()
        {
            var fragmenter = new DataFragmenter();

            var smalldata        = new BufLen(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, });
            var smalldatamessage = new DataMessage(smalldata);

            var dest   = new byte[MTUConfig.BufferSize];
            var start  = new BufLen(dest);
            var writer = new BufRefLen(dest);

            var tosend = new ConcurrentQueue <II2NPHeader16>();

            tosend.Enqueue(smalldatamessage.CreateHeader16);

            var sent = new LinkedList <II2NPHeader16>();

            foreach (var one in tosend)
            {
                sent.AddLast(one);
            }

            var sentdata = new LinkedList <BufLen>();

            while (true)
            {
                var flagbuf      = writer.ReadBufLen(1);
                var fragcountbuf = writer.ReadBufLen(1);

                var fragments = fragmenter.Send(writer, tosend);
                if (fragments == 0)
                {
                    break;
                }

                flagbuf[0] |= (byte)SSUDataMessage.DataMessageFlags.WantReply;
                // no ACKs
                fragcountbuf[0] = (byte)fragments;

                sentdata.AddLast(new BufLen(start, 0, writer - start));
                dest   = new byte[MTUConfig.BufferSize];
                start  = new BufLen(dest);
                writer = new BufRefLen(dest);
            }

            var receivedmessages = new LinkedList <II2NPHeader16>();

            var defragmenter = new DataDefragmenter();

            foreach (var frag in sentdata)
            {
                var datamsg = new SSUDataMessage(new BufRefLen(frag), defragmenter);
                if (datamsg.NewMessages != null)
                {
                    foreach (var msg in datamsg.NewMessages)
                    {
                        var i2npmsg = I2NPMessage.ReadHeader16((BufRefLen)msg.GetPayload());
                        receivedmessages.AddLast(i2npmsg);
                    }
                }
            }

            Assert.IsTrue(receivedmessages.Count == sent.Count);

            /*
             *
             * var st1 = FreenetBase64.Encode( sent.First.Value.Message.Payload );
             * var st2 = FreenetBase64.Encode( receivedmessages.First.Value.Message.Payload );
             *
             * Console.WriteLine( st1 );
             * Console.WriteLine( st2 );
             *
             * Console.WriteLine( sent.First.Value.Message );
             * Console.WriteLine( receivedmessages.First.Value.Message );
             *
             * Console.WriteLine( sent.First.Value.Message.Payload.ToString( "I500" ) );
             * Console.WriteLine( receivedmessages.First.Value.Message.Payload.ToString( "I500" ) );
             */

            foreach (var sentmsg in sent)
            {
                Assert.IsTrue(receivedmessages.Any(m => m.Message.Payload ==
                                                   sentmsg.Message.Payload));
            }
        }